repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
karivalkama/Agricola-Scripture-Editor | TranslationEditor/ConnectionManager.swift | 1 | 6378 | //
// ConnectionManager.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 8.2.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
// This interface handles database connections to server(s) and P2P hosts
class ConnectionManager
{
// ATTRBUTES ------------
static let instance = ConnectionManager()
private(set) var status = ConnectionStatus.disconnected
private(set) var targetTransferCount = 0
private(set) var completedTransferCount = 0
private var replications = [CBLReplication]()
private var observers = [NSObjectProtocol]()
private var listeners = [ConnectionListener]()
// COMPUTED PROPERTIES ----
// The relative progress of the sync process
// Between 0 and 1
var progress: Double
{
if targetTransferCount == 0
{
return status == .upToDate ? 1 : 0
}
else
{
return Double(completedTransferCount) / Double(targetTransferCount)
}
}
// INIT --------------------
// Initialisation hidden behind static interface
private init() { }
// OTHER METHODS --------
// Connects to a new server address
// Authorization is optional
// ServerURL may be 'http://localhost:4984', for example
// The connection is continuous by default
func connect(serverURL: String, userName: String? = nil, password: String? = nil, continuous: Bool = true)
{
// First disconnects the previous connection
disconnect()
let completeURL = serverURL.endsWith("/") ? serverURL + DATABASE.name : serverURL + "/" + DATABASE.name
guard let url = URL(string: completeURL) else
{
print("ERROR: Failed to create url based on '\(completeURL)'")
return
}
print("STATUS: Connecting to \(url.absoluteString)")
// Creates new connections, uses authorization if available
replications = [DATABASE.createPullReplication(url), DATABASE.createPushReplication(url)]
replications.forEach { $0.continuous = continuous }
if let userName = userName, let password = password
{
let auth = CBLAuthenticator.basicAuthenticator(withName: userName, password: password)
replications.forEach { $0.authenticator = auth }
}
// Starts the synchronization
status = .connecting
// Informs the listeners too
listeners.forEach { $0.onConnectionStatusChange(newStatus: status) }
observers = replications.map { NotificationCenter.default.addObserver(forName: NSNotification.Name.cblReplicationChange, object: $0, queue: nil, using: updateStatus) }
replications.forEach { $0.start() }
}
// Disconnects the current connection
// Has no effect if there is no connection
func disconnect()
{
if status != .disconnected
{
// Removes the observers first
observers.forEach { NotificationCenter.default.removeObserver($0) }
// Then stops the replications
replications.forEach { $0.stop() }
observers = []
replications = []
status = .disconnected
listeners.forEach { $0.onConnectionStatusChange(newStatus: status) }
}
}
// Adds a new listener to this connection manager.
// The listener will be informed whenever the manager's status changes
func registerListener(_ listener: ConnectionListener)
{
if !listeners.contains(where: { $0 === listener })
{
listeners.append(listener)
// Informs the listener of the initial status
listener.onConnectionStatusChange(newStatus: status)
listener.onConnectionProgressUpdate(transferred: completedTransferCount, of: targetTransferCount, progress: progress)
}
}
// Removes a listener from this connection manager so that it is no longer informed when connection status changes
func removeListener(_ listener: ConnectionListener)
{
listeners = listeners.filter { !($0 === listener) }
}
private func updateStatus(n: Notification)
{
let oldStatus = status
let oldTargetCount = targetTransferCount
let oldCompletedCount = completedTransferCount
// If either replication is active, this process is considered to be active too
if replications.contains(where: { $0.status == .active })
{
targetTransferCount = Int(replications.reduce(0, { $0 + $1.changesCount }))
completedTransferCount = Int(replications.reduce(0, { $0 + $1.completedChangesCount }))
status = .active
}
// Same goes with offline
else if replications.contains(where: { $0.status == .offline })
{
status = .offline
}
else
{
// Checks for authentication errors
if replications.contains(where: { ($0.lastError as NSError?)?.code == 401 })
{
status = .unauthorized
}
else if replications.contains(where: { $0.status == .stopped })
{
if let error = replications.compactMap({ $0.lastError }).first
{
print("ERROR: Database transfer failed with error: \(error)")
status = .failed
}
else
{
status = .done
}
}
else
{
completedTransferCount = targetTransferCount
status = .upToDate
}
}
// Informs the listeners of the status change
if oldStatus != status
{
listeners.forEach { $0.onConnectionStatusChange(newStatus: status) }
}
if oldTargetCount != targetTransferCount || oldCompletedCount != completedTransferCount
{
listeners.forEach { $0.onConnectionProgressUpdate(transferred: completedTransferCount, of: targetTransferCount, progress: progress) }
}
}
}
// These are the different statuses a connection may have
enum ConnectionStatus
{
// Connection is disconnected when there is no attempt to connect, connecting before any connection results have been made,
// offline when connection establishing fails, unauthorized when the provided credentials are not accepted
// and upToDate when all data has been synced
case disconnected, connecting, upToDate, offline, unauthorized
// The connection is active while it is transferring data
case active
// These two states are only used for one time connections.
// Done implicates a successful transfer while failed means that an error prevented success
case done, failed
// COMPUTED PROPERTIES ----------
// Whether this status represents an error situation of some sort
var isError: Bool
{
switch self
{
case .offline: return true
case .unauthorized: return true
case .failed: return true
default: return false
}
}
// Whether this status is not likely to change without some user action
var isFinal: Bool { return self != .connecting && self != .active }
}
| mit | 1039a266a43ba96f0b85746ad0255e20 | 28.387097 | 169 | 0.710365 | 3.985625 | false | false | false | false |
phatblat/Butler | Tests/ButlerTests/OrganizationFolderSpec.swift | 1 | 2533 | //
// OrganizationFolderSpec.swift
// ButlerTests
//
// Created by Ben Chatelain on 6/9/17.
//
@testable import Butler
import Quick
import Nimble
import Foundation
class OrganizationFolderSpec: QuickSpec {
override func spec() {
describe("matrix project") {
let jsonFile: NSString = "OrganizationFolder.json"
var job: OrganizationFolder! = nil
beforeEach {
let bundle = Bundle(for: type(of: self))
let url = bundle.url(forResource: jsonFile.deletingPathExtension,
withExtension: jsonFile.pathExtension,
subdirectory: "JSON/Job")!
let data = try! Data(contentsOf: url)
let decoder = JSONDecoder()
job = try! decoder.decode(OrganizationFolder.self, from: data)
}
it("has class") {
expect(job._class) == JavaClass.organizationFolder
}
it("has no description") {
expect(job.description).to(beNil())
}
it("has a display name") {
expect(job.displayName) == "GitHub Organization"
}
it("has no display name or null") {
expect(job.displayNameOrNull).to(beNil())
}
it("has a full display name") {
expect(job.fullDisplayName) == "Job Types » GitHub Organization"
}
it("has a full name") {
expect(job.fullName) == "Job Types/GitHub Organization"
}
it("has no health reports") {
expect(job.healthReport).toNot(beNil())
expect(job.healthReport.count) == 0
}
it("has no jobs") {
expect(job.jobs).toNot(beNil())
expect(job.jobs.count) == 0
}
it("has a name") {
expect(job.name) == "GitHub Organization"
}
it("has a primary view") {
expect(job.primaryView).toNot(beNil())
expect(job.primaryView["_class"]) == JavaClass.organizationFolderEmptyView.rawValue
}
it("has a url") {
expect(job.url) == URL(string: "http://jenkins.log-g.co/job/Job%20Types/job/GitHub%20Organization/")
}
it("has some views") {
expect(job.views).toNot(beNil())
expect(job.views.count) == 1
}
}
}
}
| mit | bce58ab453c2375bff221cf05c59152e | 34.661972 | 116 | 0.502765 | 4.715084 | false | false | false | false |
trident10/TDMediaPicker | TDMediaPicker/Classes/View/CustomCell/TDAlbumCell.swift | 1 | 1956 | //
// TDAlbumCell.swift
// ImagePicker
//
// Created by Abhimanu Jindal on 26/06/17.
// Copyright © 2017 Abhimanu Jindal. All rights reserved.
//
import UIKit
import Photos
class TDAlbumCell: UITableViewCell{
// MARK: - Variables
@IBOutlet var albumImageView: UIImageView!
@IBOutlet weak var imageWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var imageHeightConstraint: NSLayoutConstraint!
@IBOutlet var titleLabel: UILabel!
private var requestID: PHImageRequestID?
// MARK: - Initialization
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// fatalError("init(coder:) has not been implemented")
}
// MARK: - Config
func configure(_ album: TDAlbumViewModel, completionHandler: ((_ image: UIImage)->Void)?) {
imageWidthConstraint.constant = album.imageSize.width
imageHeightConstraint.constant = album.imageSize.height
requestID = TDMediaUtil.fetchImage(album.asset, targetSize: albumImageView.frame.size, completionHandler: { (image, error) in
if image != nil{
self.albumImageView.image = image
if TDMediaUtil.isImageResolutionValid(self.albumImageView, image: image!){
completionHandler?(image!)
}
}
})
}
func configure(_ album: TDAlbumViewModel, image: UIImage) {
imageWidthConstraint.constant = album.imageSize.width
imageHeightConstraint.constant = album.imageSize.height
albumImageView.layoutIfNeeded()
albumImageView.image = image
}
func purgeCell(){
if requestID != nil{
TDMediaUtil.cancelImageRequest(requestID: requestID!)
}
}
}
| mit | c9d6405b89952caa1ebbb7b93e8ead8e | 29.546875 | 133 | 0.644501 | 5.091146 | false | false | false | false |
zisko/swift | test/DebugInfo/basic.swift | 1 | 4836 | // A (no longer) basic test for debug info.
// --------------------------------------------------------------------
// Verify that we don't emit any debug info by default.
// RUN: %target-swift-frontend %s -emit-ir -o - \
// RUN: | %FileCheck %s --check-prefix NDEBUG
// NDEBUG-NOT: !dbg
// NDEBUG-NOT: DW_TAG
// --------------------------------------------------------------------
// Verify that we don't emit any debug info with -gnone.
// RUN: %target-swift-frontend %s -emit-ir -gnone -o - \
// RUN: | %FileCheck %s --check-prefix NDEBUG
// --------------------------------------------------------------------
// Verify that we don't emit any type info with -gline-tables-only.
// RUN: %target-swift-frontend %s -emit-ir -gline-tables-only -o - \
// RUN: | %FileCheck %s --check-prefix CHECK-LINETABLES
// CHECK: !dbg
// CHECK-LINETABLES-NOT: DW_TAG_{{.*}}variable
// CHECK-LINETABLES-NOT: DW_TAG_structure_type
// CHECK-LINETABLES-NOT: DW_TAG_basic_type
// --------------------------------------------------------------------
// Now check that we do generate line+scope info with -g.
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
// RUN: %target-swift-frontend %s -emit-ir -g -o - -disable-sil-linking \
// RUN: | %FileCheck %s --check-prefix=CHECK-NOSIL
// --------------------------------------------------------------------
// Currently -gdwarf-types should give the same results as -g.
// RUN: %target-swift-frontend %s -emit-ir -gdwarf-types -o - | %FileCheck %s
// --------------------------------------------------------------------
//
// CHECK: foo
// CHECK-DAG: ret{{.*}}, !dbg ![[RET:[0-9]+]]
// CHECK-DAG: ![[FOO:[0-9]+]] = distinct !DISubprogram(name: "foo",{{.*}} line: [[@LINE+2]],{{.*}} type: ![[FOOTYPE:[0-9]+]]
public
func foo(_ a: Int64, _ b: Int64) -> Int64 {
var a = a
var b = b
// CHECK-DAG: !DILexicalBlock(scope: ![[FOO]],{{.*}} line: [[@LINE-3]], column: 43)
// CHECK-DAG: ![[ASCOPE:.*]] = !DILocation(line: [[@LINE-4]], column: 10, scope: ![[FOO]])
// Check that a is the first and b is the second argument.
// CHECK-DAG: store i64 %0, i64* [[AADDR:.*]], align
// CHECK-DAG: store i64 %1, i64* [[BADDR:.*]], align
// CHECK-DAG: [[AVAL:%.*]] = getelementptr inbounds {{.*}}, [[AMEM:.*]], i32 0, i32 0
// CHECK-DAG: [[BVAL:%.*]] = getelementptr inbounds {{.*}}, [[BMEM:.*]], i32 0, i32 0
// CHECK-DAG: call void @llvm.dbg.declare(metadata i64* [[AADDR]], metadata ![[AARG:.*]], metadata !DIExpression()), !dbg ![[ASCOPE]]
// CHECK-DAG: call void @llvm.dbg.declare(metadata i64* [[BADDR]], metadata ![[BARG:.*]], metadata !DIExpression())
// CHECK-DAG: ![[AARG]] = !DILocalVariable(name: "a", arg: 1
// CHECK-DAG: ![[BARG]] = !DILocalVariable(name: "b", arg: 2
if b != 0 {
// CHECK-DAG: !DILexicalBlock({{.*}} line: [[@LINE-1]]
// Transparent inlined multiply:
// CHECK-DAG: smul{{.*}}, !dbg ![[MUL:[0-9]+]]
// CHECK-DAG: [[MUL]] = !DILocation(line: [[@LINE+4]], column: 16,
// Runtime call to multiply function:
// CHECK-NOSIL: @"$Ss5Int64V1moiyA2B_ABtFZ{{.*}}, !dbg ![[MUL:[0-9]+]]
// CHECK-NOSIL: [[MUL]] = !DILocation(line: [[@LINE+1]], column: 16,
return a*b
} else {
// CHECK-DAG: ![[PARENT:[0-9]+]] = distinct !DILexicalBlock({{.*}} line: [[@LINE-1]], column: 13)
var c: Int64 = 42
// CHECK-DAG: ![[CONDITION:[0-9]+]] = distinct !DILexicalBlock(scope: ![[PARENT]], {{.*}}, line: [[@LINE+1]],
if a == 0 {
// CHECK-DAG: !DILexicalBlock(scope: ![[CONDITION]], {{.*}}, line: [[@LINE-1]], column: 18)
// What about a nested scope?
return 0
}
return c
}
}
// CHECK-DAG: ![[FILE_CWD:[0-9]+]] = !DIFile(filename: "{{.*}}DebugInfo/basic.swift", directory: "{{.*}}")
// CHECK-DAG: ![[MAINFILE:[0-9]+]] = !DIFile(filename: "basic.swift", directory: "{{.*}}DebugInfo")
// CHECK-DAG: !DICompileUnit(language: DW_LANG_Swift, file: ![[FILE_CWD]],{{.*}} producer: "{{.*}}Swift version{{.*}},{{.*}} flags: "{{[^"]*}}-emit-ir
// CHECK-DAG: !DISubprogram(name: "main", {{.*}}file: ![[MAINFILE]],
// Function type for foo.
// CHECK-DAG: ![[FOOTYPE]] = !DISubroutineType(types: ![[PARAMTYPES:[0-9]+]])
// CHECK-DAG: ![[INT64:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Int64", {{.*}}, identifier: "$Ss5Int64VD")
// CHECK-DAG: ![[PARAMTYPES]] = !{![[INT64]], ![[INT64]], ![[INT64]]}
// Import of the main module with the implicit name.
// CHECK-DAG: !DIImportedEntity(tag: DW_TAG_imported_module, scope: ![[MAINFILE]], entity: ![[MAINMODULE:[0-9]+]], file: ![[MAINFILE]])
// CHECK-DAG: ![[MAINMODULE]] = !DIModule({{.*}}, name: "basic"
// DWARF Version
// CHECK-DAG: i32 2, !"Dwarf Version", i32 4}
// Debug Info Version
// CHECK-DAG: i32 2, !"Debug Info Version", i32
| apache-2.0 | c0cbdbcfe2355c87ee4025292ba383bd | 54.586207 | 150 | 0.527295 | 3.388928 | false | false | false | false |
acidstudios/WorldCupSwift | WorldCup/Classes/Model/CountryModel.swift | 1 | 534 | //
// CountryModel.swift
// WorldCup
//
// Created by Acid Studios on 19/06/14.
// Copyright (c) 2014 Acid Studios. All rights reserved.
//
import UIKit
class CountryModel: NSObject {
var country: String? = ""
var alternate_name: String? = ""
var fifa_code: String? = ""
var group_id:Int = 0
var wins: Int? = 0
var draws: Int? = 0
var losses: Int? = 0
var goals_for: Int? = 0
var goals_against: Int? = 0
var knocked_out: Int? = 0
var goals: Int = 0
init() {
}
}
| mit | 3ada9358faa27d4585ed822a45ce2e99 | 18.777778 | 57 | 0.567416 | 3.159763 | false | false | false | false |
marklin2012/iOS_Animation | Section2/Chapter7/O2PackingList_challenge/O2PackingList/ViewController.swift | 1 | 5680 | //
// ViewController.swift
// O2PackingList
//
// Created by O2.LinYi on 16/3/14.
// Copyright © 2016年 jd.com. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var tableView: UITableView!
@IBOutlet var buttonMenu: UIButton!
@IBOutlet var titleLabel: UILabel!
@IBOutlet weak var menuHeightConstraint: NSLayoutConstraint!
var slider: HorizontalItemList!
var isMenuOpen = false
var items: [Int] = [5, 6, 7]
@IBAction func actionToggleMenu(sender: AnyObject) {
isMenuOpen = !isMenuOpen
// animating the label
for constraint in titleLabel.superview!.constraints {
if constraint.firstItem as? NSObject == titleLabel && constraint.firstAttribute == .CenterX {
constraint.constant = isMenuOpen ? -100 : 0
}
if constraint.identifier == "TitleCenterY" {
constraint.active = false
// add new constraint
let newConstraint = NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: titleLabel.superview!, attribute: .CenterY, multiplier: (isMenuOpen ? 0.67 : 1), constant: 5)
newConstraint.identifier = "TitleCenterY"
newConstraint.active = true
continue
}
}
menuHeightConstraint.constant = isMenuOpen ? 200 : 60
titleLabel.text = isMenuOpen ? "Select Item" : "Packing List"
// animate TitleView
UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 10, options: [.CurveEaseIn], animations: { () -> Void in
self.view.layoutIfNeeded()
// rotate + button
let angle = self.isMenuOpen ? CGFloat(M_PI_4) : 0
self.buttonMenu.transform = CGAffineTransformMakeRotation(angle)
}, completion: nil)
for con in titleLabel.superview!.constraints {
print("-> \(con.description)\n")
}
// add change constraint
if isMenuOpen {
slider = HorizontalItemList(inView: view)
slider.didSelectItem = { index in
print("add \(index)")
self.items.append(index)
self.tableView.reloadData()
self.actionToggleMenu(self)
}
self.titleLabel.superview!.addSubview(slider)
} else {
slider.removeFromSuperview()
}
}
func showItem(index: Int) {
print("tapped item \(index)")
let imageView = UIImageView(image: UIImage(named: "summericons_100px_0\(index).png"))
imageView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
imageView.layer.cornerRadius = 5
imageView.layer.masksToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(imageView)
// create theconstraints for the image view
let conX = imageView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor)
let conBottom = imageView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor, constant: imageView.frame.height)
let conWidth = imageView.widthAnchor.constraintEqualToAnchor(view.widthAnchor, multiplier: 0.33, constant: -50)
let conHeight = imageView.heightAnchor.constraintEqualToAnchor(imageView.widthAnchor)
NSLayoutConstraint.activateConstraints([conX, conBottom, conWidth, conHeight])
view.layoutIfNeeded()
UIView.animateWithDuration(0.8, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0, options: [], animations: { () -> Void in
conBottom.constant = -imageView.frame.size.height/2
conWidth.constant = 0
self.view.layoutIfNeeded()
}, completion: nil)
UIView.animateWithDuration(0.8, delay: 1, usingSpringWithDamping: 0.4, initialSpringVelocity: 0, options: [], animations: { () -> Void in
conBottom.constant = imageView.frame.size.height
conWidth.constant = -50
self.view.layoutIfNeeded()
}, completion: { _ in
imageView.removeFromSuperview()
})
}
}
let itemTitles = ["Icecream money", "Great weather", "Beach ball", "Swim suit for him", "Swim suit for her", "Beach games", "Ironing board", "Cocktail mood", "Sunglasses", "Flip flops"]
extension ViewController: UITableViewDelegate, UITableViewDataSource {
// MARK: - ViewController methods
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = 54
}
// MARK: - Table DataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
cell.accessoryType = .None
cell.textLabel?.text = itemTitles[items[indexPath.row]]
cell.imageView?.image = UIImage(named: "summericons_100px_0\(items[indexPath.row]).png")
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
showItem(items[indexPath.row])
}
}
| mit | 821d89c36c86a40061a24230c1f896ff | 36.846667 | 214 | 0.613176 | 5.175023 | false | false | false | false |
hyperoslo/Orchestra | Source/Extensions/UITabBar+Orchestra.swift | 1 | 591 | import UIKit
import Sugar
extension UITabBar {
// MARK: - Method Swizzling
public override class func initialize() {
struct Static {
static var token: dispatch_once_t = 0
}
if self !== UITabBar.self { return }
dispatch_once(&Static.token) {
Swizzler.swizzle("setSelectedItem:", cls: self, prefix: "orchestra")
}
}
func orchestra_setSelectedItem(tabBarItem: UITabBarItem?) {
let selected = tabBarItem == selectedItem
orchestra_setSelectedItem(tabBarItem)
if selected {
Kapellmeister.engine.autoPlay(Sound.TabBar)
}
}
}
| mit | 76bd55ab24c0ca12d2c29476ad987ae6 | 18.7 | 74 | 0.668359 | 4.191489 | false | false | false | false |
jkereako/MassStateKeno | Sources/Coordinators/LocationsCoordinator.swift | 1 | 914 | //
// LocationsCoordinator.swift
// MassLotteryKeno
//
// Created by Jeff Kereakoglow on 5/24/19.
// Copyright © 2019 Alexis Digital. All rights reserved.
//
import Kringle
import UIKit
final class LocationsCoordinator: RootCoordinator {
var rootViewController: UIViewController {
let viewController = UIViewController()
viewController.title = "Locations"
viewController.view.backgroundColor = .orange
navigationController = UINavigationController(
rootViewController: viewController
)
return navigationController!
}
private let networkClient: NetworkClient
private let dateFormatter: DateFormatter
private var navigationController: UINavigationController?
init(networkClient: NetworkClient, dateFormatter: DateFormatter) {
self.networkClient = networkClient
self.dateFormatter = dateFormatter
}
}
| mit | da89a4facf001d757cb8208270229da8 | 25.852941 | 70 | 0.722892 | 5.670807 | false | false | false | false |
magistral-io/MagistralSwift | MagistralSwift/RestApiManager.swift | 1 | 6148 | //
// RestApiManager.swift
// ios
//
// Created by rizarse on 01/08/16.
// Copyright © 2016 magistral.io. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
typealias ServiceResponse = (JSON, NSError?) -> Void
typealias ServiceResponseText = (String, NSError?) -> Void
public struct MagistralEncoding : ParameterEncoding {
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
let res = try URLEncoding.queryString.encode(urlRequest, with: parameters).url?.absoluteString.replacingOccurrences(of: "%5B%5D=", with: "=");
return URLRequest(url: URL(string: res!)!);
}
}
public class RestApiManager {
var manager = Alamofire.SessionManager.default
var cookies = HTTPCookieStorage()
init() {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
configuration.httpCookieStorage = cookies
manager = Alamofire.SessionManager(configuration: configuration)
manager.session.configuration.timeoutIntervalForRequest = 180
}
enum ResponseType {
case json
case text
}
// let queue = DispatchQueue(label: "io.magistral.response-queue", qos: .utility, attributes: [.concurrent])
func makeHTTPGetRequest(path: String, parameters : Parameters, user : String, password : String, onCompletion: @escaping ServiceResponse) {
let credential = URLCredential(user: user, password: password, persistence: .forSession)
// debugPrint(
manager.request(path, method: .get, parameters: parameters, encoding: MagistralEncoding.init())
.authenticate(usingCredential: credential)
.validate(statusCode: 200..<300).validate()
.responseJSON { response in
switch response.result {
case .success:
let json = JSON(response.data!);
onCompletion(json , nil)
case .failure(let error):
onCompletion(JSON.null, error as NSError?)
}
}
// )
}
func makeHTTPGetRequestText(_ path: String, parameters : Parameters, user : String, password : String, onCompletion: @escaping ServiceResponseText) {
let credential = URLCredential(user: user, password: password, persistence: .forSession)
manager
.request(path, method: .get, parameters: parameters)
.authenticate(usingCredential: credential)
.validate(statusCode: 200..<300)
.validate()
.responseString { response in
switch response.result {
case .success:
onCompletion(response.result.value! , nil)
case .failure(let error):
onCompletion("", error as NSError?)
}
}
}
func makeHTTPPutRequest(_ path: String, parameters : Parameters, user : String, password : String, onCompletion: @escaping ServiceResponse) {
manager
.request(path, method: .put, parameters: parameters, encoding: URLEncoding.default)
.authenticate(user: user, password: password)
.validate(statusCode: 200..<300)
.responseString { response in
switch response.result {
case .success:
do {
let json: JSON = try JSON(data: response.data!);
onCompletion(json , nil)
} catch {
onCompletion("", MagistralException.conversionError as NSError?)
}
case .failure(let error):
onCompletion("", error as NSError?)
}
}
}
func makeHTTPDeleteRequestText(_ path: String, parameters : Parameters, user : String, password : String, onCompletion: @escaping ServiceResponseText) {
manager
.request(path, method: .delete, parameters: parameters, encoding: URLEncoding.default)
.authenticate(user: user, password: password)
.validate(statusCode: 200..<300)
.responseString { response in
switch response.result {
case .success:
onCompletion(response.result.value! , nil)
case .failure(let error):
onCompletion("", error as NSError?)
}
}
}
func makeHTTPPutRequestText(_ path: String, parameters : Parameters, user : String, password : String, onCompletion: @escaping ServiceResponseText) {
manager
.request(path, method: .put, parameters: parameters, encoding: URLEncoding.default)
.authenticate(user: user, password: password)
.validate(statusCode: 200..<300)
.responseString { response in
switch response.result {
case .success:
onCompletion(response.result.value! , nil)
case .failure(let error):
onCompletion("", error as NSError?)
}
}
}
// MARK: Perform a POST Request
func makeHTTPPostRequest(_ path: String, body: Parameters, onCompletion: @escaping ServiceResponse) {
manager.request(path, method: .post, parameters: body, encoding: JSONEncoding.default)
.responseString { response in
switch response.result {
case .success:
do {
let json: JSON = try JSON(data: response.data!);
onCompletion(json , nil)
} catch {
onCompletion("", MagistralException.conversionError as NSError?)
}
case .failure(let error):
onCompletion("", error as NSError?)
}
}
}
}
| mit | 3ed7e4b0fe5961257029de7fef00b6ae | 39.440789 | 156 | 0.571986 | 5.449468 | false | false | false | false |
wesj/firefox-ios-1 | Client/Frontend/Widgets/SiteTableViewController.swift | 1 | 4429 | /* 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
import Storage
struct SiteTableViewControllerUX {
static let HeaderHeight = CGFloat(25)
static let RowHeight = CGFloat(58)
static let HeaderBorderColor = UIColor(rgb: 0x979797).colorWithAlphaComponent(0.5)
static let HeaderTextColor = UIColor(rgb: 0x565656)
static let HeaderBackgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.4)
}
private class SiteTableViewHeader : UITableViewHeaderFooterView {
// I can't get drawRect to play nicely with the glass background. As a fallback
// we just use views for the top and bottom borders.
let topBorder = UIView()
let bottomBorder = UIView()
override init() {
super.init()
}
override init(frame: CGRect) {
super.init(frame: frame)
didLoad()
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
}
private func didLoad() {
addSubview(topBorder)
addSubview(bottomBorder)
backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .Light))
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
topBorder.frame = CGRect(x: 0, y: -0.5, width: frame.width, height: 0.5)
bottomBorder.frame = CGRect(x: 0, y: frame.height, width: frame.width, height: 0.5)
topBorder.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor
bottomBorder.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor
super.layoutSubviews()
textLabel.font = UIFont(name: "HelveticaNeue-Medium", size: 11)
textLabel.textColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.blackColor() : SiteTableViewControllerUX.HeaderTextColor
textLabel.textAlignment = .Center
contentView.backgroundColor = SiteTableViewControllerUX.HeaderBackgroundColor
}
}
/**
* Provides base shared functionality for site rows and headers.
*/
class SiteTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
private let CellIdentifier = "CellIdentifier"
private let HeaderIdentifier = "HeaderIdentifier"
var profile: Profile! {
didSet {
reloadData()
}
}
var data: Cursor = Cursor(status: .Success, msg: "No data set")
var tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.snp_makeConstraints { make in
make.edges.equalTo(self.view)
return
}
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(TwoLineTableViewCell.self, forCellReuseIdentifier: CellIdentifier)
tableView.registerClass(SiteTableViewHeader.self, forHeaderFooterViewReuseIdentifier: HeaderIdentifier)
tableView.layoutMargins = UIEdgeInsetsZero
tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
}
func reloadData() {
if data.status != .Success {
println("Err: \(data.statusMessage)")
} else {
self.tableView.reloadData()
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier(CellIdentifier) as UITableViewCell
// Callers should override this to fill in the cell returned here
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return tableView.dequeueReusableHeaderFooterViewWithIdentifier(HeaderIdentifier) as? UIView
// Callers should override this to fill in the cell returned here
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return SiteTableViewControllerUX.HeaderHeight
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return SiteTableViewControllerUX.RowHeight
}
}
| mpl-2.0 | 8b9b46a0c039b65531deda87175bcbef | 36.533898 | 139 | 0.7049 | 5.349034 | false | false | false | false |
elpassion/el-space-ios | ELSpaceTests/TestDoubles/Spies/ActivityControllerSpy.swift | 1 | 1206 | @testable import ELSpace
import RxSwift
class ActivitiesControllerSpy: ActivitiesControlling {
private(set) var didCallFetchData = false
private(set) var dateCaptured: Date?
let isLoadingSubject = PublishSubject<Bool>()
let reportsSubject = PublishSubject<[ReportDTO]>()
let projectsSubject = PublishSubject<[ProjectDTO]>()
let holidaysSubject = PublishSubject<[Int]>()
let didFinishFetchSubject = PublishSubject<Void>()
let errorSubject = PublishSubject<Error>()
// MARK: - ActivityControlling
var reports: Observable<[ReportDTO]> {
return reportsSubject.asObservable()
}
var projects: Observable<[ProjectDTO]> {
return projectsSubject.asObservable()
}
var isLoading: Observable<Bool> {
return isLoadingSubject.asObservable()
}
var didFinishFetch: Observable<Void> {
return didFinishFetchSubject.asObservable()
}
var holidays: Observable<[Int]> {
return holidaysSubject.asObservable()
}
var error: Observable<Error> {
return errorSubject.asObservable()
}
func fetchData(for date: Date) {
didCallFetchData = true
dateCaptured = date
}
}
| gpl-3.0 | f17ee65bd7ecbfea418837e32070583f | 24.125 | 56 | 0.68325 | 4.983471 | false | false | false | false |
yrchen/edx-app-ios | Source/CourseDataManager.swift | 1 | 3089 | //
// CourseDataManager.swift
// edX
//
// Created by Akiva Leffert on 5/6/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
private let CourseOutlineModeChangedNotification = "CourseOutlineModeChangedNotification"
private let CurrentCourseOutlineModeKey = "OEXCurrentCourseOutlineMode"
private let DefaultCourseMode = CourseOutlineMode.Full
public class CourseDataManager: NSObject, CourseOutlineModeControllerDataSource {
private let analytics : OEXAnalytics?
private let interface : OEXInterface?
private let session : OEXSession?
private let networkManager : NetworkManager?
private let outlineQueriers = LiveObjectCache<CourseOutlineQuerier>()
private let discussionDataManagers = LiveObjectCache<DiscussionDataManager>()
public init(analytics: OEXAnalytics?, interface : OEXInterface?, networkManager : NetworkManager?, session : OEXSession?) {
self.analytics = analytics
self.interface = interface
self.networkManager = networkManager
self.session = session
super.init()
NSNotificationCenter.defaultCenter().oex_addObserver(self, name: OEXSessionEndedNotification) { (_, observer, _) -> Void in
observer.outlineQueriers.empty()
observer.discussionDataManagers.empty()
NSUserDefaults.standardUserDefaults().setObject(DefaultCourseMode.rawValue, forKey: CurrentCourseOutlineModeKey)
}
}
public func querierForCourseWithID(courseID : String) -> CourseOutlineQuerier {
return outlineQueriers.objectForKey(courseID) {
let querier = CourseOutlineQuerier(courseID: courseID, interface : self.interface, networkManager : self.networkManager, session : self.session)
return querier
}
}
public func discussionManagerForCourseWithID(courseID : String) -> DiscussionDataManager {
return discussionDataManagers.objectForKey(courseID) {
let manager = DiscussionDataManager(courseID: courseID, networkManager: self.networkManager)
return manager
}
}
public static var currentOutlineMode : CourseOutlineMode {
return CourseOutlineMode(rawValue: NSUserDefaults.standardUserDefaults().stringForKey(CurrentCourseOutlineModeKey) ?? "") ?? DefaultCourseMode
}
public var currentOutlineMode : CourseOutlineMode {
get {
return CourseDataManager.currentOutlineMode
}
set {
NSUserDefaults.standardUserDefaults().setObject(newValue.rawValue, forKey: CurrentCourseOutlineModeKey)
NSNotificationCenter.defaultCenter().postNotificationName(CourseOutlineModeChangedNotification, object: nil)
analytics?.trackOutlineModeChanged(currentOutlineMode)
}
}
func freshOutlineModeController() -> CourseOutlineModeController {
return CourseOutlineModeController(dataSource : self)
}
public var modeChangedNotificationName : String {
return CourseOutlineModeChangedNotification
}
}
| apache-2.0 | 80d17fee0c976dcbc4ccc6e63491e7dc | 39.644737 | 156 | 0.719974 | 5.828302 | false | false | false | false |
nakau1/NeroBlu | NeroBlu/NB+Collection.swift | 1 | 6359 | // =============================================================================
// NerobluCore
// Copyright (C) NeroBlu. All rights reserved.
// =============================================================================
import UIKit
// MARK: - Array拡張 -
extension Array {
/// 最初の要素のインデックス
public var firstIndex: Int? {
return self.indices.first
}
/// 最後の要素のインデックス
public var lastIndex: Int? {
return self.indices.last
}
/// 配列内からランダムに要素を取り出す
///
/// 要素が空の場合はnilを返す
public var random: Element? {
guard let min = self.firstIndex, let max = self.lastIndex else { return nil }
let index = Int.random(min: min, max: max)
return self[index]
}
/// 新しい要素を足した配列を返す
/// - note: 元の配列自身の要素は変わりません。その用途の場合は appendメソッドを使います
/// - parameter e: 要素
/// - returns: 要素を足した配列(元の配列自身は変わりません)
public func add(_ e: Element) -> Array<Element> {
return self + [e]
}
/// 新しい要素を足した配列を返す
/// - note: 元の配列自身の要素は変わりません。その用途の場合は appendメソッドを使います
/// - parameter e: 要素
/// - returns: 要素を足した配列(元の配列自身は変わりません)
public func add(_ e: [Element]) -> Array<Element> {
return self + e
}
/// 配列の範囲内かどうかを返す
/// - parameter index: インデックス
/// - returns: 配列の範囲内かどうか
public func inRange(at index: Int) -> Bool {
guard
let first = self.firstIndex,
let last = self.lastIndex
else {
return false
}
return first <= index && index <= last
}
/// 配列範囲内に収まるインデックスを返す
/// - note: 配列に要素がない場合は-1を返す
/// - parameter index: インデックス
/// - returns: 引数が0未満であれば最初のインデックス、最大インデックス以上であれば最後のインデックスを返す
public func indexInRange(for index: Int) -> Int {
guard
let first = self.firstIndex,
let last = self.lastIndex
else {
return -1
}
if index < first {
return first
} else if last < index {
return last
} else {
return index
}
}
/// 配列範囲内に収まる要素を返す
/// - note: 配列に要素がない場合はnilを返す
/// - parameter index: インデックス
/// - returns: 引数が0未満であれば最初の要素、最大インデックス以上であれば最後の要素を返す
public func elementInRange(for index: Int) -> Element? {
let i = self.indexInRange(for: index)
if i < 0 {
return nil
}
return self[i]
}
/// ループさせる場合の次の配列のインデックスを取得する
/// - note: 配列に要素がない場合は-1を返す
/// - parameter index: インデックス
/// - returns: 次のインデックス
public func nextLoopIndex(of index: Int) -> Int {
guard let last = self.lastIndex else { return -1 }
if index + 1 > last {
return 0
} else {
return index + 1
}
}
/// ループさせる場合の前の配列のインデックスを取得する
/// - note: 配列に要素がない場合は-1を返す
/// - parameter index: インデックス
/// - returns: 前のインデックス
public func previousLoopIndex(of index: Int) -> Int {
guard let last = self.lastIndex else { return -1 }
if index - 1 < 0 {
return last
} else {
return index - 1
}
}
/// 指定したインデックスの要素同士の入れ替え(移動)が可能かどうかを返す
/// - parameter from: 移動する元のインデックス
/// - parameter to: 移動する先のインデックス
/// - returns: 要素が入れ替え(移動)可能かどうか
public func isExchangable(from: Int, to: Int) -> Bool {
return self.indices.contains(from) && self.indices.contains(to)
}
/// 指定したインデックスの要素同士を入れ替える
/// - parameter from: 移動する元のインデックス
/// - parameter to: 移動する先のインデックス
/// - returns: 要素が入れ替え(移動)ができたかどうか
public mutating func exchange(from: Int, to: Int) -> Bool {
if from == to {
return false
} else if !self.isExchangable(from: from, to: to) {
return false
}
swap(&self[from], &self[to])
return true
}
}
// MARK: - Dictionary拡張 -
public extension Dictionary {
/// 渡された辞書を自身にマージする(自身を書き換えます)
/// - parameter dictionary: マージする辞書
public mutating func merge(dictionary dic: Dictionary) {
dic.forEach { self.updateValue($1, forKey: $0) }
}
/// 渡された辞書を自身にマージした新しい辞書を取得する(自身は書き換わりません)
/// - parameter dictionary: マージする辞書
/// - returns: 新しい辞書オブジェクト
public func merged(dictionary dic: Dictionary) -> Dictionary {
var ret = self
dic.forEach { ret.updateValue($1, forKey: $0) }
return ret
}
}
// MARK: - flatMap拡張 -
public protocol NBSequenceOptionalType {
associatedtype T
var optionalValue: T? { get }
}
extension Optional: NBSequenceOptionalType {
public var optionalValue: Wrapped? { return self }
}
public extension Sequence where Iterator.Element: NBSequenceOptionalType {
/// nilを取り除いた非オプショナルなコレクション
public var flatten: [Iterator.Element.T] {
return self.flatMap { $0.optionalValue }
}
}
| mit | c50792b1a53c594c6d878debedea6d84 | 26.711864 | 85 | 0.552905 | 3.486141 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/Authentication/PhoneAuthentication/AuthPhoneNumberController.swift | 1 | 1360 | //
// AuthPhoneNumberController.swift
// Pigeon-project
//
// Created by Roman Mizin on 3/30/18.
// Copyright © 2018 Roman Mizin. All rights reserved.
//
import UIKit
import ARSLineProgress
final class AuthPhoneNumberController: PhoneNumberController, VerificationDelegate {
final func verificationFinished(with success: Bool, error: String?) {
ARSLineProgress.hide()
guard success, error == nil else {
basicErrorAlertWith(title: "Error", message: error ?? "", controller: self)
return
}
let destination = AuthVerificationController()
destination.enterVerificationContainerView.titleNumber.text = phoneNumberContainerView.countryCode.text! + phoneNumberContainerView.phoneNumber.text!
navigationController?.pushViewController(destination, animated: true)
}
override func configurePhoneNumberContainerView() {
super.configurePhoneNumberContainerView()
phoneNumberContainerView.termsAndPrivacy.isHidden = false
phoneNumberContainerView.instructions.text = "Please confirm your country code\nand enter your phone number."
let attributes = [NSAttributedString.Key.foregroundColor: ThemeManager.currentTheme().generalSubtitleColor]
phoneNumberContainerView.phoneNumber.attributedPlaceholder = NSAttributedString(string: "Phone number", attributes: attributes)
verificationDelegate = self
}
}
| gpl-3.0 | 81bf5587dd16149271fe1a78546b224d | 40.181818 | 153 | 0.7844 | 5.070896 | false | true | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/00161-swift-tupletype-get.swift | 11 | 1098 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
import Foundation
class ed<a>: NSObject {
var o: a
y(o: a) {
r.o = o
b.y()
}
}
protocol dc {
typealias t
func v(t)
}
struct v<l> : dc {
func v(v: v.u) {
}
}
func ^(x: j, s) -> s {
typealias w
typealias m = w
typealias v = w
}
class v<o : k, cb : k n o.dc == cb> : x {
}
class v<o, cb> {
}
protocol k {
typealias dc
}
class x {
typealias v = v
}
enum m<a> {
w cb(a, () -> ())
}
protocol v {
class func m()
}
struct k {
var w: v.u
func m() {
w.m()
}
}
protocol dc {
}
struct t : dc {
}
struct cb<k, p: dc n k.cb == p> {
}
struct w<v : m, dc: m n dc.o == v.o> {
}
protocol m {
q v {
w k
}
}
class dc<a : dc
| apache-2.0 | 7c33c0d94cebd65eeaea0109394d2196 | 15.892308 | 78 | 0.559199 | 2.822622 | false | false | false | false |
natecook1000/swift | test/IRGen/same_type_constraints.swift | 3 | 3295 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -primary-file %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
// RUN: %target-swift-frontend -Osize -assume-parsing-unqualified-ownership-sil -emit-ir -primary-file %s -disable-objc-attr-requires-foundation-module | %FileCheck %s --check-prefix=OSIZE
// Ensure that same-type constraints between generic arguments get reflected
// correctly in the type context descriptor.
// CHECK-LABEL: @"$S21same_type_constraints4SG11VA2A2P2Rzq_RszrlE13InnerTEqualsUVMn" =
// T U(==T) V padding
// CHECK-SAME: , i8 -128, i8 0, i8 -128, i8 0,
// <rdar://problem/21665983> IRGen crash with protocol extension involving same-type constraint to X<T>
public struct DefaultFoo<T> {
var t: T?
}
public protocol P {
associatedtype Foo
}
public extension P where Foo == DefaultFoo<Self> {
public func foo() -> DefaultFoo<Self> {
return DefaultFoo()
}
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$S21same_type_constraints1PPA2A10DefaultFooVyxG0E0RtzrlE3fooAFyF"
// <rdar://26873036> IRGen crash with derived class declaring same-type constraint on constrained associatedtype.
public class C1<T: Equatable> { }
public class C2<T: Equatable, U: P>: C1<T> where T == U.Foo {}
// CHECK: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$S21same_type_constraints2C1CfD"
public protocol MyHashable {}
public protocol DataType : MyHashable {}
public protocol E {
associatedtype Data: DataType
}
struct Dict<V : MyHashable, K> {}
struct Val {}
public class GenericKlazz<T: DataType, R: E> : E where R.Data == T
{
public typealias Data = T
var d: Dict<T, Val>
init() {
d = Dict()
}
}
// This used to hit an infinite loop - <rdar://problem/27018457>
public protocol CodingType {
associatedtype ValueType
}
public protocol ValueCoding {
associatedtype Coder: CodingType
}
func foo<Self>(s: Self)
where Self : CodingType,
Self.ValueType: ValueCoding,
Self.ValueType.Coder == Self {
print(Self.ValueType.self)
}
// OSIZE: define internal swiftcc i8** @"$S21same_type_constraints12GenericKlazzCyxq_GAA1EAA4Data_AA0F4TypePWT"(%swift.type* %"GenericKlazz<T, R>.Data", %swift.type* nocapture readonly %"GenericKlazz<T, R>", i8** nocapture readnone %"GenericKlazz<T, R>.E") [[ATTRS:#[0-9]+]] {
// OSIZE: [[ATTRS]] = {{{.*}}noinline
// Check that same-typing two generic parameters together lowers correctly.
protocol P1 {}
protocol P2 {}
protocol P3 {}
struct ConformsToP1: P1 {}
struct ConformsToP2: P2 {}
struct ConformsToP3: P3 {}
struct SG11<T: P1, U: P2> {}
struct ConformsToP1AndP2 : P1, P2 { }
extension SG11 where U == T {
struct InnerTEqualsU<V: P3> { }
}
extension SG11 where T == ConformsToP1 {
struct InnerTEqualsConformsToP1<V: P3> { }
}
extension SG11 where U == ConformsToP2 {
struct InnerUEqualsConformsToP2<V: P3> { }
}
func inner1() -> Any.Type {
return SG11<ConformsToP1AndP2, ConformsToP1AndP2>.InnerTEqualsU<ConformsToP3>.self
}
func inner2() -> Any.Type {
return SG11<ConformsToP1, ConformsToP2>.InnerTEqualsConformsToP1<ConformsToP3>.self
}
func inner3() -> Any.Type {
return SG11<ConformsToP1, ConformsToP2>.InnerTEqualsConformsToP1<ConformsToP3>.self
}
| apache-2.0 | 468d47a0c3a8517f87e5f9c35449f64e | 29.509259 | 276 | 0.711988 | 3.272095 | false | false | false | false |
kz56cd/ios_sandbox_animate | IosSandboxAnimate/CustomParts/CustomButton.swift | 1 | 3590 | //
// CustomButton.swift
// e-park
//
// Created by Yoshikuni Kato on 2015/09/15.
// Copyright © 2015年 Ohako Inc. All rights reserved.
//
import UIKit
@IBDesignable class CustomButton: UIButton {
@IBInspectable var cornerRadius: CGFloat = 0.0 {
didSet {
layer.cornerRadius = cornerRadius
layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).CGPath
}
}
@IBInspectable var shadowRadius: CGFloat = 0.0 {
didSet {
layer.shadowRadius = shadowRadius
}
}
@IBInspectable var shadowColor: UIColor? = nil {
didSet {
layer.shadowColor = shadowColor?.CGColor
}
}
@IBInspectable var shadowOffset: CGSize = CGSizeZero {
didSet {
layer.shadowOffset = shadowOffset
}
}
@IBInspectable var shadowOpacity: Float = 0.0 {
didSet {
layer.shadowOpacity = shadowOpacity
if shadowOpacity > 0.0 {
layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).CGPath
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.mainScreen().scale
}
}
}
@IBInspectable var borderColor: UIColor? = nil {
didSet {
layer.borderColor = borderColor?.CGColor
}
}
@IBInspectable var borderWidth: CGFloat = 0.0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var bounceTouch: Bool = false
@IBInspectable var parentBounceTouch: Bool = false
@IBInspectable var bounceScale: CGFloat = 0.96
@IBInspectable var movingTouch: Bool = false
@IBInspectable var adjustParent: Bool = false
@IBInspectable var movingPoint: CGPoint = CGPointMake(0, 2)
var normalBackgroundColor: UIColor? = nil
@IBInspectable var highlightedBackgroundColor: UIColor? = nil {
didSet {
normalBackgroundColor = backgroundColor
}
}
override var highlighted: Bool {
didSet {
movingTouchAnimation(highlighted)
backgroundColorAnimation(highlighted)
}
}
private func movingTouchAnimation(highlighted: Bool) {
let position = highlighted ? movingPoint : CGPointZero
if movingTouch {
let target: UIView = adjustParent ? superview! : self
UIView.animateWithDuration(
0.1,
delay: 0.0,
options: .CurveLinear,
animations: { () -> Void in
target.transform = CGAffineTransformMakeTranslation(position.x, position.y)
},
completion: nil
)
}
}
private func backgroundColorAnimation(highlighted: Bool) {
guard let _ = highlightedBackgroundColor else {
return
}
let color = highlighted ? highlightedBackgroundColor : normalBackgroundColor
UIView.animateWithDuration(
0.1,
delay: 0.0,
options: .CurveLinear,
animations: { () -> Void in
self.backgroundColor = color
},
completion: nil
)
}
override var bounds: CGRect {
didSet {
layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).CGPath
}
}
}
| mit | a8815d6f08403352f07a98665633a0d5 | 26.381679 | 103 | 0.561193 | 5.631083 | false | false | false | false |
ello/ello-ios | Specs/Controllers/Stream/Calculators/NotificationCellSizeCalculatorSpec.swift | 1 | 5618 | ////
/// NotificationCellSizeCalculatorSpec.swift
//
@testable import Ello
import Quick
import Nimble
class NotificationCellSizeCalculatorSpec: QuickSpec {
override func spec() {
describe("NotificationCellSizeCalculator") {
var user: User!
var text: TextRegion!
var image: ImageRegion!
var postWithText: Post!
var postWithImage: Post!
var postWithTextAndImage: Post!
var commentWithText: ElloComment!
beforeEach {
user = User.stub([:])
text = TextRegion.stub(["content": "Lorem ipsum dolor sit amet."])
image = ImageRegion.stub([
"asset": Asset.stub([
"attachment": Attachment.stub(["width": 2000, "height": 2000])
])
])
postWithText = Post.stub(["summary": [text], "content": [text], "author": user])
postWithImage = Post.stub(["summary": [image], "content": [image], "author": user])
postWithTextAndImage = Post.stub([
"summary": [text, image], "content": [text, image], "author": user
])
commentWithText = ElloComment.stub([
"parentPost": postWithText,
"content": text,
"author": user,
])
}
it("should return minimum size") {
let activity: Activity = stub(["kind": "new_follower_post", "subject": user])
let notification: Ello.Notification = stub(["activity": activity])
let item = StreamCellItem(jsonable: notification, type: .notification)
let calculator = NotificationCellSizeCalculator(
item: item,
width: 320,
columnCount: 1
)
calculator.webView = MockUIWebView()
calculator.begin {}
expect(item.calculatedCellHeights.webContent).to(beNil())
expect(item.calculatedCellHeights.oneColumn) == 69
expect(item.calculatedCellHeights.multiColumn) == 69
}
it("should return size that accounts for a message") {
let activity: Activity = stub([
"kind": "repost_notification", "subject": postWithText
])
let notification: Ello.Notification = stub(["activity": activity])
let item = StreamCellItem(jsonable: notification, type: .notification)
let calculator = NotificationCellSizeCalculator(
item: item,
width: 320,
columnCount: 1
)
calculator.webView = MockUIWebView()
calculator.begin {}
expect(item.calculatedCellHeights.oneColumn) == 119
expect(item.calculatedCellHeights.multiColumn) == 119
}
it("should return size that accounts for an image") {
let activity: Activity = stub([
"kind": "repost_notification", "subject": postWithImage
])
let notification: Ello.Notification = stub(["activity": activity])
let item = StreamCellItem(jsonable: notification, type: .notification)
let calculator = NotificationCellSizeCalculator(
item: item,
width: 320,
columnCount: 1
)
calculator.webView = MockUIWebView()
calculator.begin {}
expect(item.calculatedCellHeights.oneColumn) == 136
expect(item.calculatedCellHeights.multiColumn) == 136
}
it("should return size that accounts for an image with text") {
let activity: Activity = stub([
"kind": "repost_notification", "subject": postWithTextAndImage
])
let notification: Ello.Notification = stub(["activity": activity])
let item = StreamCellItem(jsonable: notification, type: .notification)
let calculator = NotificationCellSizeCalculator(
item: item,
width: 320,
columnCount: 1
)
calculator.webView = MockUIWebView()
calculator.begin {}
expect(item.calculatedCellHeights.webContent) == 50
expect(item.calculatedCellHeights.oneColumn) == 136
expect(item.calculatedCellHeights.multiColumn) == 136
}
it("should return size that accounts for a reply button") {
let activity: Activity = stub([
"kind": "comment_notification", "subject": commentWithText
])
let notification: Ello.Notification = stub(["activity": activity])
let item = StreamCellItem(jsonable: notification, type: .notification)
let calculator = NotificationCellSizeCalculator(
item: item,
width: 320,
columnCount: 1
)
calculator.webView = MockUIWebView()
calculator.begin {}
expect(item.calculatedCellHeights.webContent) == 50
expect(item.calculatedCellHeights.oneColumn) == 176
expect(item.calculatedCellHeights.multiColumn) == 176
}
}
}
}
| mit | 1447fa482752e7793ad4ed312c1eb1a8 | 44.306452 | 99 | 0.522072 | 5.839917 | false | false | false | false |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/0225-swift-classdecl-recordobjcmember.swift | 12 | 1356 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
import Foundation
class d<c>: NSObject {
var b: c
init(b: c) {
self.b = b
}
}
class a<f : b, g : b where f.d == g> {
}
protocol b {
typealias d
typealias e
}
struct c<h : b> : b {
typealias d = h
typealias e = a<c<h>, d>
}
protocol a {
typealias d
typealias e = d
typealias f = d
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
typealias g
}
protocol b {
class func e()
}
struct c {
var d: b.Type
func e() {
d.e()
}
}
class c {
func b((Any, c))(a: (Any, AnyObject)) {
b(a)
}
}
struct c<d, e: b where d.c == e> {
}
func f<T : BooleanType>(b: T) {
}
f(true as BooleanType)
enum S<T> {
case C(T, () -> ())
}
var f = 1
var e: Int -> Int = {
return $0
}
let d: Int = { c, b in
}(f, e)
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
typealias h
}
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(m: (Any, Any) -> Any) -> Any in
return m(t>(c : b) -> e? {
for (mx : e?) in c {
}
}
struct c<d : SequenceType> {
var b: d
}
func a<d>() -> [c<d>] {
return []
}
| apache-2.0 | 03d77be01ec8da7fc66cae7ce3cd3097 | 15.740741 | 87 | 0.514012 | 2.658824 | false | false | false | false |
Igor-Palaguta/MotoSwift | Sources/motoswift/EntityCommand.swift | 1 | 3292 | import ArgumentParser
import Foundation
import MotoSwiftFramework
import PathKit
protocol EntityFileTraitsDescribing {
static var name: String { get }
static var isRewritable: Bool { get }
static func defaultFileMask(withNamePlaceholder placeholder: String) -> String
}
struct EntityCommand<EntityFileTraits: EntityFileTraitsDescribing>: ParsableCommand {
static var configuration: CommandConfiguration {
return CommandConfiguration(
commandName: EntityFileTraits.name,
abstract: EntityFileTraits.commandAbstract
)
}
private static var classPlaceholder: String {
return "{{class}}"
}
@Option(
name: [.customShort("m"), .customLong("file-mask")],
default: EntityFileTraits.defaultFileMask(withNamePlaceholder: classPlaceholder),
help: #"The file name mask for entity file, e.g: "\(defaultMask)""#
)
var fileMask: String
@Option(name: [.short, .customLong("template")], help: "Path to model template.")
var templatePath: Path
@Option(name: [.short, .customLong("output")], default: ".", help: "The output directory.")
var outputDir: Path
@Argument(help: "CoreData model to parse.")
var modelPath: Path
func run() throws {
guard fileMask.contains(Self.classPlaceholder) else {
throw InvalidFileFormatError(actual: fileMask, placeholder: Self.classPlaceholder)
}
let model = try ModelParser().parseModel(at: modelPath)
let renderer = try Renderer(templatePath: templatePath)
try outputDir.mkpath()
for entity in model.entities {
guard let className = entity.className else {
continue
}
let fileName = fileMask.replacingOccurrences(of: Self.classPlaceholder, with: className)
let entityFilePath = outputDir + fileName
let fileOutput: Output = .file(entityFilePath)
if fileOutput.exists && !EntityFileTraits.isRewritable {
continue
}
let code = try renderer.render(entity, from: model)
try fileOutput.write(code)
}
}
}
struct HumanFile: EntityFileTraitsDescribing {
static let name = "human"
static let isRewritable = false
static func defaultFileMask(withNamePlaceholder placeholder: String) -> String {
return "\(placeholder).swift"
}
}
struct MachineFile: EntityFileTraitsDescribing {
static let name = "machine"
static let isRewritable = true
static func defaultFileMask(withNamePlaceholder placeholder: String) -> String {
return "\(placeholder)+Properties.swift"
}
}
extension EntityFileTraitsDescribing {
static var commandAbstract: String {
var result = "Generates \(name) code for your model. "
if isRewritable {
result += "Overwrites file every time."
} else {
result += "Does not write to file, if file already exists."
}
return result
}
}
struct InvalidFileFormatError: Error, CustomStringConvertible {
let actual: String
let placeholder: String
var description: String {
return "\"\(actual)\" - invalid file name mask format. Should contain \"\(placeholder)\""
}
}
| mit | e74728810edea7e8fa50d7bd7c22afab | 29.201835 | 100 | 0.657351 | 4.841176 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Money/Sources/MoneyKit/CurrencyRepresentation/Money/MoneyOperating.swift | 1 | 13163 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BigInt
import Foundation
import ToolKit
/// A money operating error.
public enum MoneyOperatingError: Error {
/// The currencies of two money do not match.
case mismatchingCurrencies(Currency, Currency)
/// Division with a zero divisior.
case divideByZero
}
public protocol MoneyOperating: MoneyImplementing {}
extension MoneyOperating {
// MARK: - Public Methods
/// Returns the greater of two money.
///
/// - Parameters:
/// - x: A value to compare.
/// - y: Another value to compare.
///
/// - Throws: A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
public static func max(_ x: Self?, _ y: Self?) throws -> Self? {
guard let x = x, let y = y else {
return x ?? y
}
return try x > y ? x : y
}
/// Returns the greater of two money.
///
/// - Parameters:
/// - x: A value to compare.
/// - y: Another value to compare.
///
/// - Throws: A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
public static func max(_ x: Self, _ y: Self) throws -> Self {
try x > y ? x : y
}
/// Returns the lesser of two money.
///
/// - Parameters:
/// - x: A value to compare.
/// - y: Another value to compare.
///
/// - Throws: A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
public static func min(_ x: Self?, _ y: Self?) throws -> Self? {
guard let x = x, let y = y else {
return x ?? y
}
return try x < y ? x : y
}
/// Returns the lesser of two money.
///
/// - Parameters:
/// - x: A value to compare.
/// - y: Another value to compare.
///
/// - Throws: A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
public static func min(_ x: Self, _ y: Self) throws -> Self {
try x < y ? x : y
}
/// Returns a `Boolean` value indicating whether the value of the first argument is greater than that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
///
/// - Throws: A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
public static func > (lhs: Self, rhs: Self) throws -> Bool {
try ensureComparable(lhs, rhs)
return lhs.amount > rhs.amount
}
/// Returns a `Boolean` value indicating whether the value of the first argument is greater than or equal to that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
///
/// - Throws: A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
public static func >= (lhs: Self, rhs: Self) throws -> Bool {
try ensureComparable(lhs, rhs)
return lhs.amount >= rhs.amount
}
/// Returns a `Boolean` value indicating whether the value of the first argument is less than that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
///
/// - Throws: A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
public static func < (lhs: Self, rhs: Self) throws -> Bool {
try ensureComparable(lhs, rhs)
return lhs.amount < rhs.amount
}
/// Returns a `Boolean` value indicating whether the value of the first argument is less than or equal to that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
///
/// - Throws: A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
public static func <= (lhs: Self, rhs: Self) throws -> Bool {
try ensureComparable(lhs, rhs)
return lhs.amount <= rhs.amount
}
/// Calculates the sum of two money.
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
///
/// - Throws: A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
public static func + (lhs: Self, rhs: Self) throws -> Self {
try ensureComparable(lhs, rhs)
return Self(amount: lhs.amount + rhs.amount, currency: lhs.currency)
}
/// Calculates the sum of two money and stores the result in the left-hand side variable.
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
///
/// - Throws: A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
public static func += (lhs: inout Self, rhs: Self) throws {
lhs = try lhs + rhs
}
/// Calculates the difference of two money.
///
/// - Parameters:
/// - lhs: The value to subtract.
/// - rhs: The value to subtract from `lhs`.
///
/// - Throws: A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
public static func - (lhs: Self, rhs: Self) throws -> Self {
try ensureComparable(lhs, rhs)
return Self(amount: lhs.amount - rhs.amount, currency: lhs.currency)
}
/// Calculates the difference of two money, and stores the result in the left-hand-side variable.
///
/// - Parameters:
/// - lhs: The value to subtract.
/// - rhs: The value to subtract from `lhs`.
///
/// - Throws: A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
public static func -= (lhs: inout Self, rhs: Self) throws {
lhs = try lhs - rhs
}
/// Calculates the product of two money.
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
///
/// - Throws: A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
public static func * (lhs: Self, rhs: Self) throws -> Self {
try ensureComparable(lhs, rhs)
let amount = (lhs.amount * rhs.amount) / BigInt(10).power(lhs.precision)
return Self(amount: amount, currency: lhs.currency)
}
/// Calculates the product of two money, and stores the result in the left-hand-side variable.
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
///
/// - Throws: A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
public static func *= (lhs: inout Self, rhs: Self) throws {
lhs = try lhs * rhs
}
/// Returns the quotient of dividing two money.
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by.
///
/// - Throws:
/// A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
/// A `MoneyOperatingError.divideByZero` if the `rhs` amount is zero.
public static func / (lhs: Self, rhs: Self) throws -> Self {
try ensureComparable(lhs, rhs)
guard !rhs.isZero else {
throw MoneyOperatingError.divideByZero
}
let amount = (lhs.amount * BigInt(10).power(rhs.precision)) / rhs.amount
return Self(amount: amount, currency: lhs.currency)
}
/// Returns the quotient of dividing two money, and stores the result in the left-hand-side variable.
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by.
///
/// - Throws:
/// A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
/// A `MoneyOperatingError.divideByZero` if the `rhs` amount is zero.
public static func /= (lhs: inout Self, rhs: Self) throws {
lhs = try lhs / rhs
}
/// Converts the current money with currency `A` into another money with currency `B`, using a given exchange rate from `A` to `B`.
///
/// - Parameter exchangeRate: An exchange rate, representing one major unit of currency `A` in currency `B`.
public func convert<T: MoneyOperating>(using exchangeRate: T) -> T {
guard currencyType != exchangeRate.currencyType else {
// Converting to the same currency.
return T(amount: amount, currency: exchangeRate.currency)
}
guard !isZero, !exchangeRate.isZero else {
return .zero(currency: exchangeRate.currency)
}
let conversionAmount = (amount * exchangeRate.amount) / BigInt(10).power(precision)
return T(amount: conversionAmount, currency: exchangeRate.currency)
}
/// Converts the current money value with currency `A` into another money value with currency `B`, using a given exchange rate from `B` to `A`.
///
/// - Parameters:
/// - exchangeRate: An exchange rate, representing one major unit of currency `B` in currency `A`.
/// - currencyType: The destination currency `B`.
public func convert<T: MoneyOperating>(usingInverse exchangeRate: Self, currency: T.MoneyCurrency) -> T {
if BuildFlag.isInternal, currencyType != exchangeRate.currencyType {
// fatalError("Self \(currencyType) currency type has to be equal exchangeRate currency type \(exchangeRate.currencyType)")
}
if currencyType == currency.currencyType {
return T(amount: amount, currency: currency)
}
guard !isZero, !exchangeRate.isZero else {
return .zero(currency: currency)
}
let conversionAmount = (amount * BigInt(10).power(currency.precision)) / exchangeRate.amount
return T(amount: conversionAmount, currency: currency)
}
/// Returns the value before a percentage increase/decrease (e.g. for a value of 15, and a `percentChange` of 0.5 i.e. 50%, this returns 10).
///
/// - Parameter percentageChange: A percentage of change.
public func value(before percentageChange: Double) -> Self {
let percentageChange = percentageChange + 1
guard !percentageChange.isNaN, !percentageChange.isZero, percentageChange.isNormal else {
return Self.zero(currency: currency)
}
let minorAmount = amount.divide(by: Decimal(percentageChange))
return Self.create(minor: minorAmount, currency: currency)
}
/// Returns the percentage of the current money in another, rounded to 4 decimal places.
///
/// - Parameter other: The value to calculate the percentage in.
public func percentage(in other: Self) throws -> Decimal {
try Self.percentage(of: self, in: other)
}
/// Rounds the current value to the current currency's `displayPrecision`.
///
/// - Warning: Rounding a money implies a **precision loss** for the underlying amount. This should only be used for displaying purposes.
///
/// - Parameter roundingMode: A rounding mode.
public func displayableRounding(roundingMode: Decimal.RoundingMode) -> Self {
displayableRounding(decimalPlaces: currency.displayPrecision, roundingMode: roundingMode)
}
/// Rounds the current value.
///
/// - Warning: Rounding a money implies a **precision loss** for the underlying amount. This should only be used for displaying purposes.
///
/// - Parameters:
/// - decimalPlaces: A number of decimal places.
/// - roundingMode: A rounding mode.
public func displayableRounding(decimalPlaces: Int, roundingMode: Decimal.RoundingMode) -> Self {
Self.create(
major: amount.toDecimalMajor(
baseDecimalPlaces: currency.precision,
roundingDecimalPlaces: decimalPlaces,
roundingMode: roundingMode
),
currency: currency
)
}
// MARK: - Private Methods
/// Returns the precentage of one money in another, rounded to 4 decimal places.
///
/// - Parameters:
/// - x: The value to calculate the percentage of.
/// - y: The value to calculate the percentage in.
private static func percentage(of x: Self, in y: Self) throws -> Decimal {
try ensureComparable(x, y)
return x.amount.decimalDivision(by: y.amount).roundTo(places: 4)
}
/// Checks that two money have matching currencies.
///
/// - Parameters:
/// - x: A value.
/// - y: Another value.
///
/// - Throws: A `MoneyOperatingError.mismatchingCurrencies` if the currencies do not match.
private static func ensureComparable(_ x: Self, _ y: Self) throws {
guard x.currencyType == y.currencyType else {
throw MoneyOperatingError.mismatchingCurrencies(x.currency, y.currency)
}
}
/// Returns true if displayable balance is greater than 0.0.
/// Account may still contain dust after `displayPrecision` decimal.
public var hasPositiveDisplayableBalance: Bool {
(try? self >= Self.create(minor: BigInt(10).power(precision - displayPrecision), currency: currency)) == true
}
}
| lgpl-3.0 | ebb3785e0d207bea0c65a0d677e55269 | 38.525526 | 147 | 0.626273 | 4.284505 | false | false | false | false |
mark-randall/Forms | Pod/Classes/Forms/FormViewController.swift | 1 | 3583 | //
// FormViewController.swift
// Forms
//
// The MIT License (MIT)
//
// Created by mrandall on 12/27/15.
// Copyright © 2015 CocoaPods. 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
public class FormFactory {
public class func createFormInputView(withInputViewModel inputViewModel: FormInputViewModelObservable) -> FormInputView? {
//select input with text
if let viewModel = inputViewModel as? FormSelectInputViewModel<String> {
let selectInputView = FormSelectInputView(withViewModel: viewModel)
return selectInputView
}
//select input with bool
if let viewModel = inputViewModel as? FormSelectInputViewModel<Bool> {
let selectInputView = FormSelectInputView(withViewModel: viewModel)
return selectInputView
}
//select input with date
if let viewModel = inputViewModel as? FormSelectInputViewModel<NSDate> {
let selectInputView = FormSelectInputView(withViewModel: viewModel)
return selectInputView
}
//select any
if let viewModel = inputViewModel as? FormSelectInputViewModel<Any> {
let selectInputView = FormSelectInputView(withViewModel: viewModel)
return selectInputView
}
//text inputs
if let viewModel = inputViewModel as? FormInputViewModel<String> {
let textInputView = FormTextInputView(withViewModel: viewModel)
return textInputView
}
//double inputs
if let viewModel = inputViewModel as? FormInputViewModel<Double> {
let textInputView = FormTextInputView(withViewModel: viewModel)
return textInputView
}
//int inputs
if let viewModel = inputViewModel as? FormInputViewModel<Int> {
let textInputView = FormTextInputView(withViewModel: viewModel)
return textInputView
}
//data inputs
if let viewModel = inputViewModel as? FormInputViewModel<NSDate> {
let selectDateInputView = FormSelectDateInputView(withViewModel: viewModel)
return selectDateInputView
}
//checkbox inputs
if let viewModel = inputViewModel as? FormInputViewModel<Bool> {
let checkboxInputView = FormCheckboxInputView(withViewModel: viewModel)
return checkboxInputView
}
return nil
}
}
| mit | 438bbd93ed35ceafe778e852eea2520a | 38.362637 | 126 | 0.676717 | 5.124464 | false | false | false | false |
Alamofire/AlamofireImage | Tests/TestHelpers.swift | 1 | 16884 | //
// TestHelpers.swift
//
// Copyright (c) 2021 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Alamofire
import AlamofireImage
import struct CoreGraphics.CGSize
import Foundation
extension String {
static let nonexistentDomain = "https://nonexistent-domain.org"
}
extension URL {
static let nonexistentDomain = URL(string: .nonexistentDomain)!
}
struct Endpoint {
enum Scheme: String {
case http, https
var port: Int {
switch self {
case .http: return 80
case .https: return 443
}
}
}
enum Host: String {
case gravatar = "secure.gravatar.com"
case httpBin = "httpbin.org"
case localhost = "127.0.0.1"
case nonexistent = "nonexistent-domain.org"
func port(for scheme: Scheme) -> Int {
switch self {
case .localhost: return 8080
case .gravatar, .httpBin, .nonexistent: return scheme.port
}
}
}
enum Path {
case basicAuth(username: String, password: String)
case bytes(count: Int)
case chunked(count: Int)
case compression(Compression)
case delay(interval: Int)
case digestAuth(qop: String = "auth", username: String, password: String)
case download(count: Int)
case gravatar(id: String)
case hiddenBasicAuth(username: String, password: String)
case image(Image)
case ip
case method(HTTPMethod)
case none
case payloads(count: Int)
case redirect(count: Int)
case redirectTo
case responseHeaders
case status(Int)
case stream(count: Int)
case xml
var string: String {
switch self {
case let .basicAuth(username: username, password: password):
return "/basic-auth/\(username)/\(password)"
case let .bytes(count):
return "/bytes/\(count)"
case let .chunked(count):
return "/chunked/\(count)"
case let .compression(compression):
return "/\(compression.rawValue)"
case let .delay(interval):
return "/delay/\(interval)"
case let .digestAuth(qop, username, password):
return "/digest-auth/\(qop)/\(username)/\(password)"
case let .download(count):
return "/download/\(count)"
case let .gravatar(id):
return "/avatar/\(id)"
case let .hiddenBasicAuth(username, password):
return "/hidden-basic-auth/\(username)/\(password)"
case let .image(type):
return "/image/\(type.rawValue)"
case .ip:
return "/ip"
case let .method(method):
return "/\(method.rawValue.lowercased())"
case .none:
return ""
case let .payloads(count):
return "/payloads/\(count)"
case let .redirect(count):
return "/redirect/\(count)"
case .redirectTo:
return "/redirect-to"
case .responseHeaders:
return "/response-headers"
case let .status(code):
return "/status/\(code)"
case let .stream(count):
return "/stream/\(count)"
case .xml:
return "/xml"
}
}
}
enum Image: String, CaseIterable {
static let universalCases: Set<Image> = {
var images = Set(Endpoint.Image.allCases)
images.remove(.webp)
images.remove(.pdf)
return images
}()
case bmp, jp2, jpeg, gif, heic, heif, pdf, png, webp
var expectedSize: CGSize {
switch self {
case .bmp, .jp2, .jpeg, .gif, .pdf, .png, .webp:
return .init(width: 1, height: 1)
case .heic, .heif:
return .init(width: 64, height: 64)
}
}
}
enum Compression: String {
case brotli, gzip, deflate
}
static var get: Endpoint { method(.get) }
static func basicAuth(forUser user: String = "user", password: String = "password") -> Endpoint {
Endpoint(path: .basicAuth(username: user, password: password))
}
static func bytes(_ count: Int) -> Endpoint {
Endpoint(path: .bytes(count: count))
}
static func chunked(_ count: Int) -> Endpoint {
Endpoint(path: .chunked(count: count))
}
static func compression(_ compression: Compression) -> Endpoint {
Endpoint(path: .compression(compression))
}
static var `default`: Endpoint { .get }
static func delay(_ interval: Int) -> Endpoint {
Endpoint(path: .delay(interval: interval))
}
static func digestAuth(forUser user: String = "user", password: String = "password") -> Endpoint {
Endpoint(path: .digestAuth(username: user, password: password))
}
static func download(_ count: Int = 10_000, produceError: Bool = false) -> Endpoint {
Endpoint(path: .download(count: count), queryItems: [.init(name: "shouldProduceError",
value: "\(produceError)")])
}
static func gravatar(_ id: String) -> Endpoint {
Endpoint(scheme: .https,
host: .gravatar,
path: .gravatar(id: id),
queryItems: [.init(name: "d", value: "identicon")])
}
static func hiddenBasicAuth(forUser user: String = "user", password: String = "password") -> Endpoint {
Endpoint(path: .hiddenBasicAuth(username: user, password: password),
headers: [.authorization(username: user, password: password)])
}
static func image(_ type: Image) -> Endpoint {
Endpoint(path: .image(type))
}
static var ip: Endpoint {
Endpoint(path: .ip)
}
static func method(_ method: HTTPMethod) -> Endpoint {
Endpoint(path: .method(method), method: method)
}
static let nonexistent = Endpoint(host: .nonexistent)
static func payloads(_ count: Int) -> Endpoint {
Endpoint(path: .payloads(count: count))
}
static func redirect(_ count: Int) -> Endpoint {
Endpoint(path: .redirect(count: count))
}
static func redirectTo(_ url: String, code: Int? = nil) -> Endpoint {
var items = [URLQueryItem(name: "url", value: url)]
items = code.map { items + [.init(name: "statusCode", value: "\($0)")] } ?? items
return Endpoint(path: .redirectTo, queryItems: items)
}
static func redirectTo(_ endpoint: Endpoint, code: Int? = nil) -> Endpoint {
var items = [URLQueryItem(name: "url", value: endpoint.url.absoluteString)]
items = code.map { items + [.init(name: "statusCode", value: "\($0)")] } ?? items
return Endpoint(path: .redirectTo, queryItems: items)
}
static var responseHeaders: Endpoint {
Endpoint(path: .responseHeaders)
}
static func status(_ code: Int) -> Endpoint {
Endpoint(path: .status(code))
}
static func stream(_ count: Int) -> Endpoint {
Endpoint(path: .stream(count: count))
}
static var xml: Endpoint {
Endpoint(path: .xml, headers: [.contentType("application/xml")])
}
var scheme = Scheme.http
var port: Int { host.port(for: scheme) }
var host = Host.localhost
var path = Path.method(.get)
var method: HTTPMethod = .get
var headers: HTTPHeaders = .init()
var timeout: TimeInterval = 60
var queryItems: [URLQueryItem] = []
var cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy
func modifying<T>(_ keyPath: WritableKeyPath<Endpoint, T>, to value: T) -> Endpoint {
var copy = self
copy[keyPath: keyPath] = value
return copy
}
}
extension Endpoint: URLRequestConvertible {
var urlRequest: URLRequest { try! asURLRequest() }
func asURLRequest() throws -> URLRequest {
var request = URLRequest(url: try asURL())
request.method = method
request.headers = headers
request.timeoutInterval = timeout
request.cachePolicy = cachePolicy
return request
}
}
extension Endpoint: URLConvertible {
var url: URL { try! asURL() }
func asURL() throws -> URL {
var components = URLComponents()
components.scheme = scheme.rawValue
components.port = port
components.host = host.rawValue
components.path = path.string
if !queryItems.isEmpty {
components.queryItems = queryItems
}
return try components.asURL()
}
}
extension Session {
func request(_ endpoint: Endpoint,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil) -> DataRequest {
request(endpoint as URLConvertible,
method: endpoint.method,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor,
requestModifier: requestModifier)
}
func request<Parameters: Encodable>(_ endpoint: Endpoint,
parameters: Parameters? = nil,
encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil) -> DataRequest {
request(endpoint as URLConvertible,
method: endpoint.method,
parameters: parameters,
encoder: encoder,
headers: headers,
interceptor: interceptor,
requestModifier: requestModifier)
}
func request(_ endpoint: Endpoint, interceptor: RequestInterceptor? = nil) -> DataRequest {
request(endpoint as URLRequestConvertible, interceptor: interceptor)
}
func streamRequest(_ endpoint: Endpoint,
headers: HTTPHeaders? = nil,
automaticallyCancelOnStreamError: Bool = false,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil) -> DataStreamRequest {
streamRequest(endpoint as URLConvertible,
method: endpoint.method,
headers: headers,
automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
interceptor: interceptor,
requestModifier: requestModifier)
}
func streamRequest(_ endpoint: Endpoint,
automaticallyCancelOnStreamError: Bool = false,
interceptor: RequestInterceptor? = nil) -> DataStreamRequest {
streamRequest(endpoint as URLRequestConvertible,
automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
interceptor: interceptor)
}
func download<Parameters: Encodable>(_ endpoint: Endpoint,
parameters: Parameters? = nil,
encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil,
to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
download(endpoint as URLConvertible,
method: endpoint.method,
parameters: parameters,
encoder: encoder,
headers: headers,
interceptor: interceptor,
requestModifier: requestModifier,
to: destination)
}
func download(_ endpoint: Endpoint,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil,
to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
download(endpoint as URLConvertible,
method: endpoint.method,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor,
requestModifier: requestModifier,
to: destination)
}
func download(_ endpoint: Endpoint,
interceptor: RequestInterceptor? = nil,
to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
download(endpoint as URLRequestConvertible, interceptor: interceptor, to: destination)
}
func upload(_ data: Data,
to endpoint: Endpoint,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default,
requestModifier: RequestModifier? = nil) -> UploadRequest {
upload(data, to: endpoint as URLConvertible,
method: endpoint.method,
headers: headers,
interceptor: interceptor,
fileManager: fileManager,
requestModifier: requestModifier)
}
}
extension ImageDownloader {
@discardableResult
func download(_ endpoint: Endpoint,
cacheKey: String? = nil,
receiptID: String = UUID().uuidString,
serializer: ImageResponseSerializer? = nil,
filter: ImageFilter? = nil,
progress: ProgressHandler? = nil,
progressQueue: DispatchQueue = DispatchQueue.main,
completion: CompletionHandler? = nil) -> RequestReceipt? {
download(endpoint as URLRequestConvertible,
cacheKey: cacheKey,
receiptID: receiptID,
serializer: serializer,
filter: filter,
progress: progress,
progressQueue: progressQueue,
completion: completion)
}
@discardableResult
func download(_ endpoints: [Endpoint],
filter: ImageFilter? = nil,
progress: ProgressHandler? = nil,
progressQueue: DispatchQueue = DispatchQueue.main,
completion: CompletionHandler? = nil)
-> [RequestReceipt] {
download(endpoints as [URLRequestConvertible],
filter: filter,
progress: progress,
progressQueue: progressQueue,
completion: completion)
}
}
extension Data {
var asString: String {
String(decoding: self, as: UTF8.self)
}
}
struct TestResponse: Decodable {
let headers: [String: String]
let origin: String
let url: String?
let data: String?
let form: [String: String]?
let args: [String: String]?
}
struct TestParameters: Encodable {
static let `default` = TestParameters(property: "property")
let property: String
}
| mit | 36edbbea03ec2195c46ad88b4cb0524c | 35 | 113 | 0.572791 | 5.246737 | false | false | false | false |
ZamzamInc/ZamzamKit | Sources/ZamzamCore/Extensions/CurrencyFormatter.swift | 1 | 4193 | //
// CurrencyFormatter.swift
// ZamzamCore
//
// Created by Basem Emara on 2018-11-24.
// Copyright © 2018 Zamzam Inc. All rights reserved.
//
import Foundation.NSLocale
import Foundation.NSNumberFormatter
/// A formatter that converts between monetary values and their textual representations.
public struct CurrencyFormatter {
private let formatter: NumberFormatter
private let autoTruncate: Bool
/// Initialize a new currency formatter.
///
/// - Parameters:
/// - locale: The locale to retrieve the currency from.
/// - autoTruncate: Truncate decimal if `.00`.
/// - decimalDigits: The minimum number of digits after the decimal separator. Default is 2.
/// - zeroSymbol: The string used to represent a zero value.
/// - usePrefix: Adds a prefix for positive and negative values.
public init(
for locale: Locale = .current,
autoTruncate: Bool = false,
decimalDigits: Int = 2,
zeroSymbol: String? = nil,
usePrefix: Bool = false
) {
self.formatter = NumberFormatter().apply {
$0.numberStyle = .currency
$0.locale = locale
$0.currencyCode = locale.currencyCode
$0.minimumFractionDigits = decimalDigits
$0.maximumFractionDigits = decimalDigits
$0.zeroSymbol ?= zeroSymbol
if usePrefix {
$0.positivePrefix = $0.plusSign + $0.currencySymbol
$0.negativePrefix = $0.negativePrefix + ""
}
}
self.autoTruncate = autoTruncate
}
}
public extension CurrencyFormatter {
/// Returns a string containing the formatted value of the provided number object.
///
/// let amount: Double = 123456789.987
///
/// let formatter = CurrencyFormatter()
/// formatter.string(fromAmount: amount) // "$123,456,789.99"
///
/// let formatter2 = CurrencyFormatter(for: Locale(identifier: "fr-FR"))
/// formatter2.string(fromAmount: amount) // "123 456 789,99 €"
///
/// - Parameter double: A monetary number that is parsed to create the returned string object.
/// - Returns: A string containing the formatted value of number using the receiver’s current settings.
func string(fromAmount double: Double?) -> String {
let validValue = getAdjustedForDefinedInterval(value: double)
guard autoTruncate, validValue.truncatingRemainder(dividingBy: 1) == 0 else {
return formatter.string(from: validValue as NSNumber) ?? "\(validValue)"
}
let truncatingFormatter = formatter.copy() as? NumberFormatter // TODO: Lazy load
truncatingFormatter?.minimumFractionDigits = 0
truncatingFormatter?.maximumFractionDigits = 0
return truncatingFormatter?.string(from: validValue as NSNumber) ?? "\(validValue)"
}
/// Returns the given value adjusted to respect formatter's min and max values.
///
/// - Parameter value: Value to be adjusted if needed
/// - Returns: Ajusted value
private func getAdjustedForDefinedInterval(value: Double?) -> Double {
if let minValue = formatter.minimum?.doubleValue, value ?? 0 < minValue {
return minValue
} else if let maxValue = formatter.maximum?.doubleValue, value ?? 0 > maxValue {
return maxValue
}
return value ?? 0
}
}
public extension CurrencyFormatter {
/// Returns a string containing the currency formatted value of the provided number object.
///
/// let cents = 123456789
///
/// let formatter = CurrencyFormatter()
/// formatter.string(fromCents: cents) // "$1,234,567.89"
///
/// let formatter2 = CurrencyFormatter(for: Locale(identifier: "fr-FR"))
/// formatter2.string(fromCents: cents) // "1 234 567,89 €"
///
/// - Parameter cents: The cents of the value.
/// - Returns: A string containing the formatted value of number using the receiver’s current currency settings.
func string(fromCents cents: Int) -> String {
let amount = Double(cents) / 100
return string(fromAmount: amount)
}
}
| mit | 4b85055eaeb3225646cc152356a7cca8 | 38.046729 | 116 | 0.640977 | 4.6268 | false | false | false | false |
sora0077/RelayoutKit | Playground.playground/Contents.swift | 1 | 1028 | //: Playground - noun: a place where people can play
import UIKit
import RelayoutKit
import XCPlayground
extension UITableViewCell: TableRowRenderer {
public static func register(tableView: UITableView) {
tableView.registerClass(self, forCellReuseIdentifier: self.identifier)
}
}
class TextTableRow<T: UITableViewCell where T: TableRowRenderer>: TableRow<T> {
override init() {
super.init()
}
override func componentDidMount() {
super.componentDidMount()
renderer?.textLabel?.text = "aaaaa"
}
}
let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 320, height: 300), style: .Plain)
tableView.controller(nil, sections: [TableSection()])
tableView[section: 0, row: 0] = TextTableRow<UITableViewCell>()
tableView[section: 0, row: 1] = TextTableRow<UITableViewCell>()
tableView[section: 0, row: 2] = TextTableRow<UITableViewCell>()
tableView[section: 0, row: 3] = TextTableRow<UITableViewCell>()
let preview = tableView
| mit | 5d547ea23e61180cc70d28274dec2924 | 21.844444 | 94 | 0.690661 | 4.213115 | false | false | false | false |
VirgilSecurity/virgil-crypto-ios | Source/StreamUtils.swift | 1 | 3537 | //
// Copyright (C) 2015-2021 Virgil Security Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// (1) Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// (3) Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Lead Maintainer: Virgil Security Inc. <[email protected]>
//
import Foundation
internal enum StreamUtils {
internal static func read(from stream: InputStream) throws -> Data? {
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: VirgilCrypto.chunkSize)
let actualReadLen = stream.read(buffer, maxLength: VirgilCrypto.chunkSize)
let deallocator = Data.Deallocator.custom { buffer, _ in
buffer.deallocate()
}
guard actualReadLen > 0 else {
if actualReadLen < 0 {
throw VirgilCryptoError.inputStreamError
}
return nil
}
return Data(bytesNoCopy: UnsafeMutableRawPointer(buffer),
count: actualReadLen,
deallocator: deallocator)
}
internal static func write(_ chunk: Data, to stream: OutputStream) throws {
guard !chunk.isEmpty else {
return
}
var actualWriteLen = 0
chunk.withUnsafeBytes { buffer in
if let pointer = buffer.bindMemory(to: UInt8.self).baseAddress {
actualWriteLen = stream.write(pointer, maxLength: chunk.count)
}
}
guard actualWriteLen == chunk.count else {
throw VirgilCryptoError.outputStreamError
}
}
internal static func forEachChunk(in stream: InputStream,
streamSize: Int?,
do process: (Data) throws -> Void) throws {
var sizeLeft = streamSize ?? 0
while stream.hasBytesAvailable {
guard let data = try self.read(from: stream) else {
break
}
if streamSize != nil {
sizeLeft -= data.count
}
try process(data)
}
guard sizeLeft == 0 else {
throw VirgilCryptoError.invalidStreamSize
}
}
}
| bsd-3-clause | 4a1a6e939e2e6f3bca2c05943d000e16 | 34.727273 | 91 | 0.644331 | 4.953782 | false | false | false | false |
tndatacommons/OfficeHours-iOS | OfficeHours/TimeSlotPickerController.swift | 1 | 2895 | //
// TimeRangePickerController.swift
// OfficeHours
//
// Created by Ismael Alonso on 12/22/16.
// Copyright © 2016 Tennessee Data Commons. All rights reserved.
//
import Foundation
class TimeSlotPickerController: UIViewController, TimePickerDelegate{
@IBOutlet weak var mSwitch: UISwitch!
@IBOutlet weak var tSwitch: UISwitch!
@IBOutlet weak var wSwitch: UISwitch!
@IBOutlet weak var rSwitch: UISwitch!
@IBOutlet weak var fSwitch: UISwitch!
@IBOutlet weak var sSwitch: UISwitch!
@IBOutlet weak var from: UILabel!
@IBOutlet weak var to: UILabel!
var delegate: TimeSlotPickerDelegate!
var multiChoice = true
private var fromSelected = false
private var fromDate: Date?
private var toDate: Date?
private var timeFormatter = DateFormatter()
override func viewDidLoad(){
super.viewDidLoad()
timeFormatter.dateFormat = "h:mm a"
}
@IBAction func onFromTapped(_ sender: Any){
fromSelected = true
performSegue(withIdentifier: "TimePickerFromSlotPicker", sender: self)
}
@IBAction func onToTapped(_ sender: Any){
fromSelected = false
performSegue(withIdentifier: "TimePickerFromSlotPicker", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
if segue.identifier == "TimePickerFromSlotPicker"{
let controller = segue.destination as! TimePickerController
controller.delegate = self
if fromSelected{
controller.time = fromDate
}
else{
controller.time = toDate
}
}
}
func onTimePicked(_ time: Date){
if fromSelected{
fromDate = time
from.text = "From \(timeFormatter.string(for: time)!)"
}
else{
toDate = time
to.text = "To \(timeFormatter.string(for: time)!)"
}
}
@IBAction func onDoneTapped(){
var result = ""
if mSwitch.isOn{
result += "M"
}
if tSwitch.isOn{
result += "T"
}
if wSwitch.isOn{
result += "W"
}
if rSwitch.isOn{
result += "R"
}
if fSwitch.isOn{
result += "F"
}
if sSwitch.isOn{
result += "S"
}
if !result.isEmpty && fromDate != nil && toDate != nil{
let fromStr = timeFormatter.string(for: fromDate!)!
let toStr = timeFormatter.string(for: toDate!)!
result += " \(fromStr)-\(toStr)"
delegate.onTimeSlotPicked(result)
navigationController!.popViewController(animated: true)
}
}
}
protocol TimeSlotPickerDelegate{
func onTimeSlotPicked(_ timeSlot: String)
}
| apache-2.0 | 4f013e94f174475d77c7df7448a7c6cd | 26.046729 | 78 | 0.572218 | 4.783471 | false | false | false | false |
rb-de0/Fluxer | FluxerTests/Observable/PublishTests.swift | 1 | 936 | //
// PublishTests.swift
// Fluxer
//
// Created by rb_de0 on 2017/04/13.
// Copyright © 2017年 rb_de0. All rights reserved.
//
import XCTest
@testable import Fluxer
class PublishTests: XCTestCase {
class PublishStore: Store {
let value = ObservableValue(0)
required init(with dispatcher: Dispatcher) {}
}
func testPublish() {
let store = PublishStore(with: Dispatcher())
var bindableValue: Int?
_ = store.value.subscribe {
bindableValue = $0
}
store.publish()
XCTAssertEqual(bindableValue, 0)
}
func testNotPublish() {
let store = PublishStore(with: Dispatcher())
var bindableValue: Int?
_ = store.value.subscribe {
bindableValue = $0
}
XCTAssertNotEqual(bindableValue, 0)
}
}
| mit | 5c21b55381c6e73fe0cd197bca5d9123 | 18.4375 | 53 | 0.535906 | 4.573529 | false | true | false | false |
edragoev1/pdfjet | Sources/PDFjet/Table.swift | 1 | 30123 | /**
* Table.swift
*
Copyright 2020 Innovatics Inc.
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
///
/// Used to create table objects and draw them on a page.
///
/// Please see Example_08.
///
public class Table {
public static let DATA_HAS_0_HEADER_ROWS = 0
public static let DATA_HAS_1_HEADER_ROWS = 1
public static let DATA_HAS_2_HEADER_ROWS = 2
public static let DATA_HAS_3_HEADER_ROWS = 3
public static let DATA_HAS_4_HEADER_ROWS = 4
public static let DATA_HAS_5_HEADER_ROWS = 5
public static let DATA_HAS_6_HEADER_ROWS = 6
public static let DATA_HAS_7_HEADER_ROWS = 7
public static let DATA_HAS_8_HEADER_ROWS = 8
public static let DATA_HAS_9_HEADER_ROWS = 9
private var rendered = 0
private var numOfPages = 0
private var tableData: [[Cell]]
private var numOfHeaderRows = 0
private var x1: Float?
private var y1: Float?
private var y1FirstPage: Float = 0.0
private var rightMargin: Float = 0.0
private var bottomMargin: Float = 30.0
private var numOfHeaderRowsAdjusted: Bool = false
///
/// Create a table object.
///
public init() {
tableData = [[Cell]]()
}
///
/// Sets the location (x, y) of the top left corner of this table on the page.
///
/// @param x the x coordinate of the top left point of the table.
/// @param y the y coordinate of the top left point of the table.
///
public func setLocation(_ x: Float, _ y: Float) {
self.x1 = x
self.y1 = y
}
///
/// Sets the bottom margin for this table.
///
/// @param bottomMargin the margin.
///
public func setBottomMargin(_ bottomMargin: Float) {
self.bottomMargin = bottomMargin
}
///
/// Sets the table data.
///
/// The table data is a perfect grid of cells.
/// All cell should be an unique object and you can not reuse blank cell objects.
/// Even if one or more cells have colspan bigger than zero the number of cells in the row will not change.
///
/// @param tableData the table data.
///
public func setData(_ tableData: [[Cell]]) {
self.tableData = tableData
self.numOfHeaderRows = 0
self.rendered = self.numOfHeaderRows
// Add the missing cells.
let numOfColumns = tableData[0].count
let font = tableData[0][0].font
for i in 0..<tableData.count {
var row = tableData[i]
let diff = numOfColumns - row.count
for _ in 0..<diff {
row.append(Cell(font, ""))
}
}
}
///
/// Sets the table data and specifies the number of header rows in this data.
///
/// @param tableData the table data.
/// @param numOfHeaderRows the number of header rows in this data.
///
public func setData(_ tableData: [[Cell]], _ numOfHeaderRows: Int) {
self.tableData = tableData
self.numOfHeaderRows = numOfHeaderRows
self.rendered = numOfHeaderRows
// Add the missing cells.
let numOfColumns = tableData[0].count
let font = tableData[0][0].font
for i in 0..<tableData.count {
var row = tableData[i]
let diff = numOfColumns - row.count
for _ in 0..<diff {
row.append(Cell(font, ""))
}
}
}
///
/// Auto adjusts the widths of all columns so that they are just wide enough to hold the text without truncation.
///
/*
public func autoAdjustColumnWidths() {
// Find the maximum text width for each column
var maxColWidths = [Float](repeating: 0, count: (tableData[0].count))
for row in tableData {
for (i, cell) in row.enumerated() {
if cell.getColSpan() == 1 {
var cellWidth: Float = 0.0
if cell.getImage() != nil {
cellWidth = cell.getImage()!.getWidth()!
}
if cell.text != nil {
if cell.font!.stringWidth(cell.fallbackFont, cell.text) > cellWidth {
cellWidth = cell.font!.stringWidth(cell.fallbackFont, cell.text)
}
}
cell.setWidth(cellWidth + cell.leftPadding + cell.rightPadding)
if maxColWidths[i] == 0.0 ||
cell.getWidth() > maxColWidths[i] {
maxColWidths[i] = cell.getWidth()
}
}
}
}
for row in tableData {
for (i, cell) in row.enumerated() {
cell.setWidth(maxColWidths[i])
}
}
}
*/
///
/// Sets the alignment of the numbers to the right.
///
public func rightAlignNumbers() {
let digitsPlus = [UnicodeScalar]("0123456789()-.,'".unicodeScalars)
var i = numOfHeaderRows
while i < tableData.count {
let row = tableData[i]
for cell in row {
if cell.text != nil {
let scalars = [UnicodeScalar](cell.text!.unicodeScalars)
var isNumber = true
for scalar in scalars {
if digitsPlus.firstIndex(of: scalar) == nil {
isNumber = false
break
}
}
if isNumber {
cell.setTextAlignment(Align.RIGHT)
}
}
}
i += 1
}
}
///
/// Removes the horizontal lines between the rows from index1 to index2.
///
public func removeLineBetweenRows(_ index1: Int, _ index2: Int) {
var j = index1
while j < index2 {
var row = tableData[j]
for cell in row {
cell.setBorder(Border.BOTTOM, false)
}
row = tableData[j + 1]
for cell in row {
cell.setBorder(Border.TOP, false)
}
j += 1
}
}
///
/// Sets the text alignment in the specified column.
/// Supported values: Align.LEFT, Align.RIGHT, Align.CENTER and Align.JUSTIFY.
///
/// @param index the index of the specified column.
/// @param alignment the specified alignment.
///
public func setTextAlignInColumn(_ index: Int, _ alignment: UInt32) throws {
for row in tableData {
if index < row.count {
let cell = row[index]
cell.setTextAlignment(alignment)
if cell.textBlock != nil {
cell.textBlock!.setTextAlignment(alignment)
}
}
}
}
///
/// Sets the color of the text in the specified column.
///
/// @param index the index of the specified column.
/// @param color the color specified as an integer.
///
public func setTextColorInColumn(_ index: Int, _ color: UInt32) {
for row in tableData {
if index < row.count {
let cell = row[index]
cell.setBrushColor(color)
if cell.textBlock != nil {
cell.textBlock!.setBrushColor(color)
}
}
}
}
///
/// Sets the font for the specified column.
///
/// @param index the column index.
/// @param font the font.
///
public func setFontInColumn(_ index: Int, _ font: Font) {
for row in tableData {
if index < row.count {
let cell = row[index]
cell.font = font
if cell.textBlock != nil {
cell.textBlock!.font = font
}
}
}
}
///
/// Sets the color of the text in the specified row.
///
/// @param index the index of the specified row.
/// @param color the color specified as an integer.
///
public func setTextColorInRow(_ index: Int, _ color: UInt32) {
if index < tableData.count {
let row = tableData[index]
for cell in row {
cell.setBrushColor(color)
if cell.textBlock != nil {
cell.textBlock!.setBrushColor(color)
}
}
}
}
///
/// Sets the font for the specified row.
///
/// @param index the row index.
/// @param font the font.
///
public func setFontInRow(_ index: Int, _ font: Font) {
if index < tableData.count {
let row = tableData[index]
for cell in row {
cell.font = font
if cell.textBlock != nil {
cell.textBlock!.font = font
}
}
}
}
///
/// Sets the width of the column with the specified index.
///
/// @param index the index of specified column.
/// @param width the specified width.
///
public func setColumnWidth(_ index: Int, _ width: Float) {
for row in tableData {
if index < row.count {
let cell = row[index]
cell.setWidth(width)
if cell.textBlock != nil {
cell.textBlock!.setWidth(width - (cell.leftPadding + cell.rightPadding))
}
}
}
}
///
/// Returns the column width of the column at the specified index.
///
/// @param index the index of the column.
/// @return the width of the column.
///
public func getColumnWidth(_ index: Int) -> Float {
return getCellAtRowColumn(0, index).getWidth();
}
///
/// Returns the cell at the specified row and column.
///
/// @param row the specified row.
/// @param col the specified column.
///
/// @return the cell at the specified row and column.
///
public func getCellAt(_ row: Int, _ col: Int) -> Cell {
if row >= 0 {
return tableData[row][col]
}
return tableData[tableData.count + row][col]
}
///
/// Returns the cell at the specified row and column.
///
/// @param row the specified row.
/// @param col the specified column.
///
/// @return the cell at the specified row and column.
///
public func getCellAtRowColumn(_ row: Int, _ col: Int) -> Cell {
return getCellAt(row, col)
}
///
/// Returns a list of cell for the specified row.
///
/// @param index the index of the specified row.
///
/// @return the list of cells.
///
public func getRow(_ index: Int) -> [Cell] {
return tableData[index]
}
public func getRowAtIndex(_ index: Int) -> [Cell] {
return getRow(index)
}
///
/// Returns a list of cell for the specified column.
///
/// @param index the index of the specified column.
///
/// @return the list of cells.
///
public func getColumn(_ index: Int) -> [Cell] {
var column = [Cell]()
for row in tableData {
if index < row.count {
column.append(row[index])
}
}
return column
}
public func getColumnAtIndex(_ index: Int) -> [Cell] {
return getColumn(index)
}
///
/// Returns the total number of pages that are required to draw this table on.
///
/// @param page the type of pages we are drawing this table on.
///
/// @return the number of pages.
///
@discardableResult
public func getNumberOfPages(_ page: Page) throws -> Int {
self.numOfPages = 1
while hasMoreData() {
drawOn(nil)
}
resetRenderedPagesCount()
return self.numOfPages
}
///
/// Draws this table on the specified page.
///
/// @param page the page to draw this table on.
/// @param draw if false - do not draw the table. Use to only find out where the table ends.
///
/// @return Point the point on the page where to draw the next component.
///
@discardableResult
public func drawOn(_ page: Page?) -> [Float] {
return drawTableRows(page, drawHeaderRows(page, 0))
}
@discardableResult
public func drawOn(_ pdf: PDF, _ pages: inout [Page], _ pageSize: [Float]) -> [Float] {
var xy: [Float]?
var pageNumber: Int = 1
while (self.hasMoreData()) {
let page = Page(pdf, pageSize, false)
pages.append(page)
xy = drawTableRows(page, drawHeaderRows(page, pageNumber))
pageNumber += 1
}
// Allow the table to be drawn again later:
resetRenderedPagesCount()
return xy!
}
private func drawHeaderRows(_ page: Page?, _ pageNumber: Int) -> [Float] {
var x = x1
var y = (pageNumber == 1) ? y1FirstPage : y1;
var cellH: Float = 0.0
for i in 0..<numOfHeaderRows {
let dataRow = tableData[i]
cellH = getMaxCellHeight(dataRow)
var j = 0
while j < dataRow.count {
let cell = dataRow[j]
var cellW = dataRow[j].getWidth()
let colspan = dataRow[j].getColSpan()
var k = 1
while k < colspan {
j += 1
cellW += dataRow[j].width
k += 1
}
if page != nil {
page!.setBrushColor(cell.getBrushColor())
cell.paint(page!, x!, y!, cellW, cellH)
}
x! += cellW
j += 1
}
x = x1
y! += cellH
}
return [x!, y!]
}
private func drawTableRows(_ page: Page?, _ parameter: [Float]) -> [Float] {
var x = parameter[0]
var y = parameter[1]
var cellH: Float = 0.0
var i = rendered
while i < tableData.count {
let dataRow = tableData[i]
cellH = getMaxCellHeight(dataRow)
var j = 0
while j < dataRow.count {
let cell = dataRow[j]
var cellW = cell.getWidth()
let colspan = dataRow[j].getColSpan()
var k = 1
while k < colspan {
j += 1
cellW += dataRow[j].getWidth()
k += 1
}
if page != nil {
page!.setBrushColor(cell.getBrushColor())
cell.paint(page!, x, y, cellW, cellH)
}
x += cellW
j += 1
}
x = x1!
y += cellH
// Consider the height of the next row when checking if we must go to a new page
if i < (tableData.count - 1) {
for cell in tableData[i + 1] {
if cell.getHeight() > cellH {
cellH = cell.getHeight()
}
}
}
if page != nil && (y + cellH) > (page!.height - bottomMargin) {
if i == (tableData.count - 1) {
rendered = -1
}
else {
rendered = i + 1
numOfPages += 1
}
return [x, y]
}
i += 1
}
rendered = -1
return [x, y]
}
private func getMaxCellHeight(_ row: [Cell]) -> Float {
var maxCellHeight: Float = 0.0
for cell in row {
if cell.getHeight() > maxCellHeight {
maxCellHeight = cell.getHeight()
}
}
return maxCellHeight
}
///
/// Returns true if the table contains more data that needs to be drawn on a page.
///
public func hasMoreData() -> Bool {
return self.rendered != -1
}
///
/// Returns the width of this table when drawn on a page.
///
/// @return the widht of this table.
///
public func getWidth() -> Float {
var table_width: Float = 0.0
if tableData.count > 0 {
let row = tableData[0]
for cell in row {
table_width += cell.getWidth()
}
}
return table_width
}
///
/// Returns the number of data rows that have been rendered so far.
///
/// @return the number of data rows that have been rendered so far.
///
public func getRowsRendered() -> Int {
return rendered == -1 ? rendered : rendered - numOfHeaderRows
}
///
/// Wraps around the text in all cells so it fits the column width.
/// This method should be called after all calls to setColumnWidth and autoAdjustColumnWidths.
///
public func wrapAroundCellText() {
var tableData2 = [[Cell]]()
for row in tableData {
var maxNumVerCells = 1
for i in 0..<row.count {
var n = 1
while n < row[i].getColSpan() {
row[i].width += row[i + n].width
row[i + n].width = 0.0
n += 1
}
let numVerCells = row[i].getNumVerCells()
if numVerCells > maxNumVerCells {
maxNumVerCells = numVerCells
}
}
for i in 0..<maxNumVerCells {
var row2 = [Cell]()
for cell in row {
let cell2 = Cell(cell.getFont(), "")
cell2.setFallbackFont(cell.getFallbackFont())
cell2.setPoint(cell.getPoint())
cell2.setWidth(cell.getWidth())
if i == 0 {
cell2.setTopPadding(cell.topPadding)
}
if i == (maxNumVerCells - 1) {
cell2.setBottomPadding(cell.bottomPadding)
}
cell2.setLeftPadding(cell.leftPadding)
cell2.setRightPadding(cell.rightPadding)
cell2.setLineWidth(cell.lineWidth)
cell2.setBgColor(cell.getBgColor())
cell2.setPenColor(cell.getPenColor())
cell2.setBrushColor(cell.getBrushColor())
cell2.setProperties(cell.getProperties())
cell2.setVerTextAlignment(cell.getVerTextAlignment())
if i == 0 {
if (cell.getImage() != nil) {
cell2.setImage(cell.getImage())
}
if cell.getCompositeTextLine() != nil {
cell2.setCompositeTextLine(cell.getCompositeTextLine())
}
else {
cell2.setText(cell.getText())
}
if maxNumVerCells > 1 {
cell2.setBorder(Border.BOTTOM, false)
}
}
else {
cell2.setBorder(Border.TOP, false)
if i < (maxNumVerCells - 1) {
cell2.setBorder(Border.BOTTOM, false)
}
}
row2.append(cell2)
}
tableData2.append(row2)
}
}
for (i, row) in tableData2.enumerated() {
for (j, cell) in row.enumerated() {
if cell.text != nil {
var n = 0
let textLines = cell.text!.trim().components(separatedBy: "\n")
for textLine in textLines {
var sb = String()
let tokens = textLine.trim().components(separatedBy: .whitespaces)
if tokens.count == 1 {
sb.append(tokens[0])
}
else {
for k in 0..<tokens.count {
let token = tokens[k].trim()
if cell.font!.stringWidth(cell.fallbackFont, sb + " " + token) >
(cell.getWidth() - (cell.leftPadding + cell.rightPadding)) {
tableData2[i + n][j].setText(sb)
sb = token
n += 1
}
else {
if k > 0 {
sb.append(" ")
}
sb.append(token)
}
}
}
tableData2[i + n][j].setText(sb)
n += 1
}
}
else {
tableData2[i][j].setCompositeTextLine(cell.getCompositeTextLine())
}
}
}
tableData = tableData2
}
///
/// Sets all table cells borders to <strong>false</strong>.
///
public func setNoCellBorders() {
for row in tableData {
for cell in row {
cell.setNoBorders()
}
}
}
///
/// Sets the color of the cell border lines.
///
/// @param color the color of the cell border lines.
///
public func setCellBordersColor(_ color: UInt32) {
for row in tableData {
for cell in row {
cell.setPenColor(color)
}
}
}
///
/// Sets the width of the cell border lines.
///
/// @param width the width of the border lines.
///
public func setCellBordersWidth(_ width: Float) {
for row in tableData {
for cell in row {
cell.setLineWidth(width)
}
}
}
///
/// Resets the rendered pages count.
/// Call this method if you have to draw this table more than one time.
///
public func resetRenderedPagesCount() {
self.rendered = numOfHeaderRows
}
///
/// This method removes borders that have the same color and overlap 100%.
/// The result is improved onscreen rendering of thin border lines by some PDF viewers.
///
public func mergeOverlaidBorders() {
for (i, row) in tableData.enumerated() {
for (j, cell) in row.enumerated() {
if j < (row.count - 1) {
let cellAtRight = row[j + 1]
if cellAtRight.getBorder(Border.LEFT) &&
cell.getPenColor() == cellAtRight.getPenColor() &&
cell.getLineWidth() == cellAtRight.getLineWidth() &&
(Int(cell.getColSpan()) + j) < (row.count - 1) {
cell.setBorder(Border.RIGHT, false)
}
}
if i < (tableData.count - 1) {
let nextRow = tableData[i + 1]
let cellBelow = nextRow[j]
if cellBelow.getBorder(Border.TOP) &&
cell.getPenColor() == cellBelow.getPenColor() &&
cell.getLineWidth() == cellBelow.getLineWidth() {
cell.setBorder(Border.BOTTOM, false)
}
}
}
}
}
/**
* Auto adjusts the widths of all columns so that they are just wide enough to hold the text without truncation.
*/
public func autoAdjustColumnWidths() {
var maxColWidths = [Float](repeating: 0, count: (tableData[0].count))
for i in 0..<numOfHeaderRows {
for j in 0..<maxColWidths.count {
let cell = tableData[i][j]
var textWidth = cell.font!.stringWidth(cell.fallbackFont, cell.text)
textWidth += cell.leftPadding + cell.rightPadding
if textWidth > maxColWidths[j] {
maxColWidths[j] = textWidth
}
}
}
for i in numOfHeaderRows..<tableData.count {
for j in 0..<maxColWidths.count {
let cell = tableData[i][j]
if cell.getColSpan() > 1 {
continue
}
if cell.text != nil {
var textWidth = cell.font!.stringWidth(cell.fallbackFont, cell.text)
textWidth += cell.leftPadding + cell.rightPadding
if textWidth > maxColWidths[j] {
maxColWidths[j] = textWidth
}
}
if cell.image != nil {
let imageWidth = cell.image!.getWidth() + cell.leftPadding + cell.rightPadding
if imageWidth > maxColWidths[j] {
maxColWidths[j] = imageWidth
}
}
if cell.barCode != nil {
let barcodeWidth = cell.barCode!.drawOn(nil)[0] + cell.leftPadding + cell.rightPadding
if barcodeWidth > maxColWidths[j] {
maxColWidths[j] = barcodeWidth
}
}
if cell.textBlock != nil {
let tokens = cell.textBlock!.text!.components(separatedBy: .whitespaces)
for token in tokens {
var tokenWidth = cell.textBlock!.font.stringWidth(cell.textBlock!.fallbackFont, token)
tokenWidth += cell.leftPadding + cell.rightPadding
if tokenWidth > maxColWidths[j] {
maxColWidths[j] = tokenWidth
}
}
}
}
}
for i in 0..<tableData.count {
let row = tableData[i]
for j in 0..<row.count {
let cell = row[j]
cell.setWidth(maxColWidths[j] + 0.1)
}
}
autoResizeColumnsWithColspanBiggerThanOne()
}
private func isTextColumn(_ index: Int) -> Bool {
for i in numOfHeaderRows..<tableData.count {
let dataRow = tableData[i]
if dataRow[index].image != nil || dataRow[index].barCode != nil {
return false
}
}
return true
}
public func fitToPage(_ pageSize: [Float]) {
autoAdjustColumnWidths()
let tableWidth: Float = (pageSize[0] - self.x1!) - rightMargin
var textColumnWidths: Float = 0.0
var otherColumnWidths: Float = 0.0
let row = tableData[0]
for i in 0..<row.count {
let cell = row[i]
if isTextColumn(i) {
textColumnWidths += cell.getWidth()
}
else {
otherColumnWidths += cell.getWidth()
}
}
var adjusted: Float = 0.0
if (tableWidth - otherColumnWidths) > textColumnWidths {
adjusted = textColumnWidths + ((tableWidth - otherColumnWidths) - textColumnWidths)
}
else {
adjusted = textColumnWidths - (textColumnWidths - (tableWidth - otherColumnWidths))
}
let factor: Float = adjusted / textColumnWidths
for i in 0..<row.count {
if isTextColumn(i) {
setColumnWidth(i, getColumnWidth(i) * factor)
}
}
autoResizeColumnsWithColspanBiggerThanOne()
mergeOverlaidBorders()
}
private func autoResizeColumnsWithColspanBiggerThanOne() {
for i in 0..<tableData.count {
let dataRow = tableData[i]
var j = 0
while j < dataRow.count {
let cell = dataRow[j]
let colspan = cell.getColSpan()
if colspan > 1 {
if cell.textBlock != nil {
var sumOfWidths = cell.getWidth()
for _ in 1..<colspan {
j += 1
sumOfWidths += dataRow[j].getWidth()
}
cell.textBlock!.setWidth(sumOfWidths - (cell.leftPadding + cell.rightPadding))
}
}
j += 1
}
}
}
public func setRightMargin(_ rightMargin: Float) {
self.rightMargin = rightMargin
}
public func setFirstPageTopMargin(_ topMargin: Float) {
self.y1FirstPage = y1! + topMargin
}
public func addToRow(_ row: inout [Cell], _ cell: Cell) {
row.append(cell)
for _ in 1..<cell.getColSpan() {
row.append(Cell(cell.getFont(), ""))
}
}
} // End of Table.swift
| mit | 7ee7ba6b5d94bd7a08710463d1548944 | 30.80887 | 117 | 0.489327 | 4.738556 | false | false | false | false |
HTWDD/HTWDresden-iOS | HTWDD/Components/Canteen/Main/CanteensViewController.swift | 1 | 5264 | //
// CanteensViewController.swift
// HTWDD
//
// Created by Mustafa Karademir on 10.07.19.
// Copyright © 2019 HTW Dresden. All rights reserved.
//
import Foundation
import RxSwift
import Action
class CanteenViewController: UITableViewController, HasSideBarItem {
// MARK: - Properties
var context: (HasApiService & HasCanteen)!
var viewModel: CanteenViewModel!
weak var appCoordinator: AppCoordinator?
var canteenCoordinator: CanteenCoordinator?
private var items = [CanteenDetail]() {
didSet {
if oldValue != items {
tableView.reloadData()
}
}
}
private let stateView: EmptyResultsView = {
return EmptyResultsView().also {
$0.isHidden = true
}
}()
private lazy var action: Action<Void, [CanteenDetail]> = Action { [weak self] (_) -> Observable<[CanteenDetail]> in
guard let self = self else { return Observable.empty() }
return self.viewModel.load().observeOn(MainScheduler.instance)
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.apply {
$0.estimatedRowHeight = 200
$0.rowHeight = UITableView.automaticDimension
}
load()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.contentInset = UIEdgeInsets(top: 4, left: 0, bottom: 4, right: 0)
}
// MARK: - Data Request
private func load() {
action
.elements
.subscribe { [weak self] event in
guard let self = self else { return }
if let details = event.element {
self.items = details
self.stateView.isHidden = true
if details.isEmpty {
self.stateView.setup(with: EmptyResultsView.Configuration(icon: "🍽", title: R.string.localizable.canteenNoResultsTitle(), message: R.string.localizable.canteenNoResultsMessage(), hint: nil, action: nil))
}
}
}.disposed(by: rx_disposeBag)
action
.errors
.subscribe { [weak self] error in
guard let self = self else { return }
self.stateView.setup(with: EmptyResultsView.Configuration(icon: "😖", title: R.string.localizable.canteenNoResultsErrorTitle(), message: R.string.localizable.canteenNoResultsErrorMessage(), hint: nil, action: nil))
}
.disposed(by: rx_disposeBag)
action.execute()
}
}
// MARK: - Setup
extension CanteenViewController {
private func setup() {
refreshControl = UIRefreshControl().also {
$0.tintColor = .white
$0.rx.bind(to: action, input: ())
}
title = R.string.localizable.canteenPluralTitle()
tableView.apply {
$0.separatorStyle = .none
$0.backgroundColor = UIColor.htw.veryLightGrey
$0.backgroundView = stateView
$0.register(CanteenViewCell.self)
}
registerForPreviewing(with: self, sourceView: tableView)
}
}
// MARK: - TableView Datasource
extension CanteenViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(CanteenViewCell.self, for: indexPath)!
cell.setup(with: items[indexPath.row])
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
appCoordinator?.goTo(controller: .meal(canteenDetail: items[indexPath.row]), animated: true)
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = UIColor.clear
}
}
// MARK: 3D Touch Peek
extension CanteenViewController: UIViewControllerPreviewingDelegate {
private func createDetailController(indexPath: IndexPath) -> MealsTabViewController {
return R.storyboard.canteen.mealsTabViewController()!.also {
$0.context = self.context
$0.canteenDetail = items[indexPath.row]
$0.canteenCoordinator = self.canteenCoordinator
}
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = tableView.indexPathForRow(at: location) else { return nil }
return createDetailController(indexPath: indexPath)
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
navigationController?.pushViewController(viewControllerToCommit, animated: true)
}
}
| gpl-2.0 | 0682d393451ca8ba106a8162974e7cef | 33.136364 | 229 | 0.621647 | 5.084139 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/InstantPageTheme.swift | 1 | 17020 | //
// InstantPageTheme.swift
// Telegram
//
// Created by Mikhail Filimonov on 12/12/2018.
// Copyright © 2018 Telegram. All rights reserved.
//
import Cocoa
import InAppSettings
import Foundation
import Postbox
enum InstantPageFontStyle {
case sans
case serif
}
struct InstantPageFont {
let style: InstantPageFontStyle
let size: CGFloat
let lineSpacingFactor: CGFloat
}
struct InstantPageTextAttributes {
let font: InstantPageFont
let color: NSColor
let underline: Bool
init(font: InstantPageFont, color: NSColor, underline: Bool = false) {
self.font = font
self.color = color
self.underline = underline
}
func withUnderline(_ underline: Bool) -> InstantPageTextAttributes {
return InstantPageTextAttributes(font: self.font, color: self.color, underline: underline)
}
func withUpdatedFontStyles(sizeMultiplier: CGFloat, forceSerif: Bool) -> InstantPageTextAttributes {
return InstantPageTextAttributes(font: InstantPageFont(style: forceSerif ? .serif : self.font.style, size: floor(self.font.size * sizeMultiplier), lineSpacingFactor: self.font.lineSpacingFactor), color: self.color, underline: self.underline)
}
}
enum InstantPageTextCategoryType {
case kicker
case header
case subheader
case paragraph
case caption
case credit
case table
case article
}
struct InstantPageTextCategories {
let kicker: InstantPageTextAttributes
let header: InstantPageTextAttributes
let subheader: InstantPageTextAttributes
let paragraph: InstantPageTextAttributes
let caption: InstantPageTextAttributes
let credit: InstantPageTextAttributes
let table: InstantPageTextAttributes
let article: InstantPageTextAttributes
func attributes(type: InstantPageTextCategoryType, link: Bool) -> InstantPageTextAttributes {
switch type {
case .kicker:
return self.kicker.withUnderline(link)
case .header:
return self.header.withUnderline(link)
case .subheader:
return self.subheader.withUnderline(link)
case .paragraph:
return self.paragraph.withUnderline(link)
case .caption:
return self.caption.withUnderline(link)
case .credit:
return self.credit.withUnderline(link)
case .table:
return self.table.withUnderline(link)
case .article:
return self.article.withUnderline(link)
}
}
func withUpdatedFontStyles(sizeMultiplier: CGFloat, forceSerif: Bool) -> InstantPageTextCategories {
return InstantPageTextCategories(kicker: self.kicker.withUpdatedFontStyles(sizeMultiplier: sizeMultiplier, forceSerif: forceSerif), header: self.header.withUpdatedFontStyles(sizeMultiplier: sizeMultiplier, forceSerif: forceSerif), subheader: self.subheader.withUpdatedFontStyles(sizeMultiplier: sizeMultiplier, forceSerif: forceSerif), paragraph: self.paragraph.withUpdatedFontStyles(sizeMultiplier: sizeMultiplier, forceSerif: forceSerif), caption: self.caption.withUpdatedFontStyles(sizeMultiplier: sizeMultiplier, forceSerif: forceSerif), credit: self.credit.withUpdatedFontStyles(sizeMultiplier: sizeMultiplier, forceSerif: forceSerif), table: self.table.withUpdatedFontStyles(sizeMultiplier: sizeMultiplier, forceSerif: forceSerif), article: self.article.withUpdatedFontStyles(sizeMultiplier: sizeMultiplier, forceSerif: forceSerif))
}
}
final class InstantPageTheme {
let type: InstantPageThemeType
let pageBackgroundColor: NSColor
let textCategories: InstantPageTextCategories
let serif: Bool
let codeBlockBackgroundColor: NSColor
let linkColor: NSColor
let textHighlightColor: NSColor
let linkHighlightColor: NSColor
let markerColor: NSColor
let panelBackgroundColor: NSColor
let panelHighlightedBackgroundColor: NSColor
let panelPrimaryColor: NSColor
let panelSecondaryColor: NSColor
let panelAccentColor: NSColor
let tableBorderColor: NSColor
let tableHeaderColor: NSColor
let controlColor: NSColor
let imageTintColor: NSColor?
let overlayPanelColor: NSColor
init(type: InstantPageThemeType, pageBackgroundColor: NSColor, textCategories: InstantPageTextCategories, serif: Bool, codeBlockBackgroundColor: NSColor, linkColor: NSColor, textHighlightColor: NSColor, linkHighlightColor: NSColor, markerColor: NSColor, panelBackgroundColor: NSColor, panelHighlightedBackgroundColor: NSColor, panelPrimaryColor: NSColor, panelSecondaryColor: NSColor, panelAccentColor: NSColor, tableBorderColor: NSColor, tableHeaderColor: NSColor, controlColor: NSColor, imageTintColor: NSColor?, overlayPanelColor: NSColor) {
self.type = type
self.pageBackgroundColor = pageBackgroundColor
self.textCategories = textCategories
self.serif = serif
self.codeBlockBackgroundColor = codeBlockBackgroundColor
self.linkColor = linkColor
self.textHighlightColor = textHighlightColor
self.linkHighlightColor = linkHighlightColor
self.markerColor = markerColor
self.panelBackgroundColor = panelBackgroundColor
self.panelHighlightedBackgroundColor = panelHighlightedBackgroundColor
self.panelPrimaryColor = panelPrimaryColor
self.panelSecondaryColor = panelSecondaryColor
self.panelAccentColor = panelAccentColor
self.tableBorderColor = tableBorderColor
self.tableHeaderColor = tableHeaderColor
self.controlColor = controlColor
self.imageTintColor = imageTintColor
self.overlayPanelColor = overlayPanelColor
}
func withUpdatedFontStyles(sizeMultiplier: CGFloat, forceSerif: Bool) -> InstantPageTheme {
return InstantPageTheme(type: type, pageBackgroundColor: pageBackgroundColor, textCategories: self.textCategories.withUpdatedFontStyles(sizeMultiplier: sizeMultiplier, forceSerif: forceSerif), serif: forceSerif, codeBlockBackgroundColor: codeBlockBackgroundColor, linkColor: linkColor, textHighlightColor: textHighlightColor, linkHighlightColor: linkHighlightColor, markerColor: markerColor, panelBackgroundColor: panelBackgroundColor, panelHighlightedBackgroundColor: panelHighlightedBackgroundColor, panelPrimaryColor: panelPrimaryColor, panelSecondaryColor: panelSecondaryColor, panelAccentColor: panelAccentColor, tableBorderColor: tableBorderColor, tableHeaderColor: tableHeaderColor, controlColor: controlColor, imageTintColor: imageTintColor, overlayPanelColor: overlayPanelColor)
}
}
private let lightTheme = InstantPageTheme(
type: .light,
pageBackgroundColor: .white,
textCategories: InstantPageTextCategories(
kicker: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 15.0, lineSpacingFactor: 0.685), color: .black),
header: InstantPageTextAttributes(font: InstantPageFont(style: .serif, size: 24.0, lineSpacingFactor: 0.685), color: .black),
subheader: InstantPageTextAttributes(font: InstantPageFont(style: .serif, size: 19.0, lineSpacingFactor: 0.685), color: .black),
paragraph: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 17.0, lineSpacingFactor: 1.0), color: .black),
caption: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 15.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0x79828b)),
credit: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 13.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0x79828b)),
table: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 15.0, lineSpacingFactor: 1.0), color: .black),
article: InstantPageTextAttributes(font: InstantPageFont(style: .serif, size: 18.0, lineSpacingFactor: 1.0), color: .black)
),
serif: false,
codeBlockBackgroundColor: NSColor(rgb: 0xf5f8fc),
linkColor: NSColor(rgb: 0x007ee5),
textHighlightColor: NSColor(rgb: 0, alpha: 0.12),
linkHighlightColor: NSColor(rgb: 0x007ee5, alpha: 0.07),
markerColor: NSColor(rgb: 0xfef3bc),
panelBackgroundColor: NSColor(rgb: 0xf3f4f5),
panelHighlightedBackgroundColor: NSColor(rgb: 0xe7e7e7),
panelPrimaryColor: .black,
panelSecondaryColor: NSColor(rgb: 0x79828b),
panelAccentColor: NSColor(rgb: 0x007ee5),
tableBorderColor: NSColor(rgb: 0xe2e2e2),
tableHeaderColor: NSColor(rgb: 0xf4f4f4),
controlColor: NSColor(rgb: 0xc7c7cd),
imageTintColor: nil,
overlayPanelColor: .white
)
private let sepiaTheme = InstantPageTheme(
type: .sepia,
pageBackgroundColor: NSColor(rgb: 0xf8f1e2),
textCategories: InstantPageTextCategories(
kicker: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 15.0, lineSpacingFactor: 0.685), color: NSColor(rgb: 0x4f321d)),
header: InstantPageTextAttributes(font: InstantPageFont(style: .serif, size: 24.0, lineSpacingFactor: 0.685), color: NSColor(rgb: 0x4f321d)),
subheader: InstantPageTextAttributes(font: InstantPageFont(style: .serif, size: 19.0, lineSpacingFactor: 0.685), color: NSColor(rgb: 0x4f321d)),
paragraph: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 17.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0x4f321d)),
caption: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 15.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0x927e6b)),
credit: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 13.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0x927e6b)),
table: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 15.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0x4f321d)),
article: InstantPageTextAttributes(font: InstantPageFont(style: .serif, size: 18.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0x4f321d))
),
serif: false,
codeBlockBackgroundColor: NSColor(rgb: 0xefe7d6),
linkColor: NSColor(rgb: 0xd19600),
textHighlightColor: NSColor(rgb: 0, alpha: 0.1),
linkHighlightColor: NSColor(rgb: 0xd19600, alpha: 0.1),
markerColor: NSColor(rgb: 0xe5ddcd),
panelBackgroundColor: NSColor(rgb: 0xefe7d6),
panelHighlightedBackgroundColor: NSColor(rgb: 0xe3dccb),
panelPrimaryColor: .black,
panelSecondaryColor: NSColor(rgb: 0x927e6b),
panelAccentColor: NSColor(rgb: 0xd19601),
tableBorderColor: NSColor(rgb: 0xddd1b8),
tableHeaderColor: NSColor(rgb: 0xf0e7d4),
controlColor: NSColor(rgb: 0xddd1b8),
imageTintColor: nil,
overlayPanelColor: NSColor(rgb: 0xf8f1e2)
)
private let grayTheme = InstantPageTheme(
type: .gray,
pageBackgroundColor: NSColor(rgb: 0x5a5a5c),
textCategories: InstantPageTextCategories(
kicker: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 15.0, lineSpacingFactor: 0.685), color: NSColor(rgb: 0xcecece)),
header: InstantPageTextAttributes(font: InstantPageFont(style: .serif, size: 24.0, lineSpacingFactor: 0.685), color: NSColor(rgb: 0xcecece)),
subheader: InstantPageTextAttributes(font: InstantPageFont(style: .serif, size: 19.0, lineSpacingFactor: 0.685), color: NSColor(rgb: 0xcecece)),
paragraph: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 17.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0xcecece)),
caption: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 15.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0xa0a0a0)),
credit: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 13.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0xa0a0a0)),
table: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 15.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0xcecece)),
article: InstantPageTextAttributes(font: InstantPageFont(style: .serif, size: 18.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0xcecece))
),
serif: false,
codeBlockBackgroundColor: NSColor(rgb: 0x555556),
linkColor: NSColor(rgb: 0x5ac8fa),
textHighlightColor: NSColor(rgb: 0, alpha: 0.16),
linkHighlightColor: NSColor(rgb: 0x5ac8fa, alpha: 0.13),
markerColor: NSColor(rgb: 0x4b4b4b),
panelBackgroundColor: NSColor(rgb: 0x555556),
panelHighlightedBackgroundColor: NSColor(rgb: 0x505051),
panelPrimaryColor: NSColor(rgb: 0xcecece),
panelSecondaryColor: NSColor(rgb: 0xa0a0a0),
panelAccentColor: NSColor(rgb: 0x54b9f8),
tableBorderColor: NSColor(rgb: 0x484848),
tableHeaderColor: NSColor(rgb: 0x555556),
controlColor: NSColor(rgb: 0x484848),
imageTintColor: NSColor(rgb: 0xcecece),
overlayPanelColor: NSColor(rgb: 0x5a5a5c)
)
private let darkTheme = InstantPageTheme(
type: .dark,
pageBackgroundColor: NSColor(rgb: 0x000000),
textCategories: InstantPageTextCategories(
kicker: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 15.0, lineSpacingFactor: 0.685), color: NSColor(rgb: 0xb0b0b0)),
header: InstantPageTextAttributes(font: InstantPageFont(style: .serif, size: 24.0, lineSpacingFactor: 0.685), color: NSColor(rgb: 0xb0b0b0)),
subheader: InstantPageTextAttributes(font: InstantPageFont(style: .serif, size: 19.0, lineSpacingFactor: 0.685), color: NSColor(rgb: 0xb0b0b0)),
paragraph: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 17.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0xb0b0b0)),
caption: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 15.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0x6a6a6a)),
credit: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 13.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0x6a6a6a)),
table: InstantPageTextAttributes(font: InstantPageFont(style: .sans, size: 15.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0xb0b0b0)),
article: InstantPageTextAttributes(font: InstantPageFont(style: .serif, size: 18.0, lineSpacingFactor: 1.0), color: NSColor(rgb: 0xb0b0b0))
),
serif: false,
codeBlockBackgroundColor: NSColor(rgb: 0x131313),
linkColor: NSColor(rgb: 0x5ac8fa),
textHighlightColor: NSColor(rgb: 0xffffff, alpha: 0.1),
linkHighlightColor: NSColor(rgb: 0x5ac8fa, alpha: 0.2),
markerColor: NSColor(rgb: 0x313131),
panelBackgroundColor: NSColor(rgb: 0x131313),
panelHighlightedBackgroundColor: NSColor(rgb: 0x1f1f1f),
panelPrimaryColor: NSColor(rgb: 0xb0b0b0),
panelSecondaryColor: NSColor(rgb: 0x6a6a6a),
panelAccentColor: NSColor(rgb: 0x50b6f3),
tableBorderColor: NSColor(rgb: 0x303030),
tableHeaderColor: NSColor(rgb: 0x131313),
controlColor: NSColor(rgb: 0x303030),
imageTintColor: NSColor(rgb: 0xb0b0b0),
overlayPanelColor: NSColor(rgb: 0x232323)
)
private func fontSizeMultiplierForVariant(_ variant: InstantPagePresentationFontSize) -> CGFloat {
switch variant {
case .small:
return 0.85
case .standard:
return 1.0
case .large:
return 1.15
case .xlarge:
return 1.3
case .xxlarge:
return 1.5
}
}
func instantPageThemeTypeForSettingsAndTime(settings: InstantViewAppearance, time: Date?) -> InstantPageThemeType {
return .dark
// switch theme.colors.name {
//
// }
// if settings.autoNightMode {
// switch settings.themeType {
// case .light, .sepia, .gray:
// var useDarkTheme = false
// /*switch presentationTheme.name {
// case let .builtin(name):
// switch name {
// case .nightAccent, .nightGrayscale:
// useDarkTheme = true
// default:
// break
// }
// default:
// break
// }*/
// if let time = time {
// let calendar = Calendar.current
// let hour = calendar.component(.hour, from: time)
// if hour <= 8 || hour >= 22 {
// useDarkTheme = true
// }
// }
// if useDarkTheme {
// return .dark
// }
// case .dark:
// break
// }
// }
//
// return settings.themeType
}
func instantPageThemeForType(_ type: InstantPageThemeType, settings: InstantViewAppearance) -> InstantPageTheme {
switch type {
case .light:
return lightTheme.withUpdatedFontStyles(sizeMultiplier: fontSizeMultiplierForVariant(.standard), forceSerif: settings.fontSerif)
case .sepia:
return sepiaTheme.withUpdatedFontStyles(sizeMultiplier: fontSizeMultiplierForVariant(.standard), forceSerif: settings.fontSerif)
case .gray:
return grayTheme.withUpdatedFontStyles(sizeMultiplier: fontSizeMultiplierForVariant(.standard), forceSerif: settings.fontSerif)
case .dark:
return darkTheme.withUpdatedFontStyles(sizeMultiplier: fontSizeMultiplierForVariant(.standard), forceSerif: settings.fontSerif)
}
}
| gpl-2.0 | d29ba441f166028d4baabd0776077276 | 49.20354 | 846 | 0.72566 | 4.080316 | false | false | false | false |
OpenKitten/MongoKitten | Sources/MongoClient/ConnectionContext.swift | 2 | 2008 | import NIO
import Logging
import MongoCore
internal struct MongoResponseContext {
let requestId: Int32
let result: EventLoopPromise<MongoServerReply>
}
public final class MongoClientContext {
private var queries = [MongoResponseContext]()
internal var serverHandshake: ServerHandshake? {
didSet {
if let version = serverHandshake?.maxWireVersion, version.isDeprecated {
logger.warning("MongoDB server is outdated, please upgrade MongoDB")
}
}
}
internal var didError = false
let logger: Logger
internal func handleReply(_ reply: MongoServerReply) -> Bool {
guard let index = queries.firstIndex(where: { $0.requestId == reply.responseTo }) else {
return false
}
let query = queries[index]
queries.remove(at: index)
query.result.succeed(reply)
return true
}
internal func awaitReply(toRequestId requestId: Int32, completing result: EventLoopPromise<MongoServerReply>) {
queries.append(MongoResponseContext(requestId: requestId, result: result))
}
deinit {
self.cancelQueries(MongoError(.queryFailure, reason: .connectionClosed))
}
public func failQuery(byRequestId requestId: Int32, error: Error) {
guard let index = queries.firstIndex(where: { $0.requestId == requestId }) else {
return
}
let query = queries[index]
queries.remove(at: index)
query.result.fail(error)
}
public func cancelQueries(_ error: Error) {
for query in queries {
query.result.fail(error)
}
queries = []
}
public init(logger: Logger) {
self.logger = logger
}
}
struct MongoClientRequest<Request: MongoRequestMessage> {
let command: Request
let namespace: MongoNamespace
init(command: Request, namespace: MongoNamespace) {
self.command = command
self.namespace = namespace
}
}
| mit | a01f8d3c1d4343b77a88efef5667b3ad | 26.888889 | 115 | 0.64243 | 4.648148 | false | false | false | false |
MA806P/SwiftDemo | Developing_iOS_10_Apps_with_Swift/SwiftDemo/SwiftDemo/FaceIt/EmotionsViewController.swift | 1 | 1390 | //
// EmotionsViewController.swift
// SwiftDemo
//
// Created by 159CaiMini02 on 17/3/23.
// Copyright © 2017年 myz. All rights reserved.
//
import UIKit
class EmotionsViewController: VCLLoggingViewController {
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var destinationViewController = segue.destination
if let navigationController = destinationViewController as? UINavigationController {
destinationViewController = navigationController.visibleViewController ?? destinationViewController
}
if let faceViewController = destinationViewController as? FaceViewController,
let identifier = segue.identifier,
let expression = emotionalFaces[identifier] {
faceViewController.expression = expression
faceViewController.navigationItem.title = (sender as? UIButton)?.currentTitle
}
}
private let emotionalFaces: Dictionary<String, FacialExpression> = [
"sad" : FacialExpression(eyes: .closed, mouth: .frown),
"happy" : FacialExpression(eyes: .open, mouth: .smile),
"worried" : FacialExpression(eyes: .open, mouth: .smirk)
]
@IBAction func presentBack(_ sender: Any) {
self.navigationController?.dismiss(animated: true, completion: nil)
}
}
| apache-2.0 | ddb59d07d00adede0d33ae4e1ceb6732 | 32.829268 | 111 | 0.674117 | 4.953571 | false | false | false | false |
PlanTeam/BSON | Sources/BSON/Types/Timestamp.swift | 1 | 537 | /// Special internal type used by MongoDB replication and sharding. First 4 bytes are an increment, second 4 are a timestamp.
public struct Timestamp: Primitive, Hashable {
public var increment: Int32
public var timestamp: Int32
public static func ==(lhs: Timestamp, rhs: Timestamp) -> Bool {
return lhs.increment == rhs.increment && lhs.timestamp == rhs.timestamp
}
public init(increment: Int32, timestamp: Int32) {
self.increment = increment
self.timestamp = timestamp
}
}
| mit | b1144fd3e18d3ed4be3fe07cac960191 | 37.357143 | 125 | 0.675978 | 4.669565 | false | false | false | false |
MukeshKumarS/Swift | stdlib/public/core/SwiftNativeNSArray.swift | 1 | 9051 | //===--- SwiftNativeNSArray.swift -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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
//
//===----------------------------------------------------------------------===//
//
// _ContiguousArrayStorageBase supplies the implementation of the
// _NSArrayCoreType API (and thus, NSArray the API) for our
// _ContiguousArrayStorage<T>. We can't put this implementation
// directly on _ContiguousArrayStorage because generic classes can't
// override Objective-C selectors.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
/// Returns `true` iff the given `index` is valid as a position, i.e. `0
/// ≤ index ≤ count`.
@_transparent
internal func _isValidArrayIndex(index: Int, _ count: Int) -> Bool {
return (index >= 0) && (index <= count)
}
/// Returns `true` iff the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
@_transparent
internal func _isValidArraySubscript(index: Int, _ count: Int) -> Bool {
return (index >= 0) && (index < count)
}
/// An `NSArray` with Swift-native reference counting and contiguous
/// storage.
class _SwiftNativeNSArrayWithContiguousStorage
: _SwiftNativeNSArray { // Provides NSArray inheritance and native refcounting
// Operate on our contiguous storage
internal func withUnsafeBufferOfObjects<R>(
@noescape body: UnsafeBufferPointer<AnyObject> throws -> R
) rethrows -> R {
_sanityCheckFailure(
"Must override withUnsafeBufferOfObjects in derived classes")
}
}
// Implement the APIs required by NSArray
extension _SwiftNativeNSArrayWithContiguousStorage: _NSArrayCoreType {
@objc internal var count: Int {
return withUnsafeBufferOfObjects { $0.count }
}
@objc internal func objectAtIndex(index: Int) -> AnyObject {
return withUnsafeBufferOfObjects {
objects in
_precondition(
_isValidArraySubscript(index, objects.count),
"Array index out of range")
return objects[index]
}
}
@objc internal func getObjects(
aBuffer: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange
) {
return withUnsafeBufferOfObjects {
objects in
_precondition(
_isValidArrayIndex(range.location, objects.count),
"Array index out of range")
_precondition(
_isValidArrayIndex(
range.location + range.length, objects.count),
"Array index out of range")
// These objects are "returned" at +0, so treat them as values to
// avoid retains.
UnsafeMutablePointer<Int>(aBuffer).initializeFrom(
UnsafeMutablePointer(objects.baseAddress + range.location),
count: range.length)
}
}
@objc internal func countByEnumeratingWithState(
state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>, count: Int
) -> Int {
var enumerationState = state.memory
if enumerationState.state != 0 {
return 0
}
return withUnsafeBufferOfObjects {
objects in
enumerationState.mutationsPtr = _fastEnumerationStorageMutationsPtr
enumerationState.itemsPtr = unsafeBitCast(
objects.baseAddress,
AutoreleasingUnsafeMutablePointer<AnyObject?>.self)
enumerationState.state = 1
state.memory = enumerationState
return objects.count
}
}
@objc internal func copyWithZone(_: _SwiftNSZone) -> AnyObject {
return self
}
}
/// An `NSArray` whose contiguous storage is created and filled, upon
/// first access, by bridging the elements of a Swift `Array`.
///
/// Ideally instances of this class would be allocated in-line in the
/// buffers used for Array storage.
@objc internal final class _SwiftDeferredNSArray
: _SwiftNativeNSArrayWithContiguousStorage {
// This stored property should be stored at offset zero. We perform atomic
// operations on it.
//
// Do not access this property directly.
internal var _heapBufferBridged_DoNotUse: AnyObject? = nil
// When this class is allocated inline, this property can become a
// computed one.
internal let _nativeStorage: _ContiguousArrayStorageBase
internal var _heapBufferBridgedPtr: UnsafeMutablePointer<AnyObject?> {
return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self))
}
internal typealias HeapBufferStorage = _HeapBufferStorage<Int, AnyObject>
internal var _heapBufferBridged: HeapBufferStorage? {
if let ref =
_stdlib_atomicLoadARCRef(object: _heapBufferBridgedPtr) {
return unsafeBitCast(ref, HeapBufferStorage.self)
}
return nil
}
internal init(_nativeStorage: _ContiguousArrayStorageBase) {
self._nativeStorage = _nativeStorage
}
internal func _destroyBridgedStorage(hb: HeapBufferStorage?) {
if let bridgedStorage = hb {
let heapBuffer = _HeapBuffer(bridgedStorage)
let count = heapBuffer.value
heapBuffer.baseAddress.destroy(count)
}
}
deinit {
_destroyBridgedStorage(_heapBufferBridged)
}
internal override func withUnsafeBufferOfObjects<R>(
@noescape body: UnsafeBufferPointer<AnyObject> throws -> R
) rethrows -> R {
repeat {
var buffer: UnsafeBufferPointer<AnyObject>
// If we've already got a buffer of bridged objects, just use it
if let bridgedStorage = _heapBufferBridged {
let heapBuffer = _HeapBuffer(bridgedStorage)
buffer = UnsafeBufferPointer(
start: heapBuffer.baseAddress, count: heapBuffer.value)
}
// If elements are bridged verbatim, the native buffer is all we
// need, so return that.
else if let buf = _nativeStorage._withVerbatimBridgedUnsafeBuffer(
{ $0 }
) {
buffer = buf
}
else {
// Create buffer of bridged objects.
let objects = _nativeStorage._getNonVerbatimBridgedHeapBuffer()
// Atomically store a reference to that buffer in self.
if !_stdlib_atomicInitializeARCRef(
object: _heapBufferBridgedPtr, desired: objects.storage!) {
// Another thread won the race. Throw out our buffer
let storage: HeapBufferStorage = unsafeDowncast(objects.storage!)
_destroyBridgedStorage(storage)
}
continue // Try again
}
defer { _fixLifetime(self) }
return try body(buffer)
}
while true
}
/// Returns the number of elements in the array.
///
/// This override allows the count to be read without triggering
/// bridging of array elements.
@objc
internal override var count: Int {
if let bridgedStorage = _heapBufferBridged {
return _HeapBuffer(bridgedStorage).value
}
// Check if elements are bridged verbatim.
return _nativeStorage._withVerbatimBridgedUnsafeBuffer { $0.count }
?? _nativeStorage._getNonVerbatimBridgedCount()
}
}
#else
// Empty shim version for non-objc platforms.
class _SwiftNativeNSArrayWithContiguousStorage {}
#endif
/// Base class of the heap buffer backing arrays.
internal class _ContiguousArrayStorageBase
: _SwiftNativeNSArrayWithContiguousStorage {
#if _runtime(_ObjC)
internal override func withUnsafeBufferOfObjects<R>(
@noescape body: UnsafeBufferPointer<AnyObject> throws -> R
) rethrows -> R {
if let result = try _withVerbatimBridgedUnsafeBuffer(body) {
return result
}
_sanityCheckFailure(
"Can't use a buffer of non-verbatim-bridged elements as an NSArray")
}
/// If the stored type is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements and return the result.
/// Otherwise, return `nil`.
internal func _withVerbatimBridgedUnsafeBuffer<R>(
@noescape body: UnsafeBufferPointer<AnyObject> throws -> R
) rethrows -> R? {
_sanityCheckFailure(
"Concrete subclasses must implement _withVerbatimBridgedUnsafeBuffer")
}
internal func _getNonVerbatimBridgedCount(dummy: Void) -> Int {
_sanityCheckFailure(
"Concrete subclasses must implement _getNonVerbatimBridgedCount")
}
internal func _getNonVerbatimBridgedHeapBuffer(dummy: Void) ->
_HeapBuffer<Int, AnyObject> {
_sanityCheckFailure(
"Concrete subclasses must implement _getNonVerbatimBridgedHeapBuffer")
}
#endif
func canStoreElementsOfDynamicType(_: Any.Type) -> Bool {
_sanityCheckFailure(
"Concrete subclasses must implement canStoreElementsOfDynamicType")
}
/// A type that every element in the array is.
var staticElementType: Any.Type {
_sanityCheckFailure(
"Concrete subclasses must implement staticElementType")
}
deinit {
_sanityCheck(
self !== _emptyArrayStorage, "Deallocating empty array storage?!")
}
}
| apache-2.0 | f40484fa3ccee95defc36e32c5865fb4 | 31.535971 | 80 | 0.686567 | 5.177447 | false | false | false | false |
segmentio/analytics-ios | SegmentTests/ContextTest.swift | 1 | 2366 | //
// ContextTest.swift
// Analytics
//
// Created by Tony Xiao on 9/20/16.
// Copyright © 2016 Segment. All rights reserved.
//
import Segment
import XCTest
class ContextTests: XCTestCase {
var analytics: Analytics!
override func setUp() {
super.setUp()
let config = AnalyticsConfiguration(writeKey: "foobar")
analytics = Analytics(configuration: config)
}
func testThrowsWhenUsedIncorrectly() {
var context: Context?
var exception: NSException?
exception = objc_tryCatch {
context = Context()
}
XCTAssertNil(context)
XCTAssertNotNil(exception)
}
func testInitializedCorrectly() {
let context = Context(analytics: analytics)
XCTAssertEqual(context._analytics, analytics)
XCTAssertEqual(context.eventType, EventType.undefined)
}
func testAcceptsModifications() {
let context = Context(analytics: analytics)
let newContext = context.modify { context in
context.payload = TrackPayload()
context.payload?.userId = "sloth"
context.eventType = .track
}
XCTAssertEqual(newContext.payload?.userId, "sloth")
XCTAssertEqual(newContext.eventType, EventType.track)
}
func testModifiesCopyInDebugMode() {
let context = Context(analytics: analytics).modify { context in
context.debug = true
context.eventType = .track
}
XCTAssertEqual(context.debug, true)
let newContext = context.modify { context in
context.eventType = .identify
}
XCTAssertNotEqual(context, newContext)
XCTAssertEqual(newContext.eventType, .identify)
XCTAssertEqual(context.eventType, .track)
}
func testModifiesSelfInNonDebug() {
let context = Context(analytics: analytics).modify { context in
context.debug = false
context.eventType = .track
}
XCTAssertFalse(context.debug)
let newContext = context.modify { context in
context.eventType = .identify
}
XCTAssertEqual(context, newContext)
XCTAssertEqual(newContext.eventType, .identify)
XCTAssertEqual(context.eventType, .identify)
}
}
| mit | 4dcf34bc06f78ac3ded0f19a728308ef | 28.197531 | 71 | 0.61649 | 5.096983 | false | true | false | false |
dathtcheapgo/Jira-Demo | Driver/MVC/Booking/Controller/BookingCurrentTripsViewController.swift | 1 | 1770 | //
// BookingCurrentTripsViewController.swift
// Driver
//
// Created by Tien Dat on 11/9/16.
// Copyright © 2016 Tien Dat. All rights reserved.
//
import UIKit
class CurrentTripCell: UITableViewCell {
}
class BookingCurrentTripsViewController: BaseViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 75
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func crossBtnPressed(_ sender: AnyObject) {
_ = navigationController?.popViewController(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.
}
*/
}
extension BookingCurrentTripsViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CurrentTripCell")
return cell!
}
}
| mit | 830c16f49c916e30c17fbb2e47667d0d | 26.215385 | 106 | 0.673262 | 5.510903 | false | false | false | false |
alessiobrozzi/firefox-ios | Client/Frontend/Widgets/ActivityStreamHighlightCell.swift | 1 | 9175 | /* 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
import Shared
import Storage
struct ActivityStreamHighlightCellUX {
static let LabelColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.black : UIColor(rgb: 0x353535)
static let BorderWidth: CGFloat = 0.5
static let CellSideOffset = 20
static let TitleLabelOffset = 2
static let CellTopBottomOffset = 12
static let SiteImageViewSize: CGSize = UIDevice.current.userInterfaceIdiom == .pad ? CGSize(width: 99, height: 120) : CGSize(width: 99, height: 90)
static let StatusIconSize = 12
static let FaviconSize = CGSize(width: 45, height: 45)
static let DescriptionLabelColor = UIColor(colorString: "919191")
static let SelectedOverlayColor = UIColor(white: 0.0, alpha: 0.25)
static let CornerRadius: CGFloat = 3
static let BorderColor = UIColor(white: 0, alpha: 0.1)
}
class ActivityStreamHighlightCell: UICollectionViewCell {
fileprivate lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFontMediumBoldActivityStream
titleLabel.textColor = ActivityStreamHighlightCellUX.LabelColor
titleLabel.textAlignment = .left
titleLabel.numberOfLines = 3
return titleLabel
}()
fileprivate lazy var descriptionLabel: UILabel = {
let descriptionLabel = UILabel()
descriptionLabel.font = DynamicFontHelper.defaultHelper.DeviceFontDescriptionActivityStream
descriptionLabel.textColor = ActivityStreamHighlightCellUX.DescriptionLabelColor
descriptionLabel.textAlignment = .left
descriptionLabel.numberOfLines = 1
return descriptionLabel
}()
fileprivate lazy var domainLabel: UILabel = {
let descriptionLabel = UILabel()
descriptionLabel.font = DynamicFontHelper.defaultHelper.DeviceFontDescriptionActivityStream
descriptionLabel.textColor = ActivityStreamHighlightCellUX.DescriptionLabelColor
descriptionLabel.textAlignment = .left
descriptionLabel.numberOfLines = 1
descriptionLabel.setContentCompressionResistancePriority(1000, for: UILayoutConstraintAxis.vertical)
return descriptionLabel
}()
lazy var siteImageView: UIImageView = {
let siteImageView = UIImageView()
siteImageView.contentMode = UIViewContentMode.scaleAspectFit
siteImageView.clipsToBounds = true
siteImageView.contentMode = UIViewContentMode.center
siteImageView.layer.cornerRadius = ActivityStreamHighlightCellUX.CornerRadius
siteImageView.layer.borderColor = ActivityStreamHighlightCellUX.BorderColor.cgColor
siteImageView.layer.borderWidth = ActivityStreamHighlightCellUX.BorderWidth
siteImageView.layer.masksToBounds = true
return siteImageView
}()
fileprivate lazy var statusIcon: UIImageView = {
let statusIcon = UIImageView()
statusIcon.contentMode = UIViewContentMode.scaleAspectFit
statusIcon.clipsToBounds = true
statusIcon.layer.cornerRadius = ActivityStreamHighlightCellUX.CornerRadius
return statusIcon
}()
fileprivate lazy var selectedOverlay: UIView = {
let selectedOverlay = UIView()
selectedOverlay.backgroundColor = ActivityStreamHighlightCellUX.SelectedOverlayColor
selectedOverlay.isHidden = true
return selectedOverlay
}()
override var isSelected: Bool {
didSet {
self.selectedOverlay.isHidden = !isSelected
}
}
override init(frame: CGRect) {
super.init(frame: frame)
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
isAccessibilityElement = true
contentView.addSubview(siteImageView)
contentView.addSubview(descriptionLabel)
contentView.addSubview(selectedOverlay)
contentView.addSubview(titleLabel)
contentView.addSubview(statusIcon)
contentView.addSubview(domainLabel)
siteImageView.snp.makeConstraints { make in
make.top.equalTo(contentView)
make.leading.trailing.equalTo(contentView)
make.centerX.equalTo(contentView)
make.height.equalTo(ActivityStreamHighlightCellUX.SiteImageViewSize)
}
selectedOverlay.snp.makeConstraints { make in
make.edges.equalTo(contentView)
}
domainLabel.snp.makeConstraints { make in
make.leading.equalTo(siteImageView)
make.trailing.equalTo(contentView)
make.top.equalTo(siteImageView.snp.bottom).offset(5)
}
titleLabel.snp.makeConstraints { make in
make.leading.equalTo(siteImageView)
make.trailing.equalTo(contentView)
make.top.equalTo(domainLabel.snp.bottom).offset(5)
}
descriptionLabel.snp.makeConstraints { make in
make.leading.equalTo(statusIcon.snp.trailing).offset(ActivityStreamHighlightCellUX.TitleLabelOffset)
make.bottom.equalTo(contentView)
}
statusIcon.snp.makeConstraints { make in
make.size.equalTo(ActivityStreamHighlightCellUX.StatusIconSize)
make.leading.equalTo(siteImageView)
make.bottom.equalTo(contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
self.siteImageView.image = nil
contentView.backgroundColor = UIColor.clear
siteImageView.backgroundColor = UIColor.clear
}
func configureWithSite(_ site: Site) {
if let mediaURLStr = site.metadata?.mediaURL,
let mediaURL = URL(string: mediaURLStr) {
self.siteImageView.sd_setImage(with: mediaURL)
self.siteImageView.contentMode = .scaleAspectFill
} else {
self.siteImageView.setFavicon(forSite: site, onCompletion: { [weak self] (color, url) in
self?.siteImageView.image = self?.siteImageView.image?.createScaled(ActivityStreamHighlightCellUX.FaviconSize)
})
self.siteImageView.contentMode = .center
}
self.domainLabel.text = site.tileURL.hostSLD
self.titleLabel.text = site.title.characters.count <= 1 ? site.url : site.title
if let bookmarked = site.bookmarked, bookmarked {
self.descriptionLabel.text = "Bookmarked"
self.statusIcon.image = UIImage(named: "context_bookmark")
} else {
self.descriptionLabel.text = "Visited"
self.statusIcon.image = UIImage(named: "context_viewed")
}
}
}
struct HighlightIntroCellUX {
static let foxImageName = "fox_finder"
static let margin: CGFloat = 20
static let foxImageWidth: CGFloat = 168
}
class HighlightIntroCell: UICollectionViewCell {
lazy var titleLabel: UILabel = {
let textLabel = UILabel()
textLabel.font = DynamicFontHelper.defaultHelper.DeviceFontMediumBold
textLabel.textColor = UIColor.black
textLabel.numberOfLines = 1
textLabel.adjustsFontSizeToFitWidth = true
textLabel.minimumScaleFactor = 0.8
return textLabel
}()
lazy var mainImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: HighlightIntroCellUX.foxImageName)
return imageView
}()
lazy var descriptionLabel: UILabel = {
let label = UILabel()
label.font = DynamicFontHelper.defaultHelper.DeviceFontDescriptionActivityStream
label.textColor = UIColor.darkGray
label.numberOfLines = 0
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(titleLabel)
contentView.addSubview(mainImageView)
contentView.addSubview(descriptionLabel)
titleLabel.text = Strings.HighlightIntroTitle
descriptionLabel.text = Strings.HighlightIntroDescription
let titleInsets = UIEdgeInsets(top: HighlightIntroCellUX.margin, left: HighlightIntroCellUX.margin, bottom: 0, right: 0)
titleLabel.snp.makeConstraints { make in
make.leading.top.equalTo(self.contentView).inset(titleInsets)
make.trailing.equalTo(mainImageView.snp.leading)
}
mainImageView.snp.makeConstraints { make in
make.top.equalTo(self.contentView)
make.width.equalTo(HighlightIntroCellUX.foxImageWidth)
make.trailing.equalTo(self.contentView).offset(-HighlightIntroCellUX.margin/2)
}
descriptionLabel.snp.makeConstraints { make in
make.leading.trailing.equalTo(titleLabel)
make.top.equalTo(titleLabel.snp.bottom).offset(HighlightIntroCellUX.margin/2)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 | 33b73b7a82e79029063b63441352be43 | 37.71308 | 151 | 0.693188 | 5.174845 | false | false | false | false |
mshhmzh/firefox-ios | Client/Frontend/Browser/TopTabsViewController.swift | 1 | 13243 | /* 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 Foundation
import Shared
import WebKit
struct TopTabsUX {
static let TopTabsViewHeight: CGFloat = 40
static let TopTabsBackgroundNormalColor = UIColor(red: 235/255, green: 235/255, blue: 235/255, alpha: 1)
static let TopTabsBackgroundPrivateColor = UIColor(red: 90/255, green: 90/255, blue: 90/255, alpha: 1)
static let TopTabsBackgroundNormalColorInactive = UIColor(red: 53/255, green: 53/255, blue: 53/255, alpha: 1)
static let TopTabsBackgroundPadding: CGFloat = 35
static let TopTabsBackgroundShadowWidth: CGFloat = 35
static let TabWidth: CGFloat = 180
static let CollectionViewPadding: CGFloat = 15
static let FaderPading: CGFloat = 5
static let BackgroundSeparatorLinePadding: CGFloat = 5
static let TabTitleWidth: CGFloat = 110
static let TabTitlePadding: CGFloat = 10
}
protocol TopTabsDelegate: class {
func topTabsDidPressTabs()
func topTabsDidPressNewTab()
func topTabsDidPressPrivateTab()
func topTabsDidChangeTab()
}
protocol TopTabCellDelegate: class {
func tabCellDidClose(cell: TopTabCell)
}
class TopTabsViewController: UIViewController {
let tabManager: TabManager
weak var delegate: TopTabsDelegate?
var isPrivate = false
lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: TopTabsViewLayout())
collectionView.registerClass(TopTabCell.self, forCellWithReuseIdentifier: TopTabCell.Identifier)
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.bounces = false
collectionView.clipsToBounds = false
collectionView.accessibilityIdentifier = "Top Tabs View"
return collectionView
}()
private lazy var tabsButton: TabsButton = {
let tabsButton = TabsButton.tabTrayButton()
tabsButton.addTarget(self, action: #selector(TopTabsViewController.tabsTrayTapped), forControlEvents: UIControlEvents.TouchUpInside)
return tabsButton
}()
private lazy var newTab: UIButton = {
let newTab = UIButton.newTabButton()
newTab.addTarget(self, action: #selector(TopTabsViewController.newTabTapped), forControlEvents: UIControlEvents.TouchUpInside)
return newTab
}()
private lazy var privateTab: UIButton = {
let privateTab = UIButton.privateModeButton()
privateTab.addTarget(self, action: #selector(TopTabsViewController.togglePrivateModeTapped), forControlEvents: UIControlEvents.TouchUpInside)
return privateTab
}()
private lazy var tabLayoutDelegate: TopTabsLayoutDelegate = {
let delegate = TopTabsLayoutDelegate()
delegate.tabSelectionDelegate = self
return delegate
}()
private var tabsToDisplay: [Tab] {
return self.isPrivate ? tabManager.privateTabs : tabManager.normalTabs
}
init(tabManager: TabManager) {
self.tabManager = tabManager
super.init(nibName: nil, bundle: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TopTabsViewController.reloadFavicons), name: FaviconManager.FaviconDidLoad, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: FaviconManager.FaviconDidLoad, object: nil)
self.tabManager.removeDelegate(self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
collectionView.dataSource = self
collectionView.delegate = tabLayoutDelegate
collectionView.reloadData()
self.scrollToCurrentTab(false, centerCell: true)
}
override func viewDidLoad() {
super.viewDidLoad()
tabManager.addDelegate(self)
let topTabFader = TopTabFader()
view.addSubview(tabsButton)
view.addSubview(newTab)
view.addSubview(privateTab)
view.addSubview(topTabFader)
topTabFader.addSubview(collectionView)
newTab.snp_makeConstraints { make in
make.centerY.equalTo(view)
make.trailing.equalTo(view)
make.size.equalTo(UIConstants.ToolbarHeight)
}
tabsButton.snp_makeConstraints { make in
make.centerY.equalTo(view)
make.trailing.equalTo(newTab.snp_leading)
make.size.equalTo(UIConstants.ToolbarHeight)
}
privateTab.snp_makeConstraints { make in
make.centerY.equalTo(view)
make.leading.equalTo(view)
make.size.equalTo(UIConstants.ToolbarHeight)
}
topTabFader.snp_makeConstraints { make in
make.top.bottom.equalTo(view)
make.leading.equalTo(privateTab.snp_trailing).offset(-TopTabsUX.FaderPading)
make.trailing.equalTo(tabsButton.snp_leading).offset(TopTabsUX.FaderPading)
}
collectionView.snp_makeConstraints { make in
make.top.bottom.equalTo(view)
make.leading.equalTo(privateTab.snp_trailing).offset(-TopTabsUX.CollectionViewPadding)
make.trailing.equalTo(tabsButton.snp_leading).offset(TopTabsUX.CollectionViewPadding)
}
view.backgroundColor = UIColor.blackColor()
tabsButton.applyTheme(Theme.NormalMode)
if let currentTab = tabManager.selectedTab {
applyTheme(currentTab.isPrivate ? Theme.PrivateMode : Theme.NormalMode)
}
updateTabCount(tabsToDisplay.count)
}
func updateTabCount(count: Int, animated: Bool = true) {
self.tabsButton.updateTabCount(count, animated: animated)
}
func tabsTrayTapped() {
delegate?.topTabsDidPressTabs()
}
func newTabTapped() {
if let currentTab = tabManager.selectedTab, let index = tabsToDisplay.indexOf(currentTab),
let cell = collectionView.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as? TopTabCell {
cell.selectedTab = false
if index > 0 {
cell.seperatorLine = true
}
}
delegate?.topTabsDidPressNewTab()
collectionView.performBatchUpdates({ _ in
let count = self.collectionView.numberOfItemsInSection(0)
self.collectionView.insertItemsAtIndexPaths([NSIndexPath(forItem: count, inSection: 0)])
}, completion: { finished in
if finished {
self.scrollToCurrentTab()
}
})
}
func togglePrivateModeTapped() {
delegate?.topTabsDidPressPrivateTab()
self.collectionView.reloadData()
self.scrollToCurrentTab(false, centerCell: true)
}
func closeTab() {
delegate?.topTabsDidPressTabs()
}
func reloadFavicons() {
self.collectionView.reloadData()
}
func scrollToCurrentTab(animated: Bool = true, centerCell: Bool = false) {
guard let currentTab = tabManager.selectedTab, let index = tabsToDisplay.indexOf(currentTab) where !collectionView.frame.isEmpty else {
return
}
if let frame = collectionView.layoutAttributesForItemAtIndexPath(NSIndexPath(forRow: index, inSection: 0))?.frame {
if centerCell {
collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0), atScrollPosition: .CenteredHorizontally, animated: false)
}
else {
// Padding is added to ensure the tab is completely visible (none of the tab is under the fader)
let padFrame = frame.insetBy(dx: -(TopTabsUX.TopTabsBackgroundShadowWidth+TopTabsUX.FaderPading), dy: 0)
collectionView.scrollRectToVisible(padFrame, animated: animated)
}
}
}
}
extension TopTabsViewController: Themeable {
func applyTheme(themeName: String) {
tabsButton.applyTheme(themeName)
isPrivate = (themeName == Theme.PrivateMode)
}
}
extension TopTabsViewController: TopTabCellDelegate {
func tabCellDidClose(cell: TopTabCell) {
guard let indexPath = collectionView.indexPathForCell(cell) else {
return
}
let tab = tabsToDisplay[indexPath.item]
var selectedTab = false
if tab == tabManager.selectedTab {
selectedTab = true
delegate?.topTabsDidChangeTab()
}
if tabsToDisplay.count == 1 {
tabManager.removeTab(tab)
tabManager.selectTab(tabsToDisplay.first)
collectionView.reloadData()
}
else {
var nextTab: Tab
let currentIndex = indexPath.item
if tabsToDisplay.count-1 > currentIndex {
nextTab = tabsToDisplay[currentIndex+1]
}
else {
nextTab = tabsToDisplay[currentIndex-1]
}
tabManager.removeTab(tab)
if selectedTab {
tabManager.selectTab(nextTab)
}
self.collectionView.performBatchUpdates({
self.collectionView.deleteItemsAtIndexPaths([indexPath])
}, completion: { finished in
self.collectionView.reloadData()
})
}
}
}
extension TopTabsViewController: UICollectionViewDataSource {
@objc func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let index = indexPath.item
let tabCell = collectionView.dequeueReusableCellWithReuseIdentifier(TopTabCell.Identifier, forIndexPath: indexPath) as! TopTabCell
tabCell.delegate = self
let tab = tabsToDisplay[index]
tabCell.style = tab.isPrivate ? .Dark : .Light
tabCell.titleText.text = tab.displayTitle
if tab.displayTitle.isEmpty {
if (tab.url?.baseDomain()?.contains("localhost") ?? true) {
tabCell.titleText.text = AppMenuConfiguration.NewTabTitleString
}
else {
tabCell.titleText.text = tab.displayURL?.absoluteString
}
tabCell.accessibilityLabel = AboutUtils.getAboutComponent(tab.url)
tabCell.closeButton.accessibilityLabel = String(format: Strings.TopSitesRemoveButtonAccessibilityLabel, tabCell.titleText.text ?? "")
}
else {
tabCell.accessibilityLabel = tab.displayTitle
tabCell.closeButton.accessibilityLabel = String(format: Strings.TopSitesRemoveButtonAccessibilityLabel, tab.displayTitle)
}
tabCell.selectedTab = (tab == tabManager.selectedTab)
if index > 0 && index < tabsToDisplay.count && tabsToDisplay[index] != tabManager.selectedTab && tabsToDisplay[index-1] != tabManager.selectedTab {
tabCell.seperatorLine = true
}
else {
tabCell.seperatorLine = false
}
if let favIcon = tab.displayFavicon,
let url = NSURL(string: favIcon.url) {
tabCell.favicon.sd_setImageWithURL(url)
} else {
var defaultFavicon = UIImage(named: "defaultFavicon")
if tab.isPrivate {
defaultFavicon = defaultFavicon?.imageWithRenderingMode(.AlwaysTemplate)
tabCell.favicon.image = defaultFavicon
tabCell.favicon.tintColor = UIColor.whiteColor()
} else {
tabCell.favicon.image = defaultFavicon
}
}
return tabCell
}
@objc func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tabsToDisplay.count
}
}
extension TopTabsViewController: TabSelectionDelegate {
func didSelectTabAtIndex(index: Int) {
let tab = tabsToDisplay[index]
tabManager.selectTab(tab)
collectionView.reloadData()
collectionView.setNeedsDisplay()
delegate?.topTabsDidChangeTab()
scrollToCurrentTab()
}
}
extension TopTabsViewController : WKNavigationDelegate {
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
collectionView.reloadData()
}
}
extension TopTabsViewController: TabManagerDelegate {
func tabManager(tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) {}
func tabManager(tabManager: TabManager, didCreateTab tab: Tab) {}
func tabManager(tabManager: TabManager, didAddTab tab: Tab) {}
func tabManager(tabManager: TabManager, didRemoveTab tab: Tab) {}
func tabManagerDidRestoreTabs(tabManager: TabManager) {}
func tabManagerDidAddTabs(tabManager: TabManager) {
collectionView.reloadData()
}
func tabManagerDidRemoveAllTabs(tabManager: TabManager, toast:ButtonToast?) {}
} | mpl-2.0 | f6ed3b12ab82ebea12e86e1f258594be | 38.652695 | 171 | 0.66269 | 5.506445 | false | false | false | false |
Raizlabs/SketchyCode | SketchyCode/Generation/Generators.swift | 1 | 3551 | //
// Generators.swift
// SketchyCode
//
// Created by Brian King on 10/3/17.
// Copyright © 2017 Brian King. All rights reserved.
//
import Foundation
protocol Generator {
func generate(in scope: Scope, context: GeneratorContext) throws
}
extension ClassDeclaration: Generator {
func generate(in scope: Scope, context: GeneratorContext) throws {
if let inheriting = inheriting {
context.writer.append(line: "class \(typeRef.name): \(inheriting.name) ", addNewline: false)
} else {
context.writer.append(line: "class \(typeRef.name) ", addNewline: false)
}
try context.writer.block() {
try children.forEach { try $0.generate(in: self, context: context) }
}
}
}
extension VariableDeclaration: Generator {
func generate(in scope: Scope, context: GeneratorContext) throws {
if let classDeclaration = scope as? ClassDeclaration, classDeclaration.selfDeclaration.value == self.value {
return
}
let name = try context.namingStrategy.name(for: value, in: scope)
if let initialization = initialization {
context.writer.append(line: "let \(name): \(value.type.name) = ", addNewline: false)
try initialization.generate(in: try scope.nonTypeScope(), context: context)
} else {
context.writer.append(line: "let \(name): \(value.type.name)")
}
}
}
extension FunctionDeclaration: Generator {
var swiftPrefix: String {
switch definition {
case .initializer: return "\(options.swiftPrefix)init"
case .function(let name, _): return "\(options.swiftPrefix)func \(name)"
}
}
var swiftSuffix: String {
switch definition {
case .initializer: return ""
case .function(_, let result):
return result.isVoid ? "" : " -> \(result.name)"
}
}
func generate(in scope: Scope, context: GeneratorContext) throws {
let parameters = self.parameters.map { $0.swiftRepresentation }.joined(separator: ", ")
context.writer.append(line: "\(swiftPrefix)(\(parameters))\(swiftSuffix) ", addNewline: false)
try block.generate(in: scope, context: context)
}
}
extension BasicExpression: Generator {
func generate(in scope: Scope, context: GeneratorContext) throws {
context.writer.append(line: try parts
.map { part -> String in
return try part.code(in: scope, with: context.namingStrategy)
}
.joined())
}
}
extension BlockExpression: Generator {
func generate(in scope: Scope, context: GeneratorContext) throws {
try context.writer.block(appending: "\(invoke ? "()" : "")") {
try children.forEach { try $0.generate(in: self, context: context) }
}
}
}
extension GlobalScope: Generator {
func generate(in scope: Scope, context: GeneratorContext) throws {
context.writer.append(line: "// Automatically generated. Do Not Edit!")
// Generate ClassDeclarations first.
try children.forEach {
if $0 is ClassDeclaration {
try $0.generate(in: self, context: context)
}
}
try children.forEach {
if !($0 is ClassDeclaration) {
try $0.generate(in: self, context: context)
}
}
}
}
extension Generator where Self: Scope {
func generate(context: GeneratorContext) throws {
try generate(in: self, context: context)
}
}
| mit | e4c06860a6df42442e0be42bd692571a | 31.87037 | 116 | 0.616338 | 4.334554 | false | false | false | false |
gregomni/swift | test/Frontend/dump-parse.swift | 3 | 5328 | // RUN: not %target-swift-frontend -dump-parse %s | %FileCheck %s
// RUN: not %target-swift-frontend -dump-ast %s | %FileCheck %s -check-prefix=CHECK-AST
// CHECK-LABEL: (func_decl{{.*}}"foo(_:)"
// CHECK-AST-LABEL: (func_decl{{.*}}"foo(_:)"
func foo(_ n: Int) -> Int {
// CHECK: (brace_stmt
// CHECK: (return_stmt
// CHECK: (integer_literal_expr type='<null>' value=42 {{.*}})))
// CHECK-AST: (brace_stmt
// CHECK-AST: (return_stmt
// CHECK-AST: (integer_literal_expr type='{{[^']+}}' {{.*}} value=42 {{.*}})
return 42
}
// -dump-parse should print an AST even though this code is invalid.
// CHECK-LABEL: (func_decl{{.*}}"bar()"
// CHECK-AST-LABEL: (func_decl{{.*}}"bar()"
func bar() {
// CHECK: (brace_stmt
// CHECK-NEXT: (unresolved_decl_ref_expr type='{{[^']+}}' name=foo
// CHECK-NEXT: (unresolved_decl_ref_expr type='{{[^']+}}' name=foo
// CHECK-NEXT: (unresolved_decl_ref_expr type='{{[^']+}}' name=foo
// CHECK-AST: (brace_stmt
// CHECK-AST-NEXT: (declref_expr type='{{[^']+}}' {{.*}} decl=main.(file).foo
// CHECK-AST-NEXT: (declref_expr type='{{[^']+}}' {{.*}} decl=main.(file).foo
// CHECK-AST-NEXT: (declref_expr type='{{[^']+}}' {{.*}} decl=main.(file).foo
foo foo foo
}
// CHECK-LABEL: (enum_decl{{.*}}trailing_semi "TrailingSemi"
enum TrailingSemi {
// CHECK-LABEL: (enum_case_decl{{.*}}trailing_semi
// CHECK-NOT: (enum_element_decl{{.*}}trailing_semi
// CHECK: (enum_element_decl{{.*}}"A")
// CHECK: (enum_element_decl{{.*}}"B")
case A,B;
// CHECK-LABEL: (subscript_decl{{.*}}trailing_semi
// CHECK-NOT: (func_decl{{.*}}trailing_semi 'anonname={{.*}}' get_for=subscript(_:)
// CHECK: (accessor_decl{{.*}}'anonname={{.*}}' get_for=subscript(_:)
subscript(x: Int) -> Int {
// CHECK-LABEL: (pattern_binding_decl{{.*}}trailing_semi
// CHECK-NOT: (var_decl{{.*}}trailing_semi "y"
// CHECK: (var_decl{{.*}}"y"
var y = 1;
// CHECK-LABEL: (sequence_expr {{.*}} trailing_semi
y += 1;
// CHECK-LABEL: (return_stmt{{.*}}trailing_semi
return y;
};
};
// The substitution map for a declref should be relatively unobtrustive.
// CHECK-AST-LABEL: (func_decl{{.*}}"generic(_:)" <T : Hashable> interface type='<T where T : Hashable> (T) -> ()' access=internal captures=(<generic> )
func generic<T: Hashable>(_: T) {}
// CHECK-AST: (pattern_binding_decl
// CHECK-AST: (declref_expr type='(Int) -> ()' location={{.*}} range={{.*}} decl=main.(file).generic@{{.*}} [with (substitution_map generic_signature=<T where T : Hashable> (substitution T -> Int))] function_ref=unapplied))
let _: (Int) -> () = generic
// Closures should be marked as escaping or not.
func escaping(_: @escaping (Int) -> Int) {}
escaping({ $0 })
// CHECK-AST: (declref_expr type='(@escaping (Int) -> Int) -> ()'
// CHECK-AST-NEXT: (argument_list
// CHECK-AST-NEXT: (argument
// CHECK-AST-NEXT: (closure_expr type='(Int) -> Int' {{.*}} discriminator=0 escaping single-expression
func nonescaping(_: (Int) -> Int) {}
nonescaping({ $0 })
// CHECK-AST: (declref_expr type='((Int) -> Int) -> ()'
// CHECK-AST-NEXT: (argument_list
// CHECK-AST-NEXT: (argument
// CHECK-AST-NEXT: (closure_expr type='(Int) -> Int' {{.*}} discriminator=1 single-expression
// CHECK-LABEL: (struct_decl range=[{{.+}}] "MyStruct")
struct MyStruct {}
// CHECK-LABEL: (enum_decl range=[{{.+}}] "MyEnum"
enum MyEnum {
// CHECK-LABEL: (enum_case_decl range=[{{.+}}]
// CHECK-NEXT: (enum_element_decl range=[{{.+}}] "foo(x:)"
// CHECK-NEXT: (parameter_list range=[{{.+}}]
// CHECK-NEXT: (parameter "x" apiName=x)))
// CHECK-NEXT: (enum_element_decl range=[{{.+}}] "bar"))
// CHECK-NEXT: (enum_element_decl range=[{{.+}}] "foo(x:)"
// CHECK-NEXT: (parameter_list range=[{{.+}}]
// CHECK-NEXT: (parameter "x" apiName=x)))
// CHECK-NEXT: (enum_element_decl range=[{{.+}}] "bar"))
case foo(x: MyStruct), bar
}
// CHECK-LABEL: (top_level_code_decl range=[{{.+}}]
// CHECK-NEXT: (brace_stmt implicit range=[{{.+}}]
// CHECK-NEXT: (sequence_expr type='<null>'
// CHECK-NEXT: (discard_assignment_expr type='<null>')
// CHECK-NEXT: (assign_expr type='<null>'
// CHECK-NEXT: (**NULL EXPRESSION**)
// CHECK-NEXT: (**NULL EXPRESSION**))
// CHECK-NEXT: (closure_expr type='<null>' discriminator={{[0-9]+}}
// CHECK-NEXT: (parameter_list range=[{{.+}}]
// CHECK-NEXT: (parameter "v"))
// CHECK-NEXT: (brace_stmt range=[{{.+}}])))))
_ = { (v: MyEnum) in }
// CHECK-LABEL: (struct_decl range=[{{.+}}] "SelfParam"
struct SelfParam {
// CHECK-LABEL: (func_decl range=[{{.+}}] "createOptional()" type
// CHECK-NEXT: (parameter "self")
// CHECK-NEXT: (parameter_list range=[{{.+}}])
// CHECK-NEXT: (result
// CHECK-NEXT: (type_optional
// CHECK-NEXT: (type_ident
// CHECK-NEXT: (component id='SelfParam' bind=none))))
static func createOptional() -> SelfParam? {
// CHECK-LABEL: (call_expr type='<null>'
// CHECK-NEXT: (unresolved_decl_ref_expr type='<null>' name=SelfParam function_ref=unapplied)
// CHECK-NEXT: (argument_list)
SelfParam()
}
}
| apache-2.0 | 7c0c49b28662540162522bb63b176bbc | 40.952756 | 231 | 0.566441 | 3.348837 | false | false | false | false |
keith/radars | TestCompilerError/Pods/Quick/Quick/ExampleGroup.swift | 136 | 3084 | /**
Example groups are logical groupings of examples, defined with
the `describe` and `context` functions. Example groups can share
setup and teardown code.
*/
final public class ExampleGroup: NSObject {
weak internal var parent: ExampleGroup?
internal let hooks = ExampleHooks()
private let internalDescription: String
private let flags: FilterFlags
private let isInternalRootExampleGroup: Bool
private var childGroups = [ExampleGroup]()
private var childExamples = [Example]()
internal init(description: String, flags: FilterFlags, isInternalRootExampleGroup: Bool = false) {
self.internalDescription = description
self.flags = flags
self.isInternalRootExampleGroup = isInternalRootExampleGroup
}
public override var description: String {
return internalDescription
}
/**
Returns a list of examples that belong to this example group,
or to any of its descendant example groups.
*/
public var examples: [Example] {
var examples = childExamples
for group in childGroups {
examples.appendContentsOf(group.examples)
}
return examples
}
internal var name: String? {
if let parent = parent {
switch(parent.name) {
case .Some(let name): return "\(name), \(description)"
case .None: return description
}
} else {
return isInternalRootExampleGroup ? nil : description
}
}
internal var filterFlags: FilterFlags {
var aggregateFlags = flags
walkUp() { (group: ExampleGroup) -> () in
for (key, value) in group.flags {
aggregateFlags[key] = value
}
}
return aggregateFlags
}
internal var befores: [BeforeExampleWithMetadataClosure] {
var closures = Array(hooks.befores.reverse())
walkUp() { (group: ExampleGroup) -> () in
closures.appendContentsOf(Array(group.hooks.befores.reverse()))
}
return Array(closures.reverse())
}
internal var afters: [AfterExampleWithMetadataClosure] {
var closures = hooks.afters
walkUp() { (group: ExampleGroup) -> () in
closures.appendContentsOf(group.hooks.afters)
}
return closures
}
internal func walkDownExamples(callback: (example: Example) -> ()) {
for example in childExamples {
callback(example: example)
}
for group in childGroups {
group.walkDownExamples(callback)
}
}
internal func appendExampleGroup(group: ExampleGroup) {
group.parent = self
childGroups.append(group)
}
internal func appendExample(example: Example) {
example.group = self
childExamples.append(example)
}
private func walkUp(callback: (group: ExampleGroup) -> ()) {
var group = self
while let parent = group.parent {
callback(group: parent)
group = parent
}
}
}
| mit | 6ad800efdfbc5c1b6b07276216d20e47 | 29.534653 | 102 | 0.616732 | 5.072368 | false | false | false | false |
HaloWang/Halo | Halo/Classes/UITableViewCell+Halo.swift | 1 | 1294 |
import UIKit
public extension UITableViewCell {
@discardableResult
func selectionStyle(_ selectionStyle: UITableViewCellSelectionStyle) -> Self {
self.selectionStyle = selectionStyle
return self
}
@discardableResult
func noneSelectionStyle() -> Self {
selectionStyle = .none
return self
}
@discardableResult
func accessoryType(_ accessoryType: UITableViewCellAccessoryType) -> Self {
self.accessoryType = accessoryType
return self
}
@discardableResult
func accessoryTypeDisclosureIndicator() -> Self {
accessoryType = .disclosureIndicator
return self
}
@discardableResult
func text(_ text: String?) -> Self {
self.textLabel?.text = text
return self
}
@discardableResult
func detail(_ detail: String?) -> Self {
self.detailTextLabel?.text = detail
return self
}
}
open class WCValue1TableViewCell: UITableViewCell {
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: UITableViewCellStyle.value1, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 43ef2fd425b0fb0d8d27de5ac54dbe8c | 22.962963 | 88 | 0.666924 | 5.650655 | false | false | false | false |
devpunk/cartesian | cartesian/Controller/Draw/CDrawList.swift | 1 | 3462 | import UIKit
class CDrawList:CController
{
let model:MDrawList
private weak var viewList:VDrawList!
override init()
{
model = MDrawList()
super.init()
model.controller = self
}
required init?(coder:NSCoder)
{
return nil
}
override func loadView()
{
let viewList:VDrawList = VDrawList(controller:self)
self.viewList = viewList
view = viewList
}
override func viewDidAppear(_ animated:Bool)
{
super.viewDidAppear(animated)
model.update()
}
//MARK: private
private func confirmDelete(project:DProject)
{
DManager.sharedInstance?.delete(data:project)
{ [weak self] in
DManager.sharedInstance?.save()
self?.model.update()
}
}
//MARK: public
func listLoaded()
{
DispatchQueue.main.async
{ [weak self] in
self?.viewList.refresh()
}
}
func newDraw()
{
let controllerProject:CDrawProject = CDrawProject(model:nil)
parentController.push(
controller:controllerProject,
horizontal:CParent.TransitionHorizontal.fromRight)
}
func openDraw(project:DProject)
{
let controllerProject:CDrawProject = CDrawProject(model:project)
parentController.push(
controller:controllerProject,
horizontal:CParent.TransitionHorizontal.fromRight)
}
func trashDraw(project:DProject)
{
UIApplication.shared.keyWindow!.endEditing(true)
let alert:UIAlertController = UIAlertController(
title:NSLocalizedString("CDrawList_alertTitle", comment:""),
message:nil,
preferredStyle:UIAlertControllerStyle.actionSheet)
let actionCancel:UIAlertAction = UIAlertAction(
title:
NSLocalizedString("CDrawList_alertCancel", comment:""),
style:
UIAlertActionStyle.cancel)
let actionDelete:UIAlertAction = UIAlertAction(
title:
NSLocalizedString("CDrawList_alertDelete", comment:""),
style:
UIAlertActionStyle.destructive)
{ (action:UIAlertAction) in
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self, weak project] in
guard
let strongProject:DProject = project
else
{
return
}
self?.confirmDelete(project:strongProject)
}
}
alert.addAction(actionDelete)
alert.addAction(actionCancel)
if let popover:UIPopoverPresentationController = alert.popoverPresentationController
{
popover.sourceView = viewList
popover.sourceRect = CGRect.zero
popover.permittedArrowDirections = UIPopoverArrowDirection.up
}
present(alert, animated:true, completion:nil)
}
func shareProject(project:DProject)
{
let controllerShare:CDrawProjectShare = CDrawProjectShare(
model:project)
parentController.animateOver(controller:controllerShare)
}
}
| mit | 956f8d26533f99f50f20e95d6eb9ed37 | 25.227273 | 92 | 0.562969 | 5.601942 | false | false | false | false |
ksco/swift-algorithm-club-cn | Binary Search Tree/Solution 2/BinarySearchTree.playground/Contents.swift | 1 | 332 | //: Playground - noun: a place where people can play
// Each time you insert something, you get back a completely new tree.
var tree = BinarySearchTree.Leaf(7)
tree = tree.insert(2)
tree = tree.insert(5)
tree = tree.insert(10)
tree = tree.insert(9)
tree = tree.insert(1)
print(tree)
tree.search(10)
tree.search(1)
tree.search(11)
| mit | c01519a2770d0b254f7f29f1c18eb22d | 22.714286 | 70 | 0.722892 | 2.990991 | false | false | false | false |
OscarSwanros/swift | test/decl/protocol/special/coding/class_codable_member_type_lookup.swift | 13 | 21222 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown
// A top-level CodingKeys type to fall back to in lookups below.
public enum CodingKeys : String, CodingKey {
case topLevel
}
// MARK: - Synthesized CodingKeys Enum
// Classes which get synthesized Codable implementations should have visible
// CodingKey enums during member type lookup.
struct SynthesizedClass : Codable {
let value: String = "foo"
// Qualified type lookup should always be unambiguous.
public func qualifiedFoo(_ key: SynthesizedClass.CodingKeys) {} // expected-error {{method cannot be declared public because its parameter uses a private type}}
internal func qualifiedBar(_ key: SynthesizedClass.CodingKeys) {} // expected-error {{method cannot be declared internal because its parameter uses a private type}}
fileprivate func qualfiedBaz(_ key: SynthesizedClass.CodingKeys) {} // expected-warning {{method should not be declared fileprivate because its parameter uses a private type}}
private func qualifiedQux(_ key: SynthesizedClass.CodingKeys) {}
// Unqualified lookups should find the synthesized CodingKeys type instead
// of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) { // expected-warning {{method should not be declared fileprivate because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.value) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) { // expected-warning {{method should not be declared fileprivate because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
// Lookup within nested types should look outside of the type.
struct Nested {
// Qualified lookup should remain as-is.
public func qualifiedFoo(_ key: SynthesizedClass.CodingKeys) {} // expected-error {{method cannot be declared public because its parameter uses a private type}}
internal func qualifiedBar(_ key: SynthesizedClass.CodingKeys) {} // expected-error {{method cannot be declared internal because its parameter uses a private type}}
fileprivate func qualfiedBaz(_ key: SynthesizedClass.CodingKeys) {} // expected-warning {{method should not be declared fileprivate because its parameter uses a private type}}
private func qualifiedQux(_ key: SynthesizedClass.CodingKeys) {}
// Unqualified lookups should find the SynthesizedClass's synthesized
// CodingKeys type instead of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) { // expected-warning {{method should not be declared fileprivate because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.value) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) { // expected-warning {{method should not be declared fileprivate because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
}
}
// MARK: - No CodingKeys Enum
// Classes which don't get synthesized Codable implementations should expose the
// appropriate CodingKeys type.
struct NonSynthesizedClass : Codable {
// No synthesized type since we implemented both methods.
init(from decoder: Decoder) throws {}
func encode(to encoder: Encoder) throws {}
// Qualified type lookup should clearly fail -- we shouldn't get a synthesized
// type here.
public func qualifiedFoo(_ key: NonSynthesizedClass.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of 'NonSynthesizedClass'}}
internal func qualifiedBar(_ key: NonSynthesizedClass.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of 'NonSynthesizedClass'}}
fileprivate func qualfiedBaz(_ key: NonSynthesizedClass.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of 'NonSynthesizedClass'}}
private func qualifiedQux(_ key: NonSynthesizedClass.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of 'NonSynthesizedClass'}}
// Unqualified lookups should find the public top-level CodingKeys type.
public func unqualifiedFoo(_ key: CodingKeys) { print(CodingKeys.topLevel) }
internal func unqualifiedBar(_ key: CodingKeys) { print(CodingKeys.topLevel) }
fileprivate func unqualifiedBaz(_ key: CodingKeys) { print(CodingKeys.topLevel) }
private func unqualifiedQux(_ key: CodingKeys) { print(CodingKeys.topLevel) }
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
qux(CodingKeys.nested)
}
}
// MARK: - Explicit CodingKeys Enum
// Classes which explicitly define their own CodingKeys types should have
// visible CodingKey enums during member type lookup.
struct ExplicitClass : Codable {
let value: String = "foo"
public enum CodingKeys {
case a
case b
case c
}
init(from decoder: Decoder) throws {}
func encode(to encoder: Encoder) throws {}
// Qualified type lookup should always be unambiguous.
public func qualifiedFoo(_ key: ExplicitClass.CodingKeys) {}
internal func qualifiedBar(_ key: ExplicitClass.CodingKeys) {}
fileprivate func qualfiedBaz(_ key: ExplicitClass.CodingKeys) {}
private func qualifiedQux(_ key: ExplicitClass.CodingKeys) {}
// Unqualified lookups should find the synthesized CodingKeys type instead
// of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
// Lookup within nested types should look outside of the type.
struct Nested {
// Qualified lookup should remain as-is.
public func qualifiedFoo(_ key: ExplicitClass.CodingKeys) {}
internal func qualifiedBar(_ key: ExplicitClass.CodingKeys) {}
fileprivate func qualfiedBaz(_ key: ExplicitClass.CodingKeys) {}
private func qualifiedQux(_ key: ExplicitClass.CodingKeys) {}
// Unqualified lookups should find the ExplicitClass's synthesized
// CodingKeys type instead of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
}
}
// MARK: - CodingKeys Enums in Extensions
// Classes which get a CodingKeys type in an extension should be able to see
// that type during member type lookup.
struct ExtendedClass : Codable {
let value: String = "foo"
// Don't get an auto-synthesized type.
init(from decoder: Decoder) throws {}
func encode(to encoder: Encoder) throws {}
// Qualified type lookup should always be unambiguous.
public func qualifiedFoo(_ key: ExtendedClass.CodingKeys) {}
internal func qualifiedBar(_ key: ExtendedClass.CodingKeys) {}
fileprivate func qualfiedBaz(_ key: ExtendedClass.CodingKeys) {}
private func qualifiedQux(_ key: ExtendedClass.CodingKeys) {}
// Unqualified lookups should find the synthesized CodingKeys type instead
// of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
// Lookup within nested types should look outside of the type.
struct Nested {
// Qualified lookup should remain as-is.
public func qualifiedFoo(_ key: ExtendedClass.CodingKeys) {}
internal func qualifiedBar(_ key: ExtendedClass.CodingKeys) {}
fileprivate func qualfiedBaz(_ key: ExtendedClass.CodingKeys) {}
private func qualifiedQux(_ key: ExtendedClass.CodingKeys) {}
// Unqualified lookups should find the ExtendedClass's synthesized
// CodingKeys type instead of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
}
}
extension ExtendedClass {
enum CodingKeys : String, CodingKey {
case a, b, c
}
}
class A {
class Inner : Codable {
var value: Int = 42
func foo() {
print(CodingKeys.value) // Not found on A.CodingKeys or top-level type.
}
}
}
extension A {
enum CodingKeys : String, CodingKey {
case a
}
}
class B : Codable {
// So B conforms to Codable using CodingKeys.b below.
var b: Int = 0
class Inner {
var value: Int = 42
func foo() {
print(CodingKeys.b) // Not found on top-level type.
}
}
}
extension B {
enum CodingKeys : String, CodingKey {
case b
}
}
class C : Codable {
class Inner : Codable {
var value: Int = 42
func foo() {
print(CodingKeys.value) // Not found on C.CodingKeys or top-level type.
}
}
}
extension C.Inner {
enum CodingKeys : String, CodingKey {
case value
}
}
| apache-2.0 | 966bc4e9c3c7fa758f58f614bb64e623 | 31.800618 | 179 | 0.690368 | 4.739169 | false | false | false | false |
szk-atmosphere/SAInboxViewController | SAInboxViewControllerSample/SAInboxViewControllerSample/FeedViewCell/FeedViewCell.swift | 1 | 1186 | //
// FeedViewCell.swift
// SAInboxViewControllerSample
//
// Created by Taiki Suzuki on 2015/08/15.
// Copyright (c) 2015年 Taiki Suzuki. All rights reserved.
//
import UIKit
import QuartzCore
class FeedViewCell: UITableViewCell {
static let cellIdentifier = "FeedViewCell"
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var mainTextLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
iconImageView.layer.masksToBounds = true
}
override func layoutSubviews() {
super.layoutSubviews()
iconImageView.layer.cornerRadius = iconImageView.frame.width / 2
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setIconImage(_ image: UIImage) {
iconImageView.image = image
}
func setMainText(_ text: String) {
mainTextLabel.text = text
}
func setUsername(_ name: String) {
usernameLabel.text = name
}
}
| mit | 2a8acba28a20fbc9695b3ff7af26947c | 23.666667 | 72 | 0.657095 | 4.813008 | false | false | false | false |
netease-app/NIMSwift | Example/NIMSwift/Common/Circle/BezierButton.swift | 1 | 1179 | //
// BezierPathButton.swift
// monitor
//
// Created by hengchengfei on 15/9/13.
// Copyright © 2015年 chengfeisoft. All rights reserved.
//
import UIKit
@IBDesignable class BezierButton: UIButton {
@IBInspectable var borderColor:UIColor = UIColor.clear {
didSet{
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var borderWidth:CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius:CGFloat = 0
/**
设置哪个角度需要切边
0:topLeft
1:topRight
2:bottomLeft
3:bottomRight
4:topLeft + bottomLeft
5:topRight + bottomRight
**/
@IBInspectable var roundingCorners:Int = 0{
didSet{
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [.topLeft,.topRight,.bottomLeft,.bottomRight], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
layer.mask = maskLayer
}
}
}
| mit | fd1e43fcaa59183eae3b4a2436c646e2 | 22.591837 | 191 | 0.584775 | 4.83682 | false | false | false | false |
bingoogolapple/SwiftNote-PartTwo | 网络基础-上传文件/网络基础-上传文件/ViewController.swift | 1 | 3440 | //
// ViewController.swift
// 网络基础-上传文件
//
// Created by bingoogol on 14/10/26.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
weak var imageView:UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
var image = UIImage(named: "头像1.png")
var imageView = UIImageView(image: image)
imageView.frame = CGRectMake(60, 20, 200, 200)
self.view.addSubview(imageView)
self.imageView = imageView
var button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(60, 240, 200, 40)
button.setTitle("upload", forState: UIControlState.Normal)
button.addTarget(self, action: Selector("uploadImage"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
}
func uploadImage() {
println("uploadImage")
// 思路:是需要使用HTTP的POST方法上传文件
// 调用的URL是http://localhost:8080/swift/upload
// 数据体的参数名:file
// 1.建立NSURL
var url = NSURL(string: "http://localhost:8080/swift/upload")
// 2.建立NSMutableRequest
var request = NSMutableURLRequest(URL: url!)
// 1)设置request的属性,设置方法
request.HTTPMethod = "POST"
// 2)设置数据体
// 1> 设置boundary的字符串,以便复用
var boundary = "uploadBoundary";
// 2> 头部字符串
var startStr = NSMutableString();
startStr.appendString("--\(boundary)\n")
startStr.appendString("Content-Disposition: form-data; name=\"file\"; filename=\"upload.png\"\n")
startStr.appendString("Content-Type: image/png\n\n")
// 3> 尾部字符串
var endStr = NSMutableString()
endStr.appendString("--\(boundary)\n")
endStr.appendString("Content-Disposition: form-data; name=\"submit\"\n\n")
endStr.appendString("Submit\n")
endStr.appendFormat("--\(boundary)--")
// 4> 拼接数据体
var bodyData = NSMutableData()
bodyData.appendData(startStr.dataUsingEncoding(NSUTF8StringEncoding)!)
var imageData = UIImagePNGRepresentation(self.imageView.image);
bodyData.appendData(imageData)
bodyData.appendData(endStr.dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = bodyData
// 5> 指定Content-Type,在上传文件时,需要指定Content-Type & Content-Length
var contentStr = "multipart/form-data; boundary=\(boundary)"
request.setValue(contentStr, forHTTPHeaderField: "Content-Type")
// 6> 指定Content-Length
var length = bodyData.length;
request.setValue("\(length)", forHTTPHeaderField: "Content-Length")
// 3.使用NSURLConnection的同步方法上传文件,因为需要用户确认上传文件是否上传成功!
// 在使用HTTP上传文件时,通常是有大小限制的
var response:NSURLResponse?
var error:NSError?
var resultData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
var resultStr = NSString(data: resultData!, encoding: NSUTF8StringEncoding)
println(resultStr)
}
} | apache-2.0 | b9f19957d26775b6b170da84f9a90d7a | 36 | 117 | 0.637405 | 4.403361 | false | false | false | false |
ontouchstart/swift3-playground | Shapes.playgroundbook/Contents/Chapters/Shapes.playgroundchapter/Pages/Create.playgroundpage/Contents.swift | 1 | 1606 | //#-code-completion(module, hide, Swift)
//#-code-completion(identifier, hide, _setup())
//#-code-completion(identifier, hide, AbstractDrawable)
//#-hidden-code
_setup()
//#-end-hidden-code
//#-editable-code Tap to enter code
// 1. Create a circle
let circle = Circle(radius: 3)
circle.center.y += 28
// 2. Create a rectangle
let rectangle = Rectangle(width: 10, height: 5, cornerRadius: 0.75)
rectangle.color = .purple
rectangle.center.y += 18
// 3. Create a line
let line = Line(start: Point(x: -10, y: 9), end: Point(x: 10, y: 9), thickness: 0.5)
line.center.y -= 2
line.rotation = 170 * (3.14159/180)
line.color = .yellow
// 4. Create text
let text = Text(string: "Hello world!", fontSize: 32.0, fontName: "Futura", color: .red)
text.center.y -= 2
// 5. Create an image
let image = Image(name: "SwiftBird", tint: .green)
image.size.width *= 0.5
image.size.height *= 0.5
image.center.y -= 11
// 6. Create a pattern with rectangles
let numRectangles = 4
var xOffset = Double((numRectangles/2) * (-1))
var yOffset = -26.0
let saturationEnd = 0.911
let saturationStart = 0.1
let saturationStride = (saturationEnd - saturationStart)/Double(numRectangles)
for i in 0...numRectangles {
let rectangle = Rectangle(width: 10, height: 5, cornerRadius: 0.75)
// set the color.
let saturation = saturationEnd - (Double(numRectangles - i) * saturationStride)
rectangle.color = Color(hue: 0.079, saturation: saturation, brightness: 0.934)
// calculate the offset.
rectangle.center = Point(x: xOffset, y: yOffset)
xOffset += 1
yOffset += 1
}
//#-end-editable-code
| mit | 5dabf3a0716ab117d5d97c9722f56ea3 | 28.2 | 88 | 0.67995 | 3.277551 | false | false | false | false |
kayoslab/CaffeineStatsview | CaffeineStatsview/CaffeineStatsview/Controller/DetailViewController.swift | 1 | 2752 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 cr0ss
*
* 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 UIKit
class DetailViewController: UIViewController {
@IBOutlet var linearCubicSegment: UISegmentedControl!
@IBOutlet var statsView: StatsView!
@IBOutlet weak var detailDescriptionLabel: UILabel!
private var catmull:Bool = false
internal var objects:Array<Double>? {
didSet {
// Update the view.
self.configureView()
}
}
internal var indexPath:NSIndexPath? {
didSet {
self.setupLabels()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
self.setupLabels()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func configureView() {
// Update the user interface for the objects item.
if let objects = self.objects {
if self.statsView != nil {
self.statsView.setUpGraphView(objects, intersectDistance:0, catmullRom: self.catmull)
}
}
}
private func setupLabels() {
if let objects = self.objects, indexPath = self.indexPath {
if self.detailDescriptionLabel != nil {
self.detailDescriptionLabel.text = "Current Value: \(objects[indexPath.row])"
}
}
}
@IBAction func linearCubicSegmentValueChanged(sender: UISegmentedControl) {
self.catmull = !self.catmull
self.configureView()
}
}
| mit | 1708fcfdef43d8d92a95a471010132f0 | 34.282051 | 101 | 0.676599 | 4.811189 | false | true | false | false |
LedgerHQ/ledger-wallet-ios | ledger-wallet-ios/Helpers/Crypto/CryptoData.swift | 1 | 1120 | //
// CryptoData.swift
// ledger-wallet-ios
//
// Created by Nicolas Bigot on 04/02/2015.
// Copyright (c) 2015 Ledger. All rights reserved.
//
import Foundation
extension Crypto {
final class Data {
class func dataFromString(string: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> NSData? {
return string.dataUsingEncoding(encoding, allowLossyConversion: false)
}
class func stringFromData(data: NSData, encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? {
if let string = NSString(data: data, encoding: encoding) {
return string as String
}
return nil
}
class func splitDataInTwo(data: NSData) -> (NSData, NSData) {
if (data.length == 0 || data.length % 2 != 0) {
return (NSData(), NSData())
}
let partLength = data.length / 2
return (data.subdataWithRange(NSMakeRange(0, partLength)), data.subdataWithRange(NSMakeRange(partLength, partLength)))
}
}
} | mit | ef8bcdf43ebbd2da33e58d4aa53d7654 | 29.297297 | 130 | 0.585714 | 4.686192 | false | false | false | false |
darrarski/SwipeToReveal-iOS | Example/UI/TableExample/TableExampleCell.swift | 1 | 3052 | import UIKit
import SnapKit
import SwipeToReveal
import Reusable
class TableExampleCell: UITableViewCell, Reusable {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
loadSubviews()
setupLayout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
label.text = nil
swipeToReveal.close(animated: false)
}
// MARK: Subviews
let label = Factory.label
let swipeToReveal = SwipeToRevealView(frame: .zero)
let swipeButtonA = Factory.button(title: "Button A", color: .red)
let swipeButtonB = Factory.button(title: "Button B", color: .blue)
private func loadSubviews() {
contentView.addSubview(swipeToReveal)
swipeToReveal.contentView = swipeContentView
swipeContentView.addSubview(label)
swipeToReveal.rightView = swipeRightView
swipeRightView.addSubview(swipeButtonA)
swipeRightView.addSubview(swipeButtonB)
}
private let swipeContentView = Factory.view(layoutMargins: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8))
private let swipeRightView = Factory.view()
// MARK: Layout
private func setupLayout() {
swipeToReveal.snp.makeConstraints {
$0.edges.equalToSuperview()
}
label.snp.makeConstraints {
guard let superview = label.superview else { fatalError() }
$0.centerYWithinMargins.equalToSuperview()
$0.top.greaterThanOrEqualTo(superview.snp.topMargin)
$0.left.equalTo(superview.snp.leftMargin)
$0.right.lessThanOrEqualTo(superview.snp.rightMargin)
$0.bottom.lessThanOrEqualTo(superview.snp.bottomMargin)
}
swipeButtonA.snp.makeConstraints {
$0.top.left.bottom.equalToSuperview()
}
swipeButtonB.snp.makeConstraints {
$0.left.equalTo(swipeButtonA.snp.right)
$0.top.right.bottom.equalToSuperview()
}
}
}
private extension TableExampleCell {
struct Factory {
static var label: UILabel {
let label = UILabel(frame: .zero)
label.font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
label.textColor = .darkText
return label
}
static func button(title: String, color: UIColor) -> UIButton {
let button = UIButton(frame: .zero)
button.setTitle(title, for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = color
button.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
return button
}
static func view(layoutMargins: UIEdgeInsets = .zero) -> UIView {
let view = UIView(frame: .zero)
view.layoutMargins = layoutMargins
return view
}
}
}
| mit | 79bea8fbd49c6a9fc8dc5346789c307b | 31.468085 | 114 | 0.638598 | 4.724458 | false | false | false | false |
stuffrabbit/SwiftCoAP | Example_Projects/SwiftCoAPServerExample/SwiftCoAPServerExample/TestResourceModel.swift | 1 | 2584 | //
// TestResourceModel.swift
// SwiftCoAPServerExample
//
// Created by Wojtek Kordylewski on 25.06.15.
// Copyright (c) 2015 Wojtek Kordylewski. All rights reserved.
//
import UIKit
class TestResourceModel: SCResourceModel {
//Individual Properties
var myText: String {
didSet {
self.dataRepresentation = myText.data(using: String.Encoding.utf8) //update observable Data anytime myText is changed
}
}
//
init(name: String, allowedRoutes: UInt, text: String) {
self.myText = text
super.init(name: name, allowedRoutes: allowedRoutes)
self.dataRepresentation = myText.data(using: String.Encoding.utf8)
}
override func dataForGet(queryDictionary: [String : String], options: [Int : [Data]]) -> (statusCode: SCCodeValue, payloadData: Data?, contentFormat: SCContentFormat?)? {
return (SCCodeValue(classValue: 2, detailValue: 05)!, myText.data(using: String.Encoding.utf8), .plain)
}
override func dataForPost(queryDictionary: [String : String], options: [Int : [Data]], requestData: Data?) -> (statusCode: SCCodeValue, payloadData: Data?, contentFormat: SCContentFormat?, locationUri: String?)? {
if let data = requestData, let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as String?{
myText = string
return (SCCodeSample.created.codeValue(), "Data created successfully".data(using: String.Encoding.utf8), .plain, self.name)
}
return (SCCodeSample.forbidden.codeValue(), "Invalid Data sent".data(using: String.Encoding.utf8), .plain, nil)
}
override func dataForPut(queryDictionary: [String : String], options: [Int : [Data]], requestData: Data?) -> (statusCode: SCCodeValue, payloadData: Data?, contentFormat: SCContentFormat?, locationUri: String?)? {
if let data = requestData, let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as String?{
myText += string
return (SCCodeSample.changed.codeValue(), "Update Successful".data(using: String.Encoding.utf8), .plain, self.name)
}
return (SCCodeSample.forbidden.codeValue(), "Invalid Data sent".data(using: String.Encoding.utf8), .plain, nil)
}
override func dataForDelete(queryDictionary: [String : String], options: [Int : [Data]]) -> (statusCode: SCCodeValue, payloadData: Data?, contentFormat: SCContentFormat?)? {
myText = ""
return (SCCodeSample.deleted.codeValue(), "Deleted".data(using: String.Encoding.utf8), .plain)
}
}
| mit | 1f9e6d475bc03ff56553c01a7bb62b3a | 50.68 | 217 | 0.679567 | 4.208469 | false | false | false | false |
1aurabrown/eidolon | KioskTests/Models/SaleTests.swift | 2 | 1813 | import Quick
import Nimble
class SaleTests: QuickSpec {
override func spec() {
it("converts from JSON") {
let id = "saf32sadasd"
let isAuction = true
let startDate = "2014-09-21T19:22:24Z"
let endDate = "2015-09-24T19:22:24Z"
let data:[String: AnyObject] = ["id":id , "is_auction" : isAuction, "start_at":startDate, "end_at":endDate]
let sale = Sale.fromJSON(data) as Sale
expect(sale.id) == id
expect(sale.isAuction) == isAuction
expect(yearFromDate(sale.startDate)) == 2014
expect(yearFromDate(sale.endDate)) == 2015
}
describe("active state") {
it("is inactive for past auction") {
let artsyTime = SystemTime()
artsyTime.systemTimeInterval = 0
let sale = Sale(id: "", isAuction: true, startDate: NSDate.distantPast() as NSDate, endDate: NSDate.distantPast() as NSDate)
expect(sale.isActive(artsyTime)) == false
}
it("is active for current auction") {
let artsyTime = SystemTime()
artsyTime.systemTimeInterval = 0
let sale = Sale(id: "", isAuction: true, startDate: NSDate.distantPast() as NSDate, endDate: NSDate.distantFuture() as NSDate)
expect(sale.isActive(artsyTime)) == true
}
it("is inactive for future auction") {
let artsyTime = SystemTime()
artsyTime.systemTimeInterval = 0
let sale = Sale(id: "", isAuction: true, startDate: NSDate.distantFuture() as NSDate, endDate: NSDate.distantFuture() as NSDate)
expect(sale.isActive(artsyTime)) == false
}
}
}
} | mit | 186c849192a91bc50fa4ad6ca0795636 | 33.226415 | 144 | 0.553778 | 4.50995 | false | false | false | false |
qxuewei/XWSwiftWB | XWSwiftWB/XWSwiftWB/Classes/Compose/View/ComposeTextView.swift | 1 | 1318 | //
// ComposeTextView.swift
// XWSwiftWB
//
// Created by 邱学伟 on 2016/11/10.
// Copyright © 2016年 邱学伟. All rights reserved.
//
import UIKit
class ComposeTextView: UITextView {
//MARK: - 私有属性
lazy var placeholderLB : UILabel = UILabel()
//添加子控件用这个
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//XWLog("添加子控件用这个 required init?(coder aDecoder: NSCoder)")
setUpUI()
}
//对子控件进行修改用这个
override func awakeFromNib() {
super.awakeFromNib()
//XWLog("对子控件进行修改用这个 override func awakeFromNib(")
}
}
//MARK: - UI
extension ComposeTextView {
fileprivate func setUpUI() {
setUpPlacehoderLB()
//文本内边距
textContainerInset = UIEdgeInsets(top: 8, left: 5, bottom: 0, right: 9)
}
fileprivate func setUpPlacehoderLB() {
addSubview(placeholderLB)
let snp = placeholderLB.snp
snp.makeConstraints { (maker) in
maker.top.equalTo(8)
maker.left.equalTo(9)
}
placeholderLB.text = "分享新鲜事..."
placeholderLB.font = font
placeholderLB.textColor = UIColor.lightGray
placeholderLB.sizeToFit()
}
}
| apache-2.0 | 90842e715d49d135e816e6988194a7da | 24.510638 | 79 | 0.615513 | 4.037037 | false | false | false | false |
Lucky-Orange/Tenon | String+MD5.swift | 1 | 7654 | //
// String+MD5.swift
// Kingfisher
//
// This file is stolen from HanekeSwift: https://github.com/Haneke/HanekeSwift/blob/master/Haneke/CryptoSwiftMD5.swift
// which is a modified version of CryptoSwift:
//
// To date, adding CommonCrypto to a Swift framework is problematic. See:
// http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework
// We're using a subset of CryptoSwift as a (temporary?) alternative.
// The following is an altered source version that only includes MD5. The original software can be found at:
// https://github.com/krzyzanowskim/CryptoSwift
// This is the original copyright notice:
/*
Copyright (C) 2014 Marcin Krzyżanowski <[email protected]>
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
- This notice may not be removed or altered from any source or binary distribution.
*/
import Foundation
/** array of bytes, little-endian representation */
func arrayOfBytes<T>(value:T, length:Int? = nil) -> [UInt8] {
let totalBytes = length ?? (sizeofValue(value) * 8)
let valuePointer = UnsafeMutablePointer<T>.alloc(1)
valuePointer.memory = value
let bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer)
var bytes = [UInt8](count: totalBytes, repeatedValue: 0)
for j in 0..<min(sizeof(T),totalBytes) {
bytes[totalBytes - 1 - j] = (bytesPointer + j).memory
}
valuePointer.destroy()
valuePointer.dealloc(1)
return bytes
}
extension Int {
/** Array of bytes with optional padding (little-endian) */
func bytes(totalBytes: Int = sizeof(Int)) -> [UInt8] {
return arrayOfBytes(self, length: totalBytes)
}
}
extension NSMutableData {
/** Convenient way to append bytes */
func appendBytes(arrayOfBytes: [UInt8]) {
appendBytes(arrayOfBytes, length: arrayOfBytes.count)
}
}
class HashBase {
var message: NSData
init(_ message: NSData) {
self.message = message
}
/** Common part for hash calculation. Prepare header data. */
func prepare(len:Int = 64) -> NSMutableData {
let tmpMessage: NSMutableData = NSMutableData(data: self.message)
// Step 1. Append Padding Bits
tmpMessage.appendBytes([0x80]) // append one bit (UInt8 with one bit) to message
// append "0" bit until message length in bits ≡ 448 (mod 512)
var msgLength = tmpMessage.length;
var counter = 0;
while msgLength % len != (len - 8) {
counter++
msgLength++
}
let bufZeros = UnsafeMutablePointer<UInt8>(calloc(counter, sizeof(UInt8)))
tmpMessage.appendBytes(bufZeros, length: counter)
bufZeros.destroy()
bufZeros.dealloc(1)
return tmpMessage
}
}
func rotateLeft(v:UInt32, n:UInt32) -> UInt32 {
return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n))
}
class MD5 : HashBase {
/** specifies the per-round shift amounts */
private let s: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
/** binary integer part of the sines of integers (Radians) */
private let k: [UInt32] = [0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,
0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501,
0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,
0x6b901122,0xfd987193,0xa679438e,0x49b40821,
0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa,
0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8,
0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,
0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a,
0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,
0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70,
0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05,
0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665,
0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,
0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1,
0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,
0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391]
private let h:[UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
func calculate() -> NSData {
let tmpMessage = prepare()
// hash values
var hh = h
// Step 2. Append Length a 64-bit representation of lengthInBits
let lengthInBits = (message.length * 8)
let lengthBytes = lengthInBits.bytes(64 / 8)
tmpMessage.appendBytes(Array(lengthBytes.reverse()));
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
var leftMessageBytes = tmpMessage.length
for (var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes) {
let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes)))
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
var M:[UInt32] = [UInt32](count: 16, repeatedValue: 0)
let range = NSRange(location:0, length: M.count * sizeof(UInt32))
chunk.getBytes(UnsafeMutablePointer<Void>(M), range: range)
// Initialize hash value for this chunk:
var A:UInt32 = hh[0]
var B:UInt32 = hh[1]
var C:UInt32 = hh[2]
var D:UInt32 = hh[3]
var dTemp:UInt32 = 0
// Main loop
for j in 0..<k.count {
var g = 0
var F:UInt32 = 0
switch (j) {
case 0...15:
F = (B & C) | ((~B) & D)
g = j
break
case 16...31:
F = (D & B) | (~D & C)
g = (5 * j + 1) % 16
break
case 32...47:
F = B ^ C ^ D
g = (3 * j + 5) % 16
break
case 48...63:
F = C ^ (B | (~D))
g = (7 * j) % 16
break
default:
break
}
dTemp = D
D = C
C = B
B = B &+ rotateLeft((A &+ F &+ k[j] &+ M[g]), n: s[j])
A = dTemp
}
hh[0] = hh[0] &+ A
hh[1] = hh[1] &+ B
hh[2] = hh[2] &+ C
hh[3] = hh[3] &+ D
}
let buf: NSMutableData = NSMutableData();
hh.forEach({ (item) -> () in
var i:UInt32 = item.littleEndian
buf.appendBytes(&i, length: sizeofValue(i))
})
return buf.copy() as! NSData;
}
} | mit | ac37805a2df3d38ed3a9ff43b4e59676 | 36.674877 | 213 | 0.582189 | 3.612187 | false | false | false | false |
Lucky-Orange/Tenon | Pitaya/Source/PitayaManager+NSURLSessionDelegate.swift | 1 | 3115 | // The MIT License (MIT)
// Copyright (c) 2015 JohnLui <[email protected]> https://github.com/johnlui
// 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.
//
// PitayaManager+NSURLSessionDelegate.swift
// Pitaya
//
// Created by 吕文翰 on 15/10/8.
//
private typealias URLSessionDelegate = PitayaManager
extension URLSessionDelegate {
/**
a delegate method to check whether the remote cartification is the same with given certification.
- parameter session: NSURLSession
- parameter challenge: NSURLAuthenticationChallenge
- parameter completionHandler: the completionHandler closure
*/
@objc func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
if let localCertificateData = self.localCertData {
if let serverTrust = challenge.protectionSpace.serverTrust,
certificate = SecTrustGetCertificateAtIndex(serverTrust, 0),
remoteCertificateData: NSData = SecCertificateCopyData(certificate) {
if localCertificateData.isEqualToData(remoteCertificateData) {
let credential = NSURLCredential(forTrust: serverTrust)
challenge.sender?.useCredential(credential, forAuthenticationChallenge: challenge)
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential)
} else {
challenge.sender?.cancelAuthenticationChallenge(challenge)
completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
self.sSLValidateErrorCallBack?()
}
} else {
// could not tested
NSLog("Pitaya: Get RemoteCertificateData or LocalCertificateData error!")
}
} else {
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, nil)
}
}
} | mit | 178372a8ef7d81b99b3c132d59727cc9 | 49.983607 | 196 | 0.704728 | 5.704587 | false | false | false | false |
ckrey/mqttswift | Sources/MqttInflight.swift | 1 | 1051 | //
// MqttInflight.swift
// mqttswift
//
// Created by Christoph Krey on 17.09.17.
//
//
import Foundation
class MqttInflight {
private var inflight : [MqttMessage]
init() {
self.inflight = [MqttMessage]()
}
func store(message: MqttMessage!) {
self.inflight.append(message)
}
func find(pid: Int!) -> (MqttMessage?) {
for message in self.inflight {
if message.packetIdentifier == pid {
return message
}
}
return nil
}
func update(message: MqttMessage!) {
for (index, aMessage) in self.inflight.enumerated() {
if aMessage.packetIdentifier == message.packetIdentifier {
self.inflight[index] = message
return
}
}
}
func remove(pid: Int!) {
for (index, message) in self.inflight.enumerated() {
if message.packetIdentifier == pid {
self.inflight.remove(at:index)
return
}
}
}
}
| gpl-3.0 | 5d15da9be5089ae932b6fe21924b54da | 20.44898 | 70 | 0.529971 | 4.137795 | false | false | false | false |
pwoosam/Surf-Map | Surf Map/MapVC.swift | 1 | 3666 | //
// MapVC.swift
// Surf Map
//
// Created by Patrick Woo-Sam on 1/23/17.
// Copyright © 2017 Patrick Woo-Sam. All rights reserved.
//
import UIKit
import GoogleMaps
class MapVC: UIViewController, GMSMapViewDelegate {
let surflineData = SurflineDataPoints(allCoordinates: SurflineDataPoints.get_all_coordinates())
var surfSpotMarkers = [GMSMarker]()
var surfData: SurfData = SurfData()
var mapView: GMSMapView!
var zoomLevel: Float = 12.0
private var currentLocContext = UnsafeMutableRawPointer(bitPattern: 0)
override func loadView() {
// Create a GMSCameraPosition that tells the map to display
// Santa Barbara, California with some zoom.
let camera = GMSCameraPosition.camera(withLatitude: 33.660057, longitude: -117.998970, zoom: self.zoomLevel)
self.mapView = GMSMapView.map(withFrame: .zero, camera: camera)
self.mapView.delegate = self
self.mapView.isMyLocationEnabled = true
// self.mapView.settings.myLocationButton = true
self.view = mapView
}
override func viewWillAppear(_ animated: Bool) {
self.mapView.addObserver(self, forKeyPath: "myLocation", options: [], context: self.currentLocContext)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == self.currentLocContext {
let curLocation = self.mapView.myLocation!.coordinate
let goCurrentLocation = GMSCameraUpdate.setTarget(curLocation)
self.mapView.animate(with: goCurrentLocation)
self.mapView.removeObserver(self, forKeyPath: keyPath!, context: context)
self.currentLocContext?.deallocate(bytes: 0, alignedTo: 0)
self.mapView.isMyLocationEnabled = false // Save the CPU
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
// Do not remove data from surfData, as this would increase data usage and put more load on Surfline's API.
for (id, (lat, long)) in self.surflineData.allCoordinates {
let position = CLLocationCoordinate2D(latitude: lat, longitude: long)
let visibleArea = mapView.projection.visibleRegion()
let bounds = GMSCoordinateBounds(region: visibleArea)
if !surfData.hasData(id) {
if bounds.contains(position) {
self.surfData.get_surfline_data(id)
} else {
// Skip adding this marker if it is not within the view.
continue
}
}
if !surfData.hasData(id) {
// Skip adding this marker if the data has not yet been received.
continue
}
self.removeOutOfBoundsMarkers(bounds)
let surfSpot = GMSMarker(position: position)
surfSpot.title = self.surfData.spot_name[id]
surfSpot.icon = self.surfData.marker_image(id: id, day_index: 0, time_index: 1)
surfSpot.map = mapView
self.surfSpotMarkers.append(surfSpot)
}
}
private func removeOutOfBoundsMarkers(_ bounds: GMSCoordinateBounds) {
var index = 0
for marker in self.surfSpotMarkers {
if !bounds.contains(marker.position) {
marker.map = nil
surfSpotMarkers.remove(at: index)
index -= 1
}
index += 1
}
}
}
| mit | ee028f58379e60aad29d6556684c9e41 | 41.126437 | 151 | 0.628649 | 4.535891 | false | false | false | false |
CodeDrunkard/Algorithm | Algorithm.playground/Pages/Queue.xcplaygroundpage/Contents.swift | 1 | 1723 | /*:
Queue
Note1: Setting array[head] to nil to remove lead object from the queue, because delete the first object must edit other objects, it doesn't make sense.
Note2: If never remove Note1's empty spots that will keep growing as enqueue and dequeue. So it must be removed in some time that you can custom.
Enqueuing and dequeuing are O(1) operations.
*/
public struct Queue<T> {
fileprivate var array = [T?]() // Must container optional value
private var head = 0;
public var count: Int {
return array.count - head;
}
public var isEmpty: Bool {
return count == 0
}
public var front: T? {
return isEmpty ? nil : array[head]
}
public mutating func enqueue(_ element: T) {
array.append(element)
}
public mutating func dequeue() -> T? {
guard head < array.count, let element = front else {
return nil
}
// Note1.
array[head] = nil
head += 1
// Note2.
if (array.count > 50) &&
(Double(head) / Double(array.count) > 0.25) {
array.removeFirst(head)
head = 0
}
return element
}
public mutating func clear() {
array.removeAll()
head = 0
}
}
extension Queue: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: T...) {
self.init()
for element in elements {
self.enqueue(element)
}
}
}
//: TEST
var queue: Queue = [0, 1, 2]
queue.count
queue.isEmpty
queue.enqueue(3)
queue.dequeue()
queue.dequeue()
queue.clear()
queue.isEmpty
//: [Contents](Contents) | [Previous](@previous) | [Next](@next)
| mit | 6186fdd541557777c3a9a62be8ce1760 | 22.930556 | 152 | 0.577481 | 4.171913 | false | false | false | false |
codestergit/LTMorphingLabel | LTMorphingLabel/LTMorphingLabel+Pixelate.swift | 1 | 3730 | //
// LTMorphingLabel+Pixelate.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2014 Lex Tang, http://LexTang.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the “Software”), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
extension LTMorphingLabel {
func PixelateLoad() {
_effectClosures["Pixelate\(LTMorphingPhaseDisappear)"] = {
(char:Character, index: Int, progress: Float) in
return LTCharacterLimbo(
char: char,
rect: self._originRects[index],
alpha: CGFloat(1.0 - progress),
size: self.font.pointSize,
drawingProgress: CGFloat(progress))
}
_effectClosures["Pixelate\(LTMorphingPhaseAppear)"] = {
(char:Character, index: Int, progress: Float) in
return LTCharacterLimbo(
char: char,
rect: self._newRects[index],
alpha: CGFloat(progress),
size: self.font.pointSize,
drawingProgress: CGFloat(1.0 - progress)
)
}
_drawingClosures["Pixelate\(LTMorphingPhaseDraw)"] = {
(charLimbo: LTCharacterLimbo) in
if charLimbo.drawingProgress > 0.0 {
let charImage = self._pixelateImageForCharLimbo(charLimbo, withBlurRadius: charLimbo.drawingProgress * 6.0)
let charRect = charLimbo.rect
charImage.drawInRect(charLimbo.rect)
return true
}
return false
}
}
func _pixelateImageForCharLimbo(charLimbo: LTCharacterLimbo, withBlurRadius blurRadius: CGFloat) -> UIImage {
let scale = min(UIScreen.mainScreen().scale, 1.0 / blurRadius)
UIGraphicsBeginImageContextWithOptions(charLimbo.rect.size, false, scale)
let fadeOutAlpha = min(1.0, max(0.0, charLimbo.drawingProgress * -2.0 + 2.0 + 0.01))
let rect = CGRectMake(0, 0, charLimbo.rect.size.width, charLimbo.rect.size.height)
// let context = UIGraphicsGetCurrentContext()
// CGContextSetShouldAntialias(context, false)
String(charLimbo.char).bridgeToObjectiveC().drawInRect(rect, withAttributes: [
NSFontAttributeName: self.font,
NSForegroundColorAttributeName: self.textColor.colorWithAlphaComponent(fadeOutAlpha)
])
// CGContextSetShouldAntialias(context, true)
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage
}
} | mit | 5c3a553324c80f06dec5a99b31a905e5 | 39.912088 | 123 | 0.635411 | 5.009421 | false | false | false | false |
zrtalent/SwiftDictModel | SwiftDict2Model/SwiftDict2Model/ViewController.swift | 1 | 3187 | //
// ViewController.swift
// 02-字典转模型
//
// Created by apple on 15/3/3.
// Copyright (c) 2015年 heima. All rights reserved.
//
import UIKit
/**
1. 获取字典
2. 根据字典的内容,"创建"并且"填充"模型类
3. 需要动态的知道模型类都包含哪些属性
class_copyPropertyList(基本类型必须设置初始值,能够获取类型 - 自定义对象,如果包含在数组中,同样无法获取)
class_copyIVarList(能够提取所有属性,但是不能获取类型)
4. 如何能够知道自定义对象的类型?
- MJExtension,定义了一个协议,通过协议告诉"工具"自定义对象的类型
- JSONModel,定义了很多协议,通过遵守协议的方式,告诉"工具"准确的类型
5. 测试子类的模型信息
运行时 class_copyIVarList 只能获取到当前类的属性列表,不会获取到父类的属性列表
解决问题:利用循环,顺序遍历父类,依次生成所有父类的属性列表
SubModel : 1 个属性 + 10 个属性 = 11 属性
Mdole : 10 个属性
...
6. 之所以要求模型类必须继承自 NSObject
1> 可以使用 KVC 设置数值,如果对象不是继承自 NSObject,是无法使用 KVC 的
2> 方便遍历
7. 拼接字典
8. 需要考虑到性能优化的问题 -> 一旦类的模型信息获取到,就不再需要再次获取
解决办法:可以使用一个缓存字典,记录所有解析过的模型类信息
[类名: 模型字典, 类名2: 模型字典]
9. 字典转模型的工具使用范围,在非常多的界面中,都会有对网络数据做字典转模型的需求!
将字典转模型工具,变成单例,统一负责应用程序中所有模型转换的工作!
10. 字典转模型
*/
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let json = loadJSON()
let obj = SwiftDictModel.sharedManager.objectWithDictionary(json, cls: SubModel.self) as! SubModel
println("object.info.name !!!! " + obj.info!.name!)
println("OTHER")
for value in obj.other! {
println(value.name)
}
println("OTHERS")
for value in obj.others! {
let o = value as! Info
println(o.name)
}
println("Demo \(obj.demo!)")
}
/// 测试模型信息
func testModleInfo() {
println(loadJSON())
let tools = SwiftDictModel()
println("模型字典 + \(tools.fullModleInfo(SubModel.self))")
println("模型字典 + \(tools.fullModleInfo(SubModel.self))")
println("模型字典 + \(tools.fullModleInfo(Model.self))")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadJSON() -> NSDictionary {
let path = NSBundle.mainBundle().pathForResource("Model01.json", ofType: nil)
let data = NSData(contentsOfFile: path!)
return NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.allZeros, error: nil) as! NSDictionary
}
}
| mit | 9830332eab0f3894c692a18f238fd740 | 24.404494 | 129 | 0.647943 | 3.216216 | false | false | false | false |
Slobako/musearch | musearch/musearch/Controllers/LyricsViewController.swift | 1 | 1843 | //
// LyricsViewController.swift
// musearch
//
// Created by Slobodan Kovrlija on 9/30/17.
// Copyright © 2017 Slobodan Kovrlija. All rights reserved.
//
import UIKit
class LyricsViewController: UIViewController {
// MARK: - IBOutlets
@IBOutlet weak var albumArtImageView: UIImageView!
@IBOutlet weak var artistLabel: UILabel!
@IBOutlet weak var songLabel: UILabel!
@IBOutlet weak var albumLabel: UILabel!
@IBOutlet weak var lyricsTextView: UITextView!
// MARK: - Properties
var selectedResult: SearchResult?
lazy var searchService: SearchService = SearchService()
override func viewDidLoad() {
super.viewDidLoad()
setViewValues()
// Performs lyrics search for chosen song and displays it in the text view
searchService.searchLyricsFor(song: songLabel.text!, artist: artistLabel.text!) { [unowned self] (lyrics) in
guard let lyrics = lyrics else { return }
if lyrics != "" {
self.lyricsTextView.text = lyrics
} else {
self.lyricsTextView.text = "LYRICS NOT FOUND"
}
}
}
// Sets artist name, song, album and album cover image
func setViewValues() {
if let artist = selectedResult?.artist {
artistLabel.text = artist
}
if let song = selectedResult?.song {
songLabel.text = song
}
if let album = selectedResult?.album {
albumLabel.text = album
}
if let albumArtURLString = selectedResult?.albumArtURL {
if let albumArtURL = URL(string: albumArtURLString) {
albumArtImageView.sd_setImage(with: albumArtURL, placeholderImage: #imageLiteral(resourceName: "album_art_placeholder"))
}
}
}
}
| gpl-3.0 | a7958928a2adacf5aa3e6caa484e017c | 30.220339 | 136 | 0.617264 | 4.628141 | false | false | false | false |
apple/swift-nio | Sources/NIOFoundationCompat/Codable+ByteBuffer.swift | 1 | 6539 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import Foundation
extension ByteBuffer {
/// Attempts to decode the `length` bytes from `index` using the `JSONDecoder` `decoder` as `T`.
///
/// - parameters:
/// - type: The type type that is attempted to be decoded.
/// - decoder: The `JSONDecoder` that is used for the decoding.
/// - index: The index of the first byte to decode.
/// - length: The number of bytes to decode.
/// - returns: The decoded value if successful or `nil` if there are not enough readable bytes available.
@inlinable
public func getJSONDecodable<T: Decodable>(_ type: T.Type,
decoder: JSONDecoder = JSONDecoder(),
at index: Int, length: Int) throws -> T? {
guard let data = self.getData(at: index, length: length, byteTransferStrategy: .noCopy) else {
return nil
}
return try decoder.decode(T.self, from: data)
}
/// Reads `length` bytes from this `ByteBuffer` and then attempts to decode them using the `JSONDecoder` `decoder`.
///
/// - parameters:
/// - type: The type type that is attempted to be decoded.
/// - decoder: The `JSONDecoder` that is used for the decoding.
/// - length: The number of bytes to decode.
/// - returns: The decoded value is successful or `nil` if there are not enough readable bytes available.
@inlinable
public mutating func readJSONDecodable<T: Decodable>(_ type: T.Type,
decoder: JSONDecoder = JSONDecoder(),
length: Int) throws -> T? {
guard let decoded = try self.getJSONDecodable(T.self,
decoder: decoder,
at: self.readerIndex,
length: length) else {
return nil
}
self.moveReaderIndex(forwardBy: length)
return decoded
}
/// Encodes `value` using the `JSONEncoder` `encoder` and set the resulting bytes into this `ByteBuffer` at the
/// given `index`.
///
/// - note: The `writerIndex` remains unchanged.
///
/// - parameters:
/// - value: An `Encodable` value to encode.
/// - encoder: The `JSONEncoder` to encode `value` with.
/// - returns: The number of bytes written.
@inlinable
@discardableResult
public mutating func setJSONEncodable<T: Encodable>(_ value: T,
encoder: JSONEncoder = JSONEncoder(),
at index: Int) throws -> Int {
let data = try encoder.encode(value)
return self.setBytes(data, at: index)
}
/// Encodes `value` using the `JSONEncoder` `encoder` and writes the resulting bytes into this `ByteBuffer`.
///
/// If successful, this will move the writer index forward by the number of bytes written.
///
/// - parameters:
/// - value: An `Encodable` value to encode.
/// - encoder: The `JSONEncoder` to encode `value` with.
/// - returns: The number of bytes written.
@inlinable
@discardableResult
public mutating func writeJSONEncodable<T: Encodable>(_ value: T,
encoder: JSONEncoder = JSONEncoder()) throws -> Int {
let result = try self.setJSONEncodable(value, encoder: encoder, at: self.writerIndex)
self.moveWriterIndex(forwardBy: result)
return result
}
}
extension JSONDecoder {
/// Returns a value of the type you specify, decoded from a JSON object inside the readable bytes of a `ByteBuffer`.
///
/// If the `ByteBuffer` does not contain valid JSON, this method throws the
/// `DecodingError.dataCorrupted(_:)` error. If a value within the JSON
/// fails to decode, this method throws the corresponding error.
///
/// - note: The provided `ByteBuffer` remains unchanged, neither the `readerIndex` nor the `writerIndex` will move.
/// If you would like the `readerIndex` to move, consider using `ByteBuffer.readJSONDecodable(_:length:)`.
///
/// - parameters:
/// - type: The type of the value to decode from the supplied JSON object.
/// - buffer: The `ByteBuffer` that contains JSON object to decode.
/// - returns: The decoded object.
public func decode<T: Decodable>(_ type: T.Type, from buffer: ByteBuffer) throws -> T {
return try buffer.getJSONDecodable(T.self,
decoder: self,
at: buffer.readerIndex,
length: buffer.readableBytes)! // must work, enough readable bytes
}
}
extension JSONEncoder {
/// Writes a JSON-encoded representation of the value you supply into the supplied `ByteBuffer`.
///
/// - parameters:
/// - value: The value to encode as JSON.
/// - buffer: The `ByteBuffer` to encode into.
public func encode<T: Encodable>(_ value: T,
into buffer: inout ByteBuffer) throws {
try buffer.writeJSONEncodable(value, encoder: self)
}
/// Writes a JSON-encoded representation of the value you supply into a `ByteBuffer` that is freshly allocated.
///
/// - parameters:
/// - value: The value to encode as JSON.
/// - allocator: The `ByteBufferAllocator` which is used to allocate the `ByteBuffer` to be returned.
/// - returns: The `ByteBuffer` containing the encoded JSON.
public func encodeAsByteBuffer<T: Encodable>(_ value: T, allocator: ByteBufferAllocator) throws -> ByteBuffer {
let data = try self.encode(value)
var buffer = allocator.buffer(capacity: data.count)
buffer.writeBytes(data)
return buffer
}
}
| apache-2.0 | 8cd2d2451e346d9caa291976f6ae21fa | 46.043165 | 120 | 0.571188 | 4.961305 | false | false | false | false |
FrancisBaileyH/Swift-Sociables | Sociables/RuleManager.swift | 1 | 9293 | //
// RuleTypeManager.swift
// Socialables
//
// Created by Francis Bailey on 2015-03-20.
//
import CoreData
import UIKit
/**
* @struct RuleType
*
* @abstract
* Contains the values used to store a rule and represent it visually.
*
* @field title
* The name of the rule
* @field explanation
* The accompanying text explaining how the rule works
* @field order
* The order in which to display the rules in a list
*/
struct RuleType {
var title : String
var explanation : String
var order: Int
}
/**
* @struct CardAndRuleType
*
* @abstract
* Binds the RuleType to a given card
*
* @field rule
* A RuleType to bind
* @field rank
* The rank to bind the rule to
* @field isDefault
* A helper value to determine if the rule is a custom one or not
*/
struct CardAndRuleType {
var rule: RuleType
var rank: String
var isDefault: Bool
}
class RuleManager
{
static let sharedInstance = RuleManager()
let coreData: NSManagedObjectContext
let ruleEntityDescription: NSEntityDescription
let defaultGirlsDrinkCard = DeckBias.girlsDrinkMore.rawValue
let defaultGuysDrinkCard = DeckBias.guysDrinkMore.rawValue
/**
* Establish a connection to coreData
*/
init() {
coreData = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
ruleEntityDescription = NSEntityDescription.entityForName("Rule", inManagedObjectContext: coreData)!
}
static let defaultRules : [String: RuleType] = [
"Ace" : RuleType(title: "Waterfall", explanation: "Drink in a circle starting with the person who drew this card. When that person stops drinking the next person may also stop and so on, until the end of the cirlce is reached.", order: 1),
"2" : RuleType(title: "Two is you", explanation: "Choose someone to drink", order: 2),
"3" : RuleType(title: "Three is me", explanation: "You drink", order: 3),
"4" : RuleType(title: "Whores", explanation: "Girls drink", order: 4),
"5" : RuleType(title: "Never have I ever", explanation: "Go around in a circle and say something you've never done. When someone has done a total of 3 things mentioned, they drink", order: 5),
"6" : RuleType(title: "Dicks", explanation: "Guys drink", order: 6),
"7" : RuleType(title: "Categories", explanation: "Pick a category such as sports teams or beer brands and go around in a circle with the next person saying something in the category. The first player who can't think of anything drinks.", order: 7),
"8" : RuleType(title: "Date", explanation: "Choose another player to drink everytime you drink.", order: 8),
"9" : RuleType(title: "Rhyme Time", explanation: "Pick a word to rhyme. Everyone goes in a circle trying to rhyme with that word. The first person who can't think of rhyme drinks.", order: 9),
"10" : RuleType(title: "Rule Card", explanation: "Pick a rule that must be followed for the rest of the game. If a person breaks the rule, they drink.", order: 10),
"Jack" : RuleType(title: "Eyes", explanation: "Everyone puts their head down and on the count of 3 looks up at a random person. If two people meet eyes, they drink. Repeat 3 times.", order: 11),
"Queen" : RuleType(title: "Question Master", explanation: "You can now ask anyone questions, if they answer they drink. You stop being question master when the next Queen is drawn.", order: 12),
"King" : RuleType(title: "Sociables", explanation: "Everyone drinks!", order: 13)
]
/**
* Save a rule into persistent storage, if the rule already exists, then simply
* update the rule
*
* @param
* A CardAndRuleType containing all values required to save the rule
*
* @return
* If an error occurs an automatically generated NSError object will be returned
*/
func saveRule( rule: CardAndRuleType ) -> NSError? {
var error: NSError?
if let savedRule = fetchRuleFromStorage(rule.rank) {
savedRule.setValue(rule.rank, forKey: Rule.ruleRankKey)
savedRule.setValue(rule.rule.title, forKey: Rule.ruleTitleKey)
savedRule.setValue(rule.rule.explanation, forKey: Rule.ruleExplanationKey)
} else {
let ruleEntity = Rule(entity: ruleEntityDescription, insertIntoManagedObjectContext: coreData)
ruleEntity.rank = rule.rank
ruleEntity.title = rule.rule.title
ruleEntity.explanation = rule.rule.explanation
}
coreData.save(&error)
return error
}
/**
* Remove a rule in persistent storage
*
* @param rank
* A case sensitive card rank
*
* @return NSError?
* If the rule was not found return a user friendly error
*/
func removePersistentRule( rank: String ) -> NSError? {
if let rule = fetchRuleFromStorage(rank) {
coreData.deleteObject(rule)
coreData.save(nil)
return nil
} else {
let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Current rule is already default rule"])
return error
}
}
/**
* Remove all rules in persistent storage
*/
func removeAllPersistentRules() {
}
/**
* Attempt to fetch a rule from CoreData
*
* @param rank
* A case sensitive card rank
*
* @return NSManagedObject?
* A coredata object representing the rule fetched, if a rule for that rank was found
*/
internal func fetchRuleFromStorage( rank: String ) -> NSManagedObject? {
let request = NSFetchRequest()
request.entity = ruleEntityDescription
request.predicate = NSPredicate(format: "(" + Rule.ruleRankKey + " = %@)", rank)
var results = coreData.executeFetchRequest(request, error: nil)
if results?.count > 0 {
return results?[0] as? NSManagedObject
} else {
return nil
}
}
/**
* Fetch individual RuleType by rank, if no rule is found in
* persistent storage, then return the default rule
*
* @param rank
* A case sensitive card rank
*
* @return CardAndRuleType
* A struct containing the rule and the card
*/
func getRule( rank : String ) -> CardAndRuleType {
if let rule = fetchRuleFromStorage(rank) {
let title = rule.valueForKey(Rule.ruleTitleKey) as! String
let explanation = rule.valueForKey(Rule.ruleExplanationKey) as! String
let order = RuleManager.defaultRules[rank]?.order
return CardAndRuleType(rule: RuleType(title: title, explanation: explanation, order: order! ), rank: rank, isDefault: false)
}
else {
return CardAndRuleType(rule: RuleManager.defaultRules[rank]!, rank: rank, isDefault: true)
}
}
/**
* Fetch all custom rules form core data and union the results with
* the default rules, creating a complete rule set
*
* @return [CardAndRuleType]
* An array of structs containing both a rule and respective card tyoe
*/
func getAllRules() -> [CardAndRuleType] {
var rules = [CardAndRuleType]()
var rulesTmp = [String: RuleType]()
let request = NSFetchRequest(entityName: "Rule")
let persistentRules = coreData.executeFetchRequest(request, error: nil) as? [Rule]
if persistentRules?.count > 0 {
for rule in persistentRules! {
let order = RuleManager.defaultRules[rule.rank.capitalizedString]?.order
rulesTmp.updateValue(RuleType(title: rule.title, explanation: rule.explanation, order: order!), forKey: rule.rank)
}
}
for rule in RuleManager.defaultRules {
if rulesTmp[rule.0] == nil {
let order = RuleManager.defaultRules[rule.0]?.order
rules.append(CardAndRuleType(rule: RuleType(title: rule.1.title, explanation: rule.1.explanation, order: order!), rank: rule.0, isDefault: true))
} else {
rules.append(CardAndRuleType(rule: rulesTmp[rule.0]!, rank: rule.0, isDefault: false))
}
}
return sortRules(rules)
}
/**
* Sort rules by order established in the RuleType struct
*
* @param rules
* An array of CardAndRuleTypes to be sorted
*
* @return [CardAndRuleType]
* An array of CardAndRuleTypes sorted by the order field in the rule value
*/
func sortRules(rules: [CardAndRuleType]) -> [CardAndRuleType] {
var sortedRules = rules
sortedRules.sort({ $0.rule.order < $1.rule.order })
return sortedRules
}
}
| gpl-3.0 | 75d7448104428e58a4ba39a2525499bc | 33.418519 | 260 | 0.609168 | 4.517744 | false | false | false | false |
Incipia/IncipiaKit | IncipiaKit/UIKit-Extensions/UITextField+Extensions.swift | 1 | 612 | //
// UITextField+Extensions.swift
// IncipiaKit
//
// Created by Gregory Klein on 7/1/16.
// Copyright © 2016 Incipia. All rights reserved.
//
import UIKit
public extension UITextField {
public func update(placeholderColor color: UIColor) {
let placeholderText = placeholder ?? ""
let placeholderFont = font ?? UIFont.systemFontOfSize(12)
let placeholderAttributes = [NSFontAttributeName : placeholderFont, NSForegroundColorAttributeName : color]
let attributedTitle = NSAttributedString(string: placeholderText, attributes: placeholderAttributes)
attributedPlaceholder = attributedTitle
}
}
| apache-2.0 | 0ed83c2ecae0f564e8cb6a637e3a52b6 | 31.157895 | 109 | 0.774141 | 4.736434 | false | false | false | false |
haijianhuo/TopStore | Pods/CircleMenu/CircleMenuLib/CircleMenuButton/CircleMenuButton.swift | 1 | 8280 | //
// CircleMenuButton.swift
//
// Copyright (c) 18/01/16. Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
internal class CircleMenuButton: UIButton {
// MARK: properties
weak var container: UIView?
// MARK: life cycle
init(size: CGSize, platform: UIView, distance: Float, angle: Float = 0) {
super.init(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: size))
backgroundColor = UIColor(red: 0.79, green: 0.24, blue: 0.27, alpha: 1)
layer.cornerRadius = size.height / 2.0
let aContainer = createContainer(CGSize(width: size.width, height: CGFloat(distance)), platform: platform)
// hack view for rotate
let view = UIView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height))
view.backgroundColor = UIColor.clear
view.addSubview(self)
// ...
aContainer.addSubview(view)
container = aContainer
view.layer.transform = CATransform3DMakeRotation(-CGFloat(angle.degrees), 0, 0, 1)
rotatedZ(angle: angle, animated: false)
}
internal required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: configure
fileprivate func createContainer(_ size: CGSize, platform: UIView) -> UIView {
let container = customize(UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: size))) {
$0.backgroundColor = UIColor.clear
$0.translatesAutoresizingMaskIntoConstraints = false
$0.layer.anchorPoint = CGPoint(x: 0.5, y: 1)
}
platform.addSubview(container)
// added constraints
let height = NSLayoutConstraint(item: container,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height,
multiplier: 1,
constant: size.height)
height.identifier = "height"
container.addConstraint(height)
container.addConstraint(NSLayoutConstraint(item: container,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .width,
multiplier: 1,
constant: size.width))
platform.addConstraint(NSLayoutConstraint(item: platform,
attribute: .centerX,
relatedBy: .equal,
toItem: container,
attribute: .centerX,
multiplier: 1,
constant: 0))
platform.addConstraint(NSLayoutConstraint(item: platform,
attribute: .centerY,
relatedBy: .equal,
toItem: container,
attribute: .centerY,
multiplier: 1,
constant: 0))
return container
}
// MARK: methods
internal func rotatedZ(angle: Float, animated: Bool, duration: Double = 0, delay: Double = 0) {
guard let container = self.container else {
fatalError("contaner don't create")
}
let rotateTransform = CATransform3DMakeRotation(CGFloat(angle.degrees), 0, 0, 1)
if animated {
UIView.animate(
withDuration: duration,
delay: delay,
options: UIViewAnimationOptions(),
animations: { () -> Void in
container.layer.transform = rotateTransform
},
completion: nil)
} else {
container.layer.transform = rotateTransform
}
}
}
// MARK: Animations
internal extension CircleMenuButton {
internal func showAnimation(distance: Float, duration: Double, delay: Double = 0) {
guard let heightConstraint = (self.container?.constraints.filter { $0.identifier == "height" })?.first else {
fatalError()
}
transform = CGAffineTransform(scaleX: 0, y: 0)
container?.superview?.layoutIfNeeded()
alpha = 0
heightConstraint.constant = CGFloat(distance)
UIView.animate(
withDuration: duration,
delay: delay,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0,
options: UIViewAnimationOptions.curveLinear,
animations: { () -> Void in
self.container?.superview?.layoutIfNeeded()
self.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.alpha = 1
}, completion: { (_) -> Void in
})
}
internal func hideAnimation(distance: Float, duration: Double, delay: Double = 0) {
guard let heightConstraint = (self.container?.constraints.filter { $0.identifier == "height" })?.first else {
return
}
heightConstraint.constant = CGFloat(distance)
UIView.animate(
withDuration: duration,
delay: delay,
options: UIViewAnimationOptions.curveEaseIn,
animations: { () -> Void in
self.container?.superview?.layoutIfNeeded()
self.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
}, completion: { (_) -> Void in
self.alpha = 0
if let _ = self.container {
self.container?.removeFromSuperview() // remove container
}
})
}
internal func changeDistance(_ distance: CGFloat, animated _: Bool, duration: Double = 0, delay: Double = 0) {
guard let heightConstraint = (self.container?.constraints.filter { $0.identifier == "height" })?.first else {
fatalError()
}
heightConstraint.constant = distance
UIView.animate(
withDuration: duration,
delay: delay,
options: UIViewAnimationOptions.curveEaseIn,
animations: { () -> Void in
self.container?.superview?.layoutIfNeeded()
},
completion: nil)
}
// MARK: layer animation
internal func rotationAnimation(_ angle: Float, duration: Double) {
let rotation = customize(CABasicAnimation(keyPath: "transform.rotation")) {
$0.duration = TimeInterval(duration)
$0.toValue = (angle.degrees)
$0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
}
container?.layer.add(rotation, forKey: "rotation")
}
}
| mit | e7e9569ea68fdaa0a88ba71a763ebadb | 38.428571 | 117 | 0.544928 | 5.465347 | false | false | false | false |
illuminati-fin/LANScan-iOS | LANScan/ScanView.swift | 1 | 4562 | //
// ScanView.swift
// TestApp
//
// Created by Ville Välimaa on 19/01/2017.
// Copyright © 2017 Ville Välimaa. All rights reserved.
//
import UIKit
import SpinKit
protocol ScanViewDelegate: class {
func didPressInitialScan()
func didSelectTargetDevice(index:Int)
}
class ScanView: UIView {
private let scanButton = with(UIButton()) { button in
button.setTitle("Start Scan", for: UIControlState.normal)
button.titleLabel?.font = UIFont(name: "Press Start 2P", size: 12.0)
button.titleLabel?.textColor = UIColor.white
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.installShadow(height: 2)
button.titleEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
button.backgroundColor = UIColor(red:0.00, green:0.56, blue:0.76, alpha:1.0)
button.layer.shadowOpacity = 1.0
button.layer.shadowOffset = CGSize(width: 0, height: 3)
button.layer.shadowRadius = 0
button.addTarget(self, action: #selector(scanButtonPressed), for: .touchUpInside)
}
private let scanningList = with(UITableView()) { list in
list.backgroundColor = UIColor(red:0.17, green:0.24, blue:0.31, alpha:1.0)
list.separatorColor = UIColor(red:0.17, green:0.24, blue:0.31, alpha:1.0)
list.separatorInset = .zero
list.layoutMargins = .zero
list.cellLayoutMarginsFollowReadableWidth = false
list.tableFooterView = UIView(frame: CGRect.zero)
list.alpha = 0
list.register(HostCell.self, forCellReuseIdentifier: "cell")
}
private let spinner = with(RTSpinKitView(style: RTSpinKitViewStyle.stylePulse)) { tSpinner in
tSpinner?.spinnerSize = 100
tSpinner?.isHidden = true
}
weak var delegate:ScanViewDelegate?
var foundHosts:Array<Host> = [] {
didSet {
scanningList.reloadData()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(red:0.17, green:0.24, blue:0.31, alpha:1.0)
addSubview(scanButton)
addSubview(scanningList)
addSubview(spinner ?? RTSpinKitView(frame: .zero))
scanningList.delegate = self
scanningList.dataSource = self
makeConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initScanView() {
UIView.animate(withDuration: 0.7, animations: {
self.scanButton.alpha = 0.0
self.scanningList.alpha = 1.0
}) { (Bool) in
self.showLoadingSpinner(show: true)
}
}
func setUIModeToFinished() { showLoadingSpinner(show: false) }
func setUIModeToScanning() {
foundHosts.removeAll()
scanningList.reloadData()
showLoadingSpinner(show: true)
}
private func showLoadingSpinner(show:Bool) { spinner?.isHidden = !show }
@objc private func scanButtonPressed(sender:AnyObject) {
self.delegate?.didPressInitialScan()
}
private func makeConstraints() {
scanButton.snp.makeConstraints { (make) in
make.center.equalTo(self)
make.width.equalTo(self).dividedBy(3)
make.height.equalTo(self.scanButton.snp.width).dividedBy(2)
}
scanningList.snp.makeConstraints { (make) in
make.edges.equalTo(self)
}
spinner?.snp.makeConstraints { (make) in
make.center.equalTo(self)
}
}
}
//-------------------- DELEGATES--------------------//
//
extension ScanView: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.foundHosts.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! HostCell
cell.setHostDetails(host: foundHosts[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
delegate?.didSelectTargetDevice(index: indexPath.row)
}
}
| mit | f75bb383115fa358e8df177aa0cbb003 | 31.564286 | 101 | 0.630401 | 4.396336 | false | false | false | false |
danielloureda/congenial-sniffle | Project14/Project14/GameScene.swift | 1 | 4124 | //
// GameScene.swift
// Project14
//
// Created by Daniel Loureda Arteaga on 20/6/17.
// Copyright © 2017 Dano. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var numRounds = 0
var popupTime = 0.85
var slots = [WhackSlot]()
var gameScore: SKLabelNode!
var score: Int = 0 {
didSet {
gameScore.text = "Score: \(score)"
}
}
func createSlot(at position: CGPoint){
let slot = WhackSlot()
slot.configure(at: position)
slots.append(slot)
addChild(slot)
}
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "whackBackground")
background.position = CGPoint(x: 512, y: 384)
background.blendMode = .replace
background.zPosition = -1
addChild(background)
gameScore = SKLabelNode(fontNamed: "Chalkduster")
gameScore.text = "Score: 0"
gameScore.position = CGPoint(x: 8, y: 8)
gameScore.horizontalAlignmentMode = .left
gameScore.fontSize = 48
addChild(gameScore)
for i in 0 ..< 5 { createSlot(at: CGPoint(x: 100 + (i * 170), y: 410)) }
for i in 0 ..< 4 { createSlot(at: CGPoint(x: 180 + (i * 170), y: 320)) }
for i in 0 ..< 5 { createSlot(at: CGPoint(x: 100 + (i * 170), y: 230)) }
for i in 0 ..< 4 { createSlot(at: CGPoint(x: 180 + (i * 170), y: 140)) }
DispatchQueue.main.asyncAfter(deadline: .now()+1){ [unowned self] in
self.createEnemy()
}
}
func createEnemy() {
numRounds += 1
if numRounds >= 30 {
for slot in slots {
slot.hide()
}
let gameOver = SKSpriteNode(imageNamed: "gameOver")
gameOver.position = CGPoint(x: 512, y: 384)
gameOver.zPosition = 1
addChild(gameOver)
return
}
popupTime *= 0.991
slots = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: slots) as! [WhackSlot]
slots[0].show(hideTime: popupTime)
if RandomInt(min: 0, max: 12) > 4 { slots[1].show(hideTime: popupTime) }
if RandomInt(min: 0, max: 12) > 8 { slots[2].show(hideTime: popupTime) }
if RandomInt(min: 0, max: 12) > 10 { slots[3].show(hideTime: popupTime) }
if RandomInt(min: 0, max: 12) > 11 { slots[4].show(hideTime: popupTime) }
let minDelay = popupTime / 2.0
let maxDelay = popupTime * 2
let delay = RandomDouble(min: minDelay, max: maxDelay)
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [unowned self] in
self.createEnemy()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: self)
let tappedNodes = nodes(at: location)
for node in tappedNodes {
if node.name == "charFriend" {
let whackSlot = node.parent!.parent as! WhackSlot
if !whackSlot.isVisible { continue }
if whackSlot.isHit { continue }
whackSlot.hit()
score -= 5
run(SKAction.playSoundFileNamed("whackBad.caf", waitForCompletion:false))
} else if node.name == "charEnemy" {
let whackSlot = node.parent!.parent as! WhackSlot
if !whackSlot.isVisible { continue }
if whackSlot.isHit { continue }
whackSlot.charNode.xScale = 0.85
whackSlot.charNode.yScale = 0.85
whackSlot.hit()
score += 1
run(SKAction.playSoundFileNamed("whack.caf", waitForCompletion:false))
}
}
}
}
}
| apache-2.0 | d8ae0c9d066a39a82a8435fb68644eef | 33.358333 | 96 | 0.518554 | 4.586207 | false | false | false | false |
lieven/fietsknelpunten-ios | App/MainViewController.swift | 1 | 10799 | //
// MainViewController.swift
// Fietsknelpunten
//
// Created by Lieven Dekeyser on 11/11/16.
// Copyright © 2016 Fietsknelpunten. All rights reserved.
//
import UIKit
import MapKit
import PureLayout
import FietsknelpuntenAPI
import CoreLocation
import MobileCoreServices
import Photos
class MainViewController: EditingViewController
{
private let mapTypeSegmentedControl: UISegmentedControl
private let mapView = MKMapView.newAutoLayout()
private var firstAppearance = true
fileprivate let geocoder = CLGeocoder()
fileprivate var reportAnnotation: ReportAnnotation?
{
didSet
{
if let oldAnnotation = oldValue
{
mapView.removeAnnotation(oldAnnotation)
}
if let newAnnotation = reportAnnotation
{
mapView.addAnnotation(newAnnotation)
reverseGeocodeReportLocation(selectWhenDone: true)
isEditing = true
}
else
{
isEditing = false
}
}
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)
{
let items = [
NSLocalizedString("MAP_TYPE_MAP", value: "Map", comment: "Map type segmented control: Map item. Should be very short."),
NSLocalizedString("MAP_TYPE_SATELLITE", value: "Satellite", comment: "Map type segmented control: Satellite item. Should be very short.")
]
mapTypeSegmentedControl = UISegmentedControl(items: items)
mapTypeSegmentedControl.selectedSegmentIndex = 0
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
title = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
mapTypeSegmentedControl.addTarget(self, action: #selector(mapTypeSelected), for: .valueChanged)
navigationItem.titleView = mapTypeSegmentedControl
hidesBottomBarWhenPushed = false
updateToolbarItems()
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad()
{
super.viewDidLoad()
setupMapView()
}
private func setupMapView()
{
self.view.addSubview(mapView)
mapView.delegate = self
mapView.autoPinEdgesToSuperviewEdges()
}
@objc private func mapTypeSelected()
{
mapView.mapType = mapTypeSegmentedControl.selectedSegmentIndex == 1 ? .hybrid : .standard
}
override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
if firstAppearance
{
showUserLocation()
firstAppearance = false
}
}
private func updateToolbarItems()
{
if self.isEditing
{
let report = NSLocalizedString("REPORT_PROBLEM_BUTTON", value: "Report", comment: "Report problem button. Should be short")
self.toolbarItems = [
UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelReportProblem)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: report, style: .done, target: self, action: #selector(showReport))
]
}
else
{
self.toolbarItems = [
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(reportProblem)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
]
}
}
override var isEditing: Bool
{
didSet
{
updateToolbarItems()
}
}
private func showUserLocation()
{
checkLocationAuthorization()
{
[weak self] in
guard let strongSelf = self else
{
return
}
let mapView = strongSelf.mapView
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow
strongSelf.updateToolbarItems()
}
}
@objc private func cancelReportProblem()
{
reportAnnotation = nil
}
@objc private func reportProblemByDroppingPin()
{
startNewReport(image: nil, coordinate: nil)
}
@objc private func reportProblem()
{
let newReportTitle = NSLocalizedString("NEW_REPORT_ACTIONSHEET_TITLE", value: "New Report", comment: "Title for the action sheet displayed when a user wants to create a new report. Should be very short")
let actionSheet = UIAlertController(title: newReportTitle, message: nil, preferredStyle: .actionSheet)
let cameraAvailable = UIImagePickerController.isSourceTypeAvailable(.camera)
#if DEBUG
let showCamera = true
#else
let showCamera = cameraAvailable
#endif // DEBUG
if showCamera
{
let takePhoto = NSLocalizedString("TAKE_PHOTO", value: "Take Photo", comment: "Take Photo button in the action sheet displayed when a user wants to pick a photo. Should be short.")
actionSheet.addAction(UIAlertAction(title: takePhoto, style: .default) { [weak self] (_) in
self?.reportProblemUsingImagePicker(sourceType: cameraAvailable ? .camera : .photoLibrary)
})
}
let chooseFromLibrary = NSLocalizedString("CHOOSE_PHOTO_FROM_LIBRARY", value: "Photo from Library", comment: "Choose from Library button in the action sheet displayed when a user wants to pick a photo. Should be short.")
actionSheet.addAction(UIAlertAction(title: chooseFromLibrary, style: .default) { [weak self] (_) in
self?.reportProblemUsingImagePicker(sourceType: .photoLibrary)
})
let withoutPhoto = NSLocalizedString("REPORT_PROBLEM_WITHOUT_PHOTO", value: "Without Photo", comment: "Report a problem without photo")
actionSheet.addAction(UIAlertAction(title: withoutPhoto, style: .default) { [weak self] (_) in
self?.startNewReport(image: nil, coordinate: nil)
})
let cancel = NSLocalizedString("CANCEL", value: "Cancel", comment: "Cancel button. Should be very short")
actionSheet.addAction(UIAlertAction(title: cancel, style: .cancel, handler: nil))
present(actionSheet, animated: true, completion: nil)
}
private func reportProblemUsingImagePicker(sourceType: UIImagePickerController.SourceType)
{
let imagePicker = UIImagePickerController()
imagePicker.sourceType = sourceType
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.delegate = self
present(imagePicker, animated: true, completion: nil)
}
fileprivate func startNewReport(image: UIImage?, coordinate: CLLocationCoordinate2D?)
{
let initialCoordinate: CLLocationCoordinate2D
if let coordinate = coordinate
{
initialCoordinate = coordinate
}
else if mapView.isUserLocationVisible
{
initialCoordinate = mapView.userLocation.coordinate
}
else
{
initialCoordinate = mapView.centerCoordinate
}
mapView.centerCoordinate = initialCoordinate
let annotation = ReportAnnotation(report: Report(coordinate: initialCoordinate, image: image))
reportAnnotation = annotation
}
@objc fileprivate func showReport()
{
guard let report = self.reportAnnotation?.report, let navigationController = self.navigationController else
{
return
}
let reportViewController = ReportProblemViewController(report: report)
reportViewController.onDiscard = { [weak self] in self?.discardProblemReport() }
navigationController.pushViewController(reportViewController, animated: true)
}
private func discardProblemReport()
{
self.reportAnnotation = nil
let _ = self.navigationController?.popToRootViewController(animated: true)
}
fileprivate func reverseGeocodeReportLocation(selectWhenDone: Bool)
{
guard let reportAnnotation = reportAnnotation else
{
return
}
let report = reportAnnotation.report
let coordinate = report.coordinate
report.countryCode = nil
report.postalCode = nil
report.jurisdiction = nil
if selectWhenDone
{
mapView.deselectAnnotation(reportAnnotation, animated: false)
}
let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
geocoder.reverseGeocodeLocation(location)
{
[weak self] (placemarks, error) in
reportAnnotation.placemark = placemarks?.first
if selectWhenDone
{
self?.mapView.selectAnnotation(reportAnnotation, animated: false)
}
}
}
}
extension MainViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
{
guard let image = info[.originalImage] as? UIImage else
{
print("Should not happen: No image")
dismiss(animated: true, completion: nil)
return
}
dismiss(animated: true)
{
[weak self] in
let continueWithoutLocation: ()->() =
{
self?.startNewReport(image: image, coordinate: nil)
}
guard let assetURL = info[.referenceURL] as? URL else
{
continueWithoutLocation()
return
}
let continueWithLocation: ()->() =
{
let asset = PHAsset.fetchAssets(withALAssetURLs: [assetURL], options: nil).firstObject
let location = asset?.location
self?.startNewReport(image: image, coordinate: location?.coordinate)
}
self?.checkPhotosAuthorization(denied: continueWithoutLocation, authorized: continueWithLocation)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
{
dismiss(animated: true, completion: nil)
}
}
extension MainViewController: MKMapViewDelegate
{
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
{
if let reportAnnotation = annotation as? ReportAnnotation
{
let reportPinReuseIdentifier = "ReportPin"
let pin: MKPinAnnotationView
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reportPinReuseIdentifier) as? MKPinAnnotationView
{
pin = dequeuedAnnotationView
pin.annotation = reportAnnotation
}
else
{
pin = MKPinAnnotationView(annotation: reportAnnotation, reuseIdentifier: reportPinReuseIdentifier)
pin.pinTintColor = UIColor.red
pin.isDraggable = true
pin.animatesDrop = true
pin.canShowCallout = true
}
if let image = reportAnnotation.report.images.first
{
let imageView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0))
imageView.image = image
imageView.contentMode = .scaleAspectFill
pin.leftCalloutAccessoryView = imageView
}
else
{
pin.leftCalloutAccessoryView = nil
}
return pin
}
return nil
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl)
{
if control == view.rightCalloutAccessoryView
{
showReport()
}
}
func mapView(_ mapView: MKMapView, annotationView: MKAnnotationView, didChange newState: MKAnnotationView.DragState, fromOldState oldState: MKAnnotationView.DragState)
{
if newState == .ending
{
reverseGeocodeReportLocation(selectWhenDone: annotationView.isSelected)
}
}
}
| mit | 54b03fe502407639ce97849e9ca17d88 | 26.198992 | 222 | 0.737081 | 4.221267 | false | false | false | false |
xedin/swift | stdlib/public/Darwin/Accelerate/vImage_Converter.swift | 2 | 10264 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// vImageConverter
//
//===----------------------------------------------------------------------===//
@available(iOS 9999, OSX 9999, tvOS 9999, watchOS 9999, *)
extension vImageConverter {
//===----------------------------------------------------------------------===//
/// Returns an array of vImage source buffer types specifying the order of planes.
///
/// - Parameter colorSpace: The color space of the source format.
public func sourceBuffers(colorSpace: CGColorSpace) -> [vImage.BufferType?] {
let sourceBuffers = vImageConverter_GetSourceBufferOrder(self)
let codes = Array(UnsafeBufferPointer(start: sourceBuffers,
count: sourceBufferCount))
return codes.map {
vImage.BufferType(bufferTypeCode: Int($0),
model: colorSpace.model)
}
}
/// Returns an array of vImage source buffer types specifying the order of planes.
///
/// - Parameter colorSpace: The color space of the destination format.
public func destinationBuffers(colorSpace: CGColorSpace) -> [vImage.BufferType?] {
let destinationBuffers = vImageConverter_GetDestinationBufferOrder(self)
let codes = Array(UnsafeBufferPointer(start: destinationBuffers,
count: destinationBufferCount))
return codes.map {
vImage.BufferType(bufferTypeCode: Int($0),
model: colorSpace.model)
}
}
/// The number of source buffers consumed by the converter.
public var sourceBufferCount: Int {
return Int(vImageConverter_GetNumberOfSourceBuffers(self))
}
/// The number of destination buffers written to by the converter.
public var destinationBufferCount: Int {
return Int(vImageConverter_GetNumberOfDestinationBuffers(self))
}
//===----------------------------------------------------------------------===//
/// Determines whether a converter is capable of operating in place.
///
/// - Parameter source: The source buffer.
/// - Parameter destination: The destination buffer.
/// - Parameter options: The options to use when performing this operation.
///
/// - Returns: `true` if the conversion must operate out of place or `false`
/// if the operation will work in place.
public func mustOperateOutOfPlace(source: vImage_Buffer,
destination: vImage_Buffer,
flags options: vImage.Options = .noFlags) throws -> Bool {
var error = kvImageNoError
withUnsafePointer(to: source) { src in
withUnsafePointer(to: destination) { dest in
error = vImageConverter_MustOperateOutOfPlace(self,
src,
dest,
vImage_Flags(options.rawValue))
}
}
switch error {
case kvImageOutOfPlaceOperationRequired:
return true
case kvImageNoError:
return false
default:
throw vImage.Error(vImageError: error)
}
}
//===----------------------------------------------------------------------===//
//
// MARK: CG -> CG
//
//===----------------------------------------------------------------------===//
/// Creates a vImage converter to convert from one vImage Core Graphics image format to another.
///
/// - Parameter sourceFormat: A `vImage_CGImageFormat` structure describing the image format of the source image
/// - Parameter destinationFormat: A `vImage_CGImageFormat` structure describing the image format of the destination image
/// - Parameter options: The options to use when performing this operation.
///
/// - Returns: a vImage converter to convert from one vImage Core Graphics image format to another.
public static func make(sourceFormat: vImage_CGImageFormat,
destinationFormat: vImage_CGImageFormat,
flags options: vImage.Options = .noFlags) throws -> vImageConverter {
var error = kvImageNoError
var unmanagedConverter: Unmanaged<vImageConverter>?
withUnsafePointer(to: destinationFormat) { dest in
withUnsafePointer(to: sourceFormat) { src in
unmanagedConverter = vImageConverter_CreateWithCGImageFormat(
src,
dest,
nil,
vImage_Flags(options.rawValue),
&error)
}
}
if error != kvImageNoError {
throw vImage.Error(vImageError: error)
} else if unmanagedConverter == nil {
throw vImage.Error.internalError
}
return unmanagedConverter!.takeRetainedValue()
}
//===----------------------------------------------------------------------===//
//
// MARK: CG -> CV
//
//===----------------------------------------------------------------------===//
/// Creates a vImage converter that converts a Core Graphics-formatted image to a Core Video-formatted image.
///
/// - Parameter sourceFormat: A `vImage_CGImageFormat` structure describing the image format of the source image
/// - Parameter destinationFormat: A `vImageCVImageFormat` structure describing the image format of the destination image
/// - Parameter options: The options to use when performing this operation.
///
/// - Returns: a vImage converter to convert a Core Graphics-formatted image to a Core Video-formatted image.
public static func make(sourceFormat: vImage_CGImageFormat,
destinationFormat: vImageCVImageFormat,
flags options: vImage.Options = .noFlags) throws -> vImageConverter {
var error = kvImageNoError
var unmanagedConverter: Unmanaged<vImageConverter>?
withUnsafePointer(to: sourceFormat) { src in
unmanagedConverter = vImageConverter_CreateForCGToCVImageFormat(
src,
destinationFormat,
nil,
vImage_Flags(options.rawValue),
&error)
}
if error != kvImageNoError {
throw vImage.Error(vImageError: error)
} else if unmanagedConverter == nil {
throw vImage.Error.internalError
}
return unmanagedConverter!.takeRetainedValue()
}
//===----------------------------------------------------------------------===//
//
// MARK: CV -> CG
//
//===----------------------------------------------------------------------===//
/// Creates a vImage converter that converts a Core Video-formatted image to a Core Graphics-formatted image.
///
/// - Parameter sourceFormat: A `vImageCVImageFormat` structure describing the image format of the source image
/// - Parameter destinationFormat: A `vImage_CGImageFormat` structure describing the image format of the destination image
/// - Parameter options: The options to use when performing this operation.
///
/// - Returns: a vImage converter to convert a Core Video-formatted image to a Core Graphics-formatted image.
public static func make(sourceFormat: vImageCVImageFormat,
destinationFormat: vImage_CGImageFormat,
flags options: vImage.Options = .noFlags) throws -> vImageConverter {
var error = kvImageInternalError
var unmanagedConverter: Unmanaged<vImageConverter>?
withUnsafePointer(to: destinationFormat) { dest in
unmanagedConverter = vImageConverter_CreateForCVToCGImageFormat(
sourceFormat,
dest,
nil,
vImage_Flags(options.rawValue),
&error)
}
if error != kvImageNoError {
throw vImage.Error(vImageError: error)
} else if unmanagedConverter == nil {
throw vImage.Error.internalError
}
return unmanagedConverter!.takeRetainedValue()
}
//===----------------------------------------------------------------------===//
/// Converts the pixels in a vImage buffer to another format.
///
/// - Parameter source: The source buffer.
/// - Parameter destination: The destination buffer.
/// - Parameter options: The options to use when performing this operation.
///
/// - Returns: `kvImageNoError`; otherwise, one of the error codes described in _Data Types and Constants.
public func convert(source: vImage_Buffer,
destination: inout vImage_Buffer,
flags options: vImage.Options = .noFlags) throws {
var error = kvImageNoError
_ = withUnsafePointer(to: source) { src in
error = vImageConvert_AnyToAny(self,
src,
&destination,
nil,
vImage_Flags(options.rawValue))
}
if error != kvImageNoError {
throw vImage.Error(vImageError: error)
}
}
}
| apache-2.0 | f577cf9d86d52a328d205d43f4bc3c7a | 41.766667 | 126 | 0.527377 | 6.051887 | false | false | false | false |
Mikelulu/BaiSiBuDeQiJie | LKBS/LKBS/Classes/Main/TabbarController/Views/LKTabBar.swift | 1 | 2399 | //
// LKTabBar.swift
// LKBS
//
// Created by admin on 2017/6/19.
// Copyright © 2017年 LK. All rights reserved.
//
import UIKit
class LKTabBar: UITabBar {
/// 中间的按钮
let plusBtn = UIButton()
override init(frame: CGRect) {
super.init(frame: frame)
plusBtn.setImage(UIImage.init(named: "tabBar_publish_icon"), for: .normal)
plusBtn.setImage(UIImage.init(named: "tabBar_publish_click_icon"), for: .selected)
plusBtn.sizeToFit()
plusBtn.addTarget(self, action: #selector(plusBtnClick(_:)), for: .touchUpInside)
addSubview(plusBtn)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
var btnX: CGFloat = 0
let btnW: CGFloat = self.bounds.width / CGFloat((self.items?.count)! + 1)
let btnH: CGFloat = self.bounds.height - kTabbarSafeBottomMargin
var btnArr: Array<UIControl> = []
for view: UIView in self.subviews {
// LKLog(view)
/**
UITabBarButton 私有变量 ,知道了UITabBarButton之后
&1. 可以直观的实时的检测UITabBarButton的情况,实时监控tabBar的状态;
&2. 我们可以在不全部推倒tabBar重来的情况下,自定义UITabBarButton的位置,
*/
if view.isKind(of: NSClassFromString("UITabBarButton")!) {
btnArr.append(view as! UIControl)
}
}
for (index, btn) in btnArr.enumerated() {
if index >= 2 {
btnX = CGFloat(index + 1) * btnW
}else {
btnX = CGFloat(index) * btnW
}
btn.frame = CGRect.init(x: btnX, y: 0, width: btnW, height: btnH)
}
/// 设置中间按钮的位置
plusBtn.center = CGPoint.init(x: self.bounds.size.width * 0.5, y: (self.bounds.height - kTabbarSafeBottomMargin) * 0.5)
}
}
// MARK: - 事件处理
extension LKTabBar {
@objc fileprivate func plusBtnClick(_ btn: UIButton) {
LKLog("点击了中间按钮")
let publicVC = LKPublishViewController()
UIApplication.shared.keyWindow?.rootViewController?.present(publicVC, animated: true, completion: nil)
}
}
| mit | 51350f9047e045716f952ba597594267 | 23.369565 | 127 | 0.578055 | 3.989324 | false | false | false | false |
lieonCX/TodayHeadline | Pods/LRefresh/Source/LRefreshView.swift | 1 | 1690 | //
// RefreshView.swift
// Refresh
//
// Created by lieon on 2017/1/15.
// Copyright © 2017年 ChangHongCloudTechService. All rights reserved.
//
import UIKit
class RefreshView: UIView {
@IBOutlet weak var pullArrow: UIImageView!
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var loadingView: UIActivityIndicatorView!
var state: RefrehState = .normal {
didSet {
switch state {
case .normal:
textLabel.text = "继续使劲拉"
pullArrow.isHidden = false
loadingView.isHidden = true
UIView.animate(withDuration: 0.25, animations: {
self.pullArrow.transform = CGAffineTransform.identity
})
case .pulling:
textLabel.text = "放手就刷新"
UIView.animate(withDuration: 0.25, animations: {
self.pullArrow.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI - 0.0001))
})
case .wilRefresh:
textLabel.text = "正在刷新中..."
loadingView.isHidden = false
pullArrow.isHidden = true
loadingView.startAnimating()
}
}
}
class func refreView() -> RefreshView {
let bundle = Bundle(for: self.classForCoder())
let nib = UINib(nibName: "LRefreshView", bundle: bundle)
guard let view = nib.instantiate(withOwner: nil, options: nil)[0] as? RefreshView else { return RefreshView() }
return view
}
override func awakeFromNib() {
super.awakeFromNib()
loadingView.isHidden = true
}
}
| mit | 4b1434a995046c2f0dc7e6cb3ae16823 | 30.865385 | 119 | 0.572722 | 4.761494 | false | false | false | false |
buithuyen/ioscreator | IOS8SwiftFileManagementTutorial/IOS8SwiftFileManagementTutorial/ViewController.swift | 41 | 2753 | //
// ViewController.swift
// IOS8SwiftFileManagementTutorial
//
// Created by Arthur Knopper on 03/03/15.
// Copyright (c) 2015 Arthur Knopper. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var fileManager = NSFileManager()
var tmpDir = NSTemporaryDirectory()
let fileName = "sample.txt"
@IBAction func createFile(sender: AnyObject) {
let path = tmpDir.stringByAppendingPathComponent(fileName)
let contentsOfFile = "Sample Text"
var error: NSError?
// Write File
if contentsOfFile.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: &error) == false {
if let errorMessage = error {
println("Failed to create file")
println("\(errorMessage)")
}
} else {
println("File sample.txt created at tmp directory")
}
}
@IBAction func listDirectory(sender: AnyObject) {
// List Content of Path
let isFileInDir = enumerateDirectory() ?? "Empty"
println("Contents of Directory = \(isFileInDir)")
}
@IBAction func viewFileContent(sender: AnyObject) {
let isFileInDir = enumerateDirectory() ?? ""
let path = tmpDir.stringByAppendingPathComponent(isFileInDir)
let contentsOfFile = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
if let content = contentsOfFile {
println("Content of file = \(content)")
} else {
println("No file found")
}
}
@IBAction func deleteFile(sender: AnyObject) {
var error: NSError?
if let isFileInDir = enumerateDirectory() {
let path = tmpDir.stringByAppendingPathComponent(isFileInDir)
fileManager.removeItemAtPath(path, error: &error)
} else {
println("No file found")
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func enumerateDirectory() -> String? {
var error: NSError?
let filesInDirectory = fileManager.contentsOfDirectoryAtPath(tmpDir, error: &error) as? [String]
if let files = filesInDirectory {
if files.count > 0 {
if files[0] == fileName {
println("sample.txt found")
return files[0]
} else {
println("File not found")
return nil
}
}
}
return nil
}
}
| mit | 0e984c650b437eb3886a6b3ddcfe1949 | 29.932584 | 119 | 0.578278 | 5.204159 | false | false | false | false |
roambotics/swift | test/attr/attr_specialize.swift | 4 | 17618 | // RUN: %target-typecheck-verify-swift -warn-redundant-requirements
// RUN: %target-swift-ide-test -print-ast-typechecked -source-filename=%s -disable-objc-attr-requires-foundation-module -define-availability 'SwiftStdlib 5.1:macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0' | %FileCheck %s
struct S<T> {}
public protocol P {
}
extension Int: P {
}
public protocol ProtocolWithDep {
associatedtype Element
}
public class C1 {
}
class Base {}
class Sub : Base {}
class NonSub {}
// Specialize freestanding functions with the correct number of concrete types.
// ----------------------------------------------------------------------------
// CHECK: @_specialize(exported: false, kind: full, where T == Int)
@_specialize(where T == Int)
// CHECK: @_specialize(exported: false, kind: full, where T == S<Int>)
@_specialize(where T == S<Int>)
@_specialize(where T == Int, U == Int) // expected-error{{cannot find type 'U' in scope}},
@_specialize(where T == T1) // expected-error{{cannot find type 'T1' in scope}}
public func oneGenericParam<T>(_ t: T) -> T {
return t
}
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Int)
@_specialize(where T == Int, U == Int)
@_specialize(where T == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'U' in '_specialize' attribute}}
public func twoGenericParams<T, U>(_ t: T, u: U) -> (T, U) {
return (t, u)
}
@_specialize(where T == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'nonGenericParam(x:)'}}
func nonGenericParam(x: Int) {}
// Specialize contextual types.
// ----------------------------
class G<T> {
// CHECK: @_specialize(exported: false, kind: full, where T == Int)
@_specialize(where T == Int)
@_specialize(where T == T) // expected-warning{{redundant same-type constraint 'T' == 'T'}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T == S<T>)
// expected-error@-1 {{cannot build rewrite system for generic signature; concrete nesting limit exceeded}}
// expected-note@-2 {{failed rewrite rule is τ_0_0.[concrete: S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<τ_0_0>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] => τ_0_0}}
// expected-error@-3 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-4 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T == Int, U == Int) // expected-error{{cannot find type 'U' in scope}}
func noGenericParams() {}
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Float)
@_specialize(where T == Int, U == Float)
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == S<Int>)
@_specialize(where T == Int, U == S<Int>)
@_specialize(where T == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note {{missing constraint for 'U' in '_specialize' attribute}}
func oneGenericParam<U>(_ t: T, u: U) -> (U, T) {
return (u, t)
}
}
// Specialize with requirements.
// -----------------------------
protocol Thing {}
struct AThing : Thing {}
// CHECK: @_specialize(exported: false, kind: full, where T == AThing)
@_specialize(where T == AThing)
@_specialize(where T == Int) // expected-error{{no type for 'T' can satisfy both 'T == Int' and 'T : Thing'}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
func oneRequirement<T : Thing>(_ t: T) {}
protocol HasElt {
associatedtype Element
}
struct IntElement : HasElt {
typealias Element = Int
}
struct FloatElement : HasElt {
typealias Element = Float
}
@_specialize(where T == FloatElement)
@_specialize(where T == IntElement) // FIXME e/xpected-error{{'T.Element' cannot be equal to both 'IntElement.Element' (aka 'Int') and 'Float'}}
func sameTypeRequirement<T : HasElt>(_ t: T) where T.Element == Float {}
@_specialize(where T == Sub)
@_specialize(where T == NonSub) // expected-error{{no type for 'T' can satisfy both 'T : NonSub' and 'T : Base'}}
func superTypeRequirement<T : Base>(_ t: T) {}
@_specialize(where X:_Trivial(8), Y == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'requirementOnNonGenericFunction(x:y:)'}}
public func requirementOnNonGenericFunction(x: Int, y: Int) {
}
@_specialize(where Y == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}}
public func missingRequirement<X:P, Y>(x: X, y: Y) {
}
@_specialize(where) // expected-error{{expected type}}
@_specialize() // expected-error{{expected a parameter label or a where clause in '_specialize' attribute}} expected-error{{expected declaration}}
public func funcWithEmptySpecializeAttr<X: P, Y>(x: X, y: Y) {
}
@_specialize(where X:_Trivial(8), Y:_Trivial(32), Z == Int) // expected-error{{cannot find type 'Z' in scope}}
@_specialize(where X:_Trivial(8), Y:_Trivial(32, 4))
@_specialize(where X == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}}
@_specialize(where Y:_Trivial(32)) // expected-error {{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}}
@_specialize(where Y: P) // expected-error{{only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where Y: MyClass) // expected-error{{cannot find type 'MyClass' in scope}} expected-error{{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}}
@_specialize(where X:_Trivial(8), Y == Int)
@_specialize(where X == Int, Y == Int)
@_specialize(where X == Int, X == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}}
// expected-warning@-1{{redundant same-type constraint 'X' == 'Int'}}
@_specialize(where Y:_Trivial(32), X == Float)
@_specialize(where X1 == Int, Y1 == Int) // expected-error{{cannot find type 'X1' in scope}} expected-error{{cannot find type 'Y1' in scope}} expected-error{{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}}
public func funcWithTwoGenericParameters<X, Y>(x: X, y: Y) {
}
@_specialize(where X == Int, Y == Int)
@_specialize(exported: true, where X == Int, Y == Int)
@_specialize(exported: false, where X == Int, Y == Int)
@_specialize(exported: false where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}}
@_specialize(exported: yes, where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}}
@_specialize(exported: , where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}}
@_specialize(kind: partial, where X == Int, Y == Int)
@_specialize(kind: partial, where X == Int)
@_specialize(kind: full, where X == Int, Y == Int)
@_specialize(kind: any, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}}
@_specialize(kind: false, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}}
@_specialize(kind: partial where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}}
@_specialize(kind: partial, where X == Int, Y == Int)
@_specialize(kind: , where X == Int, Y == Int)
@_specialize(exported: true, kind: partial, where X == Int, Y == Int)
@_specialize(exported: true, exported: true, where X == Int, Y == Int) // expected-error{{parameter 'exported' was already defined in '_specialize' attribute}}
@_specialize(kind: partial, exported: true, where X == Int, Y == Int)
@_specialize(kind: partial, kind: partial, where X == Int, Y == Int) // expected-error{{parameter 'kind' was already defined in '_specialize' attribute}}
@_specialize(where X == Int, Y == Int, exported: true, kind: partial) // expected-error{{cannot find type 'exported' in scope}} expected-error{{cannot find type 'kind' in scope}} expected-error{{cannot find type 'partial' in scope}} expected-error{{expected type}}
public func anotherFuncWithTwoGenericParameters<X: P, Y>(x: X, y: Y) {
}
@_specialize(where T: P) // expected-error{{only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where T: Int) // expected-error{{type 'T' constrained to non-protocol, non-class type 'Int'}} expected-note {{use 'T == Int' to require 'T' to be 'Int'}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T: S1) // expected-error{{type 'T' constrained to non-protocol, non-class type 'S1'}} expected-note {{use 'T == S1' to require 'T' to be 'S1'}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T: C1) // expected-error{{only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where Int: P) // expected-warning{{redundant conformance constraint 'Int' : 'P'}} expected-error{{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}} expected-note{{missing constraint for 'T' in '_specialize' attribute}}
func funcWithForbiddenSpecializeRequirement<T>(_ t: T) {
}
@_specialize(where T: _Trivial(32), T: _Trivial(64), T: _Trivial, T: _RefCountedObject)
// expected-error@-1{{no type for 'T' can satisfy both 'T : _RefCountedObject' and 'T : _Trivial(32)'}}
// expected-error@-2{{no type for 'T' can satisfy both 'T : _Trivial(64)' and 'T : _Trivial(32)'}}
// expected-warning@-3{{redundant constraint 'T' : '_Trivial'}}
// expected-error@-4 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-5 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T: _Trivial, T: _Trivial(64))
// expected-warning@-1{{redundant constraint 'T' : '_Trivial'}}
@_specialize(where T: _RefCountedObject, T: _NativeRefCountedObject)
// expected-warning@-1{{redundant constraint 'T' : '_RefCountedObject'}}
@_specialize(where Array<T> == Int) // expected-error{{generic signature requires types 'Array<T>' and 'Int' to be the same}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T.Element == Int) // expected-error{{only requirements on generic parameters are supported by '_specialize' attribute}}
public func funcWithComplexSpecializeRequirements<T: ProtocolWithDep>(t: T) -> Int {
return 55555
}
public protocol Proto: class {
}
@_specialize(where T: _RefCountedObject)
// expected-warning@-1 {{redundant constraint 'T' : '_RefCountedObject'}}
// expected-error@-2 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-3 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T: _Trivial)
// expected-error@-1{{no type for 'T' can satisfy both 'T : _NativeClass' and 'T : _Trivial'}}
// expected-error@-2 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-3 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T: _Trivial(64))
// expected-error@-1{{no type for 'T' can satisfy both 'T : _NativeClass' and 'T : _Trivial(64)'}}
// expected-error@-2 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-3 {{missing constraint for 'T' in '_specialize' attribute}}
public func funcWithABaseClassRequirement<T>(t: T) -> Int where T: C1 {
return 44444
}
public struct S1 {
}
@_specialize(exported: false, where T == Int64)
public func simpleGeneric<T>(t: T) -> T {
return t
}
@_specialize(exported: true, where S: _Trivial(64))
// Check that any bitsize size is OK, not only powers of 8.
@_specialize(where S: _Trivial(60))
@_specialize(exported: true, where S: _RefCountedObject)
@inline(never)
public func copyValue<S>(_ t: S, s: inout S) -> Int64 where S: P{
return 1
}
@_specialize(exported: true, where S: _Trivial)
@_specialize(exported: true, where S: _Trivial(64))
@_specialize(exported: true, where S: _Trivial(32))
@_specialize(exported: true, where S: _RefCountedObject)
@_specialize(exported: true, where S: _NativeRefCountedObject)
@_specialize(exported: true, where S: _Class)
@_specialize(exported: true, where S: _NativeClass)
@inline(never)
public func copyValueAndReturn<S>(_ t: S, s: inout S) -> S where S: P{
return s
}
struct OuterStruct<S> {
struct MyStruct<T> {
@_specialize(where T == Int, U == Float) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 2, but expected 3)}} expected-note{{missing constraint for 'S' in '_specialize' attribute}}
public func foo<U>(u : U) {
}
@_specialize(where T == Int, U == Float, S == Int)
public func bar<U>(u : U) {
}
}
}
// Check _TrivialAtMostN constraints.
@_specialize(exported: true, where S: _TrivialAtMost(64))
@inline(never)
public func copy2<S>(_ t: S, s: inout S) -> S where S: P{
return s
}
// Check missing alignment.
@_specialize(where S: _Trivial(64, )) // expected-error{{expected non-negative alignment to be specified in layout constraint}}
// Check non-numeric size.
@_specialize(where S: _Trivial(Int)) // expected-error{{expected non-negative size to be specified in layout constraint}}
// Check non-numeric alignment.
@_specialize(where S: _Trivial(64, X)) // expected-error{{expected non-negative alignment to be specified in layout constraint}}
@inline(never)
public func copy3<S>(_ s: S) -> S {
return s
}
public func funcWithWhereClause<T>(t: T) where T:P, T: _Trivial(64) { // expected-error{{layout constraints are only allowed inside '_specialize' attributes}}
}
// rdar://problem/29333056
public protocol P1 {
associatedtype DP1
associatedtype DP11
}
public protocol P2 {
associatedtype DP2 : P1
}
public struct H<T> {
}
public struct MyStruct3 : P1 {
public typealias DP1 = Int
public typealias DP11 = H<Int>
}
public struct MyStruct4 : P2 {
public typealias DP2 = MyStruct3
}
@_specialize(where T==MyStruct4)
public func foo<T: P2>(_ t: T) where T.DP2.DP11 == H<T.DP2.DP1> {
}
public func targetFun<T>(_ t: T) {}
@_specialize(exported: true, target: targetFun(_:), where T == Int)
public func specifyTargetFunc<T>(_ t: T) {
}
public struct Container {
public func targetFun<T>(_ t: T) {}
}
extension Container {
@_specialize(exported: true, target: targetFun(_:), where T == Int)
public func specifyTargetFunc<T>(_ t: T) { }
@_specialize(exported: true, target: targetFun2(_:), where T == Int) // expected-error{{target function 'targetFun2' could not be found}}
public func specifyTargetFunc2<T>(_ t: T) { }
}
// Make sure we don't complain that 'E' is not explicitly specialized here.
// E becomes concrete via the combination of 'S == Set<String>' and
// 'E == S.Element'.
@_specialize(where S == Set<String>)
public func takesSequenceAndElement<S, E>(_: S, _: E)
where S : Sequence, E == S.Element {}
// CHECK: @_specialize(exported: true, kind: full, availability: macOS 11, iOS 13, *; where T == Int)
// CHECK: public func testAvailability<T>(_ t: T)
@_specialize(exported: true, availability: macOS 11, iOS 13, *; where T == Int)
public func testAvailability<T>(_ t: T) {}
// CHECK: @_specialize(exported: true, kind: full, availability: macOS, introduced: 11; where T == Int)
// CHECK: public func testAvailability2<T>(_ t: T)
@_specialize(exported: true, availability: macOS 11, *; where T == Int)
public func testAvailability2<T>(_ t: T) {}
// CHECK: @_specialize(exported: true, kind: full, availability: macOS, introduced: 11; where T == Int)
// CHECK: public func testAvailability3<T>(_ t: T)
@_specialize(exported: true, availability: macOS, introduced: 11; where T == Int)
public func testAvailability3<T>(_ t: T) {}
// CHECK: @_specialize(exported: true, kind: full, availability: macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *; where T == Int)
// CHECK: public func testAvailability4<T>(_ t: T)
@_specialize(exported: true, availability: SwiftStdlib 5.1, *; where T == Int)
public func testAvailability4<T>(_ t: T) {}
| apache-2.0 | 621f64f0873712d0b5e646459868caf6 | 50.656891 | 393 | 0.689072 | 3.590501 | false | false | false | false |
Piwigo/Piwigo-Mobile | piwigo/Image/Parameters/Cells/EditImageThumbTableViewCell.swift | 1 | 6455 | //
// EditImageThumbTableViewCell.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 02/01/2020.
// Copyright © 2020 Piwigo.org. All rights reserved.
//
// Converted to Swift 5.3 by Eddy Lelièvre-Berna on 30/08/2021.
//
import UIKit
import piwigoKit
@objc protocol EditImageThumbnailCellDelegate: NSObjectProtocol {
func didDeselectImage(withId imageId: Int)
func didRenameFileOfImage(_ imageData: PiwigoImageData)
}
class EditImageThumbTableViewCell: UITableViewCell, UICollectionViewDelegate
{
weak var delegate: EditImageThumbnailCellDelegate?
@IBOutlet private var editImageThumbCollectionView: UICollectionView!
private var images: [PiwigoImageData]?
private var startingScrollingOffset = CGPoint.zero
override func awakeFromNib() {
super.awakeFromNib()
// Register thumbnail collection view cell
editImageThumbCollectionView.register(UINib(nibName: "EditImageThumbCollectionViewCell",
bundle: nil), forCellWithReuseIdentifier: "EditImageThumbCollectionViewCell")
}
func config(withImages imageSelection: [PiwigoImageData]?) {
// Data
images = imageSelection
// Collection of images
backgroundColor = .piwigoColorCellBackground()
if editImageThumbCollectionView == nil {
editImageThumbCollectionView = UICollectionView(frame: CGRect.zero,
collectionViewLayout: UICollectionViewFlowLayout())
editImageThumbCollectionView.reloadData()
} else {
editImageThumbCollectionView.collectionViewLayout.invalidateLayout()
}
}
}
// MARK: - UICollectionViewDataSource Methods
extension EditImageThumbTableViewCell: UICollectionViewDataSource
{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// Returns number of images or albums
return images?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "EditImageThumbCollectionViewCell", for: indexPath) as? EditImageThumbCollectionViewCell else {
print("Error: collectionView.dequeueReusableCell does not return a EditImageThumbCollectionViewCell!")
return EditImageThumbCollectionViewCell()
}
cell.config(withImage: images?[indexPath.row], removeOption: ((images?.count ?? 0) > 1))
cell.delegate = self
return cell
}
}
// MARK: - UICollectionViewDelegateFlowLayout Methods
extension EditImageThumbTableViewCell: UICollectionViewDelegateFlowLayout
{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
// Avoid unwanted spaces
return UIEdgeInsets(top: 0, left: AlbumUtilities.kImageDetailsMarginsSpacing,
bottom: 0, right: AlbumUtilities.kImageDetailsMarginsSpacing)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return AlbumUtilities.kImageDetailsCellSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: AlbumUtilities.imageDetailsSize(forView: self), height: 152.0)
}
}
// MARK: - EditImageThumbnailDelegate Methods
extension EditImageThumbTableViewCell: EditImageThumbnailDelegate
{
@objc
func didDeselectImage(withId imageId: Int) {
// Update data source
let newImages = images?.filter({ $0.imageId != imageId })
images = newImages
editImageThumbCollectionView.reloadData()
// Deselect image in parent view
if delegate?.responds(to: #selector(EditImageThumbnailCellDelegate.didDeselectImage(withId:))) ?? false {
delegate?.didDeselectImage(withId: imageId)
}
}
@objc
func didRenameFileOfImage(withId imageId: Int, andFilename fileName: String) {
// Check accessible data
guard let indexOfImage = images?.firstIndex(where: { $0.imageId == imageId }),
let imageToUpdate: PiwigoImageData = images?[indexOfImage] else { return }
// Update data source
/// Cached data cannot be updated as we may not have downloaded image data.
/// This happens for example if the user used the search tool right after launching the app.
imageToUpdate.fileName = fileName
images?.replaceSubrange(indexOfImage...indexOfImage, with: [imageToUpdate])
// Update parent image view
if delegate?.responds(to: #selector(EditImageThumbnailCellDelegate.didRenameFileOfImage(_:))) ?? false {
delegate?.didRenameFileOfImage(imageToUpdate)
}
}
}
// MARK: - UIScrollViewDelegate Methods
extension EditImageThumbTableViewCell: UIScrollViewDelegate
{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
startingScrollingOffset = scrollView.contentOffset
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
{
let cellWidth: CGFloat = collectionView(editImageThumbCollectionView, layout: editImageThumbCollectionView.collectionViewLayout, sizeForItemAt: IndexPath(row: 0, section: 0)).width + AlbumUtilities.kImageDetailsMarginsSpacing / 2.0
let offset:CGFloat = scrollView.contentOffset.x + scrollView.contentInset.left
let proposedPage: CGFloat = offset / fmax(1.0, cellWidth)
let snapPoint: CGFloat = 0.1
let snapDelta: CGFloat = offset > startingScrollingOffset.x ? (1 - snapPoint) : snapPoint
var page: CGFloat
if floor(proposedPage + snapDelta) == floor(proposedPage) {
page = floor(proposedPage)
} else {
page = floor(proposedPage + 1)
}
targetContentOffset.pointee = CGPoint(x: cellWidth * page,
y: targetContentOffset.pointee.y)
}
}
| mit | 8f7d7035073301ffa5cad72c6016951b | 40.095541 | 239 | 0.708617 | 5.472434 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothGATT/GATTBootKeyboardInputReport.swift | 1 | 1768 | //
// GATTBootKeyboardInputReport.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/18/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/**
Boot Keyboard Input Report
The Boot Keyboard Input Report characteristic is used to transfer fixed format and length Input Report data between a HID Host operating in Boot Protocol Mode and a HID Service corresponding to a boot keyboard.
[Boot Keyboard Input Report](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.boot_keyboard_input_report.xml)
*/
@frozen
public struct GATTBootKeyboardInputReport: RawRepresentable, GATTCharacteristic {
internal static let length = MemoryLayout<UInt8>.size
public static var uuid: BluetoothUUID { return .bootKeyboardInputReport }
public var rawValue: UInt8
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
self.init(rawValue: data[0])
}
public var data: Data {
return Data([rawValue])
}
}
extension GATTBootKeyboardInputReport: Equatable {
public static func == (lhs: GATTBootKeyboardInputReport, rhs: GATTBootKeyboardInputReport) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension GATTBootKeyboardInputReport: CustomStringConvertible {
public var description: String {
return rawValue.description
}
}
extension GATTBootKeyboardInputReport: ExpressibleByIntegerLiteral {
public init(integerLiteral value: UInt8) {
self.init(rawValue: value)
}
}
| mit | b79f9f02f56e4de73fa0d2b6751eaa67 | 24.985294 | 211 | 0.681381 | 4.80163 | false | false | false | false |
fsproru/ScoutReport | ScoutReport/Config.swift | 1 | 1365 | import UIKit
class Config {
// MARK: - Colors
static let instagramBackgroundColor = UIColor.whiteColor()
static let youtubeBackgroundColor = UIColor.whiteColor()
// MARK: - Fonts
static let standardHeaderFont = UIFont.systemFontOfSize(30, weight: UIFontWeightLight)
static let standardBodyFont = UIFont.systemFontOfSize(17, weight: UIFontWeightLight)
// MARK: - Images
static let logoImage = UIImage(named: "logo")!
static let instagramLogoImage = UIImage(named: "instagram-logo")!
static let youtubeLogoImage = UIImage(named: "youtube-logo")!
// MARK: - Text
static let appNameText = "Scout Report"
static let chooseInstagramText = "Type in someone's instagram username below"
static let chooseYoutubeText = "and a youtube username of the same person"
// MARK: - Text Attributes
static let standardInputFieldTextAlignment: NSTextAlignment = .Center
// MARK: - Instagram API
static let instagramAuthURL = NSURL(string: "https://instagram.com/oauth/authorize/?client_id=f82a6b07a9924d2f86ef69e961242855&redirect_uri=https://localhost&response_type=token")!
static let instagramAccessTokenURLSubstring = "#access_token="
// MARK: - Errors
static let scoutReportErrorDomain = "ScoutReportError"
static let scoutReportErrorCode = 999
} | mit | b072c271c9c814a79c87b6287f3dba18 | 41.6875 | 184 | 0.715751 | 4.50495 | false | false | false | false |
MartinOSix/DemoKit | dSwift/SwiftDemoKit/SwiftDemoKit/TAManager.swift | 1 | 4740 | //
// TAManager.swift
// SwiftDemoKit
//
// Created by runo on 17/5/4.
// Copyright © 2017年 com.runo. All rights reserved.
//
import UIKit
enum TransitionType {
case Pop
case Push
}
class TAManager: NSObject, UIViewControllerAnimatedTransitioning, CAAnimationDelegate{
var type: TransitionType
var transitionContext: UIViewControllerContextTransitioning? = nil
init(Type type:TransitionType ) {
self.type = type
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.35
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if self.type == .Pop {
self.pushAnimateTransition(using: transitionContext)
}else{
self.popAnimateTransition(using: transitionContext)
}
}
func pushAnimateTransition(using transitionContext: UIViewControllerContextTransitioning) {
//print(" push ")
//该参数包含了控制转场动画必要的信息
self.transitionContext = transitionContext
//目标VC
let toVC = transitionContext.viewController(forKey: .to)
//当前VC
let fromVC = transitionContext.viewController(forKey: .from)
//容器View,转场动画都是在该容器中进行的,导航控制的wrapper view就是改容器
let containerView = transitionContext.containerView
containerView.addSubview((fromVC?.view)!)
containerView.addSubview((toVC?.view)!)
let starPath = UIBezierPath(rect: CGRect(x: kScreenWidth, y: 0, width: kScreenWidth, height: kScreenHeight))
let finalPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight))
let maskLayer = CAShapeLayer()
maskLayer.path = finalPath.cgPath
toVC?.view.layer.mask = maskLayer
let animation = CABasicAnimation(keyPath: "path")
animation.fromValue = starPath.cgPath
animation.toValue = finalPath.cgPath
animation.duration = transitionDuration(using: transitionContext)
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.delegate = self
maskLayer.add(animation, forKey: "path")
}
func popAnimateTransition(using transitionContext: UIViewControllerContextTransitioning) {
//print(" pop ")
//该参数包含了控制转场动画必要的信息
self.transitionContext = transitionContext
//目标VC
let toVC = transitionContext.viewController(forKey: .to)
//当前VC
let fromVC = transitionContext.viewController(forKey: .from)
//容器View,转场动画都是在该容器中进行的,导航控制的wrapper view就是改容器
let containerView = transitionContext.containerView
containerView.addSubview((fromVC?.view)!)
containerView.addSubview((toVC?.view)!)
var starPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight))
var finalPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 0, height: kScreenHeight))
starPath = UIBezierPath(arcCenter: CGPoint.init(x: kScreenWidth/2, y: kScreenHeight/2), radius: 100, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true)
finalPath = UIBezierPath(arcCenter: CGPoint.init(x: kScreenWidth/2, y: kScreenHeight/2), radius: kScreenHeight/2, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true)
let maskLayer = CAShapeLayer()
maskLayer.path = finalPath.cgPath
toVC?.view.layer.mask = maskLayer
maskLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
//let animation = CABasicAnimation(keyPath: "strokeEnd")
//transform.scale
let animation = CABasicAnimation(keyPath: "path")
animation.fromValue = starPath.cgPath
animation.toValue = finalPath.cgPath
animation.duration = transitionDuration(using: transitionContext)
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.delegate = self
maskLayer.add(animation, forKey: "path")
}
//动画结束
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
//通知transition完成,该方法一定要调用
self.transitionContext?.completeTransition(!(self.transitionContext?.transitionWasCancelled)!)
//清除fromVC的mask
self.transitionContext?.viewController(forKey: .from)?.view.layer.mask = nil
self.transitionContext?.viewController(forKey: .to)?.view.layer.mask = nil
}
}
| apache-2.0 | fb8b19d19c9ccb4b8c3706ee734d4793 | 41.481132 | 180 | 0.686209 | 4.948352 | false | false | false | false |
nghialv/Mockingjay | Mockingjay/XCTest.swift | 2 | 943 | //
// XCTest.swift
// Mockingjay
//
// Created by Kyle Fuller on 28/02/2015.
// Copyright (c) 2015 Cocode. All rights reserved.
//
import Foundation
import XCTest
import Mockingjay
extension XCTest {
// MARK: Stubbing
public func stub(matcher:Matcher, builder:Builder) -> Stub {
return MockingjayProtocol.addStub(matcher, builder: builder)
}
public func removeStub(stub:Stub) {
MockingjayProtocol.removeStub(stub)
}
public func removeAllStubs() {
MockingjayProtocol.removeAllStubs()
}
// MARK: Teardown
override public class func initialize() {
if (self === XCTest.self) {
let tearDown = class_getInstanceMethod(self, "tearDown")
let mockingjayTearDown = class_getInstanceMethod(self, "mockingjayTearDown")
method_exchangeImplementations(tearDown, mockingjayTearDown)
}
}
func mockingjayTearDown() {
mockingjayTearDown()
MockingjayProtocol.removeAllStubs()
}
}
| bsd-3-clause | c79d3027cb0db800efc4c1ef9e0e946f | 21.452381 | 82 | 0.710498 | 4.286364 | false | true | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceComponents/Tests/ScheduleComponentTests/Presenter Tests/Searching/WhenBindingEventFromSearchResult_SchedulePresenterShould.swift | 1 | 1338 | import EurofurenceModel
import ScheduleComponent
import XCTest
import XCTScheduleComponent
class WhenBindingEventFromSearchResult_SchedulePresenterShould: XCTestCase {
func testBindTheEventAttributesOntoTheComponent() {
let searchViewModel = CapturingScheduleSearchViewModel()
let viewModelFactory = FakeScheduleViewModelFactory(searchViewModel: searchViewModel)
let context = SchedulePresenterTestBuilder().with(viewModelFactory).build()
context.simulateSceneDidLoad()
let results = [ScheduleEventGroupViewModel].random
searchViewModel.simulateSearchResultsUpdated(results)
let randomGroup = results.randomElement()
let randomEvent = randomGroup.element.events.randomElement()
let eventViewModel = randomEvent.element
let indexPath = IndexPath(item: randomEvent.index, section: randomGroup.index)
let component = CapturingScheduleEventComponent()
context.bindSearchResultComponent(component, forSearchResultAt: indexPath)
XCTAssertEqual(eventViewModel.title, component.capturedEventTitle)
XCTAssertEqual(eventViewModel.startTime, component.capturedStartTime)
XCTAssertEqual(eventViewModel.endTime, component.capturedEndTime)
XCTAssertEqual(eventViewModel.location, component.capturedLocation)
}
}
| mit | 0da11939061f2943f792ec082111f81f | 46.785714 | 93 | 0.781764 | 6.401914 | false | true | false | false |
LucianoPAlmeida/SwifterSwift | Tests/UIKitTests/UITableViewExtensionsTests.swift | 1 | 5642 | //
// UITableViewExtensionsTests.swift
// SwifterSwift
//
// Created by Omar Albeik on 2/24/17.
// Copyright © 2017 SwifterSwift
//
#if os(iOS) || os(tvOS)
import XCTest
@testable import SwifterSwift
final class UITableViewExtensionsTests: XCTestCase {
let tableView = UITableView()
let emptyTableView = UITableView()
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
tableView.dataSource = self
emptyTableView.dataSource = self
tableView.reloadData()
}
func testIndexPathForLastRow() {
XCTAssertEqual(tableView.indexPathForLastRow, IndexPath(row: 7, section: 1))
}
func testLastSection() {
XCTAssertEqual(tableView.lastSection, 1)
XCTAssertEqual(emptyTableView.lastSection, 0)
}
func testNumberOfRows() {
XCTAssertEqual(tableView.numberOfRows(), 13)
XCTAssertEqual(emptyTableView.numberOfRows(), 0)
}
func testIndexPathForLastRowInSection() {
XCTAssertNil(tableView.indexPathForLastRow(inSection: -1))
XCTAssertEqual(tableView.indexPathForLastRow(inSection: 0), IndexPath(row: 4, section: 0))
XCTAssertEqual(UITableView().indexPathForLastRow(inSection: 0), IndexPath(row: 0, section: 0))
}
func testReloadData() {
let exp = expectation(description: "reloadCallback")
tableView.reloadData {
XCTAssert(true)
exp.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
func testRemoveTableFooterView() {
tableView.tableFooterView = UIView()
XCTAssertNotNil(tableView.tableFooterView)
tableView.removeTableFooterView()
XCTAssertNil(tableView.tableFooterView)
}
func testRemoveTableHeaderView() {
tableView.tableHeaderView = UIView()
XCTAssertNotNil(tableView.tableHeaderView)
tableView.removeTableHeaderView()
XCTAssertNil(tableView.tableHeaderView)
}
func testScrollToBottom() {
let bottomOffset = CGPoint(x: 0, y: tableView.contentSize.height - tableView.bounds.size.height)
tableView.scrollToBottom()
XCTAssertEqual(bottomOffset, tableView.contentOffset)
}
func testScrollToTop() {
tableView.scrollToTop()
XCTAssertEqual(CGPoint.zero, tableView.contentOffset)
}
func testDequeueReusableCellWithClass() {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
let cell = tableView.dequeueReusableCell(withClass: UITableViewCell.self)
XCTAssertNotNil(cell)
}
func testDequeueReusableCellWithClassForIndexPath() {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
let indexPath = tableView.indexPathForLastRow!
let cell = tableView.dequeueReusableCell(withClass: UITableViewCell.self, for: indexPath)
XCTAssertNotNil(cell)
}
func testDequeueReusableHeaderFooterView() {
tableView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "UITableViewHeaderFooterView")
let headerFooterView = tableView.dequeueReusableHeaderFooterView(withClass: UITableViewHeaderFooterView.self)
XCTAssertNotNil(headerFooterView)
}
#if os(iOS)
func testRegisterReusableViewWithClassAndNib() {
let nilView = tableView.dequeueReusableHeaderFooterView(withClass: UITableViewHeaderFooterView.self)
XCTAssertNil(nilView)
let nib = UINib(nibName: "UITableViewHeaderFooterView", bundle: Bundle(for: UITableViewExtensionsTests.self))
tableView.register(nib: nib, withHeaderFooterViewClass: UITableViewHeaderFooterView.self)
let view = tableView.dequeueReusableHeaderFooterView(withClass: UITableViewHeaderFooterView.self)
XCTAssertNotNil(view)
}
#endif
func testRegisterReusableViewWithClass() {
let nilView = tableView.dequeueReusableHeaderFooterView(withClass: UITableViewHeaderFooterView.self)
XCTAssertNil(nilView)
tableView.register(headerFooterViewClassWith: UITableViewHeaderFooterView.self)
let view = tableView.dequeueReusableHeaderFooterView(withClass: UITableViewHeaderFooterView.self)
XCTAssertNotNil(view)
}
func testRegisterCellWithClass() {
let nilCell = tableView.dequeueReusableCell(withClass: UITableViewCell.self)
XCTAssertNil(nilCell)
tableView.register(cellWithClass: UITableViewCell.self)
let cell = tableView.dequeueReusableCell(withClass: UITableViewCell.self)
XCTAssertNotNil(cell)
}
#if os(iOS)
func testRegisterCellWithClassAndNib() {
let nilCell = tableView.dequeueReusableCell(withClass: UITableViewCell.self)
XCTAssertNil(nilCell)
let nib = UINib(nibName: "UITableViewCell", bundle: Bundle(for: UITableViewExtensionsTests.self))
tableView.register(nib: nib, withCellClass: UITableViewCell.self)
let cell = tableView.dequeueReusableCell(withClass: UITableViewCell.self)
XCTAssertNotNil(cell)
}
#endif
#if os(iOS)
func testRegisterCellWithNibUsingClass() {
let nilCell = tableView.dequeueReusableCell(withClass: UITableViewCell.self)
XCTAssertNil(nilCell)
tableView.register(nibWithCellClass: UITableViewCell.self, at: UITableViewExtensionsTests.self)
let cell = tableView.dequeueReusableCell(withClass: UITableViewCell.self)
XCTAssertNotNil(cell)
}
#endif
}
extension UITableViewExtensionsTests: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return tableView == self.emptyTableView ? 0 : 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.emptyTableView {
return 0
} else {
return section == 0 ? 5 : 8
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell()
}
}
#endif
| mit | 85f33650ae5176df6d37e56b237e21f6 | 32.378698 | 121 | 0.779826 | 4.538214 | false | true | false | false |
Elm-Tree-Island/Shower | Shower/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/UIKit/UISegmentedControlSpec.swift | 6 | 706 | import Quick
import Nimble
import ReactiveSwift
import ReactiveCocoa
import Result
class UISegmentedControlSpec: QuickSpec {
override func spec() {
it("should accept changes from bindings to its selected segment index") {
let s = UISegmentedControl(items: ["0", "1", "2"])
s.selectedSegmentIndex = UISegmentedControlNoSegment
expect(s.numberOfSegments) == 3
let (pipeSignal, observer) = Signal<Int, NoError>.pipe()
s.reactive.selectedSegmentIndex <~ SignalProducer(pipeSignal)
expect(s.selectedSegmentIndex) == UISegmentedControlNoSegment
observer.send(value: 1)
expect(s.selectedSegmentIndex) == 1
observer.send(value: 2)
expect(s.selectedSegmentIndex) == 2
}
}
}
| gpl-3.0 | 99505b54bf80156696c1783741953f43 | 26.153846 | 75 | 0.743626 | 4.152941 | false | false | false | false |
ChristianKienle/highway | Sources/Task/Finding and Executing/SystemExecutor.swift | 1 | 1661 | import Foundation
import Arguments
import Terminal
public final class SystemExecutor: TaskExecutorProtocol {
public var ui: UIProtocol
// MARK: - Init
public init(ui: UIProtocol) {
self.ui = ui
}
// MARK: - Working with the Executor
public func launch(task: Task, wait: Bool) {
let process = task.toProcess
ui.verbose(task.description)
task.state = .executing
process.launch()
if wait {
process.waitUntilExit()
}
if task.successfullyFinished == false {
ui.error(task.state.description)
} else {
ui.verbose(task.state.description)
}
}
}
private extension Process {
func takeIOFrom(_ task: Task) {
standardInput = task.input.asProcessChannel
standardOutput = task.output.asProcessChannel
}
}
// internal because it is tested
extension Task {
// sourcery:skipProtocol
var toProcess: Process {
let result = Process()
result.arguments = arguments.all
result.launchPath = executable.path
if let currentDirectoryPath = currentDirectoryUrl?.path {
result.currentDirectoryPath = currentDirectoryPath
}
var _environment: [String:String] = ProcessInfo.processInfo.environment
self.environment.forEach {
_environment[$0.key] = $0.value
}
result.environment = _environment
result.terminationHandler = { terminatedProcess in
self.state = .terminated(Termination(describing: terminatedProcess))
}
result.takeIOFrom(self)
return result
}
}
| mit | dd62b9750f4788e7649d0e1d9f03b217 | 27.152542 | 80 | 0.623721 | 4.732194 | false | false | false | false |
cloudinary/cloudinary_ios | Example/Tests/BaseNetwork/Extensions/CLDNError+CloudinaryTests.swift | 1 | 10402 | //
// CLDNError+CloudinaryTests.swift
//
//
// 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.
//
@testable import Cloudinary
extension CLDNError {
// ParameterEncodingFailureReason
var isMissingURLFailed: Bool {
if case let .parameterEncodingFailed(reason) = self, reason.isMissingURL { return true }
return false
}
var isJSONEncodingFailed: Bool {
if case let .parameterEncodingFailed(reason) = self, reason.isJSONEncodingFailed { return true }
return false
}
var isPropertyListEncodingFailed: Bool {
if case let .parameterEncodingFailed(reason) = self, reason.isPropertyListEncodingFailed { return true }
return false
}
// MultipartEncodingFailureReason
var isBodyPartURLInvalid: Bool {
if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartURLInvalid { return true }
return false
}
var isBodyPartFilenameInvalid: Bool {
if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartFilenameInvalid { return true }
return false
}
var isBodyPartFileNotReachable: Bool {
if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartFileNotReachable { return true }
return false
}
var isBodyPartFileNotReachableWithError: Bool {
if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartFileNotReachableWithError { return true }
return false
}
var isBodyPartFileIsDirectory: Bool {
if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartFileIsDirectory { return true }
return false
}
var isBodyPartFileSizeNotAvailable: Bool {
if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartFileSizeNotAvailable { return true }
return false
}
var isBodyPartFileSizeQueryFailedWithError: Bool {
if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartFileSizeQueryFailedWithError { return true }
return false
}
var isBodyPartInputStreamCreationFailed: Bool {
if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartInputStreamCreationFailed { return true }
return false
}
var isOutputStreamCreationFailed: Bool {
if case let .multipartEncodingFailed(reason) = self, reason.isOutputStreamCreationFailed { return true }
return false
}
var isOutputStreamFileAlreadyExists: Bool {
if case let .multipartEncodingFailed(reason) = self, reason.isOutputStreamFileAlreadyExists { return true }
return false
}
var isOutputStreamURLInvalid: Bool {
if case let .multipartEncodingFailed(reason) = self, reason.isOutputStreamURLInvalid { return true }
return false
}
var isOutputStreamWriteFailed: Bool {
if case let .multipartEncodingFailed(reason) = self, reason.isOutputStreamWriteFailed { return true }
return false
}
var isInputStreamReadFailed: Bool {
if case let .multipartEncodingFailed(reason) = self, reason.isInputStreamReadFailed { return true }
return false
}
// ResponseSerializationFailureReason
var isInputDataNil: Bool {
if case let .responseSerializationFailed(reason) = self, reason.isInputDataNil { return true }
return false
}
var isInputDataNilOrZeroLength: Bool {
if case let .responseSerializationFailed(reason) = self, reason.isInputDataNilOrZeroLength { return true }
return false
}
var isInputFileNil: Bool {
if case let .responseSerializationFailed(reason) = self, reason.isInputFileNil { return true }
return false
}
var isInputFileReadFailed: Bool {
if case let .responseSerializationFailed(reason) = self, reason.isInputFileReadFailed { return true }
return false
}
var isStringSerializationFailed: Bool {
if case let .responseSerializationFailed(reason) = self, reason.isStringSerializationFailed { return true }
return false
}
var isJSONSerializationFailed: Bool {
if case let .responseSerializationFailed(reason) = self, reason.isJSONSerializationFailed { return true }
return false
}
var isPropertyListSerializationFailed: Bool {
if case let .responseSerializationFailed(reason) = self, reason.isPropertyListSerializationFailed { return true }
return false
}
// ResponseValidationFailureReason
var isDataFileNil: Bool {
if case let .responseValidationFailed(reason) = self, reason.isDataFileNil { return true }
return false
}
var isDataFileReadFailed: Bool {
if case let .responseValidationFailed(reason) = self, reason.isDataFileReadFailed { return true }
return false
}
var isMissingContentType: Bool {
if case let .responseValidationFailed(reason) = self, reason.isMissingContentType { return true }
return false
}
var isUnacceptableContentType: Bool {
if case let .responseValidationFailed(reason) = self, reason.isUnacceptableContentType { return true }
return false
}
var isUnacceptableStatusCode: Bool {
if case let .responseValidationFailed(reason) = self, reason.isUnacceptableStatusCode { return true }
return false
}
}
// MARK: -
extension CLDNError.ParameterEncodingFailureReason {
var isMissingURL: Bool {
if case .missingURL = self { return true }
return false
}
var isJSONEncodingFailed: Bool {
if case .jsonEncodingFailed = self { return true }
return false
}
var isPropertyListEncodingFailed: Bool {
if case .propertyListEncodingFailed = self { return true }
return false
}
}
// MARK: -
extension CLDNError.MultipartEncodingFailureReason {
var isBodyPartURLInvalid: Bool {
if case .bodyPartURLInvalid = self { return true }
return false
}
var isBodyPartFilenameInvalid: Bool {
if case .bodyPartFilenameInvalid = self { return true }
return false
}
var isBodyPartFileNotReachable: Bool {
if case .bodyPartFileNotReachable = self { return true }
return false
}
var isBodyPartFileNotReachableWithError: Bool {
if case .bodyPartFileNotReachableWithError = self { return true }
return false
}
var isBodyPartFileIsDirectory: Bool {
if case .bodyPartFileIsDirectory = self { return true }
return false
}
var isBodyPartFileSizeNotAvailable: Bool {
if case .bodyPartFileSizeNotAvailable = self { return true }
return false
}
var isBodyPartFileSizeQueryFailedWithError: Bool {
if case .bodyPartFileSizeQueryFailedWithError = self { return true }
return false
}
var isBodyPartInputStreamCreationFailed: Bool {
if case .bodyPartInputStreamCreationFailed = self { return true }
return false
}
var isOutputStreamCreationFailed: Bool {
if case .outputStreamCreationFailed = self { return true }
return false
}
var isOutputStreamFileAlreadyExists: Bool {
if case .outputStreamFileAlreadyExists = self { return true }
return false
}
var isOutputStreamURLInvalid: Bool {
if case .outputStreamURLInvalid = self { return true }
return false
}
var isOutputStreamWriteFailed: Bool {
if case .outputStreamWriteFailed = self { return true }
return false
}
var isInputStreamReadFailed: Bool {
if case .inputStreamReadFailed = self { return true }
return false
}
}
// MARK: -
extension CLDNError.ResponseSerializationFailureReason {
var isInputDataNil: Bool {
if case .inputDataNil = self { return true }
return false
}
var isInputDataNilOrZeroLength: Bool {
if case .inputDataNilOrZeroLength = self { return true }
return false
}
var isInputFileNil: Bool {
if case .inputFileNil = self { return true }
return false
}
var isInputFileReadFailed: Bool {
if case .inputFileReadFailed = self { return true }
return false
}
var isStringSerializationFailed: Bool {
if case .stringSerializationFailed = self { return true }
return false
}
var isJSONSerializationFailed: Bool {
if case .jsonSerializationFailed = self { return true }
return false
}
var isPropertyListSerializationFailed: Bool {
if case .propertyListSerializationFailed = self { return true }
return false
}
}
// MARK: -
extension CLDNError.ResponseValidationFailureReason {
var isDataFileNil: Bool {
if case .dataFileNil = self { return true }
return false
}
var isDataFileReadFailed: Bool {
if case .dataFileReadFailed = self { return true }
return false
}
var isMissingContentType: Bool {
if case .missingContentType = self { return true }
return false
}
var isUnacceptableContentType: Bool {
if case .unacceptableContentType = self { return true }
return false
}
var isUnacceptableStatusCode: Bool {
if case .unacceptableStatusCode = self { return true }
return false
}
}
| mit | 73406124b72e165bdb2e2e259b02b31e | 30.425982 | 122 | 0.688137 | 5.121615 | false | false | false | false |
AlphaJian/LarsonApp | LarsonApp/LarsonApp/Class/Parts/PartResultTableView/PartsResultTableViewCell.swift | 1 | 1225 | //
// PartsResultTableViewCell.swift
// LarsonApp
//
// Created by Jian Zhang on 11/8/16.
// Copyright © 2016 Jian Zhang. All rights reserved.
//
import UIKit
class PartsResultTableViewCell: UITableViewCell {
@IBOutlet weak var partCountLbl: UILabel!
@IBOutlet weak var partNameLbl: UILabel!
@IBOutlet weak var partIdLbl: UILabel!
@IBOutlet weak var partPriceLbl: UILabel!
var model : PartModel?
var indexPath : IndexPath?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func initUI(partmodel : PartModel, index : IndexPath){
model = partmodel
indexPath = index
partNameLbl.text = partmodel.name
partIdLbl.text = "#\(partmodel.number)"
partPriceLbl.text = "$\(partmodel.price)"
partCountLbl.text = "In Truck:0"
}
func clearCell(){
partNameLbl.text = ""
partIdLbl.text = ""
partPriceLbl.text = ""
partCountLbl.text = ""
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| apache-2.0 | 4e8b4a3bf40290cbe63d12e8a648d059 | 23.979592 | 65 | 0.621732 | 4.264808 | false | false | false | false |
rgkobashi/PhotoSearcher | PhotoViewer/ServiceTracker.swift | 1 | 4390 | //
// ServiceTracker.swift
// PhotoViewer
//
// Created by Rogelio Martinez Kobashi on 2/28/17.
// Copyright © 2017 Rogelio Martinez Kobashi. All rights reserved.
//
import Foundation
// TODO fix prints
/// ServiceTracker was designed to track every service call made from SessionManager. It will print all the following logs:
///
/// - The information of the service when has been requested
/// - The information when the request has been finished regardless if it failed or if it succeed
///
/// NOTE: Since Swift 3 update ServiceTracker fails when it tries to print the body of the request
class ServiceTracker
{
fileprivate var content = ""
fileprivate let startTime = Date()
fileprivate var endTime: Date!
fileprivate var durationTime: String!
init(service: Service, request: URLRequest)
{
printInfoForService(service)
createLogForRequest(request)
}
// MARK: - Private methods
fileprivate func printInfoForService(_ service: Service)
{
var result = "\n*************Service info*************\n"
result += "Service: \(String(describing: service))\n"
result += "Resquest URL: \(service.requestURL)\n"
result += "Resquest type: \(service.requestType)\n"
result += "Content type: \(service.contentType)\n"
result += "Accept type: \(service.acceptType)\n"
result += "Timeout: \(service.timeOut)\n"
if let requestParams = service.requestParams
{
result += "Request params: \n\(requestParams)\n"
}
else
{
result += "Request params: \n"
}
if let additionalHeaders = service.additionalHeaders
{
result += "Additional headers: \n\(additionalHeaders)\n"
}
else
{
result += "Additional headers: \n"
}
result += "***************************************\n"
NSLog("%@", result)
}
fileprivate func createLogForRequest(_ request: URLRequest)
{
content += "Resquest URL: \(request.url!)\n"
content += "Resquest headers: \(request.allHTTPHeaderFields!)\n"
if let body = request.httpBody
{
if let string = String(data: body, encoding: String.Encoding.utf8)
{
content += "Request body: \n\(string)\n"
}
}
}
fileprivate func finishLog(_ response: HTTPURLResponse, body: Any?)
{
content += "Status code: \(response.statusCode)\n"
content += "Response headers: \(response.allHeaderFields)\n"
if let body = body
{
do {
let data = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
if let string = String(data: data, encoding: String.Encoding.utf8)
{
content += "Response body: \n\(string)\n"
}
} catch{
}
}
}
fileprivate func addErrorToLog(_ error: Error)
{
content += "Error: \(error.localizedDescription)\n"
}
fileprivate func printLog()
{
let format = DateFormatter()
format.dateFormat = "yyyy/MM/dd' 'HH:mm:ss.SSS"
var result = "\n*************START: \(format.string(from: startTime))*************\n"
result += "Time: \(durationTime)ms\n"
result += content
result += "*************END: \(format.string(from: endTime))*************\n"
NSLog("%@", result)
}
// MARK: - Public methods
func callFinished()
{
endTime = Date()
let difference = endTime.timeIntervalSince(startTime)
durationTime = String(format: "%.0f", difference * 1000.0)
}
func finishWithResponse(_ response: HTTPURLResponse)
{
finishLog(response, body: nil)
printLog()
}
func finishWithResponse(_ response: HTTPURLResponse, body: Any)
{
finishLog(response, body: body)
printLog()
}
func finishWithError(_ error: Error, response: HTTPURLResponse, body: Any)
{
finishLog(response, body: body)
addErrorToLog(error)
printLog()
}
func finishWithError(_ error: Error)
{
addErrorToLog(error)
printLog()
}
}
| mit | a08b9e829ac3d838971df399f9a8371a | 28.857143 | 123 | 0.558669 | 4.639535 | false | false | false | false |
nakau1/NeroBlu | NeroBlu/NBDate.swift | 1 | 18702 | // =============================================================================
// NerobluCore
// Copyright (C) NeroBlu. All rights reserved.
// =============================================================================
import UIKit
// MARK: - NBDateWeek -
/// 曜日
public enum NBDateWeek: Int {
case sunday, monday, tuesday, wednesday, thursday, friday, saturday
/// 曜日の数
public static let count = 7
/// 開始曜日から並べた配列
/// - parameter startWeek: 開始曜日
/// - returns: NBDateWeekの配列
public static func weeks(_ startWeek: NBDateWeek) -> [NBDateWeek] {
var ret = [NBDateWeek]()
for i in 0..<NBDateWeek.count {
let n = startWeek.rawValue + i
let m = (n < NBDateWeek.count) ? n : n - NBDateWeek.count
ret.append(NBDateWeek(rawValue: m)!)
}
return ret
}
}
// MARK: - NBDateMonth -
/// 月
public enum NBDateMonth: Int {
case january, february, march, april, may, june, july, august, september, october, november, december
/// 月の数
public static let count = 12
/// 月
public var month: Int { return self.rawValue + 1 }
}
// MARK: - NBDate -
/// 日付クラス
open class NBDate: CustomStringConvertible {
/// 取り扱うNSDateオブジェクト
fileprivate(set) var date = Date()
/// カレンダーオブジェクト
open var calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian)
/// デフォルトの出力日付フォーマット
open static var defaultOutputFormat = "yyyy/MM/dd HH:mm:ss"
/// デフォルトの入力日付フォーマット
open static var defaultInputFormat = "yyyy-MM-dd HH:mm:ss"
/// イニシャライザ
/// - parameter date: 日付
public init(date: Date) {
self.date = date
}
}
// MARK: - NBDate: コンビニエンスイニシャライザ -
public extension NBDate {
/// イニシャライザ
/// - parameter year: 年
/// - parameter month: 月
/// - parameter day: 日
/// - parameter hour: 時
/// - parameter minute: 分
/// - parameter second: 秒
public convenience init(year y: Int? = nil, month m: Int? = nil, day d: Int? = nil, hour h: Int? = nil, minute i: Int? = nil, second s: Int? = nil) {
self.init(date: Date())
self.date = self.date(year: y, month: m, day: d, hour: h, minute: i, second: s)
}
}
// MARK: - NBDate: 日付コンポーネントの取得/設定 -
public extension NBDate {
/// 年
public var year: Int {
get { return (self.calendar as NSCalendar).components(.year, from: self.date).year! }
set(v) { self.date = self.date(year: v) }
}
/// 月
public var month: Int {
get { return (self.calendar as NSCalendar).components(.month, from: self.date).month! }
set(v) { self.date = self.date(month: v) }
}
/// 日
public var day: Int {
get { return (self.calendar as NSCalendar).components(.day, from: self.date).day! }
set(v) { self.date = self.date(day: v) }
}
/// 時
public var hour: Int {
get { return (self.calendar as NSCalendar).components(.hour, from: self.date).hour! }
set(v) { self.date = self.date(hour: v) }
}
/// 分
public var minute: Int {
get { return (self.calendar as NSCalendar).components(.minute, from: self.date).minute! }
set(v) { self.date = self.date(minute: v) }
}
/// 秒
public var second: Int {
get { return (self.calendar as NSCalendar).components(.second, from: self.date).second! }
set(v) { self.date = self.date(second: v) }
}
}
// MARK: - NBDate: 読取専用の日付コンポーネント -
extension NBDate {
/// 曜日
public var week: NBDateWeek { return NBDateWeek(rawValue: self.weekIndex)! }
/// 曜日インデックス
public var weekIndex: Int { return (self.calendar as NSCalendar).components(.weekday, from: self.date).weekday! - 1 }
/// 月オブジェクト(enum)
public var monthObject: NBDateMonth { return NBDateMonth(rawValue: self.monthIndex)! }
/// 月インデックス
public var monthIndex: Int { return self.month - 1 }
/// 月の最終日
public var lastDayOfMonth: Int { return NBDate(year: self.year, month: self.month + 1, day: 0).day }
}
// MARK: - NBDate: 日付コンポーネントの文字列取得 -
extension NBDate {
/// 曜日名 ... 月/Mon
public var weekName: String { return self.localizedName({ fmt in fmt.shortWeekdaySymbols }, index: self.weekIndex) }
/// 曜日名(Long) ... 月曜日/Monday
public var weekLongName: String { return self.localizedName({ fmt in fmt.weekdaySymbols }, index: self.weekIndex) }
/// 曜日名(Short) ... 月/M
public var weekShortName: String { return self.localizedName({ fmt in fmt.veryShortWeekdaySymbols }, index: self.weekIndex) }
/// 月名 ... 4月/April
public var monthName: String { return self.localizedName({ fmt in fmt.monthSymbols }, index: self.monthIndex) }
/// 月名(Short) ... 4月/Apr
public var monthShortName: String { return self.localizedName({ fmt in fmt.shortMonthSymbols }, index: self.monthIndex) }
/// 和暦
public var japaneseYearName: String {
let fmt = DateFormatter()
fmt.calendar = Calendar(identifier: Calendar.Identifier.japanese)
fmt.locale = Locale.current
fmt.formatterBehavior = .behavior10_4
fmt.dateFormat = "GG"
var ret = fmt.string(from: self.date)
fmt.dateFormat = "y"
let year = fmt.string(from: self.date)
if self.isJapaneseLocale {
ret += (year == "1") ? "元" : year
ret += "年"
} else {
ret += year
}
return ret
}
}
// MARK: - NBDate: 日付文字列取得 -
public extension NBDate {
/// 日付文字列
public var string: String {
return self.string(NBDate.defaultOutputFormat)
}
/// 指定した日付フォーマットから文字列を生成する
/// - parameter format: 日付フォーマット
/// - returns: 日付文字列
public func string(_ format: String) -> String {
return self.dateFormatter(format).string(from: self.date)
}
/// 指定した日付フォーマットから日付フォーマッタを生成する
/// - parameter format: 日付フォーマット
/// - returns: 日付フォーマッタ
public func dateFormatter(_ format: String) -> DateFormatter {
let fmt = DateFormatter()
fmt.calendar = self.calendar
fmt.dateFormat = format
fmt.locale = Locale.current
fmt.timeZone = TimeZone.current
return fmt
}
public var description: String { return self.string }
}
// MARK: - NBDate: 文字列からのNBDate取得 -
public extension NBDate {
/// 文字列からNBDateを生成する
/// - parameter format: 日付フォーマット
/// - parameter format: 日付フォーマット(省略した場合は)
/// - returns: 日付文字列
public class func create(string: String, format: String? = nil) -> NBDate? {
let temp = NBDate()
let fmt = format ?? NBDate.defaultInputFormat
guard let d = temp.dateFormatter(fmt).date(from: string) else { return nil }
return NBDate(date: d)
}
}
// MARK: - NBDate: ファクトリ -
public extension NBDate {
/// 新しいNBDateオブジェクトを生成する
///
/// イニシャライザによる生成とは時刻の省略時に0にする点が異なります
/// - parameter year: 年
/// - parameter month: 月
/// - parameter day: 日
/// - parameter hour: 時(省略した場合は0)
/// - parameter minute: 分(省略した場合は0)
/// - parameter second: 秒(省略した場合は0)
/// - returns: 新しいインスタンス
public class func create(_ year: Int, _ month: Int, _ day: Int, _ hour: Int? = nil, _ minute: Int? = nil, _ second: Int? = nil) -> NBDate {
return NBDate(
year: year,
month: month,
day: day,
hour: hour ?? 0,
minute: minute ?? 0,
second: second ?? 0
)
}
/// 現時刻を指す新しいインスタンス
public class var now: NBDate {
return NBDate(date: Date())
}
/// 今日の00:00の時刻を指す新しいインスタンス
public class var today: NBDate {
let ret = self.now
//ret.oclock()
return ret
}
/// 値をコピーした新しいインスタンスを返す
/// - returns: 新しいインスタンス
public func clone() -> NBDate {
return NBDate(date: self.date)
}
}
// MARK: - NBDate: 日付コンポーネントの変更 -
public extension NBDate {
/// 指定した年に変更する
/// - parameter value: 設定する年
/// - returns: 自身の参照
public func modifyYear(_ value: Int) -> Self {
self.date = self.date(year: value)
return self
}
/// 指定した月に変更する
/// - parameter value: 設定する月
/// - returns: 自身の参照
public func modifyMonth(_ value: Int) -> Self {
self.date = self.date(month: value)
return self
}
/// 指定した日に変更する
/// - parameter value: 設定する日
/// - returns: 自身の参照
public func modifyDay(_ value: Int) -> Self {
self.date = self.date(day: value)
return self
}
/// 指定した時に変更する
/// - parameter value: 設定する時
/// - returns: 自身の参照
public func modifyHour(_ value: Int) -> Self {
self.date = self.date(hour: value)
return self
}
/// 指定した分に変更する
/// - parameter value: 設定する分
/// - returns: 自身の参照
public func modifyMinute(_ value: Int) -> Self {
self.date = self.date(minute: value)
return self
}
/// 指定した秒に変更する
/// - parameter value: 設定する秒
/// - returns: 自身の参照
public func modifySecond(_ value: Int) -> Self {
self.date = self.date(second: value)
return self
}
}
// MARK: - NBDate: 日付コンポーネントの加算 -
public extension NBDate {
/// 指定した年数を足す
/// - parameter add: 追加する年
/// - returns: 自身の参照
public func addYear(_ add: Int = 1) -> Self {
self.date = self.date(year: self.year + add)
return self
}
/// 指定した月数を足す
/// - parameter add: 追加する月
/// - returns: 自身の参照
public func addMonth(_ add: Int = 1) -> Self {
self.date = self.date(month: self.month + add)
return self
}
/// 指定した日数を足す
/// - parameter add: 追加する日
/// - returns: 自身の参照
public func addDay(_ add: Int = 1) -> Self {
self.date = self.date(day: self.day + add)
return self
}
/// 指定した時数を足す
/// - parameter add: 追加する時
/// - returns: 自身の参照
public func addHour(_ add: Int = 1) -> Self {
self.date = self.date(hour: self.hour + add)
return self
}
/// 指定した分数を足す
/// - parameter add: 追加する分
/// - returns: 自身の参照
public func addMinute(_ add: Int = 1) -> Self {
self.date = self.date(minute: self.minute + add)
return self
}
/// 指定した秒数を足す
/// - parameter add: 追加する分
/// - returns: 自身の参照
public func addSecond(_ add: Int = 1) -> Self {
self.date = self.date(second: self.second + add)
return self
}
}
// MARK: - NBDate: 日付コンポーネントの調整 -
public extension NBDate {
/// 時刻をその日の00:00に設定する
public func oclock() -> Self {
self.date = self.date(year: self.year, month: self.month, day: self.day, hour: 0, minute: 0, second: 0)
return self
}
/// 日付をその月の1日に設定する
public func toFirstDayOfMonth() -> Self {
self.date = self.date(year: self.year, month: self.month, day: 1, hour: 0, minute: 0, second: 0)
return self
}
/// 日付をその年の1月1日に設定する
public func toFirstDayOfYear() -> Self {
self.date = self.date(year: self.year, month: 1, day: 1, hour: 0, minute: 0, second: 0)
return self
}
}
// MARK: - NBDate: 比較 -
public extension NBDate {
/// 比較を行う(NSDate#cpmpare(_:)のラッパ)
/// - parameter date: 比較対象の日付
/// - returns: 比較結果
public func compare(_ date: NBDate) -> ComparisonResult {
return self.date.compare(date.date)
}
/// 同じ日時かどうかを取得する
/// - parameter date: 比較対象の日付
/// - returns: 同じ日時かどうか
public func isSame(_ date: NBDate) -> Bool {
return self.compare(date) == .orderedSame
}
/// 自身が対象の日付よりも未来の日付かどうかを取得する
/// - parameter date: 比較対象の日付
/// - returns: 自身が未来かどうか
public func isFuture(than date: NBDate) -> Bool {
return self.compare(date) == .orderedDescending
}
/// 自身が対象の日付よりも過去の日付かどうかを取得する
/// - parameter date: 比較対象の日付
/// - returns: 自身が過去かどうか
public func isPast(than date: NBDate) -> Bool {
return self.compare(date) == .orderedAscending
}
/// 日付のみを比較して同じ日付かどうかを取得する
/// - parameter date: 比較対象の日付
/// - returns: 同じ日付かどうか(時刻は比較しません)
public func isSameDay(_ date: NBDate) -> Bool {
let flags: NSCalendar.Unit = [.year, .month, .day]
let comps1 = (self.calendar as NSCalendar).components(flags, from: self.date)
let comps2 = (self.calendar as NSCalendar).components(flags, from: date.date)
return ((comps1.year == comps2.year) && (comps1.month == comps2.month) && (comps1.day == comps2.day))
}
/// 時刻のみを比較して同じ時刻かどうかを取得する
/// - parameter date: 比較対象の日付
/// - returns: 同じ時刻かどうか(日付は比較しません)
public func isSameTime(_ date: NBDate) -> Bool {
let flags: NSCalendar.Unit = [.hour, .minute, .second]
let comps1 = (self.calendar as NSCalendar).components(flags, from: self.date)
let comps2 = (self.calendar as NSCalendar).components(flags, from: date.date)
return ((comps1.hour == comps2.hour) && (comps1.minute == comps2.minute) && (comps1.second == comps2.second))
}
/// 日付が今日かどうか
public var isToday: Bool {
return self.isSameDay(NBDate())
}
/// 日付が明日かどうか
public var isTomorrow: Bool {
return self.isSameDay(NBDate().addDay())
}
/// 日付が昨日かどうか
public var isYesterday: Bool {
return self.isSameDay(NBDate().addDay(-1))
}
/// 日付が日曜日かどうか
public var isSunday: Bool {
return self.week == .sunday
}
/// 日付が土曜日かどうか
public var isSaturday: Bool {
return self.week == .saturday
}
/// 日付が平日かどうか
public var isUsualDay: Bool {
return !self.isSunday && !self.isSaturday
}
}
// MARK: - NBDate: 配列生成 -
public extension NBDate {
/// 指定した月の日付すべてを配列で取得する
/// - parameter year: 年
/// - parameter month: 月
/// - returns: NBDateの配列
class func datesInMonth(year: Int, month: Int) -> [NBDate] {
var ret = [NBDate]()
let lastDay = NBDate.create(year, month, 1).lastDayOfMonth
for day in 1...lastDay {
ret.append(NBDate.create(year, month, day))
}
return ret
}
/// 指定した月の日付をカレンダー用にすべて配列で取得する
/// - parameter year: 年
/// - parameter month: 月
/// - parameter startWeek: 開始曜日
/// - returns: NBDateの配列
class func datesForCalendarInMonth(year: Int, month: Int, startWeek: NBDateWeek = .sunday) -> [NBDate] {
var ret = [NBDate]()
let lastDay = NBDate.create(year, month, 1).lastDayOfMonth
let weeks = NBDateWeek.weeks(startWeek)
for day in 1...lastDay {
let date = NBDate.create(year, month, day)
if day == 1 {
if let weekIndex = weeks.index(of: date.week) {
for j in 0..<weekIndex {
ret.append(date.clone().addDay((weekIndex - j) * -1))
}
}
}
ret.append(date)
if day == lastDay {
if let weekIndex = weeks.index(of: date.week), weekIndex + 1 < NBDateWeek.count {
for _ in (weekIndex + 1)..<NBDateWeek.count {
ret.append(date.clone().addDay())
}
}
}
}
return ret
}
}
// MARK: - NBDate: ブライベート -
private extension NBDate {
func date(year y: Int? = nil, month m: Int? = nil, day d: Int? = nil, hour h: Int? = nil, minute i: Int? = nil, second s: Int? = nil) -> Date {
var comps = DateComponents()
comps.year = y ?? self.year
comps.month = m ?? self.month
comps.day = d ?? self.day
comps.hour = h ?? self.hour
comps.minute = i ?? self.minute
comps.second = s ?? self.second
return self.calendar.date(from: comps)!
}
func localizedName(_ symbols: (DateFormatter) -> [String]!, index: Int) -> String {
let fmt = DateFormatter()
fmt.calendar = self.calendar
fmt.locale = Locale.current
return symbols(fmt)[index]
}
var isJapaneseLocale: Bool { return Locale.current.identifier == "ja_JP" }
}
| mit | a9b17af583669dbcafa81ea19fbf401b | 28.495495 | 153 | 0.562431 | 3.487431 | false | false | false | false |
SSuryawanshi/trackTheRide | iOS-App/trackTheRide-iOS/sampleTrackTheRide/sampleTrackTheRide/AppDelegate.swift | 1 | 4621 | //
// AppDelegate.swift
// sampleTrackTheRide
//
// Created by Pratima Suryawanshi on 23/11/16.
// Copyright © 2016 SSuryawanshi. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "sampleTrackTheRide")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| apache-2.0 | 9ed2fe821c92fafaf4b53e567b2aa17f | 48.677419 | 285 | 0.687879 | 5.796738 | false | false | false | false |
crewshin/GasLog | Pods/Material/Sources/NavigationBarView.swift | 1 | 9090 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Material nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public class NavigationBarView : MaterialView {
/**
:name: statusBarStyle
*/
public var statusBarStyle: UIStatusBarStyle = UIApplication.sharedApplication().statusBarStyle {
didSet {
UIApplication.sharedApplication().statusBarStyle = statusBarStyle
}
}
/**
:name: contentInsets
*/
public var contentInsetPreset: MaterialEdgeInsetPreset = .None {
didSet {
contentInset = MaterialEdgeInsetPresetToValue(contentInsetPreset)
}
}
/**
:name: contentInset
*/
public var contentInset: UIEdgeInsets = MaterialEdgeInsetPresetToValue(.Square2) {
didSet {
reloadView()
}
}
/**
:name: titleLabelInsets
*/
public var titleLabelInsetPreset: MaterialEdgeInsetPreset = .None {
didSet {
titleLabelInset = MaterialEdgeInsetPresetToValue(titleLabelInsetPreset)
}
}
/**
:name: titleLabelInset
*/
public var titleLabelInset: UIEdgeInsets = UIEdgeInsets(top: 12, left: 0, bottom: 0, right: 0) {
didSet {
reloadView()
}
}
/**
:name: titleLabel
*/
public var titleLabel: UILabel? {
didSet {
titleLabel?.translatesAutoresizingMaskIntoConstraints = false
reloadView()
}
}
/**
:name: detailLabelInsets
*/
public var detailLabelInsetPreset: MaterialEdgeInsetPreset = .None {
didSet {
detailLabelInset = MaterialEdgeInsetPresetToValue(detailLabelInsetPreset)
}
}
/**
:name: detailLabelInset
*/
public var detailLabelInset: UIEdgeInsets = MaterialEdgeInsetPresetToValue(.None) {
didSet {
reloadView()
}
}
/**
:name: detailLabel
*/
public var detailLabel: UILabel? {
didSet {
detailLabel?.translatesAutoresizingMaskIntoConstraints = false
reloadView()
}
}
/**
:name: leftButtonsInsets
*/
public var leftButtonsInsetPreset: MaterialEdgeInsetPreset = .None {
didSet {
leftButtonsInset = MaterialEdgeInsetPresetToValue(leftButtonsInsetPreset)
}
}
/**
:name: leftButtonsInset
*/
public var leftButtonsInset: UIEdgeInsets = UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0) {
didSet {
reloadView()
}
}
/**
:name: leftButtons
*/
public var leftButtons: Array<UIButton>? {
didSet {
if let v = leftButtons {
for b in v {
b.translatesAutoresizingMaskIntoConstraints = false
}
}
reloadView()
}
}
/**
:name: rightButtonsInsets
*/
public var rightButtonsInsetPreset: MaterialEdgeInsetPreset = .None {
didSet {
rightButtonsInset = MaterialEdgeInsetPresetToValue(rightButtonsInsetPreset)
}
}
/**
:name: rightButtonsInset
*/
public var rightButtonsInset: UIEdgeInsets = UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0) {
didSet {
reloadView()
}
}
/**
:name: rightButtons
*/
public var rightButtons: Array<UIButton>? {
didSet {
if let v = rightButtons {
for b in v {
b.translatesAutoresizingMaskIntoConstraints = false
}
}
reloadView()
}
}
/**
:name: init
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
:name: init
*/
public override init(frame: CGRect) {
super.init(frame: frame)
}
/**
:name: init
*/
public convenience init() {
self.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 70))
}
/**
:name: init
*/
public convenience init?(titleLabel: UILabel? = nil, detailLabel: UILabel? = nil, leftButtons: Array<UIButton>? = nil, rightButtons: Array<UIButton>? = nil) {
self.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 70))
prepareProperties(titleLabel, detailLabel: detailLabel, leftButtons: leftButtons, rightButtons: rightButtons)
}
/**
:name: reloadView
*/
public func reloadView() {
// clear constraints so new ones do not conflict
removeConstraints(constraints)
for v in subviews {
v.removeFromSuperview()
}
var verticalFormat: String = "V:|"
var views: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
var metrics: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
if nil != titleLabel {
verticalFormat += "-(insetTop)"
metrics["insetTop"] = contentInset.top + titleLabelInset.top
} else if nil != detailLabel {
verticalFormat += "-(insetTop)"
metrics["insetTop"] = contentInset.top + detailLabelInset.top
}
// title
if let v = titleLabel {
verticalFormat += "-[titleLabel]"
views["titleLabel"] = v
addSubview(v)
MaterialLayout.alignToParentHorizontally(self, child: v, left: contentInset.left + titleLabelInset.left, right: contentInset.right + titleLabelInset.right)
}
// detail
if let v = detailLabel {
if nil != titleLabel {
verticalFormat += "-(insetB)"
metrics["insetB"] = titleLabelInset.bottom + detailLabelInset.top
}
verticalFormat += "-[detailLabel]"
views["detailLabel"] = v
addSubview(v)
MaterialLayout.alignToParentHorizontally(self, child: v, left: contentInset.left + detailLabelInset.left, right: contentInset.right + detailLabelInset.right)
}
// leftButtons
if let v = leftButtons {
if 0 < v.count {
var h: String = "H:|"
var d: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
var i: Int = 0
for b in v {
let k: String = "b\(i)"
d[k] = b
if 0 == i++ {
h += "-(left)-"
} else {
h += "-(left_right)-"
}
h += "[\(k)]"
addSubview(b)
MaterialLayout.alignFromBottom(self, child: b, bottom: contentInset.bottom + leftButtonsInset.bottom)
}
addConstraints(MaterialLayout.constraint(h, options: [], metrics: ["left" : contentInset.left + leftButtonsInset.left, "left_right" : leftButtonsInset.left + leftButtonsInset.right], views: d))
}
}
// rightButtons
if let v = rightButtons {
if 0 < v.count {
var h: String = "H:"
var d: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
var i: Int = v.count - 1
for b in v {
let k: String = "b\(i)"
d[k] = b
h += "[\(k)]"
if 0 == i-- {
h += "-(right)-"
} else {
h += "-(right_left)-"
}
addSubview(b)
MaterialLayout.alignFromBottom(self, child: b, bottom: contentInset.bottom + rightButtonsInset.bottom)
}
addConstraints(MaterialLayout.constraint(h + "|", options: [], metrics: ["right" : contentInset.right + rightButtonsInset.right, "right_left" : rightButtonsInset.right + rightButtonsInset.left], views: d))
}
}
if nil != detailLabel {
if nil == metrics["insetC"] {
metrics["insetBottom"] = contentInset.bottom + detailLabelInset.bottom
} else {
metrics["insetC"] = (metrics["insetC"] as! CGFloat) + detailLabelInset.bottom
}
} else if nil != titleLabel {
if nil == metrics["insetC"] {
metrics["insetBottom"] = contentInset.bottom + titleLabelInset.bottom
} else {
metrics["insetC"] = (metrics["insetC"] as! CGFloat) + titleLabelInset.bottom
}
}
if 0 < views.count {
verticalFormat += "-(insetBottom)-|"
addConstraints(MaterialLayout.constraint(verticalFormat, options: [], metrics: metrics, views: views))
}
}
/**
:name: prepareView
*/
public override func prepareView() {
super.prepareView()
depth = .Depth2
}
/**
:name: prepareProperties
*/
internal func prepareProperties(titleLabel: UILabel?, detailLabel: UILabel?, leftButtons: Array<UIButton>?, rightButtons: Array<UIButton>?) {
self.titleLabel = titleLabel
self.detailLabel = detailLabel
self.leftButtons = leftButtons
self.rightButtons = rightButtons
}
}
| mit | 308552d0aa85b5419a9e2ed6890d5e91 | 25.195965 | 209 | 0.684598 | 3.726937 | false | false | false | false |
midoks/Swift-Learning | GitHubStar/GitHubStar/GitHubStar/Controllers/common/issues/GsUserCommentCell.swift | 1 | 3131 | //
// GsUserCommentCell.swift
// GitHubStar
//
// Created by midoks on 16/4/24.
// Copyright © 2016年 midoks. All rights reserved.
//
import UIKit
//用户提交Cell
class GsUserCommentCell: UITableViewCell {
//头像视图
var userIcon = UIImageView()
//项目名
var userName = UILabel()
//项目创建时间
var userCommentTime = UILabel()
//项目介绍
var userCommentContent = UILabel()
let repoH:CGFloat = 40
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.initView()
}
//初始化视图
func initView(){
let w = self.getWinWidth()
//提交人头像
userIcon.image = UIImage(named: "avatar_default")
userIcon.layer.cornerRadius = 15
userIcon.frame = CGRect(x:5, y: 5, width:30, height:30)
userIcon.clipsToBounds = true
userIcon.backgroundColor = UIColor.white
contentView.addSubview(userIcon)
//提交用户名
userName = UILabel(frame: CGRect(x: 40, y: 5, width: w-40-140, height: 18))
userName.font = UIFont.systemFont(ofSize: 16)
userName.text = "项目名"
userName.textColor = UIColor(red: 64/255, green: 120/255, blue: 192/255, alpha: 1)
userName.font = UIFont.boldSystemFont(ofSize: 16)
contentView.addSubview(userName)
//提交时间
userCommentTime = UILabel(frame: CGRect(x: 40, y: 23, width: 140, height: 17))
userCommentTime.font = UIFont.systemFont(ofSize: 12)
userCommentTime.text = "create at:2008-12-12"
contentView.addSubview(userCommentTime)
//userCommentTime.backgroundColor = UIColor.blueColor()
//
//提交内容
userCommentContent.frame = CGRect(x: 40, y: repoH, width: w - 50, height:0)
userCommentContent.font = UIFont.systemFont(ofSize: 14)
userCommentContent.text = ""
userCommentContent.numberOfLines = 0
userCommentContent.lineBreakMode = .byWordWrapping
contentView.addSubview(userCommentContent)
//userCommentContent.backgroundColor = UIColor.blueColor()
}
func getCommentSize(text:String) -> CGSize{
userCommentContent.text = text
userCommentContent.frame.size.width = self.getWinWidth() - 50
let size = self.getLabelSize(label: userCommentContent)
return size
}
override func layoutSubviews() {
super.layoutSubviews()
if userCommentContent.text != "" {
let size = self.getCommentSize(text: userCommentContent.text!)
userCommentContent.frame.size.height = size.height
}
}
}
| apache-2.0 | a8e27e56fadc1063fb2da01a1bf31842 | 29.959184 | 90 | 0.625247 | 4.384393 | false | false | false | false |
git-hushuai/MOMO | MMHSMeterialProject/LibaryFile/DGElasticPullToRefresh/DGElasticPullToRefreshExtensions.swift | 1 | 5277 | /*
The MIT License (MIT)
Copyright (c) 2015 Danil Gontovnik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
import ObjectiveC
// MARK: -
// MARK: (NSObject) Extension
public extension NSObject {
// MARK: -
// MARK: Vars
private struct dg_associatedKeys {
static var observersArray = "observers"
}
private var dg_observers: [[String : NSObject]] {
get {
if let observers = objc_getAssociatedObject(self, &dg_associatedKeys.observersArray) as? [[String : NSObject]] {
return observers
} else {
let observers = [[String : NSObject]]()
self.dg_observers = observers
return observers
}
} set {
objc_setAssociatedObject(self, &dg_associatedKeys.observersArray, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: -
// MARK: Methods
public func dg_addObserver(observer: NSObject, forKeyPath keyPath: String) {
let observerInfo = [keyPath : observer]
if dg_observers.indexOf({ $0 == observerInfo }) == nil {
dg_observers.append(observerInfo)
addObserver(observer, forKeyPath: keyPath, options: .New, context: nil)
}
}
public func dg_removeObserver(observer: NSObject, forKeyPath keyPath: String) {
let observerInfo = [keyPath : observer]
if let index = dg_observers.indexOf({ $0 == observerInfo}) {
dg_observers.removeAtIndex(index)
removeObserver(observer, forKeyPath: keyPath)
}
}
}
// MARK: -
// MARK: (UIScrollView) Extension
public extension UIScrollView {
// MARK: - Vars
private struct dg_associatedKeys {
static var pullToRefreshView = "pullToRefreshView"
}
private var pullToRefreshView: DGElasticPullToRefreshView? {
get {
return objc_getAssociatedObject(self, &dg_associatedKeys.pullToRefreshView) as? DGElasticPullToRefreshView
}
set {
objc_setAssociatedObject(self, &dg_associatedKeys.pullToRefreshView, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Methods (Public)
public func dg_addPullToRefreshWithActionHandler(actionHandler: () -> Void, loadingView: DGElasticPullToRefreshLoadingView?) {
multipleTouchEnabled = false
panGestureRecognizer.maximumNumberOfTouches = 1
let pullToRefreshView = DGElasticPullToRefreshView()
self.pullToRefreshView = pullToRefreshView
pullToRefreshView.actionHandler = actionHandler
pullToRefreshView.loadingView = loadingView
addSubview(pullToRefreshView)
pullToRefreshView.observing = true
}
public func dg_removePullToRefresh() {
pullToRefreshView?.disassociateDisplayLink()
pullToRefreshView?.observing = false
pullToRefreshView?.removeFromSuperview()
}
public func dg_setPullToRefreshBackgroundColor(color: UIColor) {
pullToRefreshView?.backgroundColor = color
}
public func dg_setPullToRefreshFillColor(color: UIColor) {
pullToRefreshView?.fillColor = color
}
public func dg_stopLoading() {
pullToRefreshView?.stopLoading()
}
public func dg_headViewStrtLoading(){
pullToRefreshView?.startLoading();
}
}
// MARK: -
// MARK: (UIView) Extension
public extension UIView {
func dg_center(usePresentationLayerIfPossible: Bool) -> CGPoint {
if usePresentationLayerIfPossible, let presentationLayer = layer.presentationLayer() as? CALayer {
// Position can be used as a center, because anchorPoint is (0.5, 0.5)
return presentationLayer.position
}
return center
}
}
// MARK: -
// MARK: (UIPanGestureRecognizer) Extension
public extension UIPanGestureRecognizer {
func dg_resign() {
enabled = false
enabled = true
}
}
// MARK: -
// MARK: (UIGestureRecognizerState) Extension
public extension UIGestureRecognizerState {
func dg_isAnyOf(values: [UIGestureRecognizerState]) -> Bool {
return values.contains({ $0 == self })
}
}
| mit | 3605dcaea71b0c2da79b8e7f916657bb | 30.224852 | 148 | 0.674057 | 5.103482 | false | false | false | false |
Mars182838/WJNumericKeyboard | WJNumericKeyboard/WJLineView.swift | 1 | 2005 | //
// WJLineView.swift
// WJNumericKeyboardDemo
//
// Created by 俊王 on 16/6/2.
// Copyright © 2016年 WJ. All rights reserved.
//
import UIKit
class WJHorizonLineView: UIView {
var lineHeight:CGFloat?
var lineColor:UIColor?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
self.lineHeight = frame.size.height
self.lineColor = UIColor.init(red: 206/255.0, green: 206/255.0, blue: 206/255.0, alpha: 1)
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, self.lineHeight!)
CGContextSetStrokeColorWithColor(context, self.lineColor!.CGColor)
CGContextBeginPath(context)
CGContextMoveToPoint(context, 0, 0)
CGContextAddLineToPoint(context, self.frame.size.width, 0)
CGContextStrokePath(context)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class WJVerticalLineView: UIView {
var lineHeight:CGFloat?
var lineColor:UIColor?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
self.lineHeight = frame.size.width
self.lineColor = UIColor.init(red: 206/255.0, green: 206/255.0, blue: 206/255.0, alpha: 1)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, self.lineHeight!)
CGContextSetStrokeColorWithColor(context, self.lineColor!.CGColor)
CGContextBeginPath(context)
CGContextMoveToPoint(context, 0, 0)
CGContextAddLineToPoint(context, 0, self.frame.size.height)
CGContextStrokePath(context)
}
}
| mit | 6092f4581e6f123005bf88d69719446b | 27.542857 | 98 | 0.655656 | 4.520362 | false | false | false | false |
kevin0511/imitateDouYu | DouYu/DouYu/RecommandViewController.swift | 1 | 3029 | //
// RecommandViewController.swift
// DouYu
//
// Created by Kevin on 2017/3/24.
// Copyright © 2017年 kevin.zhang. All rights reserved.
//
import UIKit
private let kItemMargin:CGFloat = 10
private let kItemW = (kScreenW - 3 * kItemMargin)/2
private let kItemH = kItemW * 3 / 4
private let kHeaderViewH : CGFloat = 50
private let kNormalCellID = "kNormalCellID"
private let kHeaderViewID = "kHeaderViewID"
class RecommandViewController: UIViewController {
// MARK:- 懒加载属性
fileprivate lazy var collectionView:UICollectionView = {[unowned self]in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kItemH)
layout.minimumLineSpacing = 0 //行间距
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
//设置section内边距
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
//注册cell
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kNormalCellID)
//注册header
collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
collectionView.backgroundColor = UIColor.red
return collectionView
}()
// MARK:- 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
extension RecommandViewController{
fileprivate func setupUI(){
view.addSubview(collectionView)
}
}
extension RecommandViewController:UICollectionViewDataSource{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 12
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0{
return 8
}
return 4
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//取出section的headerView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath)
headerView.backgroundColor = UIColor.blue
return headerView
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath)
cell.backgroundColor = UIColor.lightGray
return cell
}
}
| mit | bc050abb4b9f30c095102a5ee1772a76 | 32.044444 | 164 | 0.701748 | 5.87747 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/Browser/Tabs/InactiveTabViewModel.swift | 2 | 8166 | // 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 Foundation
import Storage
import Shared
enum InactiveTabStatus: String, Codable {
case normal
case inactive
case shouldBecomeInactive
}
struct InactiveTabStates: Codable {
var currentState: InactiveTabStatus?
var nextState: InactiveTabStatus?
}
enum TabUpdateState {
case coldStart
case sameSession
}
struct InactiveTabModel: Codable {
// Contains [TabUUID String : InactiveTabState current or for next launch]
var tabWithStatus: [String: InactiveTabStates] = [String: InactiveTabStates]()
static let userDefaults = UserDefaults()
/// Check to see if we ever ran this feature before, this is mainly
/// to avoid tabs automatically going to their state on their first ever run
static var hasRunInactiveTabFeatureBefore: Bool {
get { return userDefaults.bool(forKey: PrefsKeys.KeyInactiveTabsFirstTimeRun) }
set(value) { userDefaults.setValue(value, forKey: PrefsKeys.KeyInactiveTabsFirstTimeRun) }
}
static func save(tabModel: InactiveTabModel) {
userDefaults.removeObject(forKey: PrefsKeys.KeyInactiveTabsModel)
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(tabModel) {
userDefaults.set(encoded, forKey: PrefsKeys.KeyInactiveTabsModel)
}
}
static func get() -> InactiveTabModel? {
if let inactiveTabsModel = userDefaults.object(forKey: PrefsKeys.KeyInactiveTabsModel) as? Data {
do {
let jsonDecoder = JSONDecoder()
let inactiveTabModel = try jsonDecoder.decode(InactiveTabModel.self, from: inactiveTabsModel)
return inactiveTabModel
} catch {
print("Error occured")
}
}
return nil
}
static func clear() {
userDefaults.removeObject(forKey: PrefsKeys.KeyInactiveTabsModel)
}
}
class InactiveTabViewModel {
private var inactiveTabModel = InactiveTabModel()
private var allTabs = [Tab]()
private var selectedTab: Tab?
var inactiveTabs = [Tab]()
var activeTabs = [Tab]()
func updateInactiveTabs(with selectedTab: Tab?, tabs: [Tab]) {
self.allTabs = tabs
self.selectedTab = selectedTab
clearAll()
inactiveTabModel.tabWithStatus = InactiveTabModel.get()?.tabWithStatus ?? [String: InactiveTabStates]()
let bvc = BrowserViewController.foregroundBVC()
// First time starting up with this feature we'll have cold start as update state
// after updating model we can mark tabs that needs to become inactive
updateModelState(state: bvc.updateState)
bvc.updateState = bvc.updateState == .coldStart ? .sameSession : bvc.updateState
updateFilteredTabs()
}
private func updateModelState(state: TabUpdateState) {
let currentDate = Date()
let noon = Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: currentDate) ?? Date()
let day14Old = Calendar.current.date(byAdding: .day, value: -14, to: noon) ?? Date()
let defaultOldDay = day14Old
// Debug for inactive tabs to easily test in code
// TODO: Add a switch in the debug menu to switch between debug or regular
// let min_Old = Calendar.current.date(byAdding: .second, value: -10, to: currentDate) ?? Date() // testing only
// let defaultOldDay = min_Old
let hasRunInactiveTabFeatureBefore = InactiveTabModel.hasRunInactiveTabFeatureBefore
if hasRunInactiveTabFeatureBefore == false { InactiveTabModel.hasRunInactiveTabFeatureBefore = true }
for tab in self.allTabs {
// Append selected tab to normal tab as we don't want to remove that
let tabTimeStamp = tab.lastExecutedTime ?? tab.sessionData?.lastUsedTime ?? tab.firstCreatedTime ?? 0
let tabDate = Date.fromTimestamp(tabTimeStamp)
// 1. Initializing and assigning an empty inactive tab state to the inactiveTabModel mode
if inactiveTabModel.tabWithStatus[tab.tabUUID] == nil {
inactiveTabModel.tabWithStatus[tab.tabUUID] = InactiveTabStates()
}
// 2. Current tab type from inactive tab model
// Note:
// a) newly assigned inactive tab model will have empty `tabWithStatus`
// with nil current and next states
// b) an older inactive tab model will have a proper `tabWithStatus`
let tabType = inactiveTabModel.tabWithStatus[tab.tabUUID]
// 3. All tabs should start with a normal current state if they don't have any current state
if tabType?.currentState == nil { inactiveTabModel.tabWithStatus[tab.tabUUID]?.currentState = .normal }
if tab == selectedTab {
inactiveTabModel.tabWithStatus[tab.tabUUID]?.currentState = .normal
} else if tabType?.nextState == .shouldBecomeInactive && state == .sameSession {
continue
} else if tab == selectedTab || tabDate > defaultOldDay || tabTimeStamp == 0 {
inactiveTabModel.tabWithStatus[tab.tabUUID]?.currentState = .normal
} else if tabDate <= defaultOldDay {
if hasRunInactiveTabFeatureBefore == false {
inactiveTabModel.tabWithStatus[tab.tabUUID]?.nextState = .shouldBecomeInactive
} else if state == .coldStart {
inactiveTabModel.tabWithStatus[tab.tabUUID]?.currentState = .inactive
inactiveTabModel.tabWithStatus[tab.tabUUID]?.nextState = nil
} else if state == .sameSession && tabType?.currentState != .inactive {
inactiveTabModel.tabWithStatus[tab.tabUUID]?.nextState = .shouldBecomeInactive
}
}
}
InactiveTabModel.save(tabModel: inactiveTabModel)
}
private func updateFilteredTabs() {
inactiveTabModel.tabWithStatus = InactiveTabModel.get()?.tabWithStatus ?? [String: InactiveTabStates]()
clearAll()
for tab in self.allTabs {
let status = inactiveTabModel.tabWithStatus[tab.tabUUID]
if status == nil {
activeTabs.append(tab)
} else if let status = status, let currentState = status.currentState {
addTab(state: currentState, tab: tab)
}
}
}
private func addTab(state: InactiveTabStatus?, tab: Tab) {
switch state {
case .inactive:
inactiveTabs.append(tab)
case .normal, .none:
activeTabs.append(tab)
case .shouldBecomeInactive: break
}
}
private func clearAll() {
activeTabs.removeAll()
inactiveTabs.removeAll()
}
}
extension InactiveTabViewModel {
/// This function returns any tabs that are less than four days old.
///
/// Because the "Jump Back In" and "Inactive Tabs" features are separate features,
/// it is not a given that a tab has an active/inactive state. Thus, we must
/// assume that if we want to use active/inactive state, we can do so without
/// that particular feature being active but still respecting that logic.
static func getActiveEligibleTabsFrom(_ tabs: [Tab], profile: Profile) -> [Tab] {
var activeTabs = [Tab]()
let currentDate = Date()
let noon = Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: currentDate) ?? Date()
let day14Old = Calendar.current.date(byAdding: .day, value: -14, to: noon) ?? Date()
let defaultOldDay = day14Old
for tab in tabs {
let tabTimeStamp = tab.lastExecutedTime ?? tab.sessionData?.lastUsedTime ?? tab.firstCreatedTime ?? 0
let tabDate = Date.fromTimestamp(tabTimeStamp)
if tabDate > defaultOldDay || tabTimeStamp == 0 {
activeTabs.append(tab)
}
}
return activeTabs
}
}
| mpl-2.0 | b464d3df7e509a83568594b58c91f93d | 40.242424 | 119 | 0.648665 | 4.613559 | false | false | false | false |
morbrian/udacity-nano-virtualtourist | VirtualTourist/PhotoExtension.swift | 1 | 4579 | //
// PhotoExtension.swift
// VirtualTourist
//
// Created by Brian Moriarty on 7/12/15.
// Copyright (c) 2015 Brian Moriarty. All rights reserved.
//
import Foundation
import CoreData
import UIKit
// Photo Extension
// Exposes additional capabilities on the Photo Model.
extension Photo {
// creates a new Photo, associates it with the pin and photoUrl, and persist it.
class func createInManagedObjectContext(context: NSManagedObjectContext, pin: Pin, photoUrlString: String) -> Photo {
var photo: Photo?
context.performBlockAndWait {
let newPhoto = NSEntityDescription.insertNewObjectForEntityForName(Constants.PhotoEntityName, inManagedObjectContext: context) as! Photo
newPhoto.pin = pin
newPhoto.photoUrlString = photoUrlString
CoreDataStackManager.sharedInstance().saveContext()
photo = newPhoto
}
return photo!
}
var copyPhotoPath: String? {
var copy: String?
CoreDataStackManager.sharedInstance().managedObjectContext!.performBlockAndWait {
copy = self.photoPath
}
return copy
}
var title: String? {
return photoUrlString
}
var photoUrlString: String? {
get {
if let photoPath = copyPhotoPath where !photoPath.isEmpty {
let parts = photoPath.pathComponents
let firstSeparator = find(photoPath, "/")
let host = photoPath[photoPath.startIndex..<firstSeparator!]
let path = photoPath[firstSeparator!..<photoPath.endIndex]
return "https://\(host)\(path)"
} else {
return nil
}
}
set {
if let newValue = newValue,
newPathUrl = NSURL(string: newValue) {
photoPath = "\(newPathUrl.host!)\(newPathUrl.path!)"
} else {
photoPath = nil
}
}
}
var photoImage: UIImage? {
get {
return FlickrService.Caches.imageCache.imageWithIdentifier(copyPhotoPath)
}
set {
if let photoPath = copyPhotoPath {
FlickrService.Caches.imageCache.storeImage(newValue, withIdentifier: photoPath)
}
}
}
// MARK: - All purpose task method for images
func taskForImage(completionHandler: (imageData: NSData?, error: NSError?) -> Void) -> NSURLSessionTask {
let url = NSURL(string: self.photoUrlString!)!
let request = NSURLRequest(URL: url)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {data, response, downloadError in
if let error = downloadError {
//let newError = TheMovieDB.errorForData(data, response: response, error: downloadError)
dispatch_async(dispatch_get_main_queue(), {
completionHandler(imageData: nil, error: error)
})
} else {
dispatch_async(dispatch_get_main_queue(), {
completionHandler(imageData: data, error: nil)
})
}
}
task.resume()
return task
}
// loads the image on a background thread, runs the completion handler back on the main thread
// func loadImageTask(completionHandler: (image: UIImage?, error: NSError?) -> (Void)) -> NSURLSessionTask {
//
// let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, downloadError in
//
// dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) {
// if let imageUrlString = self.photoUrlString,
// imageUrl = NSURL(string: imageUrlString),
// imageData = NSData(contentsOfURL: imageUrl) {
// dispatch_async(dispatch_get_main_queue(), {
// completionHandler(image: UIImage(data: imageData), error: nil)
// })
// } else {
// Logger.error("No Image Data From URL: \(self.photoUrlString)")
// dispatch_async(dispatch_get_main_queue(), {
// // TODO: create error object
// completionHandler(image: nil, error: nil)
// })
// }
// }
// }
// task.resume()
// return task
// }
}
| mit | 4e5f9f67c09ac4243b4cd8d064403ed0 | 34.223077 | 148 | 0.555798 | 5.065265 | false | false | false | false |
adrfer/swift | validation-test/compiler_crashers_fixed/27087-swift-declcontext-getlocalconformances.swift | 13 | 772 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
re g{ enum b = c("))
let a{}()
}class A {
a
B<T where g:b(")
class d>(_ = c{
import Foundation
func f.C{let:T? = [Void{
class A {
class d<f<T : {
init()
var b<T : T
if true{
T] {
init()
class A{
if tocol c(){
struct S <T.c
var a
struct Q<T where H:T.c()
class A : {enum b {
class B:P{
end " ( 1 ]
var a{
struct c(){
class B<C<d<d<d<T{}struct S< C {
func c(_ = F>()
struct A<
class C<T {
struct S< {
class B< g<T where T.e: {let v{{}
b{{
var b:T.c{ enum b<T{
let c{
var b(_ = 0
B
func f<T : T.c{ enum b = e
class A : a {
if true {}class B:P{
class C{
struct
| apache-2.0 | e23d9fad101c3335565f175a7d07e9b2 | 15.425532 | 87 | 0.612694 | 2.4125 | false | false | false | false |
radazzouz/firefox-ios | Shared/SystemUtils.swift | 2 | 2614 | /* 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 Foundation
/**
* System helper methods written in Swift.
*/
public struct SystemUtils {
/**
Returns an accurate version of the system uptime even while the device is asleep.
http://stackoverflow.com/questions/12488481/getting-ios-system-uptime-that-doesnt-pause-when-asleep
- returns: Time interval since last reboot.
*/
public static func systemUptime() -> TimeInterval {
var boottime = timeval()
var mib = [CTL_KERN, KERN_BOOTTIME]
var size = MemoryLayout<timeval>.stride
var now = time_t()
time(&now)
sysctl(&mib, u_int(mib.count), &boottime, &size, nil, 0)
let tv_sec: time_t = withUnsafePointer(to: &boottime.tv_sec) { $0.pointee }
return TimeInterval(now - tv_sec)
}
}
extension SystemUtils {
// This should be run on first run of the application.
// It shouldn't be run from an extension.
// Its function is to write a lock file that is only accessible from the application,
// and not accessible from extension when the device is locked. Thus, we can tell if an extension is being run
// when the device is locked.
public static func onFirstRun() {
guard let lockFileURL = lockedDeviceURL else {
return
}
let lockFile = lockFileURL.path
let fm = FileManager.default
if fm.fileExists(atPath: lockFile) {
return
}
let contents = "Device is unlocked".data(using: String.Encoding.utf8)
fm.createFile(atPath: lockFile, contents: contents, attributes: [FileAttributeKey.protectionKey.rawValue: FileProtectionType.complete])
}
private static var lockedDeviceURL: URL? {
guard let groupIdentifier = AppInfo.sharedContainerIdentifier() else {
return nil
}
let directoryURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: groupIdentifier)
return directoryURL?.appendingPathComponent("security.dummy")
}
public static func isDeviceLocked() -> Bool {
guard let lockFileURL = lockedDeviceURL else {
return true
}
do {
let _ = try Data(contentsOf: lockFileURL, options: .mappedIfSafe)
return false
} catch let err as NSError {
return err.code == 257
} catch _ {
return true
}
}
}
| mpl-2.0 | dceabdcab9901b3daa3ca171c132af64 | 35.305556 | 143 | 0.644989 | 4.438031 | false | false | false | false |
elpassion/el-space-ios | ELSpaceTests/TestCases/Commons/Validators/EmailValidatorSpec.swift | 1 | 3229 | import Quick
import Nimble
import RxSwift
import RxTest
@testable import ELSpace
class EmailValidatorSpec: QuickSpec {
override func spec() {
describe("EmailValidator") {
var sut: EmailValidator!
var scheduler: TestScheduler!
var observer: TestableObserver<Error>!
beforeEach {
sut = EmailValidator()
scheduler = TestScheduler(initialClock: 0)
observer = scheduler.createObserver(Error.self)
}
afterEach {
sut = nil
scheduler = nil
observer = nil
}
context("when validate good email") {
var result: Bool!
beforeEach {
result = sut.validateEmail(email: "[email protected]", hostedDomain: "elpassion.pl")
}
it("should validation be true") {
expect(result).to(beTrue())
}
}
context("when validate email with incorrect format") {
var result: Bool!
beforeEach {
_ = sut.error.subscribe(observer)
result = sut.validateEmail(email: "aaaaaa", hostedDomain: "gmail.com")
}
it("should validation NOT be true") {
expect(result).to(beFalse())
}
describe("error") {
var emailValidationError: EmailValidator.EmailValidationError!
beforeEach {
let error = observer.events.first!.value.element!
emailValidationError = error as? EmailValidator.EmailValidationError
}
it("should emit one event") {
expect(observer.events).to(haveCount(1))
}
it("should be 'emailFormat' error") {
expect(emailValidationError == .emailFormat).to(beTrue())
}
}
}
context("when validate email with incorrect domain") {
var result: Bool!
beforeEach {
_ = sut.error.subscribe(observer)
result = sut.validateEmail(email: "[email protected]", hostedDomain: "gmail.com")
}
it("should validation NOT be true") {
expect(result).to(beFalse())
}
describe("error") {
var emailValidationError: EmailValidator.EmailValidationError!
beforeEach {
let error = observer.events.first!.value.element!
emailValidationError = error as? EmailValidator.EmailValidationError
}
it("should emit one event") {
expect(observer.events).to(haveCount(1))
}
it("should be 'emailFormat' error") {
expect(emailValidationError == .incorrectDomain).to(beTrue())
}
}
}
}
}
}
| gpl-3.0 | c7c8bf443fce5d9da35b03fa6c4b1b7f | 30.656863 | 103 | 0.468566 | 5.870909 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.