repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
macteo/bezier | Bézier.playgroundbook/Contents/Chapters/Bezier.playgroundchapter/Pages/Animation.playgroundpage/LiveView.swift | 1 | 97 | import PlaygroundSupport
let page = PlaygroundPage.current
page.liveView = AnimationController()
| mit |
galv/reddift | reddiftTests/LinksTest.swift | 1 | 21098 | //
// LinksTest.swift
// reddift
//
// Created by sonson on 2015/05/09.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
import XCTest
class LinksTest: SessionTestSpec {
/// Link ID, https://www.reddit.com/r/sandboxtest/comments/35dpes/reddift_test/
let testLinkId = "35dpes"
let testCommentId = "cr3g41y"
var postedThings:[Comment] = []
func test_deleteCommentOrLink(thing:Thing) {
let documentOpenExpectation = self.expectationWithDescription("test_deleteCommentOrLink")
var isSucceeded = false
self.session?.deleteCommentOrLink(thing.name, completion: { (result) -> Void in
switch result {
case .Failure(let error):
print(error.description)
case .Success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to delete the last posted comment.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
func testPostingCommentToExistingComment() {
print("Test posting a comment to existing comment")
do {
var comment:Comment? = nil
print ("Check whether the comment is posted as a child of the specified link")
do {
let name = "t3_" + self.testLinkId
let documentOpenExpectation = self.expectationWithDescription("Check whether the comment is posted as a child of the specified link")
self.session?.postComment("test comment2", parentName:name, completion: { (result) -> Void in
switch result {
case .Failure(let error):
print(error.description)
case .Success(let postedComment):
comment = postedComment
}
XCTAssert(comment != nil, "Check whether the comment is posted as a child of the specified link")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print ("Test to delete the last posted comment.")
do {
if let comment = comment {
self.test_deleteCommentOrLink(comment)
}
}
}
}
func testPostingCommentToExistingLink() {
print("Test posting a comment to existing link")
do {
var comment:Comment? = nil
print("the comment is posted as a child of the specified comment")
do {
let name = "t1_" + self.testCommentId
let documentOpenExpectation = self.expectationWithDescription("the comment is posted as a child of the specified comment")
self.session?.postComment("test comment3", parentName:name, completion: { (result) -> Void in
switch result {
case .Failure(let error):
print(error.description)
case .Success(let postedComment):
comment = postedComment
}
XCTAssert(comment != nil, "the comment is posted as a child of the specified comment")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print("Test to delete the last posted comment.")
do {
if let comment = comment {
self.test_deleteCommentOrLink(comment)
}
}
}
}
func testSetNSFW() {
print("Test to make specified Link NSFW.")
do {
var isSucceeded = false
let link = Link(id: self.testLinkId)
let documentOpenExpectation = self.expectationWithDescription("Test to make specified Link NSFW.")
self.session?.setNSFW(true, thing: link, completion: { (result) -> Void in
switch result {
case .Failure(let error):
print(error.description)
case .Success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to make specified Link NSFW.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print("Check whether the specified Link is NSFW.")
do{
let link = Link(id: self.testLinkId)
let documentOpenExpectation = self.expectationWithDescription("Check whether the specified Link is NSFW.")
self.session?.getInfo([link.name], completion: { (result) -> Void in
var isSucceeded = false
switch result {
case .Failure(let error):
print(error.description)
case .Success(let listing):
isSucceeded = listing.children
.flatMap({(thing:Thing) -> Link? in
if let obj = thing as? Link {if obj.name == link.name { return obj }}
return nil
})
.reduce(true) {(a:Bool, link:Link) -> Bool in
return (a && link.over18)
}
}
XCTAssert(isSucceeded, "Check whether the specified Link is NSFW.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print("Test to make specified Link NOT NSFW.")
do{
var isSucceeded = false
let link = Link(id: self.testLinkId)
let documentOpenExpectation = self.expectationWithDescription("Test to make specified Link NOT NSFW.")
self.session?.setNSFW(false, thing: link, completion: { (result) -> Void in
switch result {
case .Failure(let error):
print(error.description)
case .Success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to make specified Link NOT NSFW.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print("Check whether the specified Link is NOT NSFW.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectationWithDescription("Test to make specified Link NOT NSFW.")
let link = Link(id: self.testLinkId)
self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .Failure(let error):
print(error.description)
case .Success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
isSucceeded = (incommingLink.name == link.name && !incommingLink.over18)
}
}
}
XCTAssert(isSucceeded, "Test to make specified Link NOT NSFW.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
}
func testToSaveLinkOrComment() {
print("Test to save specified Link.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectationWithDescription("Test to save specified Link.")
let link = Link(id: self.testLinkId)
self.session?.setSave(true, name: link.name, category: "", completion: { (result) -> Void in
switch result {
case .Failure:
print(result.error!.description)
case .Success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to save specified Link.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print("Check whether the specified Link is saved.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectationWithDescription("Check whether the specified Link is saved.")
let link = Link(id: self.testLinkId)
self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .Failure(let error):
print(error.description)
case .Success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
isSucceeded = (incommingLink.name == link.name && incommingLink.saved)
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Link is saved.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print("Test to unsave specified Link.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectationWithDescription("Test to unsave specified Link.")
let link = Link(id: self.testLinkId)
self.session?.setSave(false, name: link.name, category: "", completion: { (result) -> Void in
switch result {
case .Failure:
print(result.error!.description)
case .Success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to unsave specified Link.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print("Check whether the specified Link is unsaved.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectationWithDescription("Check whether the specified Link is unsaved.")
let link = Link(id: self.testLinkId)
self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .Failure(let error):
print(error.description)
case .Success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
isSucceeded = (incommingLink.name == link.name && !incommingLink.saved)
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Link is unsaved.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
}
func testToHideCommentOrLink() {
print("Test to hide the specified Link.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectationWithDescription("Test to hide the specified Link.")
let link = Link(id: self.testLinkId)
self.session?.setHide(true, name: link.name, completion: { (result) -> Void in
switch result {
case .Failure:
print(result.error!.description)
case .Success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to hide the specified Link.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print("Check whether the specified Link is hidden.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectationWithDescription("Check whether the specified Link is hidden.")
let link = Link(id: self.testLinkId)
self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .Failure(let error):
print(error.description)
case .Success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
isSucceeded = (incommingLink.name == link.name && incommingLink.hidden)
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Link is hidden.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print("Test to show the specified Link.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectationWithDescription("Test to show the specified Link.")
let link = Link(id: self.testLinkId)
self.session?.setHide(false, name: link.name, completion: { (result) -> Void in
switch result {
case .Failure:
print(result.error!.description)
case .Success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to show the specified Link.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print("Check whether the specified Link is not hidden.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectationWithDescription("Check whether the specified Link is not hidden.")
let link = Link(id: self.testLinkId)
self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .Failure(let error):
print(error.description)
case .Success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
isSucceeded = (incommingLink.name == link.name && !incommingLink.hidden)
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Link is not hidden.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
}
func testToVoteCommentOrLink() {
print("Test to upvote the specified Link.")
do {
var isSucceeded = false
let link = Link(id: self.testLinkId)
let documentOpenExpectation = self.expectationWithDescription("Test to upvote the specified Link.")
self.session?.setVote(VoteDirection.Up, name: link.name, completion: { (result) -> Void in
switch result {
case .Failure:
print(result.error!.description)
case .Success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to upvote the specified Link.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print("Check whether the specified Link is gave upvote.")
do {
var isSucceeded = false
let link = Link(id: self.testLinkId)
let documentOpenExpectation = self.expectationWithDescription("Check whether the specified Link is gave upvote.")
self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .Failure(let error):
print(error.description)
case .Success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
if let likes = incommingLink.likes {
isSucceeded = (incommingLink.name == link.name && likes)
}
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Link is gave upvote.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print("Test to give a downvote to the specified Link.")
do {
var isSucceeded = false
let link = Link(id: self.testLinkId)
let documentOpenExpectation = self.expectationWithDescription("Test to give a downvote to the specified Link.")
self.session?.setVote(VoteDirection.Down, name: link.name, completion: { (result) -> Void in
switch result {
case .Failure:
print(result.error!.description)
case .Success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to give a downvote to the specified Link.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print("Check whether the specified Link is gave downvote.")
do {
var isSucceeded = false
let link = Link(id: self.testLinkId)
let documentOpenExpectation = self.expectationWithDescription("Check whether the specified Link is gave downvote.")
self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .Failure(let error):
print(error.description)
case .Success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
if let likes = incommingLink.likes {
isSucceeded = (incommingLink.name == link.name && !likes)
}
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Link is gave downvote.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print("Test to revoke voting to the specified Link.")
do {
var isSucceeded = false
let link = Link(id: self.testLinkId)
let documentOpenExpectation = self.expectationWithDescription("Test to revoke voting to the specified Link.")
self.session?.setVote(VoteDirection.No, name: link.name, completion: { (result) -> Void in
switch result {
case .Failure:
print(result.error!.description)
case .Success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to revoke voting to the specified Link.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
print("Check whether the downvote to the specified Link has benn revoked.")
do {
var isSucceeded = false
let link = Link(id: self.testLinkId)
let documentOpenExpectation = self.expectationWithDescription("Check whether the downvote to the specified Link has benn revoked.")
self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .Failure(let error):
print(error.description)
case .Success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
isSucceeded = (incommingLink.name == link.name && (incommingLink.likes == nil))
}
}
}
XCTAssert(isSucceeded, "Check whether the downvote to the specified Link has benn revoked.")
documentOpenExpectation.fulfill()
})
self.waitForExpectationsWithTimeout(self.timeoutDuration, handler: nil)
}
}
}
| mit |
box/box-ios-sdk | Sources/Responses/WebLink.swift | 1 | 4433 | import Foundation
/// Object that points to URLs. These objects are also known as bookmarks within the Box web application.
public class WebLink: BoxModel {
/// Web link permissions
public struct Permissions: BoxInnerModel {
/// Can rename web link
public let canRename: Bool?
/// Can delete web link
public let canDelete: Bool?
/// Can comment on web link
public let canComment: Bool?
/// Can share web link
public let canShare: Bool?
/// Can set share access for web link
public let canSetShareAccess: Bool?
}
// MARK: - BoxModel
private static var resourceType: String = "web_link"
/// Box item type
public var type: String
public private(set) var rawData: [String: Any]
// MARK: - Properties
/// Identifier
public let id: String
/// A unique ID for use with the events.
public let sequenceId: String?
/// The entity tag of this web link. Used with If-Match headers.
public let etag: String?
/// The name of this web link.
public let name: String?
/// The URL this web link points to.
public let url: URL?
/// The user who created this web link
public let createdBy: User?
/// When this web link was created
public let createdAt: Date?
/// When this web link was last updated
public let modifiedAt: Date?
/// The parent object the web link belongs to.
public let parent: Folder?
/// The description accompanying the web link. This is visible within the Box web application.
public let description: String?
/// Status of the web link
public let itemStatus: ItemStatus?
/// When this web link was last moved to the trash
public let trashedAt: Date?
/// When this web link will be permanently deleted.
public let purgedAt: Date?
/// The shared link object for this web link. Is nil if no shared link has been created.
public let sharedLink: SharedLink?
/// The path of folders to this link, starting at the root
public let pathCollection: PathCollection?
/// The user who last modified this web link
public let modifiedBy: User?
/// The user who owns this web link
public let ownedBy: User?
/// Web link permissions
public let permissions: Permissions?
/// Initializer.
///
/// - Parameter json: JSON dictionary.
/// - Throws: Decoding error.
public required init(json: [String: Any]) throws {
guard let itemType = json["type"] as? String else {
throw BoxCodingError(message: .typeMismatch(key: "type"))
}
guard itemType == WebLink.resourceType else {
throw BoxCodingError(message: .valueMismatch(key: "type", value: itemType, acceptedValues: [WebLink.resourceType]))
}
rawData = json
type = itemType
id = try BoxJSONDecoder.decode(json: json, forKey: "id")
sequenceId = try BoxJSONDecoder.optionalDecode(json: json, forKey: "sequence_id")
etag = try BoxJSONDecoder.optionalDecode(json: json, forKey: "etag")
name = try BoxJSONDecoder.optionalDecode(json: json, forKey: "name")
url = try BoxJSONDecoder.optionalDecodeURL(json: json, forKey: "url")
createdBy = try BoxJSONDecoder.optionalDecode(json: json, forKey: "created_by")
createdAt = try BoxJSONDecoder.optionalDecodeDate(json: json, forKey: "created_at")
modifiedAt = try BoxJSONDecoder.optionalDecodeDate(json: json, forKey: "modified_at")
parent = try BoxJSONDecoder.optionalDecode(json: json, forKey: "parent")
description = try BoxJSONDecoder.optionalDecode(json: json, forKey: "description")
itemStatus = try BoxJSONDecoder.optionalDecodeEnum(json: json, forKey: "item_status")
trashedAt = try BoxJSONDecoder.optionalDecodeDate(json: json, forKey: "trashed_at")
purgedAt = try BoxJSONDecoder.optionalDecodeDate(json: json, forKey: "purged_at")
sharedLink = try BoxJSONDecoder.optionalDecode(json: json, forKey: "shared_link")
pathCollection = try BoxJSONDecoder.optionalDecode(json: json, forKey: "path_collection")
modifiedBy = try BoxJSONDecoder.optionalDecode(json: json, forKey: "modified_by")
ownedBy = try BoxJSONDecoder.optionalDecode(json: json, forKey: "owned_by")
permissions = try BoxJSONDecoder.optionalDecode(json: json, forKey: "permissions")
}
}
| apache-2.0 |
atl009/WordPress-iOS | WordPress/Classes/Models/ReaderSearchTopic.swift | 4 | 157 | import Foundation
@objc open class ReaderSearchTopic: ReaderAbstractTopic {
override open class var TopicType: String {
return "search"
}
}
| gpl-2.0 |
sleifer/SKLBits | bits/CGRect-SKLBits.swift | 1 | 1099 | //
// CGRect-SKLBits.swift
// slidekey
//
// Created by Simeon Leifer on 7/11/16.
// Copyright © 2016 droolingcat.com. All rights reserved.
//
#if os(OSX)
import AppKit
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#endif
public extension CGRect {
public func floored() -> CGRect {
var r: CGRect = self
r.origin.x = ceil(r.origin.x)
r.origin.y = ceil(r.origin.y)
r.size.width = floor(r.size.width)
r.size.height = floor(r.size.height)
if r.maxX > self.maxX {
r.size.width -= 1
}
if r.maxY > self.maxY {
r.size.height -= 1
}
return r
}
mutating public func center(in rect: CGRect) {
self.position(in: rect, px: 0.5, py: 0.5)
}
mutating public func position(in rect: CGRect, px: CGFloat, py: CGFloat) {
let offset = offsetToPosition(in: rect, px: px, py: py)
self = self.offsetBy(dx: offset.x, dy: offset.y)
}
public func offsetToPosition(in rect: CGRect, px: CGFloat, py: CGFloat) -> CGPoint {
let xoff = floor((rect.width - self.width) * px)
let yoff = floor((rect.height - self.height) * py)
return CGPoint(x: xoff, y: yoff)
}
}
| mit |
prot3ct/Ventio | Ventio/Ventio/Extensions/StringCount.swift | 2 | 94 | extension String
{
func count() -> Int
{
return self.characters.count
}
}
| apache-2.0 |
colbylwilliams/bugtrap | iOS/Code/Swift/bugTrap/bugTrapKit/Trackers/JIRA/Domain/JiraIssueTypeField.swift | 1 | 2265 | //
// JiraIssueTypeField.swift
// bugTrap
//
// Created by Colby L Williams on 1/26/15.
// Copyright (c) 2015 bugTrap. All rights reserved.
//
import Foundation
class JiraIssueTypeField : JsonSerializable {
private struct fields {
static let required = "required"
static let schema = "schema"
static let name = "name"
static let hasDefaultValue = "hasDefaultValue"
static let operations = "operations"
static let allowedValues = "allowedValues"
}
var required = false
var schema = JiraIssueTypeFieldSchema()
var name = ""
var hasDefaultValue = false
var operations = [String]()
var allowedValues = [JiraSimpleItem]()
var isEmpty: Bool {
return name.isEmpty
}
var hasAllowedValues: Bool {
return !isEmpty && allowedValues.count > 0 && !allowedValues[0].name.isEmpty && allowedValues[0].id != nil
}
init() {
}
init(required: Bool, schema: JiraIssueTypeFieldSchema, name: String, hasDefaultValue: Bool, operations: [String], allowedValues: [JiraSimpleItem]) {
self.required = required
self.schema = schema
self.name = name
self.hasDefaultValue = hasDefaultValue
self.operations = operations
self.allowedValues = allowedValues
}
class func deserialize (json: JSON) -> JiraIssueTypeField? {
let required = json[fields.required].boolValue
let schema = JiraIssueTypeFieldSchema.deserialize(json[fields.schema])
let name = json[fields.name].stringValue
let hasDefaultValue = json[fields.hasDefaultValue].boolValue
var operations = [String]()
for item in json[fields.operations].arrayValue {
if let operation = item.string {
operations.append(operation)
}
}
let allowedValues = JiraSimpleItem.deserializeAll(json[fields.allowedValues])
return JiraIssueTypeField(required: required, schema: schema!, name: name, hasDefaultValue: hasDefaultValue, operations: operations, allowedValues: allowedValues)
}
class func deserializeAll(json: JSON) -> [JiraIssueTypeField] {
var items = [JiraIssueTypeField]()
if let jsonArray = json.array {
for item: JSON in jsonArray {
if let si = deserialize(item) {
items.append(si)
}
}
}
return items
}
func serialize () -> NSMutableDictionary {
let dict = NSMutableDictionary()
return dict
}
}
| mit |
S2dentik/Taylor | TaylorFramework/Modules/temper/Output/PMDCoordinator.swift | 3 | 2322 | //
// PMDCoordinator.swift
// Temper
//
// Created by Mihai Seremet on 9/4/15.
// Copyright © 2015 Yopeso. All rights reserved.
//
import Foundation
private typealias ViolationsMap = [Path: [Violation]]
final class PMDCoordinator: WritingCoordinator {
func writeViolations(_ violations: [Violation], atPath path: String) {
FileManager().removeFileAtPath(path)
let map = mapViolations(violations)
let xml = generateXML(from: map)
let xmlData = xml.xmlData(options: .nodePrettyPrint)
do {
try xmlData.write(to: URL(fileURLWithPath: path), options: .atomic)
} catch let error {
let message = "Error while creating PMD report." + "\n" +
"Reason: " + error.localizedDescription
Printer(verbosityLevel: .error).printError(message)
}
}
private func mapViolations(_ violations: [Violation]) -> ViolationsMap {
return violations.reduce([Path : [Violation]]()) { result, violation in
let path = violation.path
// Add violation to the group with the same path
var violations = result[path] ?? []
violations.append(violation)
// Update the result
var nextResult = result
nextResult[path] = violations
return nextResult
}
}
private func generateXML(from violationsMap: ViolationsMap) -> XMLDocument {
let xml = XMLDocument(rootElement: XMLElement(name: "pmd"))
xml.version = "1.0"
xml.characterEncoding = "UTF-8"
let fileElements = violationsMap.map(generateFileElement)
xml.rootElement()?.addChildren(fileElements)
return xml
}
private func generateFileElement(path: Path, violations: [Violation]) -> XMLElement {
let element = XMLElement(name: "file")
if let attribute = XMLNode.attribute(withName: "name", stringValue: path) as? XMLNode {
element.addAttribute(attribute)
}
violations.forEach { element.addChild($0.toXMLElement()) }
return element
}
}
extension XMLElement {
func addChildren(_ children: [XMLElement]) {
children.forEach(addChild)
}
}
| mit |
linweiqiang/WQDouShi | WQDouShi/WQDouShi/Mine/View/MineHeaderView.swift | 1 | 1162 | //
// MineHeaderView.swift
// WQDouShi
//
// Created by yoke2 on 2017/3/29.
// Copyright © 2017年 yoke121. All rights reserved.
//
import UIKit
class MineHeaderView: UIView {
lazy var iconImg = UIImageView()
lazy var nameL = UILabel()
override init(frame: CGRect){
super.init(frame: frame)
iconImg.image = UIImage(named:"default-user")
nameL.text = "what you name!!!"
nameL.textAlignment = .center
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension MineHeaderView
{
func setUpUI() {
addSubview(iconImg)
addSubview(nameL)
iconImg.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.top.equalToSuperview().offset(10)
make.width.height.equalTo(70)
}
nameL.snp.makeConstraints { (make) in
make.top.equalTo(iconImg.snp.bottom).offset(5)
make.centerX.equalToSuperview()
make.width.equalTo(180)
make.height.equalTo(25)
}
}
}
| mit |
haijianhuo/PhotoBox | Pods/JSQCoreDataKit/Source/StackResult.swift | 2 | 1249 | //
// Created by Jesse Squires
// https://www.jessesquires.com
//
//
// Documentation
// https://jessesquires.github.io/JSQCoreDataKit
//
//
// GitHub
// https://github.com/jessesquires/JSQCoreDataKit
//
//
// License
// Copyright © 2015 Jesse Squires
// Released under an MIT license: https://opensource.org/licenses/MIT
//
import CoreData
import Foundation
/**
A result object representing the result of creating a `CoreDataStack` via a `CoreDataStackFactory`.
*/
public enum StackResult: Equatable {
/// The success result, containing the successfully initialized `CoreDataStack`.
case success(CoreDataStack)
/// The failure result, containing an `NSError` instance that describes the error.
case failure(NSError)
// MARK: Methods
/**
- returns: The result's `CoreDataStack` if `.Success`, otherwise `nil`.
*/
public func stack() -> CoreDataStack? {
if case .success(let stack) = self {
return stack
}
return nil
}
/**
- returns: The result's `NSError` if `.Failure`, otherwise `nil`.
*/
public func error() -> NSError? {
if case .failure(let error) = self {
return error
}
return nil
}
}
| mit |
Codility-BMSTU/Codility | Codility/Codility/OBHomeATMQuestsViewCell.swift | 1 | 692 | //
// OBHomeATMQuestsViewCell.swift
// Codility
//
// Created by Aleksander Evtuhov on 17/09/2017.
// Copyright © 2017 Кирилл Володин. All rights reserved.
//
import UIKit
class OBHomeATMQuestsViewCell: UITableViewCell {
@IBOutlet weak var questsButton: UIButton!
@IBOutlet weak var ATMOutletButton: UIButton!
@IBOutlet weak var QRCodeButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| apache-2.0 |
dreamsxin/swift | validation-test/compiler_crashers/28272-swift-expr-walk.swift | 8 | 425 | // 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 --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
.A[
| apache-2.0 |
dreamsxin/swift | test/Driver/environment.swift | 10 | 291 | // UNSUPPORTED: objc_interop
// Apple's "System Integrity Protection" makes this test fail on OS X.
// RUN: %swift_driver -target x86_64-unknown-gnu-linux -L/foo/ -driver-use-frontend-path %S/Inputs/print-var.sh %s LD_LIBRARY_PATH | FileCheck %s
// CHECK: {{^/foo/:[^:]+/lib/swift/linux$}}
| apache-2.0 |
segabor/OSCCore | Source/OSCCore/conversion/RGBA+OSCMessageArgument.swift | 1 | 1057 | //
// RGBA+OSCType.swift
// OSCCore
//
// Created by Sebestyén Gábor on 2017. 12. 29..
//
import Foundation
extension RGBA: OSCMessageArgument {
public init?(data: ArraySlice<Byte>) {
let binary: [Byte] = [Byte](data)
guard let flatValue = UInt32(data: binary) else {
return nil
}
let red = UInt8(flatValue >> 24)
let green = UInt8( (flatValue >> 16) & 0xFF)
let blue = UInt8( (flatValue >> 8) & 0xFF)
let alpha = UInt8(flatValue & 0xFF)
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
public var oscType: TypeTagValues { .RGBA_COLOR_TYPE_TAG }
public var oscValue: [Byte]? {
let red: UInt32 = UInt32(self.red)
let green: UInt32 = UInt32(self.green)
let blue: UInt32 = UInt32(self.blue)
let alpha: UInt32 = UInt32(self.alpha)
let flatValue: UInt32 = red << 24 | green << 16 | blue << 8 | alpha
return flatValue.oscValue
}
public var packetSize: Int { MemoryLayout<UInt32>.size }
}
| mit |
victorwon/SwiftBus | Example/Tests/Tests.swift | 1 | 2254 | //
// SwiftBusTests.swift
// SwiftBusTests
//
// Created by Adam on 2015-08-29.
// Copyright (c) 2017 Adam Boyd. All rights reserved.
//
import UIKit
import XCTest
import SwiftBus
class SwiftBusTests: XCTestCase {
var agency = TransitAgency()
var route = TransitRoute()
var stopOB = TransitStop(routeTitle: "N-Judah", routeTag: "N", stopTitle: "Carl & Cole", stopTag: "3909")
//This method is called before the invocation of each test method in the class.
override func setUp() {
//Creating agency
let agency = TransitAgency()
agency.agencyTag = "sf-muni"
agency.agencyTitle = "San Francisco Muni"
agency.agencyRegion = "California-Northern"
//Creating route
route.agencyTag = "sf-muni"
route.routeTitle = "N-Judah"
//Creating OB stop
stopOB.predictions["Outbound to Ocean Beach"] = [TransitPrediction(predictionInMinutes: 1), TransitPrediction(predictionInMinutes: 2), TransitPrediction(predictionInMinutes: 3)]
stopOB.predictions["Outbound to Ocean Beach via Downtown"] = [TransitPrediction(predictionInMinutes: 4), TransitPrediction(predictionInMinutes: 5), TransitPrediction(predictionInMinutes: 6)]
route.stops["Outbound to Ocean Beach Via Downtown"] = [stopOB]
}
//This method is called after the invocation of each test method in the class.
override func tearDown() {
super.tearDown()
}
func testRouteGetStop() {
if let _ = route.stop(forTag: "3909") {
XCTAssert(true, "Stop is gotten properly")
} else {
XCTAssert(false, "Stop is not gotten properly")
}
}
func testPredictionsInOrder() {
if stopOB.allPredictions[0].predictionInSeconds < stopOB.allPredictions[1].predictionInSeconds {
XCTAssert(true, "Sorted predictions are in order")
} else {
XCTAssert(false, "Sorted predictions are not in order")
}
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
adrfer/swift | validation-test/compiler_crashers_fixed/27957-swift-inflightdiagnostic-fixitremove.swift | 4 | 316 | // 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
class b{let e=()?var d{struct d<T where h:b{class a{{}class a{struct S<T{enum B{enum A{class b<f:f.c
| apache-2.0 |
insidegui/WWDC | WWDCAgent/WWDCAgentInterface.swift | 1 | 1126 | //
// WWDCAgentInterface.swift
// WWDCAgent
//
// Created by Guilherme Rambo on 24/05/21.
// Copyright © 2021 Guilherme Rambo. All rights reserved.
//
import Foundation
@objc protocol WWDCAgentInterface: AnyObject {
func testAgentConnection(with completion: @escaping (Bool) -> Void)
func fetchFavoriteSessions(for event: String?, completion: @escaping ([String]) -> Void)
func fetchDownloadedSessions(for event: String?, completion: @escaping ([String]) -> Void)
func fetchWatchedSessions(for event: String?, completion: @escaping ([String]) -> Void)
func fetchUnwatchedSessions(for event: String?, completion: @escaping ([String]) -> Void)
func revealVideo(with id: String, completion: @escaping (Bool) -> Void)
func setFavorite(_ isFavorite: Bool, for videoId: String, completion: @escaping (Bool) -> Void)
func setWatched(_ watched: Bool, for videoId: String, completion: @escaping (Bool) -> Void)
func startDownload(for videoId: String, completion: @escaping (Bool) -> Void)
func stopDownload(for videoId: String, completion: @escaping (Bool) -> Void)
}
| bsd-2-clause |
sebcode/SwiftHelperKit | Tests/FileTest-SHA256.swift | 1 | 2233 | //
// FileTest-SHA256.swift
// SwiftHelperKit
//
// Copyright © 2015 Sebastian Volland. All rights reserved.
//
import XCTest
@testable import SwiftHelperKit
class FileTestSHA256: BaseTest {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testComputeSHA256() {
let file = try! File.createTemp()
try! file.setContents("hallo123")
XCTAssertEqual("f0c3cd6fc4b23eae95e39de1943792f62ccefd837158b69c63aebaf3041ed345", try! file.computeSHA256())
try! file.delete()
}
func testComputeSHA256Range() {
let file1 = try! File.createTemp()
try! file1.setContents("hallo123")
XCTAssertEqual("f0c3cd6fc4b23eae95e39de1943792f62ccefd837158b69c63aebaf3041ed345", try! file1.computeSHA256())
try! file1.delete()
let file2 = try! File.createTemp()
try! file2.setContents("test123")
XCTAssertEqual("ecd71870d1963316a97e3ac3408c9835ad8cf0f3c1bc703527c30265534f75ae", try! file2.computeSHA256())
try! file2.delete()
let file = try! File.createTemp()
try! file.setContents("hallo123test123xxx")
XCTAssertEqual("f0c3cd6fc4b23eae95e39de1943792f62ccefd837158b69c63aebaf3041ed345", try! file.computeSHA256((from: 0, to: 7)))
XCTAssertEqual("ecd71870d1963316a97e3ac3408c9835ad8cf0f3c1bc703527c30265534f75ae", try! file.computeSHA256((from: 8, to: 14)))
try! file.delete()
}
func testComputeSHA256RangeFail() {
// let task = Process()
// let pipe = Pipe()
// task.launchPath = "/usr/bin/mkfifo"
// task.arguments = ["/tmp/testpipe"]
// task.standardOutput = pipe
// task.launch()
// let exception = tryBlock {
// let fileHandle = FileHandle(forReadingAtPath: "/tmp/test123")!
// fileHandle.write("wurst".data(using: .utf8)!)
// }
// guard exception != nil else {
// XCTFail()
// return
// }
// let file4 = File(name: "/tmp/testinvalid")
// // do {
// _ = try! file4.computeSHA256((from: 1, to: 10))
// // XCTFail()
// // } catch { }
}
}
| mit |
ming1016/smck | smck/Lib/RxSwift/DelaySubscription.swift | 47 | 1451 | //
// DelaySubscription.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
final class DelaySubscriptionSink<O: ObserverType>
: Sink<O>, ObserverType {
typealias E = O.E
typealias Parent = DelaySubscription<E>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
forwardOn(event)
if event.isStopEvent {
dispose()
}
}
}
final class DelaySubscription<Element>: Producer<Element> {
private let _source: Observable<Element>
private let _dueTime: RxTimeInterval
private let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) {
_source = source
_dueTime = dueTime
_scheduler = scheduler
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = DelaySubscriptionSink(parent: self, observer: observer, cancel: cancel)
let subscription = _scheduler.scheduleRelative((), dueTime: _dueTime) { _ in
return self._source.subscribe(sink)
}
return (sink: sink, subscription: subscription)
}
}
| apache-2.0 |
tofergregg/WearablesDay1 | Cool Beans/Views/TemperatureView.swift | 1 | 776 | //
// TemperatureView.swift
// Cool Beans
//
// Created by Kyle on 11/14/14.
// Copyright (c) 2014 Kyle Weiner. All rights reserved.
//
import UIKit
class TemperatureView: UIView {
@IBOutlet var containerView: UIView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var xAcc : UILabel!
@IBOutlet weak var yAcc : UILabel!
@IBOutlet weak var zAcc : UILabel!
var maxX,maxY,maxZ : Double!
var timer : NSTimer!
// MARK: Lifecycle
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let bundle = NSBundle(forClass: self.dynamicType)
self.addSubview(bundle.loadNibNamed("TemperatureView", owner: self, options: nil)[0] as! UIView)
}
}
| mit |
natecook1000/swift | test/DebugInfo/WeakCapture.swift | 2 | 645 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
class A {
init(handler: (() -> ())) { }
}
class B { }
// CHECK: define {{.*}} @"$S11WeakCapture8functionyyF"()
func function() {
let b = B()
// Ensure that the local b and its weak copy are distinct local variables.
// CHECK: call void @llvm.dbg.{{.*}}(metadata %T11WeakCapture1BC*
// CHECK-SAME: metadata [[B:.*]], metadata
// CHECK: call void @llvm.dbg.{{.*}}(metadata %swift.weak*
// CHECK-NOT: metadata [[B]]
// CHECK: call
A(handler: { [weak b] in
if b != nil { }
})
}
function()
| apache-2.0 |
kstaring/swift | validation-test/compiler_crashers_fixed/01166-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 11 | 608 | // 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
struct i<f : f, g: f where g.i == f.i> { b = i) {
}
let i { f
func p(k: b) -> <i>(() -> i) -> b {
n { o f "\(k): \(o()
}
f m : m {
}
func i<o : o, m : m n m.f == o> (l: m) {
}
}
func p<m>() -> [l<m>] {
}
func f<o>()
| apache-2.0 |
kstaring/swift | validation-test/compiler_crashers_fixed/26525-swift-modulefile-maybereadgenericparams.swift | 11 | 434 | // 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
{func a{class A{let _=[[{
{
{{class
case,
| apache-2.0 |
viteinfinite/Nabigeta | Nabigeta/Navigation/NavigationStack.swift | 1 | 656 | //
// This file is part of Nabigeta
//
// Created by JC on 22/12/14.
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code
//
import Foundation
import UIKit
/**
* Represent a navigation stack. You're either
* - on the current stack
* - on a new stack, possibly displayed with a custom UiNavigationController instance
*/
public enum NavigationStack {
case Current
case Custom(UINavigationController?)
public func isNewStack() -> Bool {
switch self {
case .Custom(_):
return true
default:
return false
}
}
} | mit |
marioeguiluz/SwiftStocks | SwiftStocks/StocksTableViewController.swift | 1 | 4380 | //
// StocksTableViewController.swift
// SwiftStocks
//
// Created by MARIO EGUILUZ ALEBICTO on 07/08/14.
// Copyright (c) 2014 MARIO EGUILUZ ALEBICTO. All rights reserved.
//
import UIKit
class StocksTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//1
private var stocks: [(String,Double)] = [("AAPL",+1.5),("FB",+2.33),("GOOG",-4.3)]
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//2
NSNotificationCenter.defaultCenter().addObserver(self, selector: "stocksUpdated:", name: kNotificationStocksUpdated, object: nil)
self.updateStocks()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stocks.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "cellId")
cell.textLabel!.text = stocks[indexPath.row].0 //position 0 of the tuple: The Symbol "AAPL"
cell.detailTextLabel!.text = "\(stocks[indexPath.row].1)" + "%" //position 1 of the tuple: The value "1.5" into String
return cell
}
//UITableViewDelegate
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
}
//Customize the cell
func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
switch stocks[indexPath.row].1 {
case let x where x < 0.0:
cell.backgroundColor = UIColor(red: 255.0/255.0, green: 59.0/255.0, blue: 48.0/255.0, alpha: 1.0)
case let x where x > 0.0:
cell.backgroundColor = UIColor(red: 76.0/255.0, green: 217.0/255.0, blue: 100.0/255.0, alpha: 1.0)
case let x:
cell.backgroundColor = UIColor(red: 44.0/255.0, green: 186.0/255.0, blue: 231.0/255.0, alpha: 1.0)
}
cell.textLabel!.textColor = UIColor.whiteColor()
cell.detailTextLabel!.textColor = UIColor.whiteColor()
cell.textLabel!.font = UIFont(name: "HelveticaNeue-CondensedBold", size: 48)
cell.detailTextLabel!.font = UIFont(name: "HelveticaNeue-CondensedBold", size: 48)
cell.textLabel!.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25)
cell.textLabel!.shadowOffset = CGSize(width: 0, height: 1)
cell.detailTextLabel!.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25)
cell.detailTextLabel!.shadowOffset = CGSize(width: 0, height: 1)
}
//Customize the height of the cell
func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
return 120
}
//Stock updates
//3
func updateStocks() {
let stockManager:StockManagerSingleton = StockManagerSingleton.sharedInstance
stockManager.updateListOfSymbols(stocks)
//Repeat this method after 15 secs. (For simplicity of the tutorial we are not cancelling it never)
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(15 * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(),
{
self.updateStocks()
}
)
}
//4
func stocksUpdated(notification: NSNotification) {
let values = (notification.userInfo as Dictionary<String,NSArray>)
let stocksReceived:NSArray = values[kNotificationStocksUpdated]!
stocks.removeAll(keepCapacity: false)
for quote in stocksReceived {
let quoteDict:NSDictionary = quote as NSDictionary
var changeInPercentString = quoteDict["ChangeinPercent"] as String
let changeInPercentStringClean: NSString = (changeInPercentString as NSString).substringToIndex(countElements(changeInPercentString)-1)
stocks.append(quoteDict["symbol"] as String,changeInPercentStringClean.doubleValue)
}
tableView.reloadData()
NSLog("Symbols Values updated :)")
}
}
| mit |
tryswift/TryParsec | Sources/TryParsec/Result+Helper.swift | 1 | 462 | import Runes
import Result
// MARK: Result + applicative style
// See also https://github.com/antitypical/Result/pull/105 (unmerged)
public func <^> <T, U, Error> (transform: (T) -> U, result: Result<T, Error>) -> Result<U, Error>
{
return result.map(transform)
}
public func <*> <T, U, Error> (transform: Result<(T) -> U, Error>, result: @autoclosure () -> Result<T, Error>) -> Result<U, Error>
{
return transform.flatMap { f in result().map(f) }
}
| mit |
eurofurence/ef-app_ios | Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Application/Components/News/Widgets/Your Eurofurence/Test Doubles/StubYourEurofurenceDataSource.swift | 1 | 300 | import Combine
import EurofurenceApplication
class StubYourEurofurenceDataSource: YourEurofurenceDataSource {
let state = CurrentValueSubject<AuthenticatedUserSummary?, Never>(nil)
func enterState(_ state: AuthenticatedUserSummary?) {
self.state.value = state
}
}
| mit |
ThatCSharpGuy/silo-xamarin-comparation | iOS/Swift/Xevensthein/ViewController.swift | 1 | 1507 | //
// ViewController.swift
// Xevensthein
//
// Created by Antonio Feregrino Bolaños on 4/29/16.
// Copyright © 2016 That C# guy. Some rights reserved.
//
import UIKit
import XevenstheinCore
class ViewController: UIViewController, UITextFieldDelegate {
// MARK: Properties
@IBOutlet var firstWordTextField: UITextField!
@IBOutlet var secondWordTextField: UITextField!
@IBOutlet var compareButton: UIButton!
@IBOutlet var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
firstWordTextField.delegate = self;
secondWordTextField.delegate = self;
compareButton.addTarget(self, action: #selector(ViewController.compareButtonClicked(_:)), forControlEvents: .TouchUpInside);
}
func compareButtonClicked(_sender : AnyObject?){
let result = LevenshteinDistance.compute( firstWordTextField.text!,t: secondWordTextField.text!);
resultLabel.text = String(result);
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if(textField == firstWordTextField){
firstWordTextField.resignFirstResponder();
secondWordTextField.becomeFirstResponder();
}
else{
secondWordTextField.resignFirstResponder();
}
return true;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
Czajnikowski/TrainTrippin | Pods/RxCocoa/RxCocoa/CocoaUnits/Driver/ControlEvent+Driver.swift | 3 | 756 | //
// ControlEvent+Driver.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 9/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
extension ControlEvent {
/**
Converts `ControlEvent` to `Driver` unit.
`ControlEvent` already can't fail, so no special case needs to be handled.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func asDriver() -> Driver<E> {
return self.asDriver { (error) -> Driver<E> in
#if DEBUG
rxFatalError("Somehow driver received error from a source that shouldn't fail.")
#else
return Driver.empty()
#endif
}
}
}
| mit |
tectijuana/patrones | Bloque1SwiftArchivado/PracticasSwift/SalcedoJose/32_C5RuletaAmericana.swift | 1 | 2221 | /*
Nombre del programa: Capitulo 5. Programa 32. Ruleta americana.
Autor: Salcedo Morales Jose Manuel
Fecha de inicio: 2017-02-09
Descripcion: Cuando gira una ruleta americana (0 y 00) ¿cual es la probabilidad
de que el resultado sea: a) 0; b) 00; c) 0 o 00; d) par; e) en el primer 12;
f) en la segunda columna y g) 4, 5, 6, 7, 8 o 9?
*/
// LIBRERIAS.
import Foundation
// CONSTANTES.
let NUMEROS_RULETA: Double = 38.0 // 0, 00 y 1 a 36.
// FUNCIONES.
func DesplegarProbabilidad(texto: String, porcentaje: Double) {
print("Probabilidad de " + texto + ": " + String(porcentaje) + "%")
}
// PRINCIPAL.
// Desplegar las probabilidades de cada indice. Con texto y calculo apropiado.
print("Probabilidades en una ruleta americana.")
// a) 0.
let textoProbabilidadA: String = "a) Resultado 0"
let probabilidadA: Double = (1.0 / NUMEROS_RULETA) * 100.0
DesplegarProbabilidad(texto: textoProbabilidadA, porcentaje: probabilidadA)
// b) 00.
let textoProbabilidadB: String = "b) Resultado 00"
let probabilidadB: Double = probabilidadA
DesplegarProbabilidad(texto: textoProbabilidadB, porcentaje: probabilidadB)
// c) 0 o 00.
let textoProbabilidadC: String = "c) Resultado 0 o 00"
let probabilidadC: Double = probabilidadA + probabilidadB
DesplegarProbabilidad(texto: textoProbabilidadC, porcentaje: probabilidadC)
// d) Par.
let textoProbabilidadD: String = "d) Par"
let probabilidadD: Double = (18.0 / NUMEROS_RULETA) * 100.0
DesplegarProbabilidad(texto: textoProbabilidadD, porcentaje: probabilidadD)
// e) En el primer 12.
let textoProbabilidadE: String = "e) En el primer 12"
let probabilidadE: Double = (12.0 / NUMEROS_RULETA) * 100.0
DesplegarProbabilidad(texto: textoProbabilidadE, porcentaje: probabilidadE)
// f) En la segunda columna.
let textoProbabilidadF: String = "f) En la segunda columna"
let probabilidadF: Double = (3.0 / NUMEROS_RULETA) * 100.0
DesplegarProbabilidad(texto: textoProbabilidadF, porcentaje: probabilidadF)
// g) 4, 5, 6, 7, 8, 9.
let textoProbabilidadG: String = "g) 4, 5, 6, 7, 8, 9"
let probabilidadG: Double = (6 / NUMEROS_RULETA) * 100.0
DesplegarProbabilidad(texto: textoProbabilidadG, porcentaje: probabilidadG)
// Indicar fin de ejecucion.
print("\nFIN DE EJECUCION\n")
| gpl-3.0 |
googlearchive/science-journal-ios | ScienceJournal/BLESupport/BLEServiceScanner.swift | 1 | 8033 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import CoreBluetooth
/// A closure type for the completion of peripheral connections.
typealias ConnectionClosure = (CBPeripheral?, BLEFailedToConnectError?) -> Void
struct BLEFailedToConnectError: Error {
let peripheral: CBPeripheral
}
struct DiscoveredPeripheral: Equatable {
let peripheral: CBPeripheral
let serviceIds: [CBUUID]?
static func == (lhs: DiscoveredPeripheral, rhs: DiscoveredPeripheral) -> Bool {
let serviceIdsEqual = { () -> Bool in
if let lhsServiceIds = lhs.serviceIds, let rhsServiceIds = rhs.serviceIds {
return lhsServiceIds == rhsServiceIds
} else if lhs.serviceIds == nil && rhs.serviceIds == nil {
return true
}
return false
}()
return lhs.peripheral == rhs.peripheral && serviceIdsEqual
}
}
protocol BLEServiceScannerDelegate: class {
func serviceScannerBluetoothAvailabilityChanged(_ serviceScanner: BLEServiceScanner)
func serviceScannerDiscoveredNewPeripherals(_ serviceScanner: BLEServiceScanner)
}
/// Scans for peripherals that match a particular service uuid. Also connects to discovered
/// peripherals, either by a direct reference to a peripheral or by a known peripheral identifier.
class BLEServiceScanner: NSObject, CBCentralManagerDelegate {
weak var delegate: BLEServiceScannerDelegate?
var isBluetoothAvailable = true
fileprivate var centralManager: CBCentralManager!
fileprivate(set) var serviceUUIDs: [CBUUID]?
fileprivate(set) var discoveredPeripherals = [DiscoveredPeripheral]()
fileprivate let scanInterval: TimeInterval = 2.0
fileprivate let pauseInterval: TimeInterval = 10.0
fileprivate var shouldScan = false
fileprivate var peripheralConnectionBlocks = [UUID: ConnectionClosure]()
fileprivate(set) var requestedPeripheralId: UUID?
fileprivate(set) var requestedPeripheralConnectionBlock: ConnectionClosure?
init(services: [CBUUID]? = nil) {
serviceUUIDs = services
super.init()
centralManager = CBCentralManager(delegate: self, queue: nil)
}
deinit {
// The central manager continues to send delegate calls after deinit in iOS 9 only, so we have
// to nil the delegate here. This was surfacing when running unit tests.
centralManager.delegate = nil
}
/// Tells the device to scan for peripherals. Scans for 2 seconds then pauses for 10, repeating
/// until stopped.
func startScanning() {
guard !shouldScan else { return }
shouldScan = true
resumeScanning()
}
/// Stops scanning for peripherals.
func stopScanning() {
guard shouldScan else { return }
shouldScan = false
centralManager.stopScan()
}
func connectToPeripheral(withIdentifier identifier: String,
completion: @escaping ConnectionClosure) {
guard let uuid = UUID(uuidString: identifier) else {
completion(nil, nil)
return
}
for discovered in discoveredPeripherals where discovered.peripheral.identifier == uuid {
connectTo(discovered.peripheral, completion: completion)
return
}
// If there isn't already a peripheral with this id, store it for later.
requestedPeripheralId = uuid
requestedPeripheralConnectionBlock = completion
// Start scanning in case we're not already scanning.
startScanning()
}
func connectTo(_ peripheral: CBPeripheral, completion: ConnectionClosure? = nil) {
if let completion = completion {
peripheralConnectionBlocks[peripheral.identifier] = completion
}
centralManager.connect(peripheral, options: nil)
}
/// Disconnects from a peripheral.
///
/// - Parameter peripheral: The peripheral to disconnect from.
func disconnectFromPeripheral(_ peripheral: CBPeripheral) {
centralManager.cancelPeripheralConnection(peripheral)
}
@objc fileprivate func resumeScanning() {
guard shouldScan, let serviceUUIDs = serviceUUIDs else { return }
centralManager.scanForPeripherals(withServices: serviceUUIDs, options: nil)
Timer.scheduledTimer(timeInterval: scanInterval,
target: self,
selector: #selector(delayScanning),
userInfo: nil,
repeats: false)
}
@objc fileprivate func delayScanning() {
centralManager.stopScan()
Timer.scheduledTimer(timeInterval: pauseInterval,
target: self,
selector: #selector(resumeScanning),
userInfo: nil,
repeats: false)
}
// MARK: - CBCentralManagerDelegate
func centralManagerDidUpdateState(_ central: CBCentralManager) {
let previouslyAvailable = isBluetoothAvailable
switch central.state {
case .poweredOff:
print("Bluetooth powered off.")
isBluetoothAvailable = false
case .unsupported:
print("Bluetooth not supported on this device.")
isBluetoothAvailable = false
case .unauthorized:
print("Bluetooth not authorized.")
isBluetoothAvailable = false
case .resetting:
print("Bluetooth is resetting.")
isBluetoothAvailable = false
case .unknown:
print("Bluetooth unknown state.")
isBluetoothAvailable = false
case .poweredOn:
print("Bluetooth is powered on.")
isBluetoothAvailable = true
resumeScanning()
}
if previouslyAvailable != isBluetoothAvailable {
delegate?.serviceScannerBluetoothAvailabilityChanged(self)
}
}
func centralManager(_ central: CBCentralManager,
didDiscover peripheral: CBPeripheral,
advertisementData: [String : Any],
rssi RSSI: NSNumber) {
// Append this peripheral if it is not already in the array.
let serviceIds = advertisementData[CBAdvertisementDataServiceUUIDsKey] as? [CBUUID]
let discovered =
DiscoveredPeripheral(peripheral: peripheral,
serviceIds: serviceIds)
if discoveredPeripherals.firstIndex(of: discovered) == nil {
discoveredPeripherals.append(discovered)
}
delegate?.serviceScannerDiscoveredNewPeripherals(self)
if peripheral.identifier == requestedPeripheralId {
connectTo(peripheral, completion: requestedPeripheralConnectionBlock)
requestedPeripheralId = nil
requestedPeripheralConnectionBlock = nil
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
// Remove then fire a connection block, if it exists.
if let block = peripheralConnectionBlocks.removeValue(forKey: peripheral.identifier) {
block(peripheral, nil)
}
}
func centralManager(_ central: CBCentralManager,
didDisconnectPeripheral peripheral: CBPeripheral,
error: Error?) {
print("Disconnected peripheral: \(String(describing: peripheral.name)), " +
"Error: \(String(describing: error))")
}
func centralManager(_ central: CBCentralManager,
didFailToConnect peripheral: CBPeripheral,
error: Error?) {
print("Failed to connect to peripheral: \(String(describing: peripheral.name)), " +
"Error: \(String(describing: error))")
if let block = peripheralConnectionBlocks.removeValue(forKey: peripheral.identifier) {
block(nil, BLEFailedToConnectError(peripheral: peripheral))
}
}
}
| apache-2.0 |
Ranjana89/tippy | Tippy/ViewController.swift | 1 | 4106 | //
// ViewController.swift
// Tippy
//
// Created by Majmudar, Heshang on 3/9/17.
// Copyright © 2017 Pokharana, Ranjana. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipControl: UISegmentedControl!
let tips = [15,18,20]
var defaultTip : Int?
var userDefaults : UserDefaults?
override func viewDidLoad() {
super.viewDidLoad()
tipLabel.text = "$0.00"
totalLabel.text = "$0.00"
//show the decimal pad as soon as viewappear
billField.becomeFirstResponder()
//write the placeholder text
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
billField.attributedPlaceholder = NSAttributedString(string: currencyFormatter.string(from : 0)!)
tipControl.selectedSegmentIndex = 0
userDefaults = UserDefaults.standard
defaultTip = userDefaults?.integer(forKey: "defaultTip")
for (index,tmp) in tips.enumerated() {
if(defaultTip == tmp){
tipControl.selectedSegmentIndex = index
}
}
//remember the bill from a recent* previous session (60*10 = 10 minutes)
if (userDefaults?.object(forKey: "default_bill") != nil) {
let now = NSDate()
let previous = userDefaults?.object(forKey: "time_at_close")!
if (now.timeIntervalSince(previous as! Date) < 60 * 10 ) {
billField.text = userDefaults?.object(forKey: "default_bill") as! String!
}
}
}
override func viewWillAppear(_ animated: Bool) {
billField.becomeFirstResponder()
defaultTip = userDefaults?.integer(forKey: "defaultTip")
for (index,tmp) in tips.enumerated() {
if(defaultTip == tmp){
tipControl.selectedSegmentIndex = index
}
}
userDefaults?.set(billField.text, forKey: "default_bill")
userDefaults?.set(NSDate(),forKey : "time_at_close")
userDefaults?.synchronize()
calculateBill(self)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("view did appear")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("view will disappear")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("view did disappear")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onTap(_ sender: Any) {
view.endEditing(true)
}
@IBAction func editingChanged(_ sender: Any) {
calculateBill(self)
}
@IBAction func calculateBill(_ sender: Any) {
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
// localize to your grouping and decimal separator
currencyFormatter.locale = Locale.current
let bill = Double(billField.text!) ?? 0
let tip = (bill * (Double)(tips[tipControl.selectedSegmentIndex])/100)
let tipValue = tip as NSNumber
let total = (bill + tip ) as NSNumber
tipLabel.text = currencyFormatter.string(from: tipValue)
//String(format: "$%.2f", tip)
totalLabel.text = currencyFormatter.string(from: total)
//String(format: "$%.2f", total)
}
@IBAction func editingDidEnd(_ sender: Any) {
calculateBill(self)
}
@IBAction func onValueChanged(_ sender: Any) {
calculateBill(self)
}
}
| gpl-3.0 |
lieonCX/Live | Live/View/User/Setting/AccountBindedViewController.swift | 1 | 3839 | //
// AccountBindedViewController.swift
// Live
//
// Created by fanfans on 2017/7/13.
// Copyright © 2017年 ChengDuHuanLeHui. All rights reserved.
//
import UIKit
import RxSwift
class AccountBindedViewController: BaseViewController {
var phoneNum: String?
fileprivate lazy var icon: UIImageView = {
let icon = UIImageView()
icon.image = UIImage(named: "setting_binded_icon")
return icon
}()
fileprivate lazy var tipsLable: UILabel = {
let tipsLable = UILabel()
tipsLable.text = "已绑定的手机号"
tipsLable.font = UIFont.systemFont(ofSize: 13)
tipsLable.textAlignment = .center
tipsLable.textColor = UIColor(hex: 0x999999)
return tipsLable
}()
fileprivate lazy var phoneLabel: UILabel = {
let phoneLabel = UILabel()
phoneLabel.text = "13800000000"
phoneLabel.font = UIFont.systemFont(ofSize: 16)
phoneLabel.textAlignment = .center
phoneLabel.textColor = UIColor(hex: 0x222222)
return phoneLabel
}()
fileprivate lazy var modifyBtn: UIButton = {
let modifyBtn = UIButton()
modifyBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
modifyBtn.setTitle("更换手机号", for: .normal)
modifyBtn.setTitleColor(UIColor.white, for: .normal)
modifyBtn.backgroundColor = UIColor(hex: CustomKey.Color.mainColor)
modifyBtn.layer.cornerRadius = 40 * 0.5
modifyBtn.layer.masksToBounds = true
return modifyBtn
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "已绑定手机号"
self.view.backgroundColor = UIColor.white
phoneLabel.text = phoneNum ?? ""
// MARK: congfigUI
self.view.addSubview(icon)
self.view.addSubview(tipsLable)
self.view.addSubview(phoneLabel)
self.view.addSubview(modifyBtn)
// MARK: layout
icon.snp.makeConstraints { (maker) in
maker.top.equalTo(38)
maker.width.equalTo(59)
maker.height.equalTo(75)
maker.centerX.equalTo(self.view.snp.centerX)
}
tipsLable.snp.makeConstraints { (maker) in
maker.top.equalTo(icon.snp.bottom) .offset(25)
maker.centerX.equalTo(self.view.snp.centerX)
}
phoneLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(tipsLable.snp.bottom) .offset(15)
maker.centerX.equalTo(self.view.snp.centerX)
}
modifyBtn.snp.makeConstraints { (maker) in
maker.top.equalTo(phoneLabel.snp.bottom) .offset(30)
maker.width.equalTo(300)
maker.height.equalTo(40)
maker.centerX.equalTo(self.view.snp.centerX)
}
// MARK: modifyBtnAction
modifyBtn.rx.tap
.subscribe(onNext: { [weak self] in
let vcc = VerifyPhoneViewController()
guard let phoneNum = self?.phoneNum else { return }
vcc.phoneNum = phoneNum
let accountVM = UserSessionViewModel()
HUD.show(true, show: "", enableUserActions: false, with: self)
accountVM.sendCaptcha(phoneNum: phoneNum, type: .changePhoneNum)
.then(execute: { (_) -> Void in
self?.navigationController?.pushViewController(vcc, animated: true)
})
.always {
HUD.show(false, show: "", enableUserActions: false, with: self)
}
.catch(execute: { error in
if let error = error as? AppError {
self?.view.makeToast(error.message)
}
})
})
.disposed(by: disposeBag)
}
}
| mit |
noppoMan/aws-sdk-swift | Sources/Soto/Services/MachineLearning/MachineLearning_API.swift | 1 | 24071 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
@_exported import SotoCore
/*
Client object for interacting with AWS MachineLearning service.
Definition of the public APIs exposed by Amazon Machine Learning
*/
public struct MachineLearning: AWSService {
// MARK: Member variables
public let client: AWSClient
public let config: AWSServiceConfig
// MARK: Initialization
/// Initialize the MachineLearning client
/// - parameters:
/// - client: AWSClient used to process requests
/// - region: Region of server you want to communicate with. This will override the partition parameter.
/// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov).
/// - endpoint: Custom endpoint URL to use instead of standard AWS servers
/// - timeout: Timeout value for HTTP requests
public init(
client: AWSClient,
region: SotoCore.Region? = nil,
partition: AWSPartition = .aws,
endpoint: String? = nil,
timeout: TimeAmount? = nil,
byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(),
options: AWSServiceConfig.Options = []
) {
self.client = client
self.config = AWSServiceConfig(
region: region,
partition: region?.partition ?? partition,
amzTarget: "AmazonML_20141212",
service: "machinelearning",
serviceProtocol: .json(version: "1.1"),
apiVersion: "2014-12-12",
endpoint: endpoint,
errorType: MachineLearningErrorType.self,
timeout: timeout,
byteBufferAllocator: byteBufferAllocator,
options: options
)
}
// MARK: API Calls
/// Adds one or more tags to an object, up to a limit of 10. Each tag consists of a key and an optional value. If you add a tag using a key that is already associated with the ML object, AddTags updates the tag's value.
public func addTags(_ input: AddTagsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AddTagsOutput> {
return self.client.execute(operation: "AddTags", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Generates predictions for a group of observations. The observations to process exist in one or more data files referenced by a DataSource. This operation creates a new BatchPrediction, and uses an MLModel and the data files referenced by the DataSource as information sources. CreateBatchPrediction is an asynchronous operation. In response to CreateBatchPrediction, Amazon Machine Learning (Amazon ML) immediately returns and sets the BatchPrediction status to PENDING. After the BatchPrediction completes, Amazon ML sets the status to COMPLETED. You can poll for status updates by using the GetBatchPrediction operation and checking the Status parameter of the result. After the COMPLETED status appears, the results are available in the location specified by the OutputUri parameter.
public func createBatchPrediction(_ input: CreateBatchPredictionInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateBatchPredictionOutput> {
return self.client.execute(operation: "CreateBatchPrediction", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a DataSource object from an Amazon Relational Database Service (Amazon RDS). A DataSource references data that can be used to perform CreateMLModel, CreateEvaluation, or CreateBatchPrediction operations. CreateDataSourceFromRDS is an asynchronous operation. In response to CreateDataSourceFromRDS, Amazon Machine Learning (Amazon ML) immediately returns and sets the DataSource status to PENDING. After the DataSource is created and ready for use, Amazon ML sets the Status parameter to COMPLETED. DataSource in the COMPLETED or PENDING state can be used only to perform >CreateMLModel>, CreateEvaluation, or CreateBatchPrediction operations. If Amazon ML cannot accept the input source, it sets the Status parameter to FAILED and includes an error message in the Message attribute of the GetDataSource operation response.
public func createDataSourceFromRDS(_ input: CreateDataSourceFromRDSInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateDataSourceFromRDSOutput> {
return self.client.execute(operation: "CreateDataSourceFromRDS", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a DataSource from a database hosted on an Amazon Redshift cluster. A DataSource references data that can be used to perform either CreateMLModel, CreateEvaluation, or CreateBatchPrediction operations. CreateDataSourceFromRedshift is an asynchronous operation. In response to CreateDataSourceFromRedshift, Amazon Machine Learning (Amazon ML) immediately returns and sets the DataSource status to PENDING. After the DataSource is created and ready for use, Amazon ML sets the Status parameter to COMPLETED. DataSource in COMPLETED or PENDING states can be used to perform only CreateMLModel, CreateEvaluation, or CreateBatchPrediction operations. If Amazon ML can't accept the input source, it sets the Status parameter to FAILED and includes an error message in the Message attribute of the GetDataSource operation response. The observations should be contained in the database hosted on an Amazon Redshift cluster and should be specified by a SelectSqlQuery query. Amazon ML executes an Unload command in Amazon Redshift to transfer the result set of the SelectSqlQuery query to S3StagingLocation. After the DataSource has been created, it's ready for use in evaluations and batch predictions. If you plan to use the DataSource to train an MLModel, the DataSource also requires a recipe. A recipe describes how each input variable will be used in training an MLModel. Will the variable be included or excluded from training? Will the variable be manipulated; for example, will it be combined with another variable or will it be split apart into word combinations? The recipe provides answers to these questions. You can't change an existing datasource, but you can copy and modify the settings from an existing Amazon Redshift datasource to create a new datasource. To do so, call GetDataSource for an existing datasource and copy the values to a CreateDataSource call. Change the settings that you want to change and make sure that all required fields have the appropriate values.
public func createDataSourceFromRedshift(_ input: CreateDataSourceFromRedshiftInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateDataSourceFromRedshiftOutput> {
return self.client.execute(operation: "CreateDataSourceFromRedshift", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a DataSource object. A DataSource references data that can be used to perform CreateMLModel, CreateEvaluation, or CreateBatchPrediction operations. CreateDataSourceFromS3 is an asynchronous operation. In response to CreateDataSourceFromS3, Amazon Machine Learning (Amazon ML) immediately returns and sets the DataSource status to PENDING. After the DataSource has been created and is ready for use, Amazon ML sets the Status parameter to COMPLETED. DataSource in the COMPLETED or PENDING state can be used to perform only CreateMLModel, CreateEvaluation or CreateBatchPrediction operations. If Amazon ML can't accept the input source, it sets the Status parameter to FAILED and includes an error message in the Message attribute of the GetDataSource operation response. The observation data used in a DataSource should be ready to use; that is, it should have a consistent structure, and missing data values should be kept to a minimum. The observation data must reside in one or more .csv files in an Amazon Simple Storage Service (Amazon S3) location, along with a schema that describes the data items by name and type. The same schema must be used for all of the data files referenced by the DataSource. After the DataSource has been created, it's ready to use in evaluations and batch predictions. If you plan to use the DataSource to train an MLModel, the DataSource also needs a recipe. A recipe describes how each input variable will be used in training an MLModel. Will the variable be included or excluded from training? Will the variable be manipulated; for example, will it be combined with another variable or will it be split apart into word combinations? The recipe provides answers to these questions.
public func createDataSourceFromS3(_ input: CreateDataSourceFromS3Input, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateDataSourceFromS3Output> {
return self.client.execute(operation: "CreateDataSourceFromS3", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a new Evaluation of an MLModel. An MLModel is evaluated on a set of observations associated to a DataSource. Like a DataSource for an MLModel, the DataSource for an Evaluation contains values for the Target Variable. The Evaluation compares the predicted result for each observation to the actual outcome and provides a summary so that you know how effective the MLModel functions on the test data. Evaluation generates a relevant performance metric, such as BinaryAUC, RegressionRMSE or MulticlassAvgFScore based on the corresponding MLModelType: BINARY, REGRESSION or MULTICLASS. CreateEvaluation is an asynchronous operation. In response to CreateEvaluation, Amazon Machine Learning (Amazon ML) immediately returns and sets the evaluation status to PENDING. After the Evaluation is created and ready for use, Amazon ML sets the status to COMPLETED. You can use the GetEvaluation operation to check progress of the evaluation during the creation operation.
public func createEvaluation(_ input: CreateEvaluationInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateEvaluationOutput> {
return self.client.execute(operation: "CreateEvaluation", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a new MLModel using the DataSource and the recipe as information sources. An MLModel is nearly immutable. Users can update only the MLModelName and the ScoreThreshold in an MLModel without creating a new MLModel. CreateMLModel is an asynchronous operation. In response to CreateMLModel, Amazon Machine Learning (Amazon ML) immediately returns and sets the MLModel status to PENDING. After the MLModel has been created and ready is for use, Amazon ML sets the status to COMPLETED. You can use the GetMLModel operation to check the progress of the MLModel during the creation operation. CreateMLModel requires a DataSource with computed statistics, which can be created by setting ComputeStatistics to true in CreateDataSourceFromRDS, CreateDataSourceFromS3, or CreateDataSourceFromRedshift operations.
public func createMLModel(_ input: CreateMLModelInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateMLModelOutput> {
return self.client.execute(operation: "CreateMLModel", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a real-time endpoint for the MLModel. The endpoint contains the URI of the MLModel; that is, the location to send real-time prediction requests for the specified MLModel.
public func createRealtimeEndpoint(_ input: CreateRealtimeEndpointInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateRealtimeEndpointOutput> {
return self.client.execute(operation: "CreateRealtimeEndpoint", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Assigns the DELETED status to a BatchPrediction, rendering it unusable. After using the DeleteBatchPrediction operation, you can use the GetBatchPrediction operation to verify that the status of the BatchPrediction changed to DELETED. Caution: The result of the DeleteBatchPrediction operation is irreversible.
public func deleteBatchPrediction(_ input: DeleteBatchPredictionInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteBatchPredictionOutput> {
return self.client.execute(operation: "DeleteBatchPrediction", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Assigns the DELETED status to a DataSource, rendering it unusable. After using the DeleteDataSource operation, you can use the GetDataSource operation to verify that the status of the DataSource changed to DELETED. Caution: The results of the DeleteDataSource operation are irreversible.
public func deleteDataSource(_ input: DeleteDataSourceInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteDataSourceOutput> {
return self.client.execute(operation: "DeleteDataSource", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Assigns the DELETED status to an Evaluation, rendering it unusable. After invoking the DeleteEvaluation operation, you can use the GetEvaluation operation to verify that the status of the Evaluation changed to DELETED. Caution The results of the DeleteEvaluation operation are irreversible.
public func deleteEvaluation(_ input: DeleteEvaluationInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteEvaluationOutput> {
return self.client.execute(operation: "DeleteEvaluation", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Assigns the DELETED status to an MLModel, rendering it unusable. After using the DeleteMLModel operation, you can use the GetMLModel operation to verify that the status of the MLModel changed to DELETED. Caution: The result of the DeleteMLModel operation is irreversible.
public func deleteMLModel(_ input: DeleteMLModelInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteMLModelOutput> {
return self.client.execute(operation: "DeleteMLModel", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a real time endpoint of an MLModel.
public func deleteRealtimeEndpoint(_ input: DeleteRealtimeEndpointInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteRealtimeEndpointOutput> {
return self.client.execute(operation: "DeleteRealtimeEndpoint", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes the specified tags associated with an ML object. After this operation is complete, you can't recover deleted tags. If you specify a tag that doesn't exist, Amazon ML ignores it.
public func deleteTags(_ input: DeleteTagsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteTagsOutput> {
return self.client.execute(operation: "DeleteTags", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of BatchPrediction operations that match the search criteria in the request.
public func describeBatchPredictions(_ input: DescribeBatchPredictionsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeBatchPredictionsOutput> {
return self.client.execute(operation: "DescribeBatchPredictions", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of DataSource that match the search criteria in the request.
public func describeDataSources(_ input: DescribeDataSourcesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeDataSourcesOutput> {
return self.client.execute(operation: "DescribeDataSources", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of DescribeEvaluations that match the search criteria in the request.
public func describeEvaluations(_ input: DescribeEvaluationsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeEvaluationsOutput> {
return self.client.execute(operation: "DescribeEvaluations", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of MLModel that match the search criteria in the request.
public func describeMLModels(_ input: DescribeMLModelsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeMLModelsOutput> {
return self.client.execute(operation: "DescribeMLModels", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes one or more of the tags for your Amazon ML object.
public func describeTags(_ input: DescribeTagsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeTagsOutput> {
return self.client.execute(operation: "DescribeTags", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a BatchPrediction that includes detailed metadata, status, and data file information for a Batch Prediction request.
public func getBatchPrediction(_ input: GetBatchPredictionInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetBatchPredictionOutput> {
return self.client.execute(operation: "GetBatchPrediction", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a DataSource that includes metadata and data file information, as well as the current status of the DataSource. GetDataSource provides results in normal or verbose format. The verbose format adds the schema description and the list of files pointed to by the DataSource to the normal format.
public func getDataSource(_ input: GetDataSourceInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetDataSourceOutput> {
return self.client.execute(operation: "GetDataSource", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns an Evaluation that includes metadata as well as the current status of the Evaluation.
public func getEvaluation(_ input: GetEvaluationInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetEvaluationOutput> {
return self.client.execute(operation: "GetEvaluation", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns an MLModel that includes detailed metadata, data source information, and the current status of the MLModel. GetMLModel provides results in normal or verbose format.
public func getMLModel(_ input: GetMLModelInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetMLModelOutput> {
return self.client.execute(operation: "GetMLModel", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Generates a prediction for the observation using the specified ML Model. Note Not all response parameters will be populated. Whether a response parameter is populated depends on the type of model requested.
public func predict(_ input: PredictInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<PredictOutput> {
return self.client.execute(operation: "Predict", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates the BatchPredictionName of a BatchPrediction. You can use the GetBatchPrediction operation to view the contents of the updated data element.
public func updateBatchPrediction(_ input: UpdateBatchPredictionInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateBatchPredictionOutput> {
return self.client.execute(operation: "UpdateBatchPrediction", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates the DataSourceName of a DataSource. You can use the GetDataSource operation to view the contents of the updated data element.
public func updateDataSource(_ input: UpdateDataSourceInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateDataSourceOutput> {
return self.client.execute(operation: "UpdateDataSource", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates the EvaluationName of an Evaluation. You can use the GetEvaluation operation to view the contents of the updated data element.
public func updateEvaluation(_ input: UpdateEvaluationInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateEvaluationOutput> {
return self.client.execute(operation: "UpdateEvaluation", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates the MLModelName and the ScoreThreshold of an MLModel. You can use the GetMLModel operation to view the contents of the updated data element.
public func updateMLModel(_ input: UpdateMLModelInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateMLModelOutput> {
return self.client.execute(operation: "UpdateMLModel", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
}
extension MachineLearning {
/// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public
/// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead.
public init(from: MachineLearning, patch: AWSServiceConfig.Patch) {
self.client = from.client
self.config = from.config.with(patch: patch)
}
}
| apache-2.0 |
ChrisAU/Locution | Papyrus/Renderers/TileDistributionRenderer.swift | 2 | 3571 | //
// TileDistributionRenderer.swift
// Papyrus
//
// Created by Chris Nevin on 14/05/2016.
// Copyright © 2016 CJNevin. All rights reserved.
//
import UIKit
import PapyrusCore
struct TileDistributionRenderer {
private let inset: CGFloat = 5
private let perRow: Int = 7
private let padding: CGFloat = 4
var tileViews: [TileView]?
var shapeLayer: CAShapeLayer?
mutating func render(inView view: UIView, filterBlank: Bool = true, characters: [Character], delegate: TileViewDelegate? = nil) {
shapeLayer?.removeFromSuperlayer()
tileViews?.forEach({ $0.removeFromSuperview() })
let containerRect = view.bounds.insetBy(dx: inset, dy: inset)
let tileSize = ceil(containerRect.size.width / CGFloat(perRow))
let sorted = characters.sorted()
let tiles = filterBlank ? sorted.filter({ $0 != Game.blankLetter }) : sorted
let lastRow = tiles.count <= perRow ? 0 : Int(tiles.count / perRow)
let path = UIBezierPath()
tileViews = tiles.enumerated().map { (index, value) -> TileView in
let row = index > 0 ? Int(index / perRow) : 0
let col = index - row * perRow
var x = CGFloat(col) * tileSize + padding / 2
if lastRow == row {
x += CGFloat(perRow * (lastRow + 1) - tiles.count) * tileSize / 2
}
let tileRect = CGRect(
x: inset + x,
y: inset + CGFloat(row) * tileSize + padding / 2,
width: tileSize - padding,
height: tileSize - padding)
let pathRect = tileRect.insetBy(dx: -padding, dy: -padding)
let radii = CGSize(width: inset, height: inset)
if row == 0 && col == 0 {
let corners: UIRectCorner = row == lastRow ? [.bottomLeft, .topLeft] : .topLeft
path.append(UIBezierPath(roundedRect: pathRect, byRoundingCorners: corners, cornerRadii: radii))
} else if row == 0 && col == perRow - 1 {
let corners: UIRectCorner = row == lastRow ? [.bottomRight, .topRight] : .topRight
path.append(UIBezierPath(roundedRect: pathRect, byRoundingCorners: corners, cornerRadii: radii))
} else if (row == lastRow && col == 0) {
path.append(UIBezierPath(roundedRect: pathRect, byRoundingCorners: .bottomLeft, cornerRadii: radii))
} else if (row == lastRow - 1 && col == 0) {
path.append(UIBezierPath(roundedRect: pathRect, byRoundingCorners: .bottomLeft, cornerRadii: radii))
} else if (row == lastRow && index == tiles.count - 1) || (row == lastRow - 1 && col == perRow - 1) {
path.append(UIBezierPath(roundedRect: pathRect, byRoundingCorners: .bottomRight, cornerRadii: radii))
} else {
path.append(UIBezierPath(rect: pathRect))
}
return TileView(frame: tileRect, tile: value, points: 0, onBoard: false, delegate: delegate)
}
let shape = CAShapeLayer()
shape.path = path.cgPath
shape.fillColor = UIColor.white.withAlphaComponent(0.6).cgColor
shape.shadowOffset = CGSize(width: 1, height: 1)
shape.shadowColor = UIColor.black.cgColor
shape.shadowOpacity = 0.3
shape.shadowRadius = 4
view.backgroundColor = .clear
view.layer.addSublayer(shape)
shapeLayer = shape
tileViews?.forEach({ tileView in
view.addSubview(tileView)
})
}
}
| mit |
maxsayenko/swift-2048 | swift-2048/AppearanceProvider.swift | 2 | 1837 | //
// AppearanceProvider.swift
// swift-2048
//
// Created by Austin Zheng on 6/3/14.
// Copyright (c) 2014 Austin Zheng. All rights reserved.
//
import UIKit
protocol AppearanceProviderProtocol {
func tileColor(value: Int) -> UIColor
func numberColor(value: Int) -> UIColor
func fontForNumbers() -> UIFont
}
class AppearanceProvider: AppearanceProviderProtocol {
// Provide a tile color for a given value
func tileColor(value: Int) -> UIColor {
switch value {
case 2:
return UIColor(red: 238.0/255.0, green: 228.0/255.0, blue: 218.0/255.0, alpha: 1.0)
case 4:
return UIColor(red: 237.0/255.0, green: 224.0/255.0, blue: 200.0/255.0, alpha: 1.0)
case 8:
return UIColor(red: 242.0/255.0, green: 177.0/255.0, blue: 121.0/255.0, alpha: 1.0)
case 16:
return UIColor(red: 245.0/255.0, green: 149.0/255.0, blue: 99.0/255.0, alpha: 1.0)
case 32:
return UIColor(red: 246.0/255.0, green: 124.0/255.0, blue: 95.0/255.0, alpha: 1.0)
case 64:
return UIColor(red: 246.0/255.0, green: 94.0/255.0, blue: 59.0/255.0, alpha: 1.0)
case 128:
fallthrough
case 256:
fallthrough
case 512:
fallthrough
case 1024:
fallthrough
case 2048:
return UIColor(red: 237.0/255.0, green: 207.0/255.0, blue: 114.0/255.0, alpha: 1.0)
default:
return UIColor.whiteColor()
}
}
// Provide a numeral color for a given value
func numberColor(value: Int) -> UIColor {
switch value {
case 2:
fallthrough
case 4:
return UIColor(red: 119.0/255.0, green: 110.0/255.0, blue: 101.0/255.0, alpha: 1.0)
default:
return UIColor.whiteColor()
}
}
// Provide the font to be used on the number tiles
func fontForNumbers() -> UIFont {
return UIFont(name: "HelveticaNeue-Bold", size: 20)
}
}
| mit |
devincoughlin/swift | test/stmt/if_while_var.swift | 1 | 6551 | // RUN: %target-typecheck-verify-swift
struct NonOptionalStruct {}
enum NonOptionalEnum { case foo }
func foo() -> Int? { return .none }
func nonOptionalStruct() -> NonOptionalStruct { fatalError() }
func nonOptionalEnum() -> NonOptionalEnum { fatalError() }
func use(_ x: Int) {}
func modify(_ x: inout Int) {}
if let x = foo() {
use(x)
modify(&x) // expected-error{{cannot pass immutable value as inout argument: 'x' is a 'let' constant}}
}
use(x) // expected-error{{unresolved identifier 'x'}}
if var x = foo() {
use(x)
modify(&x)
}
use(x) // expected-error{{unresolved identifier 'x'}}
if let x = nonOptionalStruct() { } // expected-error{{initializer for conditional binding must have Optional type, not 'NonOptionalStruct'}}
if let x = nonOptionalEnum() { } // expected-error{{initializer for conditional binding must have Optional type, not 'NonOptionalEnum'}}
guard let _ = nonOptionalStruct() else { fatalError() } // expected-error{{initializer for conditional binding must have Optional type, not 'NonOptionalStruct'}}
guard let _ = nonOptionalEnum() else { fatalError() } // expected-error{{initializer for conditional binding must have Optional type, not 'NonOptionalEnum'}}
if case let x? = nonOptionalStruct() { } // expected-error{{'?' pattern cannot match values of type 'NonOptionalStruct'}}
// expected-error@-1{{variable 'x' is not bound by any pattern}}
if case let x? = nonOptionalEnum() { } // expected-error{{'?' pattern cannot match values of type 'NonOptionalEnum'}}
// expected-error@-1{{variable 'x' is not bound by any pattern}}
class B {} // expected-note * {{did you mean 'B'?}}
class D : B {}// expected-note * {{did you mean 'D'?}}
// TODO poor recovery in these cases
if let {} // expected-error {{expected '{' after 'if' condition}} expected-error {{pattern matching in a condition requires the 'case' keyword}}
if let x = {} // expected-error{{'{' after 'if'}} expected-error {{variable binding in a condition requires an initializer}} expected-error{{initializer for conditional binding must have Optional type, not '() -> ()'}}
if let x = foo() {
} else {
// TODO: more contextual error? "x is only available on the true branch"?
use(x) // expected-error{{unresolved identifier 'x'}}
}
if let x = foo() {
use(x)
} else if let y = foo() { // expected-note {{did you mean 'y'?}}
use(x) // expected-error{{unresolved identifier 'x'}}
use(y)
} else {
use(x) // expected-error{{unresolved identifier 'x'}}
use(y) // expected-error{{unresolved identifier 'y'}}
}
var opt: Int? = .none
if let x = opt {} // expected-warning {{value 'x' was defined but never used; consider replacing with boolean test}}
if var x = opt {} // expected-warning {{value 'x' was defined but never used; consider replacing with boolean test}}
// <rdar://problem/20800015> Fix error message for invalid if-let
let someInteger = 1
if let y = someInteger {} // expected-error {{initializer for conditional binding must have Optional type, not 'Int'}}
if case let y? = someInteger {} // expected-error {{'?' pattern cannot match values of type 'Int'}}
// expected-error@-1{{variable 'y' is not bound by any pattern}}
// Test multiple clauses on "if let".
if let x = opt, let y = opt, x != y,
let a = opt, var b = opt { // expected-warning {{immutable value 'a' was never used; consider replacing with '_' or removing it}} expected-warning {{variable 'b' was never used; consider replacing with '_' or removing it}}
}
// Leading boolean conditional.
if 1 != 2, let x = opt,
y = opt, // expected-error {{expected 'let' in conditional}} {{4-4=let }}
x != y,
let a = opt, var b = opt { // expected-warning {{immutable value 'a' was never used; consider replacing with '_' or removing it}} expected-warning {{variable 'b' was never used; consider replacing with '_' or removing it}}
}
// <rdar://problem/20457938> typed pattern is not allowed on if/let condition
if 1 != 2, let x : Int? = opt {} // expected-warning {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
// expected-warning @-1 {{explicitly specified type 'Int?' adds an additional level of optional to the initializer, making the optional check always succeed}} {{20-24=Int}}
if 1 != 2, case let x? : Int? = 42 {} // expected-warning {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
// expected-warning @-1 {{non-optional expression of type 'Int' used in a check for optionals}}
// Test error recovery.
// <rdar://problem/19939746> Improve error recovery for malformed if statements
if 1 != 2, { // expected-error {{cannot convert value of type '() -> ()' to expected condition type 'Bool'}}
} // expected-error {{expected '{' after 'if' condition}}
if 1 != 2, 4 == 57 {}
if 1 != 2, 4 == 57, let x = opt {} // expected-warning {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
// Test that these don't cause the parser to crash.
if true { if a == 0; {} } // expected-error {{use of unresolved identifier 'a'}} expected-error {{expected '{' after 'if' condition}}
if a == 0, where b == 0 {} // expected-error 4{{}} expected-note {{}} {{25-25=do }}
func testIfCase(_ a : Int?) {
if case nil = a, a != nil {}
if case let (b?) = a, b != 42 {}
if let case (b?) = a, b != 42 {} // expected-error {{pattern matching binding is spelled with 'case let', not 'let case'}} {{6-10=}} {{14-14= let}}
if a != nil, let c = a, case nil = a { _ = c}
if let p? = a {_ = p} // expected-error {{pattern matching in a condition implicitly unwraps optionals}} {{11-12=}}
if let .some(x) = a {_ = x} // expected-error {{pattern matching in a condition requires the 'case' keyword}} {{6-6=case }}
if case _ = a {} // expected-warning {{'if' condition is always true}}
while case _ = a {} // expected-warning {{'while' condition is always true}}
}
// <rdar://problem/20883147> Type annotation for 'let' condition still expected to be optional
func testTypeAnnotations() {
if let x: Int = Optional(1) {_ = x}
if let x: Int = .some(1) {_ = x}
if case _ : Int8 = 19 {} // expected-warning {{'if' condition is always true}}
}
func testShadowing(_ a: Int?, b: Int?, c: Int?, d: Int?) {
guard let a = a, let b = a > 0 ? b : nil else { return }
_ = b
if let c = c, let d = c > 0 ? d : nil {
_ = d
}
}
func useInt(_ x: Int) {}
func testWhileScoping(_ a: Int?) {// expected-note {{did you mean 'a'?}}
while let x = a { }
useInt(x) // expected-error{{use of unresolved identifier 'x'}}
}
| apache-2.0 |
u10int/Kinetic | Example/Kinetic/ViewController.swift | 1 | 2709 | //
// ViewController.swift
// Tween
//
// Created by Nicholas Shipes on 10/22/15.
// Copyright © 2015 Urban10 Interactive, LLC. All rights reserved.
//
import UIKit
import Kinetic
class TestObject: NSObject {
var value: CGFloat = 0
}
class ViewController: UIViewController {
var square: UIView!
var square2: UIView!
var label: UILabel!
fileprivate var originalSquareFrame = CGRect.zero
fileprivate var originalSquare2Frame = CGRect.zero
var tableView: UITableView!
var rows = [UIViewController]()
override func viewDidLoad() {
super.viewDidLoad()
title = "Kinetic"
view.backgroundColor = UIColor.white
tableView = UITableView()
tableView.frame = view.bounds
tableView.dataSource = self
tableView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Row")
view.addSubview(tableView)
rows.append(BasicTweenViewController())
rows.append(BasicFromTweenViewController())
rows.append(BasicFromToTweenViewController())
rows.append(GroupTweenViewController())
rows.append(SequenceViewController())
rows.append(TransformViewController())
rows.append(AnchorPointViewController())
rows.append(AdditiveViewController())
rows.append(PhysicsViewController())
rows.append(StaggerViewController())
rows.append(TimelineViewController())
rows.append(CountingLabelViewController())
rows.append(PathTweenViewController())
rows.append(PreloaderViewController())
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// let t = Tween(target: square).toTest(PositionProp(50, 60), SizeProp(width: 200), AlphaProp(0.2)).to(.X(100)).duration(0.5).delay(0.5)
// let t = Tween(target: square).to(Position(50, 60), Size(width: 200), BackgroundColor(.greenColor())).duration(0.5).delay(0.5)
// t.play()
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rows.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Row", for: indexPath)
let controller = rows[indexPath.row]
cell.textLabel?.text = controller.title
return cell
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let controller = rows[indexPath.row]
navigationController?.pushViewController(controller, animated: true)
}
}
| mit |
xuephil/Perfect | PerfectLib/RWLockCache.swift | 2 | 5130 | //
// RWLockCache.swift
// PerfectLib
//
// Created by Kyle Jessup on 2015-12-01.
// Copyright © 2015 PerfectlySoft. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
import Foundation
/*
NOTE: This class uses GCD and as such does not yet operate on Linux.
It is not included in the project for OS X but is left in the source directory for future consideration.
*/
/// This class implements a multi-reader single-writer thread-safe dictionary.
/// It provides a means for:
/// 1. Fetching a value given a key, with concurrent readers
/// 2. Setting the value for a key with one writer while all readers block
/// 3. Fetching a value for a key with a callback, which, if the key does NOT exist, will be called to generate the new value in a thread-safe manner.
/// 4. Fetching a value for a key with a callback, which, if the key DOES exist, will be called to validate the value. If the value does nto validate then it will be removed from the dictionary in a thread-safe manner.
/// 5. Iterating all key/value pairs in a thread-safe manner while the write lock is held.
/// 6. Retrieving all keys while the read lock is held.
/// 7. Executing arbitrary blocks while either the read or write lock is held.
///
/// Note that if the validator callback indicates that the value is not valid, it will be called a second time while the write lock is held to ensure that the value has not been re-validated by another thread.
public class RWLockCache<KeyT: Hashable, ValueT> {
public typealias KeyType = KeyT
public typealias ValueType = ValueT
public typealias ValueGenerator = () -> ValueType?
public typealias ValueValidator = (value: ValueType) -> Bool
private let queue = dispatch_queue_create("RWLockCache", DISPATCH_QUEUE_CONCURRENT)
private var cache = [KeyType : ValueType]()
public func valueForKey(key: KeyType) -> ValueType? {
var value: ValueType?
dispatch_sync(self.queue) {
value = self.cache[key]
}
return value
}
public func valueForKey(key: KeyType, missCallback: ValueGenerator, validatorCallback: ValueValidator) -> ValueType? {
var value: ValueType?
dispatch_sync(self.queue) {
value = self.cache[key]
}
if value == nil {
dispatch_barrier_sync(self.queue) {
value = self.cache[key]
if value == nil {
value = missCallback()
if value != nil {
self.cache[key] = value
}
}
}
} else if !validatorCallback(value: value!) {
dispatch_barrier_sync(self.queue) {
value = self.cache[key]
if value != nil && !validatorCallback(value: value!) {
self.cache.removeValueForKey(key)
value = nil
}
}
}
return value
}
public func valueForKey(key: KeyType, validatorCallback: ValueValidator) -> ValueType? {
var value: ValueType?
dispatch_sync(self.queue) {
value = self.cache[key]
}
if value != nil && !validatorCallback(value: value!) {
dispatch_barrier_sync(self.queue) {
value = self.cache[key]
if value != nil && !validatorCallback(value: value!) {
self.cache.removeValueForKey(key)
value = nil
}
}
}
return value
}
public func valueForKey(key: KeyType, missCallback: ValueGenerator) -> ValueType? {
var value: ValueType?
dispatch_sync(self.queue) {
value = self.cache[key]
}
if value == nil {
dispatch_barrier_sync(self.queue) {
value = self.cache[key]
if value == nil {
value = missCallback()
if value != nil {
self.cache[key] = value
}
}
}
}
return value
}
public func setValueForKey(key: KeyType, value: ValueType) {
dispatch_barrier_async(self.queue) {
self.cache[key] = value
}
}
public func keys() -> [KeyType] {
var keys = [KeyType]()
dispatch_sync(self.queue) {
for key in self.cache.keys {
keys.append(key)
}
}
return keys
}
public func keysAndValues(callback: (KeyType, ValueType) -> ()) {
dispatch_barrier_sync(self.queue) {
for (key, value) in self.cache {
callback(key, value)
}
}
}
public func withReadLock(callback: () -> ()) {
dispatch_sync(self.queue) {
callback()
}
}
public func withWriteLock(callback: () -> ()) {
dispatch_barrier_sync(self.queue) {
callback()
}
}
}
| agpl-3.0 |
CrazyTalkEntertainment/CTEAnimatedHamburgerView | AnimatedHamburgerTestAppTests/AnimatedHamburgerTestAppTests.swift | 1 | 6774 | //
// AnimatedHamburgerTestAppTests.swift
// AnimatedHamburgerTestAppTests
//
// Created by CrazyTalk Entertainment on 2014-11-03.
// Copyright (c) 2014 CrazyTalk Entertainment. All rights reserved.
//
// Created by CrazyTalk Entertainment on 2014-11-12.
// Copyright (c) 2014 CrazyTalk Entertainment. 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
import XCTest
class AnimatedHamburgerTestAppTests: XCTestCase {
let sut: CTEAnimatedHamburgerView = CTEAnimatedHamburgerView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
func testInit()
{
XCTAssertNotNil(sut, "view did not load correctly")
XCTAssertNotNil(sut.layer.sublayers, "line setup was not successful")
XCTAssertNotNil(sut.gestureRecognizers, "tap gesture was not created correctly")
}
func testCalulateLineLength_ButtLineCap()
{
sut.lineThickness = 15.0
XCTAssert(sut.lineLength == 80, "line length was not calculated correctly")
}
func testCalulateLineLength_SquareLineCap()
{
sut.lineCapType = kCALineCapSquare
sut.lineThickness = 15.0
XCTAssert(sut.lineLength == 65, "line length was not calculated correctly")
}
func testIsTransitionComplete_ZeroPercent()
{
sut.setPercentComplete(0.0)
let transition = sut.isTransitionComplete()
XCTAssertTrue(transition.isComplete, "incorrect value was returned for isComplete")
XCTAssert(transition.percent == 0.0, "incorrect value was returned for percent")
}
func testIsTransitionComplete_HundredPercent()
{
sut.setPercentComplete(1.0)
let transition = sut.isTransitionComplete()
XCTAssertTrue(transition.isComplete, "incorrect value was returned for isComplete")
XCTAssert(transition.percent == 1.0, "incorrect value was returned for percent")
}
func testIsTransitionComplete_FiftyPercent()
{
sut.setPercentComplete(0.5)
let transition = sut.isTransitionComplete()
XCTAssertFalse(transition.isComplete, "incorrect value was returned for isComplete")
XCTAssert(transition.percent == 0.5, "incorrect value was returned for percent")
}
func testCreateLineLayerWithPosition()
{
let position = CGPoint(x: 83, y: 54)
let length: CGFloat = 80.0
let shapeLayer = sut.createLineLayerWithPosition(position, length: length, lineColor: UIColor.blueColor())
XCTAssert(shapeLayer.position.x == position.x, "x position was not set correctly")
XCTAssert(shapeLayer.position.y == position.y, "y position was not set correctly")
XCTAssertTrue(CGColorEqualToColor(shapeLayer.strokeColor, UIColor.blueColor().CGColor), "color was not set correctly")
XCTAssert(shapeLayer.bounds.width == length, "length was not set correctly")
}
func testSetPercentComplete()
{
let percent: CGFloat = 0.83
sut.setPercentComplete(percent)
XCTAssert(sut.percentComplete == percent, "percent complete was not set correctly")
}
func testSetPercentCompleteOverload()
{
sut.setPercentComplete(1.5)
XCTAssert(sut.percentComplete == 1.0, "percent compete did not cap at 100%")
sut.setPercentComplete(-1.5)
XCTAssert(sut.percentComplete == 0.0, "percent compete did not cap at 0%")
}
func testRotationalCircleRadius()
{
let radius = sut.rotationalCircleRadius()
XCTAssert(radius == 27.223611075682079, "radius was not calculated correctly")
}
func testRemainingDuration()
{
//default duration is 0.8
let duration = sut.remainingDuration(0.5)
XCTAssert(duration == 0.4, "remaining duration was not calculated correctly")
}
//MARK: performance Tests
func testPerformanceInit()
{
self.measureBlock() {
let sut: CTEAnimatedHamburgerView = CTEAnimatedHamburgerView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
}
}
func testPerformanceCalulateLineLength()
{
self.measureBlock() {
let lineLength: CGFloat = self.sut.calculateLineLength()
}
}
func testPerformanceIsTransitionComplete()
{
sut.setPercentComplete(1.0)
self.measureBlock() {
let transition = self.sut.isTransitionComplete()
}
}
func testPerformanceCreateLineLayerWithPosition()
{
let position = CGPoint(x: 83, y: 54)
let length: CGFloat = 80.0
self.measureBlock() {
let shapeLayer = self.sut.createLineLayerWithPosition(position, length: length, lineColor: UIColor.blueColor())
}
}
func testPerformanceSetPercentComplete()
{
self.measureBlock() {
self.sut.setPercentComplete(0.83)
}
}
func testPerformanceRotationalCircleRadius()
{
self.measureBlock() {
let radius = self.sut.rotationalCircleRadius()
}
}
func testPerformanceRemainingDuration()
{
self.measureBlock() {
let duration = self.sut.remainingDuration(0.5)
}
}
func testPerformanceUpdateForBackArrow()
{
self.measureBlock() {
self.sut.updateLinesForBackArrow(1.0, animate: true)
}
}
func testPerformanceUpdateForClose()
{
self.measureBlock() {
self.sut.updateLinesForClose(1.0, animate: true)
}
}
}
| mit |
MoodTeam/MoodApp | MoodApp/MoodAppTests/MoodAppTests.swift | 1 | 899 | //
// MoodAppTests.swift
// MoodAppTests
//
// Created by Ashton Coghlan on 11/22/14.
// Copyright (c) 2014 42labs. All rights reserved.
//
import UIKit
import XCTest
class MoodAppTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
netguru/inbbbox-ios | Inbbbox/Source Files/Views/Custom/ShotAuthorCompactView.swift | 1 | 4029 | //
// ShotAuthorCompactView.swift
// Inbbbox
//
// Created by Lukasz Pikor on 25.05.2016.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import PureLayout
class ShotAuthorCompactView: UIView {
// MARK: Internal
lazy var avatarView: AvatarView = AvatarView(size: self.avatarSize,
bordered: false)
// MARK: Private
fileprivate let authorLabel = UILabel.newAutoLayout()
fileprivate let likesImageView: UIImageView = UIImageView(image: UIImage(named: "ic-likes-count"))
fileprivate let likesLabel = UILabel.newAutoLayout()
fileprivate let commentsImageView: UIImageView = UIImageView(image: UIImage(named: "ic-comment-count"))
fileprivate let commentsLabel = UILabel.newAutoLayout()
struct ViewData {
let author: String
let avatarURL: URL
let liked: Bool
let likesCount: UInt
let commentsCount: UInt
}
var viewData: ViewData? {
didSet {
authorLabel.text = viewData?.author
let placeholder = UIImage(named: "ic-account-nopicture")
avatarView.imageView.loadImageFromURL((viewData?.avatarURL)!, placeholderImage: placeholder)
if let viewData = viewData, viewData.liked {
likesImageView.image = UIImage(named: "ic-like-details-active")
} else {
likesImageView.image = UIImage(named: "ic-likes-count")
}
likesLabel.text = "\(viewData?.likesCount ?? 0)"
commentsLabel.text = "\(viewData?.commentsCount ?? 0)"
}
}
// Private
fileprivate var didSetupConstraints = false
fileprivate let avatarSize = CGSize(width: 16, height: 16)
fileprivate let likesSize = CGSize(width: 17, height: 16)
fileprivate let commentsSize = CGSize(width: 18, height: 16)
// MARK: Life Cycle
override init(frame: CGRect) {
super.init(frame: frame)
avatarView.backgroundColor = .clear
[authorLabel, likesLabel, commentsLabel].forEach { (label) in
label.font = UIFont.systemFont(ofSize: 10, weight: UIFontWeightRegular)
label.textColor = .followeeTextGrayColor()
}
addSubview(avatarView)
addSubview(authorLabel)
addSubview(likesImageView)
addSubview(likesLabel)
addSubview(commentsImageView)
addSubview(commentsLabel)
}
@available(*, unavailable, message: "Use init(frame:) instead")
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: UIView
override class var requiresConstraintBasedLayout: Bool {
return true
}
override func updateConstraints() {
if !didSetupConstraints {
avatarView.autoSetDimensions(to: avatarSize)
avatarView.autoPinEdge(toSuperviewEdge: .leading)
avatarView.autoAlignAxis(toSuperviewAxis: .horizontal)
authorLabel.autoPinEdge(.leading, to: .trailing, of: avatarView, withOffset: 3)
authorLabel.autoAlignAxis(toSuperviewAxis: .horizontal)
commentsLabel.autoPinEdge(toSuperviewEdge: .trailing, withInset: 3)
commentsLabel.autoAlignAxis(toSuperviewAxis: .horizontal)
commentsImageView.autoSetDimensions(to: commentsSize)
commentsImageView.autoPinEdge(.trailing, to: .leading, of: commentsLabel, withOffset: -3)
commentsImageView.autoAlignAxis(toSuperviewAxis: .horizontal)
likesLabel.autoPinEdge(.trailing, to: .leading, of: commentsImageView, withOffset: -8)
likesLabel.autoAlignAxis(toSuperviewAxis: .horizontal)
likesImageView.autoSetDimensions(to: likesSize)
likesImageView.autoPinEdge(.trailing, to: .leading, of: likesLabel, withOffset: -3)
likesImageView.autoAlignAxis(toSuperviewAxis: .horizontal)
didSetupConstraints = true
}
super.updateConstraints()
}
}
| gpl-3.0 |
hejunbinlan/Carlos | Carlos.playground/Sources/SupportCode.swift | 2 | 430 | //
// This file (and all other Swift source files in the Sources directory of this playground) will be precompiled into a framework which is automatically made available to Carlos.playground.
//
import XCPlayground
public func sharedSubfolder() -> String {
return "\(XCPSharedDataDirectoryPath)/com.carlos.cache"
}
public func initializePlayground() {
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)
} | mit |
mitsuyoshi-yamazaki/SwarmChemistry | SwarmChemistry/Population.swift | 1 | 6287 | //
// Population.swift
// SwarmChemistry
//
// Created by mitsuyoshi.yamazaki on 2017/08/09.
// Copyright © 2017 Mitsuyoshi Yamazaki. All rights reserved.
//
import Foundation
// MARK: - Population
public struct Population {
public var fieldSize = Vector2(500, 500)
public var steps = 0
public let population: [Individual]
public let recipe: Recipe
init(population: [Individual], recipe: Recipe, fieldSize: Vector2) {
self.population = population
self.recipe = recipe
self.fieldSize = fieldSize
steps = 0
}
}
// MARK: - Recipe
public extension Population {
init(_ recipe: Recipe, numberOfPopulation: Int? = nil, fieldSize: Vector2 = Vector2(500, 500), initialArea: Vector2.Rect? = nil) {
self.recipe = recipe
let sum = recipe.genomes
.reduce(0) { result, value -> Int in
result + value.count
}
let magnitude = max(Value(numberOfPopulation ?? sum) / Value(sum), 1.0)
let area: Vector2.Rect
if let initialArea = initialArea {
area = initialArea
} else {
area = .init(origin: .zero, size: fieldSize)
}
population = recipe.genomes
.map { value -> [Individual] in
let count = Int(Value(value.count) * magnitude)
return (0..<count)
.map { _ in
Individual(position: (value.area ?? area).random(), genome: value.genome)
}
}
.flatMap { $0 }
print("\(recipe.name) magnitude: \(magnitude), total population: \(population.count)")
self.fieldSize = fieldSize
}
}
// MARK: - Accessor
public extension Population {
static func empty() -> Population {
return Population(.none(), numberOfPopulation: 0, fieldSize: .zero)
}
}
// MARK: - Function
public extension Population {
func recipe(`in` rect: Vector2.Rect) -> Recipe {
let populationInRect = population
.filter { rect.contains($0.position) }
let genomesInRect = populationInRect
.reduce(into: [Parameters](), { result, individual in
if result.filter { $0 == individual.genome }.isEmpty {
result += [individual.genome]
}
})
.map { genome -> Recipe.GenomeInfo in
return Recipe.GenomeInfo(count: populationInRect.filter { $0.genome == genome }.count, area: nil, genome: genome)
}
let name = "Subset of \(recipe.name)"
return Recipe(name: name, genomes: genomesInRect)
}
mutating func step(_ count: Int = 1) {
guard count > 0 else { // swiftlint:disable:this empty_count
Log.error("Argument \"count\" should be a positive value")
return
}
func getNeighbors(individual: Individual) -> [(distance: Value, individual: Individual)] {
return population
.map { neighbor -> (distance: Value, individual: Individual)? in
guard neighbor !== individual else {
return nil
}
let distance = individual.position.distance(neighbor.position)
guard distance < individual.genome.neighborhoodRadius else {
return nil
}
return (distance: distance, individual: neighbor)
}
.compactMap { $0 }
}
(0..<count).forEach { _ in
population.forEach { individual in
let genome = individual.genome
let neighbors = getNeighbors(individual: individual)
let acceleration: Vector2
// Repulsive Force
let x = individual.position.x
let y = individual.position.y
let repulsiveDistance: Value = Parameters.neighborhoodRadiusMax * 2.0
let distanceFromBorderX = min(x, fieldSize.x - x) / repulsiveDistance
let repulsiveX = distanceFromBorderX <= 1.0 ? pow(1.0 - distanceFromBorderX, 10.0) * individual.genome.maxVelocity : 0.0
let directionX: Value = (x < fieldSize.x - x) ? 1 : -1
let distanceFromBorderY = min(y, fieldSize.y - y) / repulsiveDistance
let repulsiveY = distanceFromBorderY <= 1.0 ? pow(1.0 - distanceFromBorderY, 10.0) * individual.genome.maxVelocity : 0.0
let directionY: Value = (y < fieldSize.y - y) ? 1 : -1
let repulsiveForce = Vector2(repulsiveX * directionX, repulsiveY * directionY)
if neighbors.isEmpty {
acceleration = Vector2(1, 1).random() - Vector2(0.5, 0.5)
+ repulsiveForce
} else {
let numberOfNeighbors = Value(neighbors.count)
// Center
let sumCenter = neighbors.reduce(Vector2.zero) { result, value -> Vector2 in
return result + value.individual.position
}
let averageCenter = sumCenter / numberOfNeighbors
// Velocity
let sumVelocity = neighbors.reduce(Vector2.zero) { result, value -> Vector2 in
return result + value.individual.velocity
}
let averageVelocity = sumVelocity / numberOfNeighbors
// Separation
let sumSeparation = neighbors.reduce(Vector2.zero) { result, value -> Vector2 in
return result
+ (individual.position - value.individual.position)
/ max(value.distance * value.distance, 0.001)
* genome.separatingForce
}
// Steering
let steering: Vector2
if Double(Int.random(in: 0..<100)) < (genome.probabilityOfRandomSteering * 100.0) {
steering = Vector2(Value(arc4random() % 10) - 4.5, Value(arc4random() % 10) - 4.5)
} else {
steering = .zero
}
acceleration = (averageCenter - individual.position) * genome.cohesiveForce
+ (averageVelocity - individual.velocity) * genome.aligningForce
+ sumSeparation
+ steering
+ repulsiveForce
}
individual.accelerate(acceleration)
let accelerationSize = max(individual.acceleration.size(), 0.001)
individual.accelerate(individual.acceleration * (genome.normalSpeed - accelerationSize) / accelerationSize * genome.tendencyOfPacekeeping)
individual.move(in: self.fieldSize)
}
}
steps += count
}
}
// MARK: - CustomStringConvertible
extension Population: CustomStringConvertible {
public var description: String {
return recipe.genomes
.map { "\($0.count) * \($0.genome)" }
.joined(separator: "\n")
}
}
| mit |
tbkka/swift-protobuf | Tests/SwiftProtobufTests/map_unittest.pb.swift | 6 | 53797 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: google/protobuf/map_unittest.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. 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
// OWNER 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 Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
enum ProtobufUnittest_MapEnum: SwiftProtobuf.Enum {
typealias RawValue = Int
case foo // = 0
case bar // = 1
case baz // = 2
case UNRECOGNIZED(Int)
init() {
self = .foo
}
init?(rawValue: Int) {
switch rawValue {
case 0: self = .foo
case 1: self = .bar
case 2: self = .baz
default: self = .UNRECOGNIZED(rawValue)
}
}
var rawValue: Int {
switch self {
case .foo: return 0
case .bar: return 1
case .baz: return 2
case .UNRECOGNIZED(let i): return i
}
}
}
#if swift(>=4.2)
extension ProtobufUnittest_MapEnum: CaseIterable {
// The compiler won't synthesize support with the UNRECOGNIZED case.
static var allCases: [ProtobufUnittest_MapEnum] = [
.foo,
.bar,
.baz,
]
}
#endif // swift(>=4.2)
/// Tests maps.
struct ProtobufUnittest_TestMap {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var mapInt32Int32: Dictionary<Int32,Int32> {
get {return _storage._mapInt32Int32}
set {_uniqueStorage()._mapInt32Int32 = newValue}
}
var mapInt64Int64: Dictionary<Int64,Int64> {
get {return _storage._mapInt64Int64}
set {_uniqueStorage()._mapInt64Int64 = newValue}
}
var mapUint32Uint32: Dictionary<UInt32,UInt32> {
get {return _storage._mapUint32Uint32}
set {_uniqueStorage()._mapUint32Uint32 = newValue}
}
var mapUint64Uint64: Dictionary<UInt64,UInt64> {
get {return _storage._mapUint64Uint64}
set {_uniqueStorage()._mapUint64Uint64 = newValue}
}
var mapSint32Sint32: Dictionary<Int32,Int32> {
get {return _storage._mapSint32Sint32}
set {_uniqueStorage()._mapSint32Sint32 = newValue}
}
var mapSint64Sint64: Dictionary<Int64,Int64> {
get {return _storage._mapSint64Sint64}
set {_uniqueStorage()._mapSint64Sint64 = newValue}
}
var mapFixed32Fixed32: Dictionary<UInt32,UInt32> {
get {return _storage._mapFixed32Fixed32}
set {_uniqueStorage()._mapFixed32Fixed32 = newValue}
}
var mapFixed64Fixed64: Dictionary<UInt64,UInt64> {
get {return _storage._mapFixed64Fixed64}
set {_uniqueStorage()._mapFixed64Fixed64 = newValue}
}
var mapSfixed32Sfixed32: Dictionary<Int32,Int32> {
get {return _storage._mapSfixed32Sfixed32}
set {_uniqueStorage()._mapSfixed32Sfixed32 = newValue}
}
var mapSfixed64Sfixed64: Dictionary<Int64,Int64> {
get {return _storage._mapSfixed64Sfixed64}
set {_uniqueStorage()._mapSfixed64Sfixed64 = newValue}
}
var mapInt32Float: Dictionary<Int32,Float> {
get {return _storage._mapInt32Float}
set {_uniqueStorage()._mapInt32Float = newValue}
}
var mapInt32Double: Dictionary<Int32,Double> {
get {return _storage._mapInt32Double}
set {_uniqueStorage()._mapInt32Double = newValue}
}
var mapBoolBool: Dictionary<Bool,Bool> {
get {return _storage._mapBoolBool}
set {_uniqueStorage()._mapBoolBool = newValue}
}
var mapStringString: Dictionary<String,String> {
get {return _storage._mapStringString}
set {_uniqueStorage()._mapStringString = newValue}
}
var mapInt32Bytes: Dictionary<Int32,Data> {
get {return _storage._mapInt32Bytes}
set {_uniqueStorage()._mapInt32Bytes = newValue}
}
var mapInt32Enum: Dictionary<Int32,ProtobufUnittest_MapEnum> {
get {return _storage._mapInt32Enum}
set {_uniqueStorage()._mapInt32Enum = newValue}
}
var mapInt32ForeignMessage: Dictionary<Int32,ProtobufUnittest_ForeignMessage> {
get {return _storage._mapInt32ForeignMessage}
set {_uniqueStorage()._mapInt32ForeignMessage = newValue}
}
var mapStringForeignMessage: Dictionary<String,ProtobufUnittest_ForeignMessage> {
get {return _storage._mapStringForeignMessage}
set {_uniqueStorage()._mapStringForeignMessage = newValue}
}
var mapInt32AllTypes: Dictionary<Int32,ProtobufUnittest_TestAllTypes> {
get {return _storage._mapInt32AllTypes}
set {_uniqueStorage()._mapInt32AllTypes = newValue}
}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
struct ProtobufUnittest_TestMapSubmessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var testMap: ProtobufUnittest_TestMap {
get {return _testMap ?? ProtobufUnittest_TestMap()}
set {_testMap = newValue}
}
/// Returns true if `testMap` has been explicitly set.
var hasTestMap: Bool {return self._testMap != nil}
/// Clears the value of `testMap`. Subsequent reads from it will return its default value.
mutating func clearTestMap() {self._testMap = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _testMap: ProtobufUnittest_TestMap? = nil
}
struct ProtobufUnittest_TestMessageMap {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var mapInt32Message: Dictionary<Int32,ProtobufUnittest_TestAllTypes> = [:]
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// Two map fields share the same entry default instance.
struct ProtobufUnittest_TestSameTypeMap {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var map1: Dictionary<Int32,Int32> = [:]
var map2: Dictionary<Int32,Int32> = [:]
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// Test embedded message with required fields
struct ProtobufUnittest_TestRequiredMessageMap {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var mapField: Dictionary<Int32,ProtobufUnittest_TestRequired> = [:]
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct ProtobufUnittest_TestArenaMap {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var mapInt32Int32: Dictionary<Int32,Int32> {
get {return _storage._mapInt32Int32}
set {_uniqueStorage()._mapInt32Int32 = newValue}
}
var mapInt64Int64: Dictionary<Int64,Int64> {
get {return _storage._mapInt64Int64}
set {_uniqueStorage()._mapInt64Int64 = newValue}
}
var mapUint32Uint32: Dictionary<UInt32,UInt32> {
get {return _storage._mapUint32Uint32}
set {_uniqueStorage()._mapUint32Uint32 = newValue}
}
var mapUint64Uint64: Dictionary<UInt64,UInt64> {
get {return _storage._mapUint64Uint64}
set {_uniqueStorage()._mapUint64Uint64 = newValue}
}
var mapSint32Sint32: Dictionary<Int32,Int32> {
get {return _storage._mapSint32Sint32}
set {_uniqueStorage()._mapSint32Sint32 = newValue}
}
var mapSint64Sint64: Dictionary<Int64,Int64> {
get {return _storage._mapSint64Sint64}
set {_uniqueStorage()._mapSint64Sint64 = newValue}
}
var mapFixed32Fixed32: Dictionary<UInt32,UInt32> {
get {return _storage._mapFixed32Fixed32}
set {_uniqueStorage()._mapFixed32Fixed32 = newValue}
}
var mapFixed64Fixed64: Dictionary<UInt64,UInt64> {
get {return _storage._mapFixed64Fixed64}
set {_uniqueStorage()._mapFixed64Fixed64 = newValue}
}
var mapSfixed32Sfixed32: Dictionary<Int32,Int32> {
get {return _storage._mapSfixed32Sfixed32}
set {_uniqueStorage()._mapSfixed32Sfixed32 = newValue}
}
var mapSfixed64Sfixed64: Dictionary<Int64,Int64> {
get {return _storage._mapSfixed64Sfixed64}
set {_uniqueStorage()._mapSfixed64Sfixed64 = newValue}
}
var mapInt32Float: Dictionary<Int32,Float> {
get {return _storage._mapInt32Float}
set {_uniqueStorage()._mapInt32Float = newValue}
}
var mapInt32Double: Dictionary<Int32,Double> {
get {return _storage._mapInt32Double}
set {_uniqueStorage()._mapInt32Double = newValue}
}
var mapBoolBool: Dictionary<Bool,Bool> {
get {return _storage._mapBoolBool}
set {_uniqueStorage()._mapBoolBool = newValue}
}
var mapStringString: Dictionary<String,String> {
get {return _storage._mapStringString}
set {_uniqueStorage()._mapStringString = newValue}
}
var mapInt32Bytes: Dictionary<Int32,Data> {
get {return _storage._mapInt32Bytes}
set {_uniqueStorage()._mapInt32Bytes = newValue}
}
var mapInt32Enum: Dictionary<Int32,ProtobufUnittest_MapEnum> {
get {return _storage._mapInt32Enum}
set {_uniqueStorage()._mapInt32Enum = newValue}
}
var mapInt32ForeignMessage: Dictionary<Int32,ProtobufUnittest_ForeignMessage> {
get {return _storage._mapInt32ForeignMessage}
set {_uniqueStorage()._mapInt32ForeignMessage = newValue}
}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
/// Previously, message containing enum called Type cannot be used as value of
/// map field.
struct ProtobufUnittest_MessageContainingEnumCalledType {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var type: Dictionary<String,ProtobufUnittest_MessageContainingEnumCalledType> = [:]
var unknownFields = SwiftProtobuf.UnknownStorage()
enum TypeEnum: SwiftProtobuf.Enum {
typealias RawValue = Int
case foo // = 0
case UNRECOGNIZED(Int)
init() {
self = .foo
}
init?(rawValue: Int) {
switch rawValue {
case 0: self = .foo
default: self = .UNRECOGNIZED(rawValue)
}
}
var rawValue: Int {
switch self {
case .foo: return 0
case .UNRECOGNIZED(let i): return i
}
}
}
init() {}
}
#if swift(>=4.2)
extension ProtobufUnittest_MessageContainingEnumCalledType.TypeEnum: CaseIterable {
// The compiler won't synthesize support with the UNRECOGNIZED case.
static var allCases: [ProtobufUnittest_MessageContainingEnumCalledType.TypeEnum] = [
.foo,
]
}
#endif // swift(>=4.2)
/// Previously, message cannot contain map field called "entry".
struct ProtobufUnittest_MessageContainingMapCalledEntry {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var entry: Dictionary<Int32,Int32> = [:]
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct ProtobufUnittest_TestRecursiveMapMessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var a: Dictionary<String,ProtobufUnittest_TestRecursiveMapMessage> = [:]
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "protobuf_unittest"
extension ProtobufUnittest_MapEnum: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
0: .same(proto: "MAP_ENUM_FOO"),
1: .same(proto: "MAP_ENUM_BAR"),
2: .same(proto: "MAP_ENUM_BAZ"),
]
}
extension ProtobufUnittest_TestMap: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestMap"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "map_int32_int32"),
2: .standard(proto: "map_int64_int64"),
3: .standard(proto: "map_uint32_uint32"),
4: .standard(proto: "map_uint64_uint64"),
5: .standard(proto: "map_sint32_sint32"),
6: .standard(proto: "map_sint64_sint64"),
7: .standard(proto: "map_fixed32_fixed32"),
8: .standard(proto: "map_fixed64_fixed64"),
9: .standard(proto: "map_sfixed32_sfixed32"),
10: .standard(proto: "map_sfixed64_sfixed64"),
11: .standard(proto: "map_int32_float"),
12: .standard(proto: "map_int32_double"),
13: .standard(proto: "map_bool_bool"),
14: .standard(proto: "map_string_string"),
15: .standard(proto: "map_int32_bytes"),
16: .standard(proto: "map_int32_enum"),
17: .standard(proto: "map_int32_foreign_message"),
18: .standard(proto: "map_string_foreign_message"),
19: .standard(proto: "map_int32_all_types"),
]
fileprivate class _StorageClass {
var _mapInt32Int32: Dictionary<Int32,Int32> = [:]
var _mapInt64Int64: Dictionary<Int64,Int64> = [:]
var _mapUint32Uint32: Dictionary<UInt32,UInt32> = [:]
var _mapUint64Uint64: Dictionary<UInt64,UInt64> = [:]
var _mapSint32Sint32: Dictionary<Int32,Int32> = [:]
var _mapSint64Sint64: Dictionary<Int64,Int64> = [:]
var _mapFixed32Fixed32: Dictionary<UInt32,UInt32> = [:]
var _mapFixed64Fixed64: Dictionary<UInt64,UInt64> = [:]
var _mapSfixed32Sfixed32: Dictionary<Int32,Int32> = [:]
var _mapSfixed64Sfixed64: Dictionary<Int64,Int64> = [:]
var _mapInt32Float: Dictionary<Int32,Float> = [:]
var _mapInt32Double: Dictionary<Int32,Double> = [:]
var _mapBoolBool: Dictionary<Bool,Bool> = [:]
var _mapStringString: Dictionary<String,String> = [:]
var _mapInt32Bytes: Dictionary<Int32,Data> = [:]
var _mapInt32Enum: Dictionary<Int32,ProtobufUnittest_MapEnum> = [:]
var _mapInt32ForeignMessage: Dictionary<Int32,ProtobufUnittest_ForeignMessage> = [:]
var _mapStringForeignMessage: Dictionary<String,ProtobufUnittest_ForeignMessage> = [:]
var _mapInt32AllTypes: Dictionary<Int32,ProtobufUnittest_TestAllTypes> = [:]
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_mapInt32Int32 = source._mapInt32Int32
_mapInt64Int64 = source._mapInt64Int64
_mapUint32Uint32 = source._mapUint32Uint32
_mapUint64Uint64 = source._mapUint64Uint64
_mapSint32Sint32 = source._mapSint32Sint32
_mapSint64Sint64 = source._mapSint64Sint64
_mapFixed32Fixed32 = source._mapFixed32Fixed32
_mapFixed64Fixed64 = source._mapFixed64Fixed64
_mapSfixed32Sfixed32 = source._mapSfixed32Sfixed32
_mapSfixed64Sfixed64 = source._mapSfixed64Sfixed64
_mapInt32Float = source._mapInt32Float
_mapInt32Double = source._mapInt32Double
_mapBoolBool = source._mapBoolBool
_mapStringString = source._mapStringString
_mapInt32Bytes = source._mapInt32Bytes
_mapInt32Enum = source._mapInt32Enum
_mapInt32ForeignMessage = source._mapInt32ForeignMessage
_mapStringForeignMessage = source._mapStringForeignMessage
_mapInt32AllTypes = source._mapInt32AllTypes
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufInt32>.self, value: &_storage._mapInt32Int32) }()
case 2: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt64,SwiftProtobuf.ProtobufInt64>.self, value: &_storage._mapInt64Int64) }()
case 3: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufUInt32,SwiftProtobuf.ProtobufUInt32>.self, value: &_storage._mapUint32Uint32) }()
case 4: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufUInt64,SwiftProtobuf.ProtobufUInt64>.self, value: &_storage._mapUint64Uint64) }()
case 5: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSInt32,SwiftProtobuf.ProtobufSInt32>.self, value: &_storage._mapSint32Sint32) }()
case 6: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSInt64,SwiftProtobuf.ProtobufSInt64>.self, value: &_storage._mapSint64Sint64) }()
case 7: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufFixed32,SwiftProtobuf.ProtobufFixed32>.self, value: &_storage._mapFixed32Fixed32) }()
case 8: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufFixed64,SwiftProtobuf.ProtobufFixed64>.self, value: &_storage._mapFixed64Fixed64) }()
case 9: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSFixed32,SwiftProtobuf.ProtobufSFixed32>.self, value: &_storage._mapSfixed32Sfixed32) }()
case 10: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSFixed64,SwiftProtobuf.ProtobufSFixed64>.self, value: &_storage._mapSfixed64Sfixed64) }()
case 11: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufFloat>.self, value: &_storage._mapInt32Float) }()
case 12: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufDouble>.self, value: &_storage._mapInt32Double) }()
case 13: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufBool,SwiftProtobuf.ProtobufBool>.self, value: &_storage._mapBoolBool) }()
case 14: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufString,SwiftProtobuf.ProtobufString>.self, value: &_storage._mapStringString) }()
case 15: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufBytes>.self, value: &_storage._mapInt32Bytes) }()
case 16: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufEnumMap<SwiftProtobuf.ProtobufInt32,ProtobufUnittest_MapEnum>.self, value: &_storage._mapInt32Enum) }()
case 17: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufInt32,ProtobufUnittest_ForeignMessage>.self, value: &_storage._mapInt32ForeignMessage) }()
case 18: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufString,ProtobufUnittest_ForeignMessage>.self, value: &_storage._mapStringForeignMessage) }()
case 19: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufInt32,ProtobufUnittest_TestAllTypes>.self, value: &_storage._mapInt32AllTypes) }()
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if !_storage._mapInt32Int32.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufInt32>.self, value: _storage._mapInt32Int32, fieldNumber: 1)
}
if !_storage._mapInt64Int64.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt64,SwiftProtobuf.ProtobufInt64>.self, value: _storage._mapInt64Int64, fieldNumber: 2)
}
if !_storage._mapUint32Uint32.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufUInt32,SwiftProtobuf.ProtobufUInt32>.self, value: _storage._mapUint32Uint32, fieldNumber: 3)
}
if !_storage._mapUint64Uint64.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufUInt64,SwiftProtobuf.ProtobufUInt64>.self, value: _storage._mapUint64Uint64, fieldNumber: 4)
}
if !_storage._mapSint32Sint32.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSInt32,SwiftProtobuf.ProtobufSInt32>.self, value: _storage._mapSint32Sint32, fieldNumber: 5)
}
if !_storage._mapSint64Sint64.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSInt64,SwiftProtobuf.ProtobufSInt64>.self, value: _storage._mapSint64Sint64, fieldNumber: 6)
}
if !_storage._mapFixed32Fixed32.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufFixed32,SwiftProtobuf.ProtobufFixed32>.self, value: _storage._mapFixed32Fixed32, fieldNumber: 7)
}
if !_storage._mapFixed64Fixed64.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufFixed64,SwiftProtobuf.ProtobufFixed64>.self, value: _storage._mapFixed64Fixed64, fieldNumber: 8)
}
if !_storage._mapSfixed32Sfixed32.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSFixed32,SwiftProtobuf.ProtobufSFixed32>.self, value: _storage._mapSfixed32Sfixed32, fieldNumber: 9)
}
if !_storage._mapSfixed64Sfixed64.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSFixed64,SwiftProtobuf.ProtobufSFixed64>.self, value: _storage._mapSfixed64Sfixed64, fieldNumber: 10)
}
if !_storage._mapInt32Float.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufFloat>.self, value: _storage._mapInt32Float, fieldNumber: 11)
}
if !_storage._mapInt32Double.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufDouble>.self, value: _storage._mapInt32Double, fieldNumber: 12)
}
if !_storage._mapBoolBool.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufBool,SwiftProtobuf.ProtobufBool>.self, value: _storage._mapBoolBool, fieldNumber: 13)
}
if !_storage._mapStringString.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufString,SwiftProtobuf.ProtobufString>.self, value: _storage._mapStringString, fieldNumber: 14)
}
if !_storage._mapInt32Bytes.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufBytes>.self, value: _storage._mapInt32Bytes, fieldNumber: 15)
}
if !_storage._mapInt32Enum.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufEnumMap<SwiftProtobuf.ProtobufInt32,ProtobufUnittest_MapEnum>.self, value: _storage._mapInt32Enum, fieldNumber: 16)
}
if !_storage._mapInt32ForeignMessage.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufInt32,ProtobufUnittest_ForeignMessage>.self, value: _storage._mapInt32ForeignMessage, fieldNumber: 17)
}
if !_storage._mapStringForeignMessage.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufString,ProtobufUnittest_ForeignMessage>.self, value: _storage._mapStringForeignMessage, fieldNumber: 18)
}
if !_storage._mapInt32AllTypes.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufInt32,ProtobufUnittest_TestAllTypes>.self, value: _storage._mapInt32AllTypes, fieldNumber: 19)
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestMap, rhs: ProtobufUnittest_TestMap) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._mapInt32Int32 != rhs_storage._mapInt32Int32 {return false}
if _storage._mapInt64Int64 != rhs_storage._mapInt64Int64 {return false}
if _storage._mapUint32Uint32 != rhs_storage._mapUint32Uint32 {return false}
if _storage._mapUint64Uint64 != rhs_storage._mapUint64Uint64 {return false}
if _storage._mapSint32Sint32 != rhs_storage._mapSint32Sint32 {return false}
if _storage._mapSint64Sint64 != rhs_storage._mapSint64Sint64 {return false}
if _storage._mapFixed32Fixed32 != rhs_storage._mapFixed32Fixed32 {return false}
if _storage._mapFixed64Fixed64 != rhs_storage._mapFixed64Fixed64 {return false}
if _storage._mapSfixed32Sfixed32 != rhs_storage._mapSfixed32Sfixed32 {return false}
if _storage._mapSfixed64Sfixed64 != rhs_storage._mapSfixed64Sfixed64 {return false}
if _storage._mapInt32Float != rhs_storage._mapInt32Float {return false}
if _storage._mapInt32Double != rhs_storage._mapInt32Double {return false}
if _storage._mapBoolBool != rhs_storage._mapBoolBool {return false}
if _storage._mapStringString != rhs_storage._mapStringString {return false}
if _storage._mapInt32Bytes != rhs_storage._mapInt32Bytes {return false}
if _storage._mapInt32Enum != rhs_storage._mapInt32Enum {return false}
if _storage._mapInt32ForeignMessage != rhs_storage._mapInt32ForeignMessage {return false}
if _storage._mapStringForeignMessage != rhs_storage._mapStringForeignMessage {return false}
if _storage._mapInt32AllTypes != rhs_storage._mapInt32AllTypes {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestMapSubmessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestMapSubmessage"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "test_map"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularMessageField(value: &self._testMap) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._testMap {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestMapSubmessage, rhs: ProtobufUnittest_TestMapSubmessage) -> Bool {
if lhs._testMap != rhs._testMap {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestMessageMap: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestMessageMap"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "map_int32_message"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufInt32,ProtobufUnittest_TestAllTypes>.self, value: &self.mapInt32Message) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.mapInt32Message.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufInt32,ProtobufUnittest_TestAllTypes>.self, value: self.mapInt32Message, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestMessageMap, rhs: ProtobufUnittest_TestMessageMap) -> Bool {
if lhs.mapInt32Message != rhs.mapInt32Message {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestSameTypeMap: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestSameTypeMap"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "map1"),
2: .same(proto: "map2"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufInt32>.self, value: &self.map1) }()
case 2: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufInt32>.self, value: &self.map2) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.map1.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufInt32>.self, value: self.map1, fieldNumber: 1)
}
if !self.map2.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufInt32>.self, value: self.map2, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestSameTypeMap, rhs: ProtobufUnittest_TestSameTypeMap) -> Bool {
if lhs.map1 != rhs.map1 {return false}
if lhs.map2 != rhs.map2 {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestRequiredMessageMap: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestRequiredMessageMap"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "map_field"),
]
public var isInitialized: Bool {
if !SwiftProtobuf.Internal.areAllInitialized(self.mapField) {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufInt32,ProtobufUnittest_TestRequired>.self, value: &self.mapField) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.mapField.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufInt32,ProtobufUnittest_TestRequired>.self, value: self.mapField, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestRequiredMessageMap, rhs: ProtobufUnittest_TestRequiredMessageMap) -> Bool {
if lhs.mapField != rhs.mapField {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestArenaMap: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestArenaMap"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "map_int32_int32"),
2: .standard(proto: "map_int64_int64"),
3: .standard(proto: "map_uint32_uint32"),
4: .standard(proto: "map_uint64_uint64"),
5: .standard(proto: "map_sint32_sint32"),
6: .standard(proto: "map_sint64_sint64"),
7: .standard(proto: "map_fixed32_fixed32"),
8: .standard(proto: "map_fixed64_fixed64"),
9: .standard(proto: "map_sfixed32_sfixed32"),
10: .standard(proto: "map_sfixed64_sfixed64"),
11: .standard(proto: "map_int32_float"),
12: .standard(proto: "map_int32_double"),
13: .standard(proto: "map_bool_bool"),
14: .standard(proto: "map_string_string"),
15: .standard(proto: "map_int32_bytes"),
16: .standard(proto: "map_int32_enum"),
17: .standard(proto: "map_int32_foreign_message"),
]
fileprivate class _StorageClass {
var _mapInt32Int32: Dictionary<Int32,Int32> = [:]
var _mapInt64Int64: Dictionary<Int64,Int64> = [:]
var _mapUint32Uint32: Dictionary<UInt32,UInt32> = [:]
var _mapUint64Uint64: Dictionary<UInt64,UInt64> = [:]
var _mapSint32Sint32: Dictionary<Int32,Int32> = [:]
var _mapSint64Sint64: Dictionary<Int64,Int64> = [:]
var _mapFixed32Fixed32: Dictionary<UInt32,UInt32> = [:]
var _mapFixed64Fixed64: Dictionary<UInt64,UInt64> = [:]
var _mapSfixed32Sfixed32: Dictionary<Int32,Int32> = [:]
var _mapSfixed64Sfixed64: Dictionary<Int64,Int64> = [:]
var _mapInt32Float: Dictionary<Int32,Float> = [:]
var _mapInt32Double: Dictionary<Int32,Double> = [:]
var _mapBoolBool: Dictionary<Bool,Bool> = [:]
var _mapStringString: Dictionary<String,String> = [:]
var _mapInt32Bytes: Dictionary<Int32,Data> = [:]
var _mapInt32Enum: Dictionary<Int32,ProtobufUnittest_MapEnum> = [:]
var _mapInt32ForeignMessage: Dictionary<Int32,ProtobufUnittest_ForeignMessage> = [:]
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_mapInt32Int32 = source._mapInt32Int32
_mapInt64Int64 = source._mapInt64Int64
_mapUint32Uint32 = source._mapUint32Uint32
_mapUint64Uint64 = source._mapUint64Uint64
_mapSint32Sint32 = source._mapSint32Sint32
_mapSint64Sint64 = source._mapSint64Sint64
_mapFixed32Fixed32 = source._mapFixed32Fixed32
_mapFixed64Fixed64 = source._mapFixed64Fixed64
_mapSfixed32Sfixed32 = source._mapSfixed32Sfixed32
_mapSfixed64Sfixed64 = source._mapSfixed64Sfixed64
_mapInt32Float = source._mapInt32Float
_mapInt32Double = source._mapInt32Double
_mapBoolBool = source._mapBoolBool
_mapStringString = source._mapStringString
_mapInt32Bytes = source._mapInt32Bytes
_mapInt32Enum = source._mapInt32Enum
_mapInt32ForeignMessage = source._mapInt32ForeignMessage
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufInt32>.self, value: &_storage._mapInt32Int32) }()
case 2: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt64,SwiftProtobuf.ProtobufInt64>.self, value: &_storage._mapInt64Int64) }()
case 3: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufUInt32,SwiftProtobuf.ProtobufUInt32>.self, value: &_storage._mapUint32Uint32) }()
case 4: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufUInt64,SwiftProtobuf.ProtobufUInt64>.self, value: &_storage._mapUint64Uint64) }()
case 5: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSInt32,SwiftProtobuf.ProtobufSInt32>.self, value: &_storage._mapSint32Sint32) }()
case 6: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSInt64,SwiftProtobuf.ProtobufSInt64>.self, value: &_storage._mapSint64Sint64) }()
case 7: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufFixed32,SwiftProtobuf.ProtobufFixed32>.self, value: &_storage._mapFixed32Fixed32) }()
case 8: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufFixed64,SwiftProtobuf.ProtobufFixed64>.self, value: &_storage._mapFixed64Fixed64) }()
case 9: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSFixed32,SwiftProtobuf.ProtobufSFixed32>.self, value: &_storage._mapSfixed32Sfixed32) }()
case 10: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSFixed64,SwiftProtobuf.ProtobufSFixed64>.self, value: &_storage._mapSfixed64Sfixed64) }()
case 11: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufFloat>.self, value: &_storage._mapInt32Float) }()
case 12: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufDouble>.self, value: &_storage._mapInt32Double) }()
case 13: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufBool,SwiftProtobuf.ProtobufBool>.self, value: &_storage._mapBoolBool) }()
case 14: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufString,SwiftProtobuf.ProtobufString>.self, value: &_storage._mapStringString) }()
case 15: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufBytes>.self, value: &_storage._mapInt32Bytes) }()
case 16: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufEnumMap<SwiftProtobuf.ProtobufInt32,ProtobufUnittest_MapEnum>.self, value: &_storage._mapInt32Enum) }()
case 17: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufInt32,ProtobufUnittest_ForeignMessage>.self, value: &_storage._mapInt32ForeignMessage) }()
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if !_storage._mapInt32Int32.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufInt32>.self, value: _storage._mapInt32Int32, fieldNumber: 1)
}
if !_storage._mapInt64Int64.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt64,SwiftProtobuf.ProtobufInt64>.self, value: _storage._mapInt64Int64, fieldNumber: 2)
}
if !_storage._mapUint32Uint32.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufUInt32,SwiftProtobuf.ProtobufUInt32>.self, value: _storage._mapUint32Uint32, fieldNumber: 3)
}
if !_storage._mapUint64Uint64.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufUInt64,SwiftProtobuf.ProtobufUInt64>.self, value: _storage._mapUint64Uint64, fieldNumber: 4)
}
if !_storage._mapSint32Sint32.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSInt32,SwiftProtobuf.ProtobufSInt32>.self, value: _storage._mapSint32Sint32, fieldNumber: 5)
}
if !_storage._mapSint64Sint64.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSInt64,SwiftProtobuf.ProtobufSInt64>.self, value: _storage._mapSint64Sint64, fieldNumber: 6)
}
if !_storage._mapFixed32Fixed32.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufFixed32,SwiftProtobuf.ProtobufFixed32>.self, value: _storage._mapFixed32Fixed32, fieldNumber: 7)
}
if !_storage._mapFixed64Fixed64.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufFixed64,SwiftProtobuf.ProtobufFixed64>.self, value: _storage._mapFixed64Fixed64, fieldNumber: 8)
}
if !_storage._mapSfixed32Sfixed32.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSFixed32,SwiftProtobuf.ProtobufSFixed32>.self, value: _storage._mapSfixed32Sfixed32, fieldNumber: 9)
}
if !_storage._mapSfixed64Sfixed64.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufSFixed64,SwiftProtobuf.ProtobufSFixed64>.self, value: _storage._mapSfixed64Sfixed64, fieldNumber: 10)
}
if !_storage._mapInt32Float.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufFloat>.self, value: _storage._mapInt32Float, fieldNumber: 11)
}
if !_storage._mapInt32Double.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufDouble>.self, value: _storage._mapInt32Double, fieldNumber: 12)
}
if !_storage._mapBoolBool.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufBool,SwiftProtobuf.ProtobufBool>.self, value: _storage._mapBoolBool, fieldNumber: 13)
}
if !_storage._mapStringString.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufString,SwiftProtobuf.ProtobufString>.self, value: _storage._mapStringString, fieldNumber: 14)
}
if !_storage._mapInt32Bytes.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufBytes>.self, value: _storage._mapInt32Bytes, fieldNumber: 15)
}
if !_storage._mapInt32Enum.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufEnumMap<SwiftProtobuf.ProtobufInt32,ProtobufUnittest_MapEnum>.self, value: _storage._mapInt32Enum, fieldNumber: 16)
}
if !_storage._mapInt32ForeignMessage.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufInt32,ProtobufUnittest_ForeignMessage>.self, value: _storage._mapInt32ForeignMessage, fieldNumber: 17)
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestArenaMap, rhs: ProtobufUnittest_TestArenaMap) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._mapInt32Int32 != rhs_storage._mapInt32Int32 {return false}
if _storage._mapInt64Int64 != rhs_storage._mapInt64Int64 {return false}
if _storage._mapUint32Uint32 != rhs_storage._mapUint32Uint32 {return false}
if _storage._mapUint64Uint64 != rhs_storage._mapUint64Uint64 {return false}
if _storage._mapSint32Sint32 != rhs_storage._mapSint32Sint32 {return false}
if _storage._mapSint64Sint64 != rhs_storage._mapSint64Sint64 {return false}
if _storage._mapFixed32Fixed32 != rhs_storage._mapFixed32Fixed32 {return false}
if _storage._mapFixed64Fixed64 != rhs_storage._mapFixed64Fixed64 {return false}
if _storage._mapSfixed32Sfixed32 != rhs_storage._mapSfixed32Sfixed32 {return false}
if _storage._mapSfixed64Sfixed64 != rhs_storage._mapSfixed64Sfixed64 {return false}
if _storage._mapInt32Float != rhs_storage._mapInt32Float {return false}
if _storage._mapInt32Double != rhs_storage._mapInt32Double {return false}
if _storage._mapBoolBool != rhs_storage._mapBoolBool {return false}
if _storage._mapStringString != rhs_storage._mapStringString {return false}
if _storage._mapInt32Bytes != rhs_storage._mapInt32Bytes {return false}
if _storage._mapInt32Enum != rhs_storage._mapInt32Enum {return false}
if _storage._mapInt32ForeignMessage != rhs_storage._mapInt32ForeignMessage {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_MessageContainingEnumCalledType: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".MessageContainingEnumCalledType"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "type"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufString,ProtobufUnittest_MessageContainingEnumCalledType>.self, value: &self.type) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.type.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufString,ProtobufUnittest_MessageContainingEnumCalledType>.self, value: self.type, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_MessageContainingEnumCalledType, rhs: ProtobufUnittest_MessageContainingEnumCalledType) -> Bool {
if lhs.type != rhs.type {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_MessageContainingEnumCalledType.TypeEnum: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
0: .same(proto: "TYPE_FOO"),
]
}
extension ProtobufUnittest_MessageContainingMapCalledEntry: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".MessageContainingMapCalledEntry"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "entry"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufInt32>.self, value: &self.entry) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.entry.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufInt32,SwiftProtobuf.ProtobufInt32>.self, value: self.entry, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_MessageContainingMapCalledEntry, rhs: ProtobufUnittest_MessageContainingMapCalledEntry) -> Bool {
if lhs.entry != rhs.entry {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestRecursiveMapMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestRecursiveMapMessage"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "a"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufString,ProtobufUnittest_TestRecursiveMapMessage>.self, value: &self.a) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.a.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufString,ProtobufUnittest_TestRecursiveMapMessage>.self, value: self.a, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestRecursiveMapMessage, rhs: ProtobufUnittest_TestRecursiveMapMessage) -> Bool {
if lhs.a != rhs.a {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| apache-2.0 |
NikKovIos/NKVPhonePicker | Example/AppDelegate.swift | 1 | 178 | //
// Be happy and free :)
//
// Nik Kov
// nik-kov.com
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
| mit |
yaobanglin/viossvc | viossvc/Scenes/User/MyServerViewController.swift | 2 | 7215 | //
// MyServerViewController.swift
// viossvc
//
// Created by 木柳 on 2016/12/1.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import UIKit
class MyServerViewController: BaseTableViewController, LayoutStopDelegate, RefreshSkillDelegate{
@IBOutlet weak var zhimaAnthIcon: UIImageView!
@IBOutlet weak var idAuthIcon: UIImageView!
@IBOutlet weak var headerImage: UIImageView!
@IBOutlet weak var headerContent: UIView!
@IBOutlet weak var picAuthLabel: UILabel!
@IBOutlet weak var bgImage: UIImageView!
@IBOutlet weak var skillView: SkillLayoutView!
@IBOutlet weak var serverTabel: ServerTableView!
@IBOutlet weak var serverTabelCell: UITableViewCell!
var currentSkillsArray:Array<SkillsModel>?
var allSkillArray:Array<SkillsModel>?
var skillDict:Dictionary<Int, SkillsModel> = [:]
@IBOutlet weak var pictureCollection: UserPictureCollectionView!
var markHeight: CGFloat = 0
var serverHeight: CGFloat = 0
var pictureHeight: CGFloat = 0
var serverData: [UserServerModel] = []
//MARK: --LIFECYCLE
override func viewDidLoad() {
super.viewDidLoad()
initUI()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
initData()
}
//MARK: --DATA
func initData() {
//我的技能标签
getUserSkills()
getAllSkills()
//我的服务
AppAPIHelper.userAPI().serviceList({ [weak self](result) in
if result == nil {
return
}
self?.serverData = result as! [UserServerModel]
self?.serverTabel.updateData(result, complete: { (height) in
self?.serverHeight = height as! CGFloat
self?.tableView.reloadData()
})
}, error: errorBlockFunc())
//我的相册
let requestModel = PhotoWallRequestModel()
requestModel.uid = CurrentUserHelper.shared.userInfo.uid
requestModel.size = 12
requestModel.num = 1
AppAPIHelper.userAPI().photoWallRequest(requestModel, complete: {[weak self] (result) in
if result == nil{
return
}
let model: PhotoWallModel = result as! PhotoWallModel
self?.pictureCollection.updateMyPicture(model.photo_list) {[weak self] (height) in
self?.pictureHeight = height as! CGFloat
self?.tableView.reloadData()
}
}, error: errorBlockFunc())
}
func getUserSkills() {
guard CurrentUserHelper.shared.userInfo.skills == nil else {return}
unowned let weakSelf = self
AppAPIHelper.userAPI().getOrModfyUserSkills(0, skills: "", complete: { (response) in
if response != nil {
let dict = response as! Dictionary<String, AnyObject>
CurrentUserHelper.shared.userInfo.skills = dict["skills_"] as? String
if weakSelf.skillDict.count > 0 {
weakSelf.currentSkillsArray = AppAPIHelper.orderAPI().getSKillsWithModel(CurrentUserHelper.shared.userInfo.skills, dict:weakSelf.skillDict )
weakSelf.skillView.dataSouce = weakSelf.currentSkillsArray
}
}
}, error: errorBlockFunc())
}
func getAllSkills() {
unowned let weakSelf = self
AppAPIHelper.orderAPI().getSkills({ (response) in
let array = response as? Array<SkillsModel>
weakSelf.allSkillArray = array
for skill in array! {
let size = skill.skill_name!.boundingRectWithSize(CGSizeMake(0, 21), font: UIFont.systemFontOfSize(15), lineSpacing: 0)
skill.labelWidth = size.width + 30
weakSelf.skillDict[skill.skill_id] = skill
}
if CurrentUserHelper.shared.userInfo.skills != nil {
weakSelf.currentSkillsArray = AppAPIHelper.orderAPI().getSKillsWithModel(CurrentUserHelper.shared.userInfo.skills, dict:weakSelf.skillDict )
weakSelf.skillView.dataSouce = weakSelf.currentSkillsArray
}
}, error: errorBlockFunc())
}
//MARK: --UI
func initUI() {
headerImage.layer.cornerRadius = headerImage.frame.size.width * 0.5
headerImage.layer.masksToBounds = true
headerImage.layer.borderColor = UIColor(RGBHex: 0xb82624).CGColor
headerImage.layer.borderWidth = 2
skillView.showDelete = false
skillView.collectionView?.backgroundColor = UIColor(RGBHex: 0xf2f2f2)
skillView.delegate = self
//headerView
if (CurrentUserHelper.shared.userInfo.head_url != nil){
let headUrl = NSURL.init(string: CurrentUserHelper.shared.userInfo.head_url!)
headerImage.kf_setImageWithURL(headUrl, placeholderImage: UIImage.init(named: "head_boy"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
if CurrentUserHelper.shared.userInfo.praise_lv > 0 {
for i in 100...104 {
if i <= 100 + CurrentUserHelper.shared.userInfo.praise_lv {
let starImage: UIImageView = headerContent.viewWithTag(i) as! UIImageView
starImage.image = UIImage.init(named: "star-common-fill")
}
}
}
idAuthIcon.hidden = !(CurrentUserHelper.shared.userInfo.auth_status_ == 1)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
return 215
}
if indexPath.section == 1 && indexPath.row == 1 {
return markHeight
}
if indexPath.section == 2 && indexPath.row == 1 {
return serverHeight
}
if indexPath.section == 3 && indexPath.row == 1 {
return pictureHeight
}
return 44
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == SMSServerViewController.className() {
let controller = segue.destinationViewController as! SMSServerViewController
controller.serverData = serverData
} else if segue.identifier == MarksTableViewController.className() {
let marksVC = segue.destinationViewController as! MarksTableViewController
marksVC.allSkillArray = allSkillArray
marksVC.currentSkillsArray = currentSkillsArray
marksVC.skillDict = skillDict
marksVC.delegate = self
}
}
func refreshUserSkill() {
currentSkillsArray = AppAPIHelper.orderAPI().getSKillsWithModel(CurrentUserHelper.shared.userInfo.skills, dict:skillDict )
skillView.dataSouce = currentSkillsArray
}
/**
skillView 高度回调
- parameter layoutView:
- parameter height:
*/
func layoutStopWithHeight(layoutView: SkillLayoutView, height: CGFloat) {
markHeight = height
tableView.reloadData()
}
}
| apache-2.0 |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Components/SelectionScreen/FiatCurrency/FiatCurrencySelectionService.swift | 1 | 1266 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import MoneyKit
import PlatformKit
import RxRelay
import RxSwift
extension Notification.Name {
public static let fiatCurrencySelected = Notification.Name("fiat_currency_selected")
}
public final class FiatCurrencySelectionService: SelectionServiceAPI {
public var dataSource: Observable<[SelectionItemViewModel]> {
provider.currencies
.map { $0.map(\.selectionItem).sorted() }
}
public let selectedDataRelay: BehaviorRelay<SelectionItemViewModel>
public var selectedData: Observable<SelectionItemViewModel> {
selectedDataRelay.distinctUntilChanged()
}
private let provider: FiatCurrencySelectionProviderAPI
public init(
defaultSelectedData: FiatCurrency = .locale,
provider: FiatCurrencySelectionProviderAPI = DefaultFiatCurrencySelectionProvider()
) {
self.provider = provider
selectedDataRelay = BehaviorRelay(value: defaultSelectedData.selectionItem)
}
}
extension FiatCurrency {
fileprivate var selectionItem: SelectionItemViewModel {
SelectionItemViewModel(
id: code,
title: name,
subtitle: code,
thumb: .none
)
}
}
| lgpl-3.0 |
460467069/smzdm | 什么值得买7.1.1版本/什么值得买(5月12日)/Classes/Home(首页)/BaiCai(白菜专区)/View/ZZBaiCaiTableHeaderView.swift | 1 | 7390 | //
// ZZBaiCaiTableheaderView.swift
// 什么值得买
//
// Created by Wang_ruzhou on 2016/11/23.
// Copyright © 2016年 Wang_ruzhou. All rights reserved.
//
import UIKit
import YYText
class ZZBaiCaiItemOne: UIView { //每日精选和白菜头条
lazy var iconView: UIImageView = { //图片
let iconView = UIImageView()
iconView.width = baiCaiConstant.imageWH1
iconView.height = baiCaiConstant.imageWH1
iconView.top = baiCaiConstant.imageInset1
iconView.left = baiCaiConstant.imageInset1
iconView.contentMode = .scaleAspectFit
return iconView
}()
lazy var titleLabel: YYLabel = { //标题
let titleLabel = YYLabel()
titleLabel.numberOfLines = 2
titleLabel.width = baiCaiConstant.imageWH1
titleLabel.left = baiCaiConstant.imageInset1
titleLabel.height = baiCaiConstant.titleLabelHeight1
titleLabel.textVerticalAlignment = .bottom
return titleLabel
}()
lazy var subTitleLabel: YYLabel = { //子标题(可能为时间, 可能为价格)
let subTitleLabel = YYLabel()
subTitleLabel.numberOfLines = 1
subTitleLabel.width = baiCaiConstant.imageWH1
subTitleLabel.left = baiCaiConstant.imageInset1
subTitleLabel.height = baiCaiConstant.priceLabelHeight1
subTitleLabel.textVerticalAlignment = .top
return subTitleLabel
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.white
isUserInteractionEnabled = true
layer.cornerRadius = 3.0
addSubview(iconView)
addSubview(titleLabel)
addSubview(subTitleLabel)
titleLabel.top = iconView.bottom + baiCaiConstant.titleLabelTop1
subTitleLabel.top = titleLabel.bottom + baiCaiConstant.priceLabelTop1
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var baiCaiItemLayout: ZZBaiCaiItemLayout? {
didSet {
guard let baiCaiItemLayout = baiCaiItemLayout else { return }
iconView.zdm_setImage(urlStr: baiCaiItemLayout.worthyArticle?.article_pic, placeHolder: nil)
titleLabel.textLayout = baiCaiItemLayout.titleLayout
subTitleLabel.textLayout = baiCaiItemLayout.subTitleLayout
titleLabel.lineBreakMode = .byTruncatingTail
subTitleLabel.lineBreakMode = .byTruncatingTail
}
}
}
class ZZBaiCaiJingXuanView: UIView {
lazy var baiCaiBannerView: ZZBaiCaiBannerView = {
let baiCaiBannerView = Bundle.main.loadNibNamed("ZZBaiCaiBannerView", owner: nil, options: nil)?.last as! ZZBaiCaiBannerView
baiCaiBannerView.backgroundColor = UIColor.clear
return baiCaiBannerView
}()
lazy var scrollView: ZZHaoWuScrollView = {
let scrollView = ZZHaoWuScrollView()
return scrollView
}()
var delegete: ZZJumpToNextControllerDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
width = kScreenWidth
height = baiCaiConstant.rowHeight1
initUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initUI() {
addSubview(baiCaiBannerView)
addSubview(scrollView)
baiCaiBannerView.width = width
baiCaiBannerView.height = baiCaiConstant.bannerViewheight
scrollView.top = baiCaiBannerView.bottom
scrollView.height = baiCaiConstant.itemHeight1
scrollView.width = width
for i in 0..<baiCaiConstant.itemMaxCount {
let baiCaiItemOne = ZZBaiCaiItemOne()
baiCaiItemOne.width = baiCaiConstant.itemWidth1
baiCaiItemOne.height = baiCaiConstant.itemHeight1
baiCaiItemOne.left = baiCaiConstant.itemMargin + (baiCaiConstant.itemMargin + baiCaiConstant.itemWidth1) * CGFloat(i)
baiCaiItemOne.tag = i
scrollView.addSubview(baiCaiItemOne)
scrollView.haowuItems.append(baiCaiItemOne)
let tapGestureRecongnizer = UITapGestureRecognizer.init(target: self, action: #selector(itemDidClick(tap:)))
baiCaiItemOne.addGestureRecognizer(tapGestureRecongnizer)
}
}
@objc func itemDidClick(tap:UITapGestureRecognizer) {
let baiCaiItemOne = tap.view as! ZZBaiCaiItemOne
let redirectData = jingXuanTextLayouts?[baiCaiItemOne.tag].worthyArticle?.redirect_data
delegete?.jumpToNextController?(redirectData: redirectData!)
}
var jingXuanTextLayouts: [ZZBaiCaiItemLayout]? {
didSet {
guard let jingXuanTextLayouts = jingXuanTextLayouts else { return }
let actualCount = jingXuanTextLayouts.count
for i in 0..<baiCaiConstant.itemMaxCount {
let baicaiItemOne = scrollView.haowuItems[i] as! ZZBaiCaiItemOne
if i < actualCount {
baicaiItemOne.isHidden = false
baicaiItemOne.baiCaiItemLayout = jingXuanTextLayouts[i]
} else {
baicaiItemOne.isHidden = true
}
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
print(baiCaiBannerView)
}
}
class ZZBaiCaiTableHeaderView: UIView {
lazy var jingXuanView: ZZBaiCaiJingXuanView = {
let jingXuanView = ZZBaiCaiJingXuanView()
return jingXuanView
}()
lazy var touTiaoView: ZZBaiCaiJingXuanView = {
let touTiaoView = ZZBaiCaiJingXuanView()
return touTiaoView
}()
var baiCaiLayout: ZZZuiXinBaiCaiLayout? {
didSet {
height = (baiCaiLayout?.rowHeight)!
guard let baiCaiLayout = baiCaiLayout else { return }
if baiCaiLayout.jingXuanTextLayouts.count > 0 {
jingXuanView.baiCaiBannerView.titleLabel.text = "每日精选"
jingXuanView.baiCaiBannerView.accessoryBtn.setTitle("查看更多", for: .normal)
jingXuanView.jingXuanTextLayouts = baiCaiLayout.jingXuanTextLayouts
jingXuanView.scrollView.contentSize = (baiCaiLayout.jingXuanScrollViewContentSize)!
}
if baiCaiLayout.touTiaoTextLayouts.count > 0 {
touTiaoView.top = jingXuanView.bottom
touTiaoView.baiCaiBannerView.titleLabel.text = "白菜头条"
touTiaoView.baiCaiBannerView.accessoryBtn.setTitle("", for: .normal)
touTiaoView.jingXuanTextLayouts = baiCaiLayout.touTiaoTextLayouts
touTiaoView.scrollView.contentSize = (baiCaiLayout.touTiaoScrollViewContentSize)!
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
width = kScreenWidth
initUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initUI() {
addSubview(jingXuanView)
addSubview(touTiaoView)
touTiaoView.top = jingXuanView.bottom
}
}
| mit |
itsaboutcode/WordPress-iOS | WordPress/WordPressTest/Services/PostServiceSelfHostedTests.swift | 1 | 5425 |
import Foundation
import Nimble
@testable import WordPress
/// Tests unique behaviors of self-hosted sites.
///
/// Most the time, self-hosted, WPCom, and Jetpack sites behave the same. So, these common tests
/// are currently in `PostServiceWPComTests`.
///
/// - SeeAlso: PostServiceWPComTests
///
class PostServiceSelfHostedTests: XCTestCase {
private var remoteMock: PostServiceXMLRPCMock!
private var service: PostService!
private var context: NSManagedObjectContext!
private let impossibleFailureBlock: (Error?) -> Void = { _ in
assertionFailure("This shouldn't happen.")
}
override func setUp() {
super.setUp()
context = TestContextManager().mainContext
remoteMock = PostServiceXMLRPCMock()
let remoteFactory = PostServiceRemoteFactoryMock()
remoteFactory.remoteToReturn = remoteMock
service = PostService(managedObjectContext: context, postServiceRemoteFactory: remoteFactory)
}
override func tearDown() {
super.tearDown()
service = nil
remoteMock = nil
context = nil
ContextManager.overrideSharedInstance(nil)
}
func testAutoSavingALocalDraftWillCallTheCreateEndpointInstead() {
// Arrange
let post = PostBuilder(context).drafted().with(remoteStatus: .local).build()
try! context.save()
remoteMock.remotePostToReturnOnCreatePost = createRemotePost(.draft)
// Act
waitUntil(timeout: DispatchTimeInterval.seconds(3)) { done in
self.service.autoSave(post, success: { _, _ in
done()
}, failure: self.impossibleFailureBlock)
}
// Assert
expect(self.remoteMock.invocationsCountOfCreatePost).to(equal(1))
expect(post.remoteStatus).to(equal(.sync))
}
/// Local drafts with `.published` status will be ignored.
func testAutoSavingALocallyPublishedDraftWillFail() {
// Arrange
let post = PostBuilder(context).published().with(remoteStatus: .local).build()
try! context.save()
// Act
var failureBlockCalled = false
waitUntil(timeout: DispatchTimeInterval.seconds(3)) { done in
self.service.autoSave(post, success: { _, _ in
done()
}, failure: { _ in
failureBlockCalled = true
done()
})
}
// Assert
expect(failureBlockCalled).to(beTrue())
expect(post.remoteStatus).to(equal(.failed))
expect(self.remoteMock.invocationsCountOfCreatePost).to(equal(0))
expect(self.remoteMock.invocationsCountOfUpdate).to(equal(0))
}
func testUploadWithForceDraftCreationWillUploadALocallyPublishedPostAsDraft() {
// This applies to scenarios where a published post that only exists locally previously
// failed to upload. If the user canceled the auto-upload confirmation
// (by pressing Cancel in the Post List), we will still upload the post as a draft.
// Arrange
let post = PostBuilder(context).with(status: .publish).with(remoteStatus: .local).with(title: "sequi").build()
try! context.save()
remoteMock.remotePostToReturnOnCreatePost = createRemotePost(.draft)
// Act
waitUntil(timeout: DispatchTimeInterval.seconds(2)) { done in
self.service.uploadPost(post, forceDraftIfCreating: true, success: { _ in
done()
}, failure: self.impossibleFailureBlock)
}
// Assert
expect(self.remoteMock.invocationsCountOfCreatePost).to(equal(1))
expect(post.remoteStatus).to(equal(.sync))
let submittedRemotePost: RemotePost = remoteMock.remotePostSubmittedOnCreatePostInvocation!
expect(submittedRemotePost.title).to(equal("sequi"))
expect(submittedRemotePost.status).to(equal(BasePost.Status.draft.rawValue))
}
private func createRemotePost(_ status: BasePost.Status = .draft) -> RemotePost {
let remotePost = RemotePost(siteID: 1,
status: status.rawValue,
title: "Tenetur im",
content: "Velit tempore rerum")!
remotePost.type = "qui"
return remotePost
}
}
private class PostServiceRemoteFactoryMock: PostServiceRemoteFactory {
var remoteToReturn: PostServiceRemote?
override func forBlog(_ blog: Blog) -> PostServiceRemote? {
return remoteToReturn
}
}
private class PostServiceXMLRPCMock: PostServiceRemoteXMLRPC {
var remotePostToReturnOnCreatePost: RemotePost?
private(set) var invocationsCountOfCreatePost = 0
private(set) var invocationsCountOfUpdate = 0
private(set) var remotePostSubmittedOnCreatePostInvocation: RemotePost?
override func update(_ post: RemotePost!, success: ((RemotePost?) -> Void)!, failure: ((Error?) -> Void)!) {
DispatchQueue.global().async {
self.invocationsCountOfUpdate += 1
success(nil)
}
}
override func createPost(_ post: RemotePost!, success: ((RemotePost?) -> Void)!, failure: ((Error?) -> Void)!) {
DispatchQueue.global().async {
self.remotePostSubmittedOnCreatePostInvocation = post
self.invocationsCountOfCreatePost += 1
success(self.remotePostToReturnOnCreatePost)
}
}
}
| gpl-2.0 |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Jetpack/Jetpack Restore/Restore Complete/JetpackRestoreFailedViewController.swift | 2 | 1425 | import UIKit
import CocoaLumberjack
import WordPressShared
import WordPressUI
class JetpackRestoreFailedViewController: BaseRestoreCompleteViewController {
// MARK: - Initialization
override init(site: JetpackSiteRef, activity: Activity) {
let restoreCompleteConfiguration = JetpackRestoreCompleteConfiguration(
title: NSLocalizedString("Restore Failed", comment: "Title for Jetpack Restore Failed screen"),
iconImage: .gridicon(.notice),
iconImageColor: .error,
messageTitle: NSLocalizedString("Unable to restore your site", comment: "Title for the Jetpack Restore Failed message."),
messageDescription: NSLocalizedString("Please try again later or contact support.", comment: "Description for the Jetpack Restore Failed message."),
primaryButtonTitle: NSLocalizedString("Done", comment: "Title for the button that will dismiss this view."),
secondaryButtonTitle: nil,
hint: nil
)
super.init(site: site, activity: activity, configuration: restoreCompleteConfiguration)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Override
override func primaryButtonTapped() {
self.dismiss(animated: true)
}
}
| gpl-2.0 |
wilfreddekok/Antidote | Antidote/StaticTableAvatarCellModel.swift | 1 | 494 | // 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
class StaticTableAvatarCellModel: StaticTableBaseCellModel {
struct Constants {
static let AvatarImageSize: CGFloat = 120.0
}
var avatar: UIImage?
var didTapOnAvatar: (StaticTableAvatarCell -> Void)?
var userInteractionEnabled: Bool = true
}
| mpl-2.0 |
kaxilisi/DouYu | DYZB/DYZB/Classes/Main/Model/AnchorGroup.swift | 1 | 933 | //
// AnchorGroup.swift
// DYZB
//
// Created by apple on 2016/10/28.
// Copyright © 2016年 apple. All rights reserved.
//
import UIKit
class AnchorGroup: NSObject {
/// 房间信息
var room_list : [[String : NSObject]]?{
didSet{
guard let room_list = room_list else {return}
for dict in room_list {
anchors.append(AnchorModel(dict))
}
}
}
/// 组显示标题
var tag_name : String = ""
/// 组显示图标
var icon_name : String = "home_header_normal"
///模型对象数据
lazy var anchors : [AnchorModel] = [AnchorModel]()
var push_vertical_screen : String = ""
override init(){
}
init(_ dict : [String :NSObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String){}
}
| mit |
uasys/swift | validation-test/compiler_crashers_fixed/00989-swift-typechecker-computecaptures.swift | 65 | 512 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
var f = 1
var e: Int -> Int = {
}
let d: Int = { c, b in
}(f, e)
struct g<g : e, f: e where f.h = c {
b let g: c
| apache-2.0 |
austinzheng/swift | test/decl/protocol/special/coding/class_codable_simple_extension.swift | 17 | 1478 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown -swift-version 4
// Non-final classes where Codable conformance is added in extensions should
// only be able to derive conformance for Encodable.
class SimpleClass { // expected-note {{did you mean 'init'?}}
var x: Int = 1
var y: Double = .pi
static var z: String = "foo"
func foo() {
// They should receive a synthesized CodingKeys enum.
let _ = SimpleClass.CodingKeys.self
// The enum should have a case for each of the vars.
let _ = SimpleClass.CodingKeys.x
let _ = SimpleClass.CodingKeys.y
// Static vars should not be part of the CodingKeys enum.
let _ = SimpleClass.CodingKeys.z // expected-error {{type 'SimpleClass.CodingKeys' has no member 'z'}}
}
}
extension SimpleClass : Codable {} // expected-error 2 {{implementation of 'Decodable' for non-final class cannot be automatically synthesized in extension because initializer requirement 'init(from:)' can only be be satisfied by a 'required' initializer in the class definition}}
// They should not receive synthesized init(from:), but should receive an encode(to:).
let _ = SimpleClass.init(from:) // expected-error {{type 'SimpleClass' has no member 'init(from:)'}}
let _ = SimpleClass.encode(to:)
// The synthesized CodingKeys type should not be accessible from outside the
// struct.
let _ = SimpleClass.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
| apache-2.0 |
paulz/PerspectiveTransform | Example/Specs/BasisVectorSpec.swift | 1 | 2426 | import Quick
import Nimble
import simd
import GameKit
@testable import PerspectiveTransform
let basisVectors = [Vector3(1, 0, 0),
Vector3(0, 1, 0),
Vector3(0, 0, 1),
Vector3(1, 1, 1)]
class BasisSpec: QuickSpec {
override func spec() {
let start = Quadrilateral(CGRect(origin: CGPoint.zero, size: CGSize(width: 152, height: 122)))
let destination = Quadrilateral(
CGRect(
origin: CGPoint(x: 100, y: 100),
size: CGSize(width: 200, height: 200)
)
)
context("multiply adj by vector") {
it("should match expected") {
let adjM = Matrix3x3([-122, -152, 18544, 122, 0, 0, 0, 152, 0])
let vector = Vector3([152, 122, 1])
let result = adjM * vector
let expected = Vector3([-18544, 18544, 18544])
expect(result).to(equal(expected))
}
}
context("basisVectorsToPointsMap") {
context("any 4 points") {
var points: [CGPoint]!
var subject: Matrix3x3!
let source = GKRandomSource.sharedRandom()
beforeEach {
points = source.nextFourPoints()
subject = Perspective(points).basisVectorsToPointsMap
}
it("should map base vectors to points") {
for (index, vector) in basisVectors.enumerated() {
let tranformed = subject * vector
expect(tranformed.dehomogenized) ≈ points[index]
}
}
}
it("should match expected") {
let startBasis = Matrix3x3([[0.0, 0.0, -1.0],
[152.0, 0.0, 1.0],
[0.0, 122.0, 1.0]])
expect(Perspective(start).basisVectorsToPointsMap) ≈ (startBasis, delta:0.5)
}
it("should work for destination") {
let destBasis = Matrix3x3([[-100.0, -100.0, -1.0],
[300.0, 100.0, 1.0],
[100.0, 300.0, 1.0]])
expect(Perspective(destination).basisVectorsToPointsMap) ≈ (destBasis, delta:0.5)
}
}
}
}
| mit |
apple/swift | test/IRGen/prespecialized-metadata/struct-outmodule-frozen-1argument-1distinct_use-struct-inmodule.swift | 16 | 4364 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-frozen-1argument.swift -emit-library -o %t/%target-library-name(Generic) -emit-module -module-name Generic -emit-module-path %t/Generic.swiftmodule -enable-library-evolution
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s -L %t -I %t -lGeneric | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s7Generic11OneArgumentVy4main03TheC0VGMN" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// : i8** getelementptr inbounds (
// : %swift.vwtable,
// : %swift.vwtable* @"
// CHECK-SAME: $s7Generic11OneArgumentVy4main03TheC0VGWV
// : ",
// : i32 0,
// : i32 0
// : ),
// CHECK-SAME: [[INT]] 512,
// CHECK-SAME: $s7Generic11OneArgumentVMn
// CHECK-SAME: %swift.type* bitcast (
// CHECK-SAME: [[INT]]* getelementptr inbounds (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: <{
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32
// CHECK-SAME: }>*,
// CHECK-SAME: i32,
// : [
// : 4 x i8
// : ],
// CHECK-SAME: i64
// CHECK-SAME: }>,
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: <{
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32
// CHECK-SAME: }>*,
// CHECK-SAME: i32,
// : [
// : 4 x i8
// : ],
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main11TheArgumentVMf",
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ) to %swift.type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 {{8|4}},
// TRAILING FLAGS: ...01
// ^ statically specialized canonical (false)
// ^ statically specialized (true)
// CHECK-SAME: i64 1
// CHECK-SAME: }>,
// CHECK-SAME: align [[ALIGNMENT]]
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
import Generic
struct TheArgument {
let value: Int
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: [[CANONICALIZED_METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @swift_getCanonicalSpecializedMetadata(
// CHECK-SAME: [[INT]] 0,
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s7Generic11OneArgumentVy4main03TheC0VGMN" to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ),
// CHECK-SAME: %swift.type** @"$s7Generic11OneArgumentVy4main03TheC0VGMJ"
// CHECK-SAME: )
// CHECK-NEXT: [[CANONICALIZED_METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[CANONICALIZED_METADATA_RESPONSE]], 0
// CHECK-NEXT: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}},
// CHECK-SAME: %swift.type* [[CANONICALIZED_METADATA]]
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( OneArgument(TheArgument(value: 13)) )
}
doit()
| apache-2.0 |
coinbase/coinbase-ios-sdk | Source/Extentions/RxSwift/SessionManager+Rx.swift | 1 | 757 | //
// Request+RxSwift.swift
// Coinbase
//
// Copyright © 2018 Coinbase, Inc. All rights reserved.
//
import RxSwift
#if !COCOAPODS
import CoinbaseSDK
#endif
// MARK: - RxSwift extension for Session Manager.
extension SessionManager {
/// Generates completion closure from with `SingleObserver`
///
/// - Parameters:
/// - single: `SingleObserver`
/// - event: `SingleEvent`
///
public static func completion<T>(with single: @escaping (_ event: SingleEvent<T>) -> Void) -> ((Result<T>) -> Void) {
return { result in
switch result {
case let .success(data): single(.success(data))
case let .failure(error): single(.error(error))
}
}
}
}
| apache-2.0 |
mlibai/XZKit | Projects/Example/CarouselViewExample/CarouselViewExample/CarouselViewExample/Example1/Example1SettingsContentModeOptionsViewController.swift | 1 | 1425 | //
// Example1SettingsContentModeOptionsViewController.swift
// CarouselViewExample
//
// Created by 徐臻 on 2019/4/28.
// Copyright © 2019 mlibai. All rights reserved.
//
import UIKit
import XZKit
protocol Example1SettingsContentModeOptionsViewControllerDelegate: NSObjectProtocol {
func contentModeOptionsViewController(_ viewController: Example1SettingsContentModeOptionsViewController, didSelect contentMode: UIView.ContentMode)
}
class Example1SettingsContentModeOptionsViewController: UITableViewController {
weak var delegate: Example1SettingsContentModeOptionsViewControllerDelegate?
var contentMode = UIView.ContentMode.redraw
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
if indexPath.row == contentMode.rawValue {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .disclosureIndicator
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let contentMode = UIView.ContentMode.init(rawValue: indexPath.row) {
delegate?.contentModeOptionsViewController(self, didSelect: contentMode)
navigationController?.popViewController(animated: true)
}
}
}
| mit |
Jakobeha/lAzR4t | lAzR4t Shared/Code/Grid/Elem/ElemToController.swift | 1 | 317 | //
// ElemToController.swift
// lAzR4t
//
// Created by Jakob Hain on 9/30/17.
// Copyright © 2017 Jakob Hain. All rights reserved.
//
import Foundation
///Provides a way to create an element controller for this.
protocol ElemToController where Self: Elem {
func makeController() -> ElemController<Self>
}
| mit |
dminones/reddit-ios-client | RedditIOSClient/Client/Link.swift | 1 | 2378 | //
// Link.swift
// RedditIOSClient
//
// Created by Dario Miñones on 4/4/17.
// Copyright © 2017 Dario Miñones. All rights reserved.
//
import Foundation
class Link: NSObject, NSCoding {
let title: String
let author: String
let thumbnail: String?
var imageUrl: String?
let createdUTC: NSDate
let numComments: Int?
//MARK: NSCoding protocol methods
func encode(with aCoder: NSCoder){
aCoder.encode(self.title, forKey: "title")
aCoder.encode(self.author, forKey: "author")
aCoder.encode(self.thumbnail, forKey: "thumbnail")
aCoder.encode(self.imageUrl, forKey: "imageUrl")
aCoder.encode(self.createdUTC, forKey: "createdUTC")
aCoder.encode(self.numComments, forKey: "numComments")
}
required init(coder decoder: NSCoder) {
self.title = decoder.decodeObject(forKey: "title") as! String
self.author = decoder.decodeObject(forKey: "author") as! String
self.thumbnail = decoder.decodeObject(forKey: "thumbnail") as? String
self.imageUrl = decoder.decodeObject(forKey: "imageUrl") as? String
self.createdUTC = (decoder.decodeObject(forKey: "createdUTC") as? NSDate)!
self.numComments = decoder.decodeObject(forKey: "numComments") as? Int
}
init?(json: [String: Any]) {
let jsonData = json["data"] as? [String: Any]
guard let title = jsonData?["title"] as? String,
let author = jsonData?["author"] as? String,
let thumbnail = jsonData?["thumbnail"] as? String,
let createdUTC = jsonData?["created_utc"] as? Int,
let numComments = jsonData?["num_comments"] as? Int
else {
return nil
}
if let preview = jsonData?["preview"] as! [String: Any]?{
//print("preview \(preview)")
if let images = (preview["images"] as! [Any]?){
let image = images.first as! [String: Any]?
if let source = image?["source"] as! [String:Any]? {
self.imageUrl = source["url"] as? String
}
}
}
self.title = title
self.author = author
self.thumbnail = thumbnail
self.createdUTC = NSDate(timeIntervalSince1970: Double(createdUTC))
self.numComments = numComments
}
}
| mit |
vbudhram/firefox-ios | Client/Frontend/Browser/TopTabsViewController.swift | 1 | 24385 | /* 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 Storage
import WebKit
struct TopTabsUX {
static let TopTabsViewHeight: CGFloat = 44
static let TopTabsBackgroundShadowWidth: CGFloat = 12
static let TabWidth: CGFloat = 190
static let FaderPading: CGFloat = 8
static let SeparatorWidth: CGFloat = 1
static let HighlightLineWidth: CGFloat = 3
static let TabNudge: CGFloat = 1 // Nudge the favicon and close button by 1px
static let TabTitlePadding: CGFloat = 10
static let AnimationSpeed: TimeInterval = 0.1
static let SeparatorYOffset: CGFloat = 7
static let SeparatorHeight: CGFloat = 32
}
protocol TopTabsDelegate: class {
func topTabsDidPressTabs()
func topTabsDidPressNewTab(_ isPrivate: Bool)
func topTabsDidTogglePrivateMode()
func topTabsDidChangeTab()
}
protocol TopTabCellDelegate: class {
func tabCellDidClose(_ cell: TopTabCell)
}
class TopTabsViewController: UIViewController {
let tabManager: TabManager
weak var delegate: TopTabsDelegate?
fileprivate var isPrivate = false
lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: TopTabsViewLayout())
collectionView.register(TopTabCell.self, forCellWithReuseIdentifier: TopTabCell.Identifier)
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.bounces = false
collectionView.clipsToBounds = false
collectionView.accessibilityIdentifier = "Top Tabs View"
return collectionView
}()
fileprivate lazy var tabsButton: TabsButton = {
let tabsButton = TabsButton.tabTrayButton()
tabsButton.addTarget(self, action: #selector(TopTabsViewController.tabsTrayTapped), for: .touchUpInside)
tabsButton.accessibilityIdentifier = "TopTabsViewController.tabsButton"
return tabsButton
}()
fileprivate lazy var newTab: UIButton = {
let newTab = UIButton.newTabButton()
newTab.addTarget(self, action: #selector(TopTabsViewController.newTabTapped), for: .touchUpInside)
return newTab
}()
lazy var privateModeButton: PrivateModeButton = {
let privateModeButton = PrivateModeButton()
privateModeButton.light = true
privateModeButton.addTarget(self, action: #selector(TopTabsViewController.togglePrivateModeTapped), for: .touchUpInside)
return privateModeButton
}()
fileprivate lazy var tabLayoutDelegate: TopTabsLayoutDelegate = {
let delegate = TopTabsLayoutDelegate()
delegate.tabSelectionDelegate = self
return delegate
}()
fileprivate var tabsToDisplay: [Tab] {
return self.isPrivate ? tabManager.privateTabs : tabManager.normalTabs
}
// Handle animations.
fileprivate var tabStore: [Tab] = [] //the actual datastore
fileprivate var pendingUpdatesToTabs: [Tab] = [] //the datastore we are transitioning to
fileprivate var needReloads: [Tab?] = [] // Tabs that need to be reloaded
fileprivate var isUpdating = false
fileprivate var pendingReloadData = false
fileprivate var oldTabs: [Tab]? // The last state of the tabs before an animation
fileprivate weak var oldSelectedTab: Tab? // Used to select the right tab when transitioning between private/normal tabs
private var tabObservers: TabObservers!
init(tabManager: TabManager) {
self.tabManager = tabManager
super.init(nibName: nil, bundle: nil)
collectionView.dataSource = self
collectionView.delegate = tabLayoutDelegate
[UICollectionElementKindSectionHeader, UICollectionElementKindSectionFooter].forEach {
collectionView.register(TopTabsHeaderFooter.self, forSupplementaryViewOfKind: $0, withReuseIdentifier: "HeaderFooter")
}
self.tabObservers = registerFor(.didLoadFavicon, queue: .main)
}
deinit {
self.tabManager.removeDelegate(self)
unregister(tabObservers)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if self.tabsToDisplay != self.tabStore {
self.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
tabManager.addDelegate(self)
self.tabStore = self.tabsToDisplay
if #available(iOS 11.0, *) {
collectionView.dragDelegate = self
collectionView.dropDelegate = self
}
let topTabFader = TopTabFader()
view.addSubview(topTabFader)
topTabFader.addSubview(collectionView)
view.addSubview(tabsButton)
view.addSubview(newTab)
view.addSubview(privateModeButton)
newTab.snp.makeConstraints { make in
make.centerY.equalTo(view)
make.trailing.equalTo(tabsButton.snp.leading).offset(-10)
make.size.equalTo(view.snp.height)
}
tabsButton.snp.makeConstraints { make in
make.centerY.equalTo(view)
make.trailing.equalTo(view).offset(-10)
make.size.equalTo(view.snp.height)
}
privateModeButton.snp.makeConstraints { make in
make.centerY.equalTo(view)
make.leading.equalTo(view).offset(10)
make.size.equalTo(view.snp.height)
}
topTabFader.snp.makeConstraints { make in
make.top.bottom.equalTo(view)
make.leading.equalTo(privateModeButton.snp.trailing)
make.trailing.equalTo(newTab.snp.leading)
}
collectionView.snp.makeConstraints { make in
make.edges.equalTo(topTabFader)
}
view.backgroundColor = UIColor.Defaults.Grey80
tabsButton.applyTheme(.Normal)
if let currentTab = tabManager.selectedTab {
applyTheme(currentTab.isPrivate ? .Private : .Normal)
}
updateTabCount(tabStore.count, animated: false)
}
func switchForegroundStatus(isInForeground reveal: Bool) {
// Called when the app leaves the foreground to make sure no information is inadvertently revealed
if let cells = self.collectionView.visibleCells as? [TopTabCell] {
let alpha: CGFloat = reveal ? 1 : 0
for cell in cells {
cell.titleText.alpha = alpha
cell.favicon.alpha = alpha
}
}
}
func updateTabCount(_ count: Int, animated: Bool = true) {
self.tabsButton.updateTabCount(count, animated: animated)
}
func tabsTrayTapped() {
delegate?.topTabsDidPressTabs()
}
func newTabTapped() {
if pendingReloadData {
return
}
self.delegate?.topTabsDidPressNewTab(self.isPrivate)
LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "Add tab button in the URL Bar on iPad" as AnyObject])
}
func togglePrivateModeTapped() {
if isUpdating || pendingReloadData {
return
}
let isPrivate = self.isPrivate
delegate?.topTabsDidTogglePrivateMode()
self.pendingReloadData = true // Stops animations from happening
let oldSelectedTab = self.oldSelectedTab
self.oldSelectedTab = tabManager.selectedTab
self.privateModeButton.setSelected(!isPrivate, animated: true)
//if private tabs is empty and we are transitioning to it add a tab
if tabManager.privateTabs.isEmpty && !isPrivate {
tabManager.addTab(isPrivate: true)
}
//get the tabs from which we will select which one to nominate for tribute (selection)
//the isPrivate boolean still hasnt been flipped. (It'll be flipped in the BVC didSelectedTabChange method)
let tabs = !isPrivate ? tabManager.privateTabs : tabManager.normalTabs
if let tab = oldSelectedTab, tabs.index(of: tab) != nil {
tabManager.selectTab(tab)
} else {
tabManager.selectTab(tabs.last)
}
}
func scrollToCurrentTab(_ animated: Bool = true, centerCell: Bool = false) {
assertIsMainThread("Only animate on the main thread")
guard let currentTab = tabManager.selectedTab, let index = tabStore.index(of: currentTab), !collectionView.frame.isEmpty else {
return
}
if let frame = collectionView.layoutAttributesForItem(at: IndexPath(row: index, section: 0))?.frame {
if centerCell {
collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .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)
if animated {
UIView.animate(withDuration: TopTabsUX.AnimationSpeed, animations: {
self.collectionView.scrollRectToVisible(padFrame, animated: true)
})
} else {
collectionView.scrollRectToVisible(padFrame, animated: false)
}
}
}
}
}
extension TopTabsViewController: Themeable {
func applyTheme(_ theme: Theme) {
tabsButton.applyTheme(theme)
tabsButton.titleBackgroundColor = view.backgroundColor ?? UIColor.Defaults.Grey80
tabsButton.textColor = UIColor.Defaults.Grey40
isPrivate = (theme == Theme.Private)
privateModeButton.applyTheme(theme)
privateModeButton.tintColor = UIColor.TopTabs.PrivateModeTint.colorFor(theme)
privateModeButton.imageView?.tintColor = privateModeButton.tintColor
newTab.tintColor = UIColor.Defaults.Grey40
collectionView.backgroundColor = view.backgroundColor
}
}
extension TopTabsViewController: TopTabCellDelegate {
func tabCellDidClose(_ cell: TopTabCell) {
// Trying to remove tabs while animating can lead to crashes as indexes change. If updates are happening don't allow tabs to be removed.
guard let index = collectionView.indexPath(for: cell)?.item else {
return
}
let tab = tabStore[index]
if tabsToDisplay.index(of: tab) != nil {
tabManager.removeTab(tab)
}
}
}
extension TopTabsViewController: UICollectionViewDataSource {
@objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let index = indexPath.item
let tabCell = collectionView.dequeueReusableCell(withReuseIdentifier: TopTabCell.Identifier, for: indexPath) as! TopTabCell
tabCell.delegate = self
let tab = tabStore[index]
tabCell.style = tab.isPrivate ? .dark : .light
tabCell.titleText.text = tab.displayTitle
if tab.displayTitle.isEmpty {
if tab.webView?.url?.baseDomain?.contains("localhost") ?? true {
tabCell.titleText.text = Strings.AppMenuNewTabTitleString
} else {
tabCell.titleText.text = tab.webView?.url?.absoluteDisplayString
}
tabCell.accessibilityLabel = tab.url?.aboutComponent ?? ""
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 let siteURL = tab.url?.displayURL {
tabCell.favicon.setIcon(tab.displayFavicon, forURL: siteURL, completed: { (color, url) in
if siteURL == url {
tabCell.favicon.image = tabCell.favicon.image?.createScaled(CGSize(width: 15, height: 15))
tabCell.favicon.backgroundColor = color == .clear ? .white : color
tabCell.favicon.contentMode = .center
}
})
} else {
tabCell.favicon.image = UIImage(named: "defaultFavicon")
tabCell.favicon.contentMode = .scaleAspectFit
tabCell.favicon.backgroundColor = .clear
}
return tabCell
}
@objc func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tabStore.count
}
@objc func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderFooter", for: indexPath) as! TopTabsHeaderFooter
view.arrangeLine(kind)
return view
}
}
@available(iOS 11.0, *)
extension TopTabsViewController: UICollectionViewDragDelegate {
func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
let tab = tabStore[indexPath.item]
// Get the tab's current URL. If it is `nil`, check the `sessionData` since
// it may be a tab that has not been restored yet.
var url = tab.url
if url == nil, let sessionData = tab.sessionData {
let urls = sessionData.urls
let index = sessionData.currentPage + urls.count - 1
if index < urls.count {
url = urls[index]
}
}
// Ensure we actually have a URL for the tab being dragged and that the URL is not local.
// If not, just create an empty `NSItemProvider` so we can create a drag item with the
// `Tab` so that it can at still be re-ordered.
var itemProvider: NSItemProvider
if url != nil, !(url?.isLocal ?? true) {
itemProvider = NSItemProvider(contentsOf: url) ?? NSItemProvider()
} else {
itemProvider = NSItemProvider()
}
let dragItem = UIDragItem(itemProvider: itemProvider)
dragItem.localObject = tab
return [dragItem]
}
}
@available(iOS 11.0, *)
extension TopTabsViewController: UICollectionViewDropDelegate {
func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
guard let destinationIndexPath = coordinator.destinationIndexPath, let dragItem = coordinator.items.first?.dragItem, let tab = dragItem.localObject as? Tab, let sourceIndex = tabStore.index(of: tab) else {
return
}
collectionView.performBatchUpdates({
self.tabManager.moveTab(isPrivate: self.isPrivate, fromIndex: sourceIndex, toIndex: destinationIndexPath.item)
self.tabStore = self.tabsToDisplay
collectionView.moveItem(at: IndexPath(item: sourceIndex, section: 0), to: destinationIndexPath)
})
coordinator.drop(dragItem, toItemAt: destinationIndexPath)
}
func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
guard let _ = session.localDragSession else {
return UICollectionViewDropProposal(operation: .forbidden)
}
return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
}
}
extension TopTabsViewController: TabSelectionDelegate {
func didSelectTabAtIndex(_ index: Int) {
let tab = tabStore[index]
if tabsToDisplay.index(of: tab) != nil {
tabManager.selectTab(tab)
}
}
}
extension TopTabsViewController: TabEventHandler {
func tab(_ tab: Tab, didLoadFavicon favicon: Favicon?, with: Data?) {
assertIsMainThread("Animations can only be performed from the main thread")
if self.tabStore.index(of: tab) != nil {
self.needReloads.append(tab)
self.performTabUpdates()
}
}
}
// Collection Diff (animations)
extension TopTabsViewController {
struct TopTabChangeSet {
let reloads: Set<IndexPath>
let inserts: Set<IndexPath>
let deletes: Set<IndexPath>
init(reloadArr: [IndexPath], insertArr: [IndexPath], deleteArr: [IndexPath]) {
reloads = Set(reloadArr)
inserts = Set(insertArr)
deletes = Set(deleteArr)
}
var all: [Set<IndexPath>] {
return [inserts, reloads, deletes]
}
}
// create a TopTabChangeSet which is a snapshot of updates to perfrom on a collectionView
func calculateDiffWith(_ oldTabs: [Tab], to newTabs: [Tab], and reloadTabs: [Tab?]) -> TopTabChangeSet {
let inserts: [IndexPath] = newTabs.enumerated().flatMap { index, tab in
if oldTabs.index(of: tab) == nil {
return IndexPath(row: index, section: 0)
}
return nil
}
let deletes: [IndexPath] = oldTabs.enumerated().flatMap { index, tab in
if newTabs.index(of: tab) == nil {
return IndexPath(row: index, section: 0)
}
return nil
}
// Create based on what is visibile but filter out tabs we are about to insert/delete.
let reloads: [IndexPath] = reloadTabs.flatMap { tab in
guard let tab = tab, newTabs.index(of: tab) != nil else {
return nil
}
return IndexPath(row: newTabs.index(of: tab)!, section: 0)
}.filter { return inserts.index(of: $0) == nil && deletes.index(of: $0) == nil }
return TopTabChangeSet(reloadArr: reloads, insertArr: inserts, deleteArr: deletes)
}
func updateTabsFrom(_ oldTabs: [Tab]?, to newTabs: [Tab], on completion: (() -> Void)? = nil) {
assertIsMainThread("Updates can only be performed from the main thread")
guard let oldTabs = oldTabs, !self.isUpdating, !self.pendingReloadData else {
return
}
// Lets create our change set
let update = self.calculateDiffWith(oldTabs, to: newTabs, and: needReloads)
flushPendingChanges()
// If there are no changes. We have nothing to do
if update.all.every({ $0.isEmpty }) {
completion?()
return
}
// The actual update block. We update the dataStore right before we do the UI updates.
let updateBlock = {
self.tabStore = newTabs
self.collectionView.deleteItems(at: Array(update.deletes))
self.collectionView.insertItems(at: Array(update.inserts))
self.collectionView.reloadItems(at: Array(update.reloads))
}
//Lets lock any other updates from happening.
self.isUpdating = true
self.pendingUpdatesToTabs = newTabs // This var helps other mutations that might happen while updating.
// The actual update
UIView.animate(withDuration: TopTabsUX.AnimationSpeed, animations: {
self.collectionView.performBatchUpdates(updateBlock)
}) { (_) in
self.isUpdating = false
self.pendingUpdatesToTabs = []
// Sometimes there might be a pending reload. Lets do that.
if self.pendingReloadData {
return self.reloadData()
}
// There can be pending animations. Run update again to clear them.
let tabs = self.oldTabs ?? self.tabStore
self.updateTabsFrom(tabs, to: self.tabsToDisplay, on: {
if !update.inserts.isEmpty || !update.reloads.isEmpty {
self.scrollToCurrentTab()
}
})
}
}
fileprivate func flushPendingChanges() {
oldTabs = nil
needReloads.removeAll()
}
fileprivate func reloadData() {
assertIsMainThread("reloadData must only be called from main thread")
if self.isUpdating || self.collectionView.frame == CGRect.zero {
self.pendingReloadData = true
return
}
isUpdating = true
self.tabStore = self.tabsToDisplay
self.newTab.isUserInteractionEnabled = false
self.flushPendingChanges()
UIView.animate(withDuration: TopTabsUX.AnimationSpeed, animations: {
self.collectionView.reloadData()
self.collectionView.collectionViewLayout.invalidateLayout()
self.collectionView.layoutIfNeeded()
self.scrollToCurrentTab(true, centerCell: true)
}, completion: { (_) in
self.isUpdating = false
self.pendingReloadData = false
self.performTabUpdates()
self.newTab.isUserInteractionEnabled = true
})
}
}
extension TopTabsViewController: TabManagerDelegate {
// Because we don't know when we are about to transition to private mode
// check to make sure that the tab we are trying to add is being added to the right tab group
fileprivate func tabsMatchDisplayGroup(_ a: Tab?, b: Tab?) -> Bool {
if let a = a, let b = b, a.isPrivate == b.isPrivate {
return true
}
return false
}
func performTabUpdates() {
guard !isUpdating else {
return
}
let fromTabs = !self.pendingUpdatesToTabs.isEmpty ? self.pendingUpdatesToTabs : self.oldTabs
self.oldTabs = fromTabs ?? self.tabStore
if self.pendingReloadData && !isUpdating {
self.reloadData()
} else {
self.updateTabsFrom(self.oldTabs, to: self.tabsToDisplay)
}
}
// This helps make sure animations don't happen before the view is loaded.
fileprivate var isRestoring: Bool {
return self.tabManager.isRestoring || self.collectionView.frame == CGRect.zero
}
func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) {
if isRestoring {
return
}
if !tabsMatchDisplayGroup(selected, b: previous) {
self.reloadData()
} else {
self.needReloads.append(selected)
self.needReloads.append(previous)
performTabUpdates()
delegate?.topTabsDidChangeTab()
}
}
func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) {
// We need to store the earliest oldTabs. So if one already exists use that.
self.oldTabs = self.oldTabs ?? tabStore
}
func tabManager(_ tabManager: TabManager, didAddTab tab: Tab) {
if isRestoring || (tabManager.selectedTab != nil && !tabsMatchDisplayGroup(tab, b: tabManager.selectedTab)) {
return
}
performTabUpdates()
}
func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) {
// We need to store the earliest oldTabs. So if one already exists use that.
self.oldTabs = self.oldTabs ?? tabStore
}
func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab) {
if isRestoring {
return
}
// If we deleted the last private tab. We'll be switching back to normal browsing. Pause updates till then
if self.tabsToDisplay.isEmpty {
self.pendingReloadData = true
return
}
// dont want to hold a ref to a deleted tab
if tab === oldSelectedTab {
oldSelectedTab = nil
}
performTabUpdates()
}
func tabManagerDidRestoreTabs(_ tabManager: TabManager) {
self.reloadData()
}
func tabManagerDidAddTabs(_ tabManager: TabManager) {
self.reloadData()
}
func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) {
self.reloadData()
}
}
| mpl-2.0 |
Acidburn0zzz/firefox-ios | Client/Frontend/Home/GoogleTopSiteHelper.swift | 1 | 2258 | /* 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 Shared
import UIKit
import Storage
struct GoogleTopSiteConstants {
// A guid is required in the case the site might become a pinned site
public static let googleGUID = "DefaultGoogleGUID"
// US and rest of the world google urls
public static let usUrl = "https://www.google.com/webhp?client=firefox-b-1-m&channel=ts"
public static let rowUrl = "https://www.google.com/webhp?client=firefox-b-m&channel=ts"
}
class GoogleTopSiteHelper {
// No Google Top Site, it should be removed, if it already exists for invalid region
private let invalidRegion = ["CN", "RU", "TR", "KZ", "BY"]
private var prefs: Prefs
private var url: String? {
// Couldn't find a valid region hence returning a nil value for url
guard let regionCode = Locale.current.regionCode, !invalidRegion.contains(regionCode) else {
return nil
}
// Special case for US
if regionCode == "US" {
return GoogleTopSiteConstants.usUrl
}
return GoogleTopSiteConstants.rowUrl
}
var hasAdded: Bool {
get {
guard let value = prefs.boolForKey(PrefsKeys.GoogleTopSiteAddedKey) else {
return false
}
return value
}
set(value) {
prefs.setBool(value, forKey: PrefsKeys.GoogleTopSiteAddedKey)
}
}
var isHidden: Bool {
get {
guard let value = prefs.boolForKey(PrefsKeys.GoogleTopSiteHideKey) else {
return false
}
return value
}
set(value) {
prefs.setBool(value, forKey: PrefsKeys.GoogleTopSiteHideKey)
}
}
init(prefs: Prefs) {
self.prefs = prefs
}
func suggestedSiteData() -> PinnedSite? {
guard let url = self.url else {
return nil
}
let pinnedSite = PinnedSite(site: Site(url: url, title: "Google"))
pinnedSite.guid = GoogleTopSiteConstants.googleGUID
return pinnedSite
}
}
| mpl-2.0 |
apple/swift-corelibs-foundation | Sources/FoundationXML/CFAccess.swift | 1 | 481 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 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
//
#if canImport(SwiftFoundation)
import SwiftFoundation
#else
import Foundation
#endif
let CF = _NSCFXMLBridgeForFoundationXMLUseOnly()
| apache-2.0 |
devlucky/Kakapo | Examples/NewsFeed/NewsFeed/NewsFeedViewController.swift | 1 | 2605 | //
// NewsFeedViewController.swift
// NewsFeed
//
// Created by Alex Manzella on 08/07/16.
// Copyright © 2016 devlucky. All rights reserved.
//
import UIKit
import SnapKit
class NewsFeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let networkManager: NetworkManager = NetworkManager()
var posts: [Post] = [] {
didSet {
tableView.reloadData()
}
}
let tableView: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = UIColor(white: 0.96, alpha: 1)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
tableView.allowsSelection = false
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "NewsFeed"
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .compose, target: self, action: #selector(composePost))
tableView.register(PostTableViewCell.self, forCellReuseIdentifier: String(describing: PostTableViewCell.self))
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.edges.equalTo(view)
}
networkManager.postsDidChange.add { [weak self] (posts) in
self?.posts = posts
}
networkManager.requestNewsFeed()
}
@objc private func composePost() {
let vc = ComposeViewController(networkManager: networkManager)
let navigationController = UINavigationController(rootViewController: vc)
present(navigationController, animated: true, completion: nil)
}
// MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: PostTableViewCell.self), for: indexPath) as! PostTableViewCell
let post = posts[indexPath.row]
cell.configure(with: post) { [weak self] in
self?.networkManager.toggleLikeForPost(at: indexPath.row)
}
return cell
}
// MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
| mit |
suifengqjn/douyu | douyu/douyu/Classes/Home/Controller/RecommendController.swift | 1 | 4884 | //
// RecommendController.swift
// douyu
//
// Created by qianjn on 2016/12/8.
// Copyright © 2016年 SF. All rights reserved.
//
import UIKit
let kHomeItemMargin:CGFloat = 10
let kHomeItemWidth: CGFloat = (kScreenWidth - 3*kHomeItemMargin)/2
let kHomeItemNormalHeight: CGFloat = kHomeItemWidth * 3 / 4
let kHomeItemBeautyHeight: CGFloat = kHomeItemWidth * 4 / 3
let kHomeSectionHeaderHeight:CGFloat = 50
let kHomeCellIden = "kHomeCellIden"
let kHomeBeautyCellIden = "kHomeBeautyCellIden"
let kHomeHeaderIden = "kHomeHeaderIden"
class RecommendController: UIViewController {
lazy var recomVModel = RecommendViewModel()
lazy var cycleView : RecommendCycleView = {
let cycleView = RecommendCycleView.createCycleView()
cycleView.frame = CGRect(x: 0, y: -cycleView.frame.height, width: kScreenWidth, height: cycleView.frame.height)
return cycleView
}()
lazy var collectionView:UICollectionView = { [weak self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kHomeItemWidth, height: kHomeItemNormalHeight)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kHomeItemMargin
layout.sectionInset = UIEdgeInsets(top: 0, left: kHomeItemMargin, bottom: 0, right: kHomeItemMargin)
layout.headerReferenceSize = CGSize(width: kScreenWidth, height: kHomeSectionHeaderHeight)
let collView = UICollectionView(frame: (self?.view.bounds)!, collectionViewLayout: layout)
collView.backgroundColor = UIColor.white
collView.dataSource = self
collView.delegate = self
collView.register(UINib(nibName: "CollectionViewNormalCell", bundle: nil), forCellWithReuseIdentifier: kHomeCellIden)
collView.register(UINib(nibName: "CollectionViewBeautyCell", bundle: nil), forCellWithReuseIdentifier: kHomeBeautyCellIden)
collView.register(UINib(nibName: "CollectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHomeHeaderIden)
//宽度,高度随父视图变化
collView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
collView.contentInset = UIEdgeInsetsMake((self?.cycleView.frame.height)!, 0, 0, 0)
return collView
}()
override func viewDidLoad() {
super.viewDidLoad()
buildUI()
loadData()
}
}
// MARK - UI
extension RecommendController {
fileprivate func buildUI() {
view.addSubview(collectionView)
collectionView.addSubview(cycleView)
}
}
// MARK - 网络请求
extension RecommendController {
fileprivate func loadData() {
recomVModel.requestData {
self.collectionView.reloadData()
}
recomVModel.requestCycleData {
self.cycleView.cycleArr = self.recomVModel.cycleGroup
}
}
}
extension RecommendController: UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return recomVModel.group.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return recomVModel.group[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let group = recomVModel.group[indexPath.section]
let anchor = group.anchors[indexPath.item]
var cell : CollectionBaseCell!
if indexPath.section == 1 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kHomeBeautyCellIden, for: indexPath) as! CollectionViewBeautyCell
} else {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kHomeCellIden, for: indexPath) as! CollectionViewNormalCell
}
cell.anchor = anchor
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHomeHeaderIden, for: indexPath) as! CollectionHeader
headView.group = recomVModel.group[indexPath.section]
return headView
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kHomeItemWidth, height: kHomeItemBeautyHeight)
}
return CGSize(width: kHomeItemWidth, height: kHomeItemNormalHeight)
}
}
| apache-2.0 |
stephencelis/SQLite.swift | Tests/SQLiteTests/Extensions/CipherTests.swift | 1 | 3959 | #if SQLITE_SWIFT_SQLCIPHER
import XCTest
import SQLite
import SQLCipher
class CipherTests: XCTestCase {
var db1: Connection!
var db2: Connection!
override func setUpWithError() throws {
db1 = try Connection()
db2 = try Connection()
// db1
try db1.key("hello")
try db1.run("CREATE TABLE foo (bar TEXT)")
try db1.run("INSERT INTO foo (bar) VALUES ('world')")
// db2
let key2 = keyData()
try db2.key(Blob(data: key2))
try db2.run("CREATE TABLE foo (bar TEXT)")
try db2.run("INSERT INTO foo (bar) VALUES ('world')")
try super.setUpWithError()
}
func test_key() throws {
XCTAssertEqual(1, try db1.scalar("SELECT count(*) FROM foo") as? Int64)
}
func test_key_blob_literal() throws {
let db = try Connection()
try db.key("x'2DD29CA851E7B56E4697B0E1F08507293D761A05CE4D1B628663F411A8086D99'")
}
func test_rekey() throws {
try db1.rekey("goodbye")
XCTAssertEqual(1, try db1.scalar("SELECT count(*) FROM foo") as? Int64)
}
func test_data_key() throws {
XCTAssertEqual(1, try db2.scalar("SELECT count(*) FROM foo") as? Int64)
}
func test_data_rekey() throws {
let newKey = keyData()
try db2.rekey(Blob(data: newKey))
XCTAssertEqual(1, try db2.scalar("SELECT count(*) FROM foo") as? Int64)
}
func test_keyFailure() throws {
let path = "\(NSTemporaryDirectory())/db.sqlite3"
_ = try? FileManager.default.removeItem(atPath: path)
let connA = try Connection(path)
defer { try? FileManager.default.removeItem(atPath: path) }
try connA.key("hello")
try connA.run("CREATE TABLE foo (bar TEXT)")
let connB = try Connection(path, readonly: true)
do {
try connB.key("world")
XCTFail("expected exception")
} catch Result.error(_, let code, _) {
XCTAssertEqual(SQLITE_NOTADB, code)
} catch {
XCTFail("unexpected error: \(error)")
}
}
func test_open_db_encrypted_with_sqlcipher() throws {
// $ sqlcipher Tests/SQLiteTests/fixtures/encrypted-[version].x.sqlite
// sqlite> pragma key = 'sqlcipher-test';
// sqlite> CREATE TABLE foo (bar TEXT);
// sqlite> INSERT INTO foo (bar) VALUES ('world');
guard let cipherVersion: String = db1.cipherVersion,
cipherVersion.starts(with: "3.") || cipherVersion.starts(with: "4.")
else { return }
let encryptedFile = cipherVersion.starts(with: "3.") ?
fixture("encrypted-3.x", withExtension: "sqlite") :
fixture("encrypted-4.x", withExtension: "sqlite")
try FileManager.default.setAttributes([FileAttributeKey.immutable: 1], ofItemAtPath: encryptedFile)
XCTAssertFalse(FileManager.default.isWritableFile(atPath: encryptedFile))
defer {
// ensure file can be cleaned up afterwards
try? FileManager.default.setAttributes([FileAttributeKey.immutable: 0], ofItemAtPath: encryptedFile)
}
let conn = try Connection(encryptedFile)
try conn.key("sqlcipher-test")
XCTAssertEqual(1, try conn.scalar("SELECT count(*) FROM foo") as? Int64)
}
func test_export() throws {
let tmp = temporaryFile()
try db1.sqlcipher_export(.uri(tmp), key: "mykey")
let conn = try Connection(tmp)
try conn.key("mykey")
XCTAssertEqual(1, try conn.scalar("SELECT count(*) FROM foo") as? Int64)
}
private func keyData(length: Int = 64) -> NSData {
let keyData = NSMutableData(length: length)!
let result = SecRandomCopyBytes(kSecRandomDefault, length,
keyData.mutableBytes.assumingMemoryBound(to: UInt8.self))
XCTAssertEqual(0, result)
return NSData(data: keyData)
}
}
#endif
| mit |
Rep2/SimplerNews | Sources/App/main.swift | 1 | 805 | import Vapor
import VaporMongo
import Foundation
let drop = Droplet()
try drop.addProvider(VaporMongo.Provider.self)
drop.preparations.append(Channel.self)
drop.preparations.append(Video.self)
drop.preparations.append(User.self)
let channels = ChannelsController()
drop.resource("channels", channels)
let videos = VideosController()
drop.resource("videos", videos)
drop.post("facebook") { request in
try Facebook().facebookLogin(request: request)
}
drop.post("twitter") { request in
try Twitter().twitterLogin(request: request)
}
drop.post("google") { request in
try Google().login(request: request)
}
drop.post("user") { request in
try Google().user(request: request)
}
drop.get("user") { request in
try Google().user(request: request)
}
let timer = APICalls()
drop.run()
| mit |
JeffJin/ios9_notification | twilio/Services/Models/ViewModel/PreviousSearchViewModel.swift | 2 | 563 | //
// PreviousSearchViewModel.swift
// ReactiveSwiftFlickrSearch
//
// Created by Colin Eberhardt on 16/07/2014.
// Copyright (c) 2014 Colin Eberhardt. All rights reserved.
//
import Foundation
// Represents a search that was executed previously
@objc public class PreviousSearchViewModel: NSObject {
let searchString: String
let totalResults: Int
let thumbnail: NSURL
init(searchString: String, totalResults: Int, thumbnail: NSURL) {
self.searchString = searchString
self.totalResults = totalResults
self.thumbnail = thumbnail
}
} | apache-2.0 |
silt-lang/silt | Sources/Drill/DiagnosticRegexParser.swift | 1 | 3258 | /// DiagnosticRegexParser.swift
///
/// Copyright 2017-2018, The Silt Language Project.
///
/// This project is released under the MIT license, a copy of which is
/// available in the repository.
import Foundation
/// A RegexPiece is either:
/// - A literal string that must be matched exactly.
/// - A regular expression that must be matched using regex matching.
/// To construct a regular expression from these pieces, `literal` pieces
/// must be escaped such that they will always match special regex
/// characters literally.
enum RegexPiece {
/// The string inside must be matched by the resulting regex literally.
case literal(String)
/// The string inside is a regex that must be added wholesale into the
/// resulting regex.
case regex(String)
/// Regex-escapes the piece appropriately, taking into account the need
/// to escape special characters in literals.
var asRegex: String {
switch self {
case .literal(let str):
return NSRegularExpression.escapedPattern(for: str)
case .regex(let str):
return str
}
}
}
/// A regex that matches a sub-regex inside a diagnostic expectation.
/// It will look something like: --expected-error{{foo something {{.*}} bar}}
//swiftlint:disable force_try
private let subRegexRegex = try! NSRegularExpression(pattern:
"\\{\\{([^\\}]+)\\}\\}")
enum DiagnosticRegexParser {
/// Parses a diagnostic message as an alternating sequence of regex and non-
/// regex pieces. This will produce a regular expression that will match
/// messages and will incorporate the regexes inside the message.
static func parseMessageAsRegex(
_ message: String) -> NSRegularExpression? {
// Get an NSString for the message.
let nsString = NSString(string: message)
let range = NSRange(location: 0, length: nsString.length)
var pieces = [RegexPiece]()
// The index into the string where the last regex's '}}' ends.
// 'Starts' at 0, so we pull the beginning of the string before the first
// '{{' as well.
var previousMatchEnd = 0
// Enumerate over all matches in the string...
for match in subRegexRegex.matches(in: message, range: range) {
let fullRange = match.range(at: 0)
// Find the range where the previous matched piece ended -- this contains
// a literal that we need to add to the set of pieces.
let previousPieceRange =
NSRange(location: previousMatchEnd,
length: fullRange.location - previousMatchEnd)
previousMatchEnd = fullRange.upperBound
let previousPiece = nsString.substring(with: previousPieceRange)
pieces.append(.literal(previousPiece))
// Now, add the regex that we matched.
let regexRange = match.range(at: 1)
let pattern = nsString.substring(with: regexRange)
pieces.append(.regex(pattern))
}
// If we still have input left to consume, add it as a literal to the
// pieces.
if previousMatchEnd < nsString.length - 1 {
pieces.append(.literal(nsString.substring(from: previousMatchEnd)))
}
// Escape all the pieces and convert the pattern to an NSRegularExpression.
let pattern = pieces.map { $0.asRegex }.joined()
return try? NSRegularExpression(pattern: pattern)
}
}
| mit |
gurenupet/hah-auth-ios-swift | hah-auth-ios-swift/hah-auth-ios-swift/Libs/JHTAlertController/JHTAlertAction.swift | 2 | 1285 | //
// JHTAlertAction.swift
// JHTAlertController
//
// Created by Jessel, Jeremiah on 11/15/16.
// Copyright © 2016 Jacuzzi Hot Tubs, LLC. All rights reserved.
//
import UIKit
public class JHTAlertAction: NSObject, NSCopying {
var title: String
var style: JHTAlertActionStyle
var handler: ((JHTAlertAction) -> Void)!
var bgColor: UIColor?
var isEnabled = true
// MARK: JHTAlertAction Setup
/// Initialize the JHTAlertAction
///
/// - Parameters:
/// - title: the title of the action
/// - style: the action style
/// - bgColor: the background color of the action
/// - handler: the handler to fire when interacted with
required public init(title: String, style: JHTAlertActionStyle, bgColor: UIColor? = nil, handler: ((JHTAlertAction) -> Void)!) {
self.title = title
self.style = style
self.bgColor = bgColor
self.handler = handler
}
/// Conformance to NSCopying
///
/// - Parameter zone: the zone
/// - Returns: returns a copy of JHTAlertAction
public func copy(with zone: NSZone? = nil) -> Any {
let copy = type(of: self).init(title: title, style: style, bgColor: bgColor, handler: handler)
copy.isEnabled = self.isEnabled
return copy
}
}
| mit |
crazypoo/PTools | Pods/SwifterSwift/Sources/SwifterSwift/CoreGraphics/CGFloatExtensions.swift | 1 | 1448 | //
// CGFloatExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/23/16.
// Copyright © 2016 SwifterSwift
//
#if canImport(CoreGraphics)
import CoreGraphics
#if canImport(Foundation)
import Foundation
#endif
// MARK: - Properties
public extension CGFloat {
/// SwifterSwift: Absolute of CGFloat value.
var abs: CGFloat {
return Swift.abs(self)
}
#if canImport(Foundation)
/// SwifterSwift: Ceil of CGFloat value.
var ceil: CGFloat {
return Foundation.ceil(self)
}
#endif
/// SwifterSwift: Radian value of degree input.
var degreesToRadians: CGFloat {
return .pi * self / 180.0
}
#if canImport(Foundation)
/// SwifterSwift: Floor of CGFloat value.
var floor: CGFloat {
return Foundation.floor(self)
}
#endif
/// SwifterSwift: Check if CGFloat is positive.
var isPositive: Bool {
return self > 0
}
/// SwifterSwift: Check if CGFloat is negative.
var isNegative: Bool {
return self < 0
}
/// SwifterSwift: Int.
var int: Int {
return Int(self)
}
/// SwifterSwift: Float.
var float: Float {
return Float(self)
}
/// SwifterSwift: Double.
var double: Double {
return Double(self)
}
/// SwifterSwift: Degree value of radian input.
var radiansToDegrees: CGFloat {
return self * 180 / CGFloat.pi
}
}
#endif
| mit |
xgdgsc/AlecrimCoreData | Examples/OS X/AlecrimCoreDataExample/Event.swift | 1 | 396 | //
// Event.swift
// AlecrimCoreDataExample
//
// Created by Vanderlei Martinelli on 2014-11-30.
// Copyright (c) 2014 Alecrim. All rights reserved.
//
import Foundation
import CoreData
import AlecrimCoreData
class Event: NSManagedObject {
@NSManaged var timeStamp: NSDate
}
extension Event {
static let timeStamp = AlecrimCoreData.Attribute<NSDate>("timeStamp")
}
| mit |
brentsimmons/Frontier | BeforeTheRename/FrontierVerbs/FrontierVerbs/VerbTables/Base64Verbs.swift | 1 | 941 | //
// BitVerbs.swift
// FrontierVerbs
//
// Created by Brent Simmons on 4/15/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import FrontierData
struct Base64Verbs: VerbTable {
private enum Verb: String {
case decode = "decode"
case encode = "encode"
}
static func evaluate(_ lowerVerbName: String, _ params: VerbParams, _ verbAppDelegate: VerbAppDelegate) throws -> Value {
guard let verb = Verb(rawValue: lowerVerbName) else {
throw LangError(.verbNotFound)
}
do {
switch verb {
case .decode:
return try decode(params)
case .encode:
return try encode(params)
}
}
catch { throw error }
}
}
private extension Base64Verbs {
static func decode(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func encode(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
}
| gpl-2.0 |
simonkim/AVCapture | AVCaptureSample/AVCaptureSample/AssetRecordingController.swift | 1 | 3897 | //
// AssetWritingController.swift
// AVCaptureSample
//
// Created by Simon Kim on 9/26/16.
// Copyright © 2016 DZPub.com. All rights reserved.
//
import Foundation
import AVCapture
import AVFoundation
struct AssetRecordingOptions {
var compressAudio: Bool
var compressVideo: Bool
var videoDimensions: CMVideoDimensions
}
enum RecordingUserDefaultKey: String {
case recordingSequence = "recordingSeq" // Int
/// Get the next sequence number from user defaults and increase it by 1 for next call
static var nextRecordingSequenceNumber: Int
{
let defaults = UserDefaults()
let result = defaults.integer(forKey: recordingSequence.rawValue)
defaults.set(result + 1, forKey: recordingSequence.rawValue)
defaults.synchronize()
return result
}
}
class AssetRecordingController {
var fileWriter: AVCFileWriter? = nil
static var writerQueue: DispatchQueue = {
return DispatchQueue(label: "writer")
}()
/// start or stop recording
public var recording: Bool {
get {
return fileWriter != nil
}
set(newValue) {
toggleRecording(on: newValue)
}
}
/// Returns video dimensions currently set. Default is (0, 0)
/// Set video dimenstions through this property before starting recording by
/// setting true to 'recording' property
public var videoSize: CMVideoDimensions {
get {
return options.videoDimensions
}
set(newValue){
options.videoDimensions = newValue
}
}
private var options: AssetRecordingOptions
public init(compressAudio: Bool = true, compressVideo: Bool = true)
{
self.options = AssetRecordingOptions(compressAudio: compressAudio,
compressVideo: compressVideo,
videoDimensions: CMVideoDimensions(width: 0, height: 0))
}
private func toggleRecording(on: Bool) {
if on {
let seq = RecordingUserDefaultKey.nextRecordingSequenceNumber
if let path = RecordingsCollection.recordingFilePath(with: String(format:"recording-%03d.mov", seq)) {
let audioSettings = AVCWriterSettings(compress: self.options.compressAudio)
let videoSettings = AVCWriterVideoSettings(compress:self.options.compressVideo,
width:Int(options.videoDimensions.width),
height: Int(options.videoDimensions.height))
let writer = AVCFileWriter(URL: Foundation.URL(fileURLWithPath: path), videoSettings: videoSettings, audioSettings: audioSettings) {
sender, status, info in
print("Writer \(status.rawValue)")
switch(status) {
case .writerInitFailed, .writerStartFailed, .writerStatusFailed:
print(" : \(info)")
self.fileWriter = nil
sender.finish(silent: true)
break
case .finished:
print("Video recorded at \(path)")
break
default:
break
}
}
fileWriter = writer
}
} else {
if let fileWriter = fileWriter {
fileWriter.finish()
self.fileWriter = nil
}
}
}
func append(sbuf: CMSampleBuffer) {
type(of:self).writerQueue.async() {
self.fileWriter?.append(sbuf: sbuf)
}
}
}
| apache-2.0 |
iOSDevLog/iOSDevLog | 2048-Xcode7/2048Tests/_048Tests.swift | 1 | 963 | //
// _048Tests.swift
// 2048Tests
//
// Created by jiaxianhua on 15/9/14.
// Copyright © 2015年 jiaxianhua. All rights reserved.
//
import XCTest
@testable import _048
class _048Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| mit |
xiaomudegithub/iosstar | iOSStar/Scenes/Market/CustomView/MarketAuctionCell.swift | 3 | 1192 | //
// MarketAuctionCell.swift
// iOSStar
//
// Created by J-bb on 17/5/22.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class MarketAuctionCell: UITableViewCell {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet var price_label: UILabel!
override func awakeFromNib() {
price_label.textColor = UIColor.init(hexString: AppConst.Color.orange)
super.awakeFromNib()
}
func setFans(model:FansListModel) {
dateLabel.text = Date.yt_convertDateStrWithTimestempWithSecond(Int(model.trades!.positionTime), format: "MM-dd HH:mm:SS")
iconImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + model.user!.headUrl),placeholder:UIImage.init(named: "\(arc4random()%8+1)"))
nameLabel.text = model.user!.nickname
price_label.text = "\(model.trades!.openPrice)元/秒"
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| gpl-3.0 |
eljeff/AudioKit | Sources/AudioKit/Nodes/Generators/Physical Models/MetalBar.swift | 1 | 6781 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
// This file was auto-autogenerated by scripts and templates at http://github.com/AudioKit/AudioKitDevTools/
import AVFoundation
import CAudioKit
/// Physical model approximating the sound of a struck metal bar
///
public class MetalBar: Node, AudioUnitContainer, Tappable, Toggleable {
/// Unique four-letter identifier "mbar"
public static let ComponentDescription = AudioComponentDescription(generator: "mbar")
/// Internal type of audio unit for this node
public typealias AudioUnitType = InternalAU
/// Internal audio unit
public private(set) var internalAU: AudioUnitType?
// MARK: - Parameters
/// Specification details for leftBoundaryCondition
public static let leftBoundaryConditionDef = NodeParameterDef(
identifier: "leftBoundaryCondition",
name: "Boundary condition at left end of bar. 1 = clamped, 2 = pivoting, 3 = free",
address: akGetParameterAddress("MetalBarParameterLeftBoundaryCondition"),
range: 1 ... 3,
unit: .hertz,
flags: .default)
/// Boundary condition at left end of bar. 1 = clamped, 2 = pivoting, 3 = free
@Parameter public var leftBoundaryCondition: AUValue
/// Specification details for rightBoundaryCondition
public static let rightBoundaryConditionDef = NodeParameterDef(
identifier: "rightBoundaryCondition",
name: "Boundary condition at right end of bar. 1 = clamped, 2 = pivoting, 3 = free",
address: akGetParameterAddress("MetalBarParameterRightBoundaryCondition"),
range: 1 ... 3,
unit: .hertz,
flags: .default)
/// Boundary condition at right end of bar. 1 = clamped, 2 = pivoting, 3 = free
@Parameter public var rightBoundaryCondition: AUValue
/// Specification details for decayDuration
public static let decayDurationDef = NodeParameterDef(
identifier: "decayDuration",
name: "30db decay time (in seconds).",
address: akGetParameterAddress("MetalBarParameterDecayDuration"),
range: 0 ... 10,
unit: .hertz,
flags: .default)
/// 30db decay time (in seconds).
@Parameter public var decayDuration: AUValue
/// Specification details for scanSpeed
public static let scanSpeedDef = NodeParameterDef(
identifier: "scanSpeed",
name: "Speed of scanning the output location.",
address: akGetParameterAddress("MetalBarParameterScanSpeed"),
range: 0 ... 100,
unit: .hertz,
flags: .default)
/// Speed of scanning the output location.
@Parameter public var scanSpeed: AUValue
/// Specification details for position
public static let positionDef = NodeParameterDef(
identifier: "position",
name: "Position along bar that strike occurs.",
address: akGetParameterAddress("MetalBarParameterPosition"),
range: 0 ... 1,
unit: .generic,
flags: .default)
/// Position along bar that strike occurs.
@Parameter public var position: AUValue
/// Specification details for strikeVelocity
public static let strikeVelocityDef = NodeParameterDef(
identifier: "strikeVelocity",
name: "Normalized strike velocity",
address: akGetParameterAddress("MetalBarParameterStrikeVelocity"),
range: 0 ... 1_000,
unit: .generic,
flags: .default)
/// Normalized strike velocity
@Parameter public var strikeVelocity: AUValue
/// Specification details for strikeWidth
public static let strikeWidthDef = NodeParameterDef(
identifier: "strikeWidth",
name: "Spatial width of strike.",
address: akGetParameterAddress("MetalBarParameterStrikeWidth"),
range: 0 ... 1,
unit: .generic,
flags: .default)
/// Spatial width of strike.
@Parameter public var strikeWidth: AUValue
// MARK: - Audio Unit
/// Internal Audio Unit for MetalBar
public class InternalAU: AudioUnitBase {
/// Get an array of the parameter definitions
/// - Returns: Array of parameter definitions
public override func getParameterDefs() -> [NodeParameterDef] {
[MetalBar.leftBoundaryConditionDef,
MetalBar.rightBoundaryConditionDef,
MetalBar.decayDurationDef,
MetalBar.scanSpeedDef,
MetalBar.positionDef,
MetalBar.strikeVelocityDef,
MetalBar.strikeWidthDef]
}
/// Create the DSP Refence for this node
/// - Returns: DSP Reference
public override func createDSP() -> DSPRef {
akCreateDSP("MetalBarDSP")
}
}
// MARK: - Initialization
/// Initialize this Bar node
///
/// - Parameters:
/// - leftBoundaryCondition: Boundary condition at left end of bar. 1 = clamped, 2 = pivoting, 3 = free
/// - rightBoundaryCondition: Boundary condition at right end of bar. 1 = clamped, 2 = pivoting, 3 = free
/// - decayDuration: 30db decay time (in seconds).
/// - scanSpeed: Speed of scanning the output location.
/// - position: Position along bar that strike occurs.
/// - strikeVelocity: Normalized strike velocity
/// - strikeWidth: Spatial width of strike.
/// - stiffness: Dimensionless stiffness parameter
/// - highFrequencyDamping: High-frequency loss parameter. Keep this small
///
public init(
leftBoundaryCondition: AUValue = 1,
rightBoundaryCondition: AUValue = 1,
decayDuration: AUValue = 3,
scanSpeed: AUValue = 0.25,
position: AUValue = 0.2,
strikeVelocity: AUValue = 500,
strikeWidth: AUValue = 0.05,
stiffness: AUValue = 3,
highFrequencyDamping: AUValue = 0.001
) {
super.init(avAudioNode: AVAudioNode())
instantiateAudioUnit { avAudioUnit in
self.avAudioUnit = avAudioUnit
self.avAudioNode = avAudioUnit
guard let audioUnit = avAudioUnit.auAudioUnit as? AudioUnitType else {
fatalError("Couldn't create audio unit")
}
self.internalAU = audioUnit
self.leftBoundaryCondition = leftBoundaryCondition
self.rightBoundaryCondition = rightBoundaryCondition
self.decayDuration = decayDuration
self.scanSpeed = scanSpeed
self.position = position
self.strikeVelocity = strikeVelocity
self.strikeWidth = strikeWidth
}
}
// MARK: - Control
/// Trigger the sound with current parameters
///
open func trigger() {
internalAU?.start()
internalAU?.trigger()
}
}
| mit |
ncalexan/firefox-ios | SyncTests/TestBookmarkModel.swift | 1 | 10124 | /* 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 Deferred
import Foundation
import Shared
@testable import Storage
@testable import Sync
import XCTest
// Thieved mercilessly from TestSQLiteBookmarks.
private func getBrowserDBForFile(filename: String, files: FileAccessor) -> BrowserDB? {
return BrowserDB(filename: filename, schema: BrowserSchema(), files: files)
}
class TestBookmarkModel: FailFastTestCase {
let files = MockFiles()
override func tearDown() {
do {
try self.files.removeFilesInDirectory()
} catch {
}
super.tearDown()
}
private func getBrowserDB(name: String) -> BrowserDB? {
let file = "TBookmarkModel\(name).db"
print("DB file named: \(file)")
return getBrowserDBForFile(filename: file, files: self.files)
}
func getSyncableBookmarks(name: String) -> MergedSQLiteBookmarks? {
guard let db = self.getBrowserDB(name: name) else {
XCTFail("Couldn't get prepared DB.")
return nil
}
return MergedSQLiteBookmarks(db: db)
}
func testBookmarkEditableIfNeverSyncedAndEmptyBuffer() {
guard let bookmarks = self.getSyncableBookmarks(name: "A") else {
XCTFail("Couldn't get bookmarks.")
return
}
// Set a local bookmark
let bookmarkURL = "http://AAA.com".asURL!
bookmarks.local.insertBookmark(bookmarkURL, title: "AAA", favicon: nil, intoFolder: BookmarkRoots.MenuFolderGUID, withTitle: "").succeeded()
XCTAssertTrue(bookmarks.isMirrorEmpty().value.successValue!)
XCTAssertTrue(bookmarks.buffer.isEmpty().value.successValue!)
let menuFolder = bookmarks.menuFolder()
XCTAssertEqual(menuFolder.current.count, 1)
XCTAssertTrue(menuFolder.current[0]!.isEditable)
}
func testBookmarkEditableIfNeverSyncedWithBufferedChanges() {
guard let bookmarks = self.getSyncableBookmarks(name: "B") else {
XCTFail("Couldn't get bookmarks.")
return
}
let bookmarkURL = "http://AAA.com".asURL!
bookmarks.local.insertBookmark(bookmarkURL, title: "AAA", favicon: nil, intoFolder: BookmarkRoots.MenuFolderGUID, withTitle: "").succeeded()
// Add a buffer into the buffer
let mirrorDate = Date.now() - 100000
bookmarks.applyRecords([
BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["BBB"]),
BookmarkMirrorItem.bookmark("BBB", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "BBB", description: nil, URI: "http://BBB.com", tags: "", keyword: nil)
]).succeeded()
XCTAssertFalse(bookmarks.buffer.isEmpty().value.successValue!)
XCTAssertTrue(bookmarks.isMirrorEmpty().value.successValue!)
// Check to see if we're editable
let menuFolder = bookmarks.menuFolder()
XCTAssertEqual(menuFolder.current.count, 1)
XCTAssertTrue(menuFolder.current[0]!.isEditable)
}
func testBookmarksEditableWithEmptyBufferAndRemoteBookmark() {
guard let bookmarks = self.getSyncableBookmarks(name: "C") else {
XCTFail("Couldn't get bookmarks.")
return
}
// Add a bookmark to the menu folder in our mirror
let mirrorDate = Date.now() - 100000
bookmarks.populateMirrorViaBuffer(items: [
BookmarkMirrorItem.folder(BookmarkRoots.RootGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "", description: "", children: BookmarkRoots.RootChildren),
BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["CCC"]),
BookmarkMirrorItem.bookmark("CCC", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "CCC", description: nil, URI: "http://CCC.com", tags: "", keyword: nil)
], atDate: mirrorDate)
// Set a local bookmark
let bookmarkURL = "http://AAA.com".asURL!
bookmarks.local.insertBookmark(bookmarkURL, title: "AAA", favicon: nil, intoFolder: BookmarkRoots.MenuFolderGUID, withTitle: "").succeeded()
XCTAssertTrue(bookmarks.buffer.isEmpty().value.successValue!)
XCTAssertFalse(bookmarks.isMirrorEmpty().value.successValue!)
// Check to see if we're editable
let menuFolder = bookmarks.menuFolder()
XCTAssertEqual(menuFolder.current.count, 2)
XCTAssertTrue(menuFolder.current[0]!.isEditable)
XCTAssertTrue(menuFolder.current[1]!.isEditable)
}
func testBookmarksNotEditableForUnmergedChanges() {
guard let bookmarks = self.getSyncableBookmarks(name: "D") else {
XCTFail("Couldn't get bookmarks.")
return
}
// Add a bookmark to the menu folder in our mirror
let mirrorDate = Date.now() - 100000
bookmarks.populateMirrorViaBuffer(items: [
BookmarkMirrorItem.folder(BookmarkRoots.RootGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "", description: "", children: BookmarkRoots.RootChildren),
BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["EEE"]),
BookmarkMirrorItem.bookmark("EEE", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "EEE", description: nil, URI: "http://EEE.com", tags: "", keyword: nil)
], atDate: mirrorDate)
bookmarks.local.insertBookmark("http://AAA.com".asURL!, title: "AAA", favicon: nil, intoFolder: BookmarkRoots.MobileFolderGUID, withTitle: "Bookmarks Menu").succeeded()
// Add some unmerged bookmarks into the menu folder in the buffer.
bookmarks.applyRecords([
BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["EEE", "FFF"]),
BookmarkMirrorItem.bookmark("FFF", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "FFF", description: nil, URI: "http://FFF.com", tags: "", keyword: nil)
]).succeeded()
XCTAssertFalse(bookmarks.buffer.isEmpty().value.successValue!)
XCTAssertFalse(bookmarks.isMirrorEmpty().value.successValue!)
// Check to see that we can't edit these bookmarks
let menuFolder = bookmarks.menuFolder()
XCTAssertEqual(menuFolder.current.count, 1)
XCTAssertFalse(menuFolder.current[0]!.isEditable)
}
func testLocalBookmarksEditableWhileHavingUnmergedChangesAndEmptyMirror() {
guard let bookmarks = self.getSyncableBookmarks(name: "D") else {
XCTFail("Couldn't get bookmarks.")
return
}
bookmarks.local.insertBookmark("http://AAA.com".asURL!, title: "AAA", favicon: nil, intoFolder: BookmarkRoots.MobileFolderGUID, withTitle: "Bookmarks Menu").succeeded()
// Add some unmerged bookmarks into the menu folder in the buffer.
let mirrorDate = Date.now() - 100000
bookmarks.applyRecords([
BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["EEE", "FFF"]),
BookmarkMirrorItem.bookmark("FFF", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "FFF", description: nil, URI: "http://FFF.com", tags: "", keyword: nil)
]).succeeded()
// Local bookmark should be editable
let mobileFolder = bookmarks.mobileFolder()
XCTAssertEqual(mobileFolder.current.count, 2)
XCTAssertTrue(mobileFolder.current[1]!.isEditable)
}
}
private extension MergedSQLiteBookmarks {
func isMirrorEmpty() -> Deferred<Maybe<Bool>> {
return self.local.db.queryReturnsNoResults("SELECT 1 FROM \(TableBookmarksMirror)")
}
func wipeLocal() {
self.local.db.run(["DELETE FROM \(TableBookmarksLocalStructure)", "DELETE FROM \(TableBookmarksLocal)"]).succeeded()
}
func populateMirrorViaBuffer(items: [BookmarkMirrorItem], atDate mirrorDate: Timestamp) {
self.applyRecords(items).succeeded()
// … and add the root relationships that will be missing (we don't do those for the buffer,
// so we need to manually add them and move them across).
self.buffer.db.run([
"INSERT INTO \(TableBookmarksBufferStructure) (parent, child, idx) VALUES",
"('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.MenuFolderGUID)', 0),",
"('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.ToolbarFolderGUID)', 1),",
"('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.UnfiledFolderGUID)', 2),",
"('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.MobileFolderGUID)', 3)",
].joined(separator: " ")).succeeded()
// Move it all to the mirror.
self.local.db.moveBufferToMirrorForTesting()
}
func menuFolder() -> BookmarksModel {
return modelFactory.value.successValue!.modelForFolder(BookmarkRoots.MenuFolderGUID).value.successValue!
}
func mobileFolder() -> BookmarksModel {
return modelFactory.value.successValue!.modelForFolder(BookmarkRoots.MobileFolderGUID).value.successValue!
}
}
| mpl-2.0 |
kstaring/swift | validation-test/compiler_crashers_fixed/05431-swift-declname-printpretty.swift | 11 | 425 | // 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
class B<T where B=a{let d:a{(B<T
| apache-2.0 |
vknabel/EasyInject | Sources/EasyInject/AnyInjector.swift | 1 | 3400 | /// Wraps a given `Injector` in order to lose type details, but keeps it mutable.
/// - Todo: Replace generic `I : Injector` with a `ProvidableKey`
public struct AnyInjector<K: Hashable>: InjectorDerivingFromMutableInjector {
public typealias Key = K
/// The internally used `Injector`.
private var injector: Any
private let lambdaRevoke: (inout AnyInjector, Key) -> Void
private let lambdaKeys: (AnyInjector) -> [K]
private let lambdaResolve: (inout AnyInjector, Key) throws -> Providable
private let lambdaProvide:
(inout AnyInjector, K, @escaping (inout AnyInjector) throws -> Providable) -> Void
/**
Initializes `AnyInjector` with a given `MutableInjector`.
- Parameter injector: The `MutableInjector` that shall be wrapped.
*/
public init<I: MutableInjector>(injector: I) where I.Key == K {
self.injector = injector
self.lambdaResolve = { (this: inout AnyInjector, key: Key) in
// swiftlint:disable:next force_cast
var injector = this.injector as! I
defer { this.injector = injector }
return try injector.resolve(key: key)
}
self.lambdaProvide = { this, key, factory in
// swiftlint:disable:next force_cast
var injector = this.injector as! I
defer { this.injector = injector }
injector.provide(
key: key,
usingFactory: { inj in
var any = AnyInjector(injector: inj)
return try factory(&any)
})
}
self.lambdaRevoke = { (this: inout AnyInjector, key: Key) in
// swiftlint:disable:next force_cast
var injector = this.injector as! I
defer { this.injector = injector }
injector.revoke(key: key)
}
self.lambdaKeys = { this in
return (this.injector as! I).providedKeys
}
}
/**
Initializes `AnyInjector` with a given `Injector`.
- Parameter injector: The `Injector` that shall be wrapped.
*/
public init<I: Injector>(injector: I) where I.Key == K {
self.injector = injector
self.lambdaResolve = { (this: inout AnyInjector, key: Key) in
// swiftlint:disable:next force_cast
return try (this.injector as! I).resolving(key: key)
}
self.lambdaProvide = { this, key, factory in
// swiftlint:disable:next force_cast
let injector = this.injector as! I
this.injector = injector.providing(
key: key,
usingFactory: { inj in
var any = AnyInjector(injector: inj)
return try factory(&any)
})
}
self.lambdaRevoke = { (this: inout AnyInjector, key: Key) in
// swiftlint:disable:next force_cast
let injector = this.injector as! I
this.injector = injector.revoking(key: key)
}
self.lambdaKeys = { this in
return (this.injector as! I).providedKeys
}
}
/// See `MutableInjector.resolve(key:)`.
public mutating func resolve(key: K) throws -> Providable {
return try self.lambdaResolve(&self, key)
}
/// See `MutableInjector.provide(key:usingFactory:)`.
public mutating func provide(
key: K,
usingFactory factory: @escaping (inout AnyInjector) throws -> Providable
) {
self.lambdaProvide(&self, key, factory)
}
/// See `Injector.providedKeys`.
public var providedKeys: [K] {
return lambdaKeys(self)
}
/// See `MutableInjector.revoke(key:)`.
public mutating func revoke(key: K) {
lambdaRevoke(&self, key)
}
}
| mit |
Gitliming/Demoes | Demoes/Demoes/Common/SQLiteManager.swift | 1 | 1640 | //
// SQLiteManager.swift
// Demoes
//
// Created by 张丽明 on 2017/3/12.
// Copyright © 2017年 xpming. All rights reserved.
//
import UIKit
import FMDB
class SQLiteManager: NSObject {
// 工具单例子
static let SQManager:SQLiteManager = SQLiteManager()
var DB:FMDatabase?
var DBQ:FMDatabaseQueue?
override init() {
super.init()
openDB("Demoes_MyNote.sqlite")
}
// 打开数据库
func openDB(_ name:String?){
let path = getCachePath(name!)
print(path)
DB = FMDatabase(path: path)
DBQ = FMDatabaseQueue(path: path)
guard let db = DB else {print("数据库对象创建失败")
return}
if !db.open(){
print("打开数据库失败")
return
}
if creatTable() {
print("创表成功!!!!")
}
}
// 创建数据库
func creatTable() -> Bool{
let sqlit1 = "CREATE TABLE IF NOT EXISTS T_MyNote( \n" +
"stateid INTEGER PRIMARY KEY AUTOINCREMENT, \n" +
"id TEXT, \n" +
"title TEXT, \n" +
"desc TEXT, \n" +
"creatTime TEXT \n" +
");"
//执行语句
return DB!.executeUpdate(sqlit1, withArgumentsIn: nil)
}
//MARK:-- 拼接路径
func getCachePath(_ fileName:String) -> String{
let path1 = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory
, FileManager.SearchPathDomainMask.userDomainMask, true).first
let path2 = path1! + "/" + fileName
return path2
}
}
| apache-2.0 |
HackingGate/PDF-Reader | PDFReader/ThumbnailCollectionViewController.swift | 1 | 7340 | //
// ThumbnailCollectionViewController.swift
// PDFReader
//
// Created by ERU on H29/12/16.
// Copyright © 平成29年 Hacking Gate. All rights reserved.
//
import UIKit
import PDFKit
private let reuseIdentifier = "ThumbnailCell"
class ThumbnailCollectionViewController: UICollectionViewController {
var delegate: SettingsDelegate!
var pdfDocument: PDFDocument?
var displayBox: PDFDisplayBox = .cropBox
var transformForRTL: Bool = false
var isWidthGreaterThanHeight: Bool = false
var currentIndex: Int = 0
var onceOnly = false
let thumbnailCache = NSCache<NSNumber, UIImage>()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
collectionView?.semanticContentAttribute = delegate.isRightToLeft ? .forceRightToLeft : .forceLeftToRight
let page0 = pdfDocument?.page(at: 0)
let page1 = pdfDocument?.page(at: 1)
if let bounds0 = page0?.bounds(for: displayBox), let bounds1 = page1?.bounds(for: displayBox) {
if bounds0.size.width > bounds0.size.height && bounds1.size.width > bounds1.size.height {
isWidthGreaterThanHeight = true
}
}
}
// Start UICollectionView at a specific indexpath
// https://stackoverflow.com/a/35679859/4063462
internal override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if !onceOnly {
collectionView.scrollToItem(at: IndexPath(item: currentIndex, section: 0), at: .centeredVertically, animated: false)
onceOnly = true
}
let imageView = cell.viewWithTag(1) as? UIImageView
if imageView?.image == nil {
if let thumbnail: UIImage = thumbnailCache.object(forKey: NSNumber(value: indexPath.item)) {
imageView?.image = thumbnail
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return pdfDocument?.pageCount ?? 0
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
let numberLabel = cell.viewWithTag(2) as? PaddingLabel
numberLabel?.text = String(indexPath.item + 1)
var multiplier: CGFloat = 1.0
if UIApplication.shared.statusBarOrientation.isPortrait {
// calculate size for landscape
var safeAreaWidth = UIScreen.main.bounds.height
if UIApplication.shared.statusBarFrame.height != 20 {
// for iPhone X
safeAreaWidth -= UIApplication.shared.statusBarFrame.height * 2
}
let width: CGFloat = (safeAreaWidth - (isWidthGreaterThanHeight ? 64 : 80)) / (isWidthGreaterThanHeight ? 3 : 4)
let flooredWidth = width.flooredFloat
multiplier = flooredWidth / cell.bounds.size.width
}
let cellScreenSize = CGSize(width: cell.bounds.size.width * UIScreen.main.scale * multiplier, height: cell.bounds.size.height * UIScreen.main.scale * multiplier)
let imageView = cell.viewWithTag(1) as? UIImageView
if let thumbnail: UIImage = thumbnailCache.object(forKey: NSNumber(value: indexPath.item)) {
imageView?.image = thumbnail
} else {
imageView?.image = nil
// cache images
// https://stackoverflow.com/a/16694019/4063462
DispatchQueue.global(qos: .userInteractive).async {
if let page = self.pdfDocument?.page(at: indexPath.item) {
let thumbnail = page.thumbnail(of: cellScreenSize, for: self.displayBox)
self.thumbnailCache.setObject(thumbnail, forKey: NSNumber(value: indexPath.item))
DispatchQueue.main.async {
let updateCell = collectionView.cellForItem(at: indexPath)
let updateImageView = updateCell?.viewWithTag(1) as? UIImageView
if updateImageView?.image == nil {
updateImageView?.image = thumbnail
}
}
}
}
}
imageView?.transform = CGAffineTransform(rotationAngle: transformForRTL ? .pi : 0)
cell.layer.shadowOffset = CGSize(width: 1, height: 1)
cell.layer.shadowColor = UIColor.black.cgColor
cell.layer.shadowRadius = 5
cell.layer.shadowOpacity = 0.35
cell.clipsToBounds = false
cell.layer.masksToBounds = false
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let page = pdfDocument?.page(at: indexPath.item) {
delegate.goToPage(page: page)
navigationController?.popViewController(animated: true)
}
}
}
extension ThumbnailCollectionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let collectionViewSafeAreaWidth = collectionView.frame.size.width - collectionView.safeAreaInsets.left - collectionView.safeAreaInsets.right
var width: CGFloat = 0.0
if UIApplication.shared.statusBarOrientation.isPortrait {
// 3 items per line or 2 when width greater than height
width = (collectionView.frame.size.width - (isWidthGreaterThanHeight ? 48 : 64)) / (isWidthGreaterThanHeight ? 2 : 3)
} else {
// 4 items per line or 3 when width greater than height
width = (collectionViewSafeAreaWidth - (isWidthGreaterThanHeight ? 64 : 80)) / (isWidthGreaterThanHeight ? 3 : 4)
}
let flooredWidth = width.flooredFloat
if let page = pdfDocument?.page(at: indexPath.item) {
let rect = page.bounds(for: displayBox)
let aspectRatio = rect.width / rect.height
let height = flooredWidth / aspectRatio
return CGSize(width: flooredWidth, height: height)
}
return .zero
}
}
extension CGFloat {
// 64-bit device
var flooredFloat: CGFloat {
let flooredFloat = CGFloat(floor(Double(self) * 1000000000000) / 1000000000000)
return flooredFloat
}
}
| mit |
optimistapp/optimistapp | Optimist/MoodButton.swift | 1 | 3142 | //
// MoodButton.swift
// Optimist
//
// Created by Jacob Johannesen on 1/30/15.
// Copyright (c) 2015 Optimist. All rights reserved.
//
import Foundation
import UIKit
import CoreGraphics
public class MoodButton: UIButton
{
let DEFAULT_HEIGHT: CGFloat = 36.0
let DEFAULT_BUTTON_OPACITY: CGFloat = 0.0
let DEFAULT_BUTTON_OPACITY_TAPPED: CGFloat = 1.0
var color: UIColor = UIColor(netHex:0xffb242)
var index: Int
var moodView: MoodView
public init(width: CGFloat, title: String, moodView: MoodView, index: Int)
{
let frame = CGRectMake(0, 0, width, DEFAULT_HEIGHT)
self.moodView = moodView
self.index = index
super.init(frame: frame)
self.backgroundColor = self.color
self.backgroundColor = self.color.colorWithAlphaComponent(DEFAULT_BUTTON_OPACITY)
self.clipsToBounds = true
self.layer.cornerRadius = DEFAULT_HEIGHT/2
self.layer.borderColor = UIColor(netHex:0xffb242).CGColor
self.layer.borderWidth = 2.0
self.adjustsImageWhenHighlighted = false
self.setTitle(title, forState: UIControlState.Normal)
self.setTitleColor(UIColor(netHex:0xffb242), forState: UIControlState.Normal)
self.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin
self.addTarget(self, action: "touchDown", forControlEvents: UIControlEvents.TouchDown)
self.addTarget(self, action: "touchUpInside", forControlEvents: UIControlEvents.TouchUpInside)
self.addTarget(self, action: "touchUpOutside", forControlEvents: UIControlEvents.TouchUpOutside)
}
public func changeColor(color: UIColor)
{
self.color = color
self.setTitleColor(UIColor(netHex:0xffb242), forState: UIControlState.Normal)
self.backgroundColor = self.color.colorWithAlphaComponent(DEFAULT_BUTTON_OPACITY)
}
public func touchDown()
{
self.backgroundColor = self.color.colorWithAlphaComponent(DEFAULT_BUTTON_OPACITY_TAPPED)
self.setTitleColor(UIColor(netHex:0xfffdd7), forState: UIControlState.Normal)
println("button tapped")
}
public func touchUpInside()
{
//set MoodView array
if(moodView.booleanArr[index] == true)
{
moodView.booleanArr[index] = false
UIView.animateWithDuration(0.5, animations:
{
self.backgroundColor = self.color.colorWithAlphaComponent(self.DEFAULT_BUTTON_OPACITY)
self.setTitleColor(UIColor(netHex:0xffb242), forState: UIControlState.Normal)
})
}
else
{
moodView.booleanArr[index] = true
}
}
public func touchUpOutside()
{
self.backgroundColor = self.color.colorWithAlphaComponent(DEFAULT_BUTTON_OPACITY)
self.setTitleColor(UIColor(netHex:0xffb242), forState: UIControlState.Normal)
}
public required init(coder: NSCoder) {
fatalError("NSCoding not supported")
}
} | apache-2.0 |
ps2/rileylink_ios | NightscoutUploadKit/Models/OverrideStatus.swift | 1 | 1526 | //
// OverrideStatus.swift
// NightscoutUploadKit
//
// Created by Kenneth Stack on 5/6/19.
// Copyright © 2019 Pete Schwamb. All rights reserved.
//
import Foundation
import HealthKit
public struct OverrideStatus {
let name: String?
let timestamp: Date
let active: Bool
let currentCorrectionRange: CorrectionRange?
let duration: TimeInterval?
let multiplier: Double?
public init(name: String? = nil, timestamp: Date, active: Bool, currentCorrectionRange: CorrectionRange? = nil, duration: TimeInterval? = nil, multiplier: Double? = nil) {
self.name = name
self.timestamp = timestamp
self.active = active
self.currentCorrectionRange = currentCorrectionRange
self.duration = duration
self.multiplier = multiplier
}
public var dictionaryRepresentation: [String: Any] {
var rval = [String: Any]()
rval["timestamp"] = TimeFormat.timestampStrFromDate(timestamp)
rval["active"] = active
if let name = name {
rval["name"] = name
}
if let currentCorrectionRange = currentCorrectionRange {
rval["currentCorrectionRange"] = currentCorrectionRange.dictionaryRepresentation
}
if let duration = duration {
rval["duration"] = duration
}
if let multiplier = multiplier {
rval["multiplier"] = multiplier
}
return rval
}
}
| mit |
ReactiveKit/Bond | Sources/Bond/UIKit/UIApplication.swift | 1 | 1463 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if os(iOS) || os(tvOS)
import UIKit
import ReactiveKit
extension ReactiveExtensions where Base: UIApplication {
#if os(iOS)
public var isNetworkActivityIndicatorVisible: Bond<Bool> {
return bond { $0.isNetworkActivityIndicatorVisible = $1 }
}
#endif
}
#endif
| mit |
crspybits/SyncServerII | Sources/Server/Database/Database.swift | 1 | 18881 | //
// Database.swift
// Authentication
//
// Created by Christopher Prince on 11/26/16.
//
//
import LoggerAPI
import Foundation
import PerfectMySQL
// See https://github.com/PerfectlySoft/Perfect-MySQL for assumptions about mySQL installation.
// For mySQL interface docs, see: http://perfect.org/docs/MySQL.html
class Database {
// See http://stackoverflow.com/questions/13397038/uuid-max-character-length
static let uuidLength = 36
static let maxSharingGroupNameLength = 255
static let maxMimeTypeLength = 100
// E.g.,[ERR] Could not insert into ShortLocks: Failure: 1062 Duplicate entry '1' for key 'userId'
static let duplicateEntryForKey = UInt32(1062)
// Failure: 1213 Deadlock found when trying to get lock; try restarting transaction
static let deadlockError = UInt32(1213)
// Failure: 1205 Lock wait timeout exceeded; try restarting transaction
static let lockWaitTimeout = UInt32(1205)
private var closed = false
fileprivate var connection: MySQL!
var error: String {
return "Failure: \(self.connection.errorCode()) \(self.connection.errorMessage())"
}
init(showStartupInfo:Bool = false) {
self.connection = MySQL()
if showStartupInfo {
Log.info("Connecting to database with host: \(Configuration.server.db.host)...")
}
guard self.connection.connect(host: Configuration.server.db.host, user: Configuration.server.db.user, password: Configuration.server.db.password ) else {
Log.error("Failure connecting to mySQL server \(Configuration.server.db.host): \(self.error)")
return
}
ServerStatsKeeper.session.increment(stat: .dbConnectionsOpened)
if showStartupInfo {
Log.info("Connecting to database named: \(Configuration.server.db.database)...")
}
Log.info("DB CONNECTION STATS: opened: \(ServerStatsKeeper.session.currentValue(stat: .dbConnectionsOpened)); closed: \(ServerStatsKeeper.session.currentValue(stat: .dbConnectionsClosed))")
guard self.connection.selectDatabase(named: Configuration.server.db.database) else {
Log.error("Failure: \(self.error)")
return
}
}
func query(statement: String) -> Bool {
DBLog.query(statement)
return connection.query(statement: statement)
}
func numberAffectedRows() -> Int64 {
return connection.numberAffectedRows()
}
func lastInsertId() -> Int64 {
return connection.lastInsertId()
}
func errorCode() -> UInt32 {
return connection.errorCode()
}
func errorMessage() -> String {
return connection.errorMessage()
}
deinit {
close()
}
// Do not close the database connection until rollback or commit have been called.
func close() {
if !closed {
ServerStatsKeeper.session.increment(stat: .dbConnectionsClosed)
Log.info("CLOSING DB CONNECTION: opened: \(ServerStatsKeeper.session.currentValue(stat: .dbConnectionsOpened)); closed: \(ServerStatsKeeper.session.currentValue(stat: .dbConnectionsClosed))")
connection = nil
closed = true
}
}
enum TableUpcreateSuccess {
case created
case updated
case alreadyPresent
}
enum TableUpcreateError : Error {
case query
case tableCreation
case columnCreation
case columnRemoval
}
enum TableUpcreateResult {
case success(TableUpcreateSuccess)
case failure(TableUpcreateError)
}
// columnCreateQuery is the table creation query without the prefix "CREATE TABLE <TableName>"
func createTableIfNeeded(tableName:String, columnCreateQuery:String) -> TableUpcreateResult {
let checkForTable = "SELECT * " +
"FROM information_schema.tables " +
"WHERE table_schema = '\(Configuration.server.db.database)' " +
"AND table_name = '\(tableName)' " +
"LIMIT 1;"
guard query(statement: checkForTable) else {
Log.error("Failure: \(self.error)")
return .failure(.query)
}
if let results = connection.storeResults(), results.numRows() == 1 {
Log.info("Table \(tableName) was already in database")
return .success(.alreadyPresent)
}
Log.info("**** Table \(tableName) was not already in database")
let createTable = "CREATE TABLE \(tableName) \(columnCreateQuery) ENGINE=InnoDB;"
guard query(statement: createTable) else {
Log.error("Failure: \(self.error)")
return .failure(.tableCreation)
}
return .success(.created)
}
// Returns nil on error.
func columnExists(_ column:String, in tableName:String) -> Bool? {
let checkForColumn = "SELECT * " +
"FROM information_schema.columns " +
"WHERE table_schema = '\(Configuration.server.db.database)' " +
"AND table_name = '\(tableName)' " +
"AND column_name = '\(column)' " +
"LIMIT 1;"
guard query(statement: checkForColumn) else {
Log.error("Failure: \(self.error)")
return nil
}
if let results = connection.storeResults(), results.numRows() == 1 {
Log.info("Column \(column) was already in database table \(tableName)")
return true
}
Log.info("Column \(column) was not in database table \(tableName)")
return false
}
// column should be something like "newStrCol VARCHAR(255)"
func addColumn(_ column:String, to tableName:String) -> Bool {
let alterTable = "ALTER TABLE \(tableName) ADD \(column)"
guard query(statement: alterTable) else {
Log.error("Failure: \(self.error)")
return false
}
return true
}
func removeColumn(_ columnName:String, from tableName:String) -> Bool {
let alterTable = "ALTER TABLE \(tableName) DROP \(columnName)"
guard query(statement: alterTable) else {
Log.error("Failure: \(self.error)")
return false
}
return true
}
/* References on mySQL transactions, locks, and blocking
http://www.informit.com/articles/article.aspx?p=2036581&seqNum=12
https://dev.mysql.com/doc/refman/5.5/en/innodb-information-schema-understanding-innodb-locking.html
The default isolation level for InnoDB is REPEATABLE READ
See https://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-isolation-levels.html#isolevel_repeatable-read
*/
func startTransaction() -> Bool {
let start = "START TRANSACTION;"
if query(statement: start) {
return true
}
else {
Log.error("Could not start transaction: \(self.error)")
return false
}
}
func commit() -> Bool {
let commit = "COMMIT;"
if query(statement: commit) {
return true
}
else {
Log.error("Could not commit transaction: \(self.error)")
return false
}
}
func rollback() -> Bool {
let rollback = "ROLLBACK;"
if query(statement: rollback) {
return true
}
else {
Log.error("Could not rollback transaction: \(self.error)")
return false
}
}
}
private struct DBLog {
static func query(_ query: String) {
// Log.debug("DB QUERY: \(query)")
}
}
class Select {
private var stmt:MySQLStmt!
private var fieldNames:[Int: String]!
private var fieldTypes:[Int: String]!
private var modelInit:(() -> Model)?
private var ignoreErrors:Bool!
// Pass a mySQL select statement; the modelInit will be used to create the object type that will be returned in forEachRow
// ignoreErrors, if true, will ignore type conversion errors and missing fields in your model. ignoreErrors is only used with `forEachRow`.
init?(db:Database, query:String, modelInit:(() -> Model)? = nil, ignoreErrors:Bool = true) {
self.modelInit = modelInit
self.stmt = MySQLStmt(db.connection)
self.ignoreErrors = ignoreErrors
DBLog.query(query)
if !self.stmt.prepare(statement: query) {
Log.error("Failed on preparing statement: \(query)")
return nil
}
if !self.stmt.execute() {
Log.error("Failed on executing statement: \(query)")
return nil
}
self.fieldTypes = [Int: String]()
for index in 0 ..< Int(stmt.fieldCount()) {
let currField:MySQLStmt.FieldInfo = stmt.fieldInfo(index: index)!
self.fieldTypes[index] = String(describing: currField.type)
}
self.fieldNames = self.stmt.fieldNames()
if self.fieldNames == nil {
Log.error("Failed on stmt.fieldNames: \(query)")
return nil
}
}
enum ProcessResultRowsError : Error {
case failedRowIterator
case unknownFieldType
case failedSettingFieldValueInModel(String)
case problemConvertingFieldValueToModel(String)
}
private(set) var forEachRowStatus: ProcessResultRowsError?
typealias FieldName = String
func numberResultRows() -> Int {
return self.stmt.results().numRows
}
// Check forEachRowStatus after you have finished this -- it will indicate the error, if any.
// TODO: *3* The callback could return a boolean, which indicates whether to continue iterating. This would be useful to enable the iteration to stop, e.g., on an error condition.
func forEachRow(callback:@escaping (_ row: Model?) ->()) {
let results = self.stmt.results()
var failure = false
let returnCode = results.forEachRow { row in
if failure {
return
}
guard let rowModel = self.modelInit?() else {
failure = true
return
}
for fieldNumber in 0 ..< results.numFields {
guard let fieldName = self.fieldNames[fieldNumber] else {
Log.error("Failed on getting field name for field number: \(fieldNumber)")
failure = true
return
}
guard fieldNumber < row.count else {
Log.error("Field number exceeds row.count: \(fieldNumber)")
failure = true
return
}
// If this particular field is nil (not given), then skip it. Won't return it in the row.
guard var rowFieldValue: Any = row[fieldNumber] else {
continue
}
guard let fieldType = self.fieldTypes[fieldNumber] else {
failure = true
return
}
switch fieldType {
case "integer", "double", "string", "date":
break
case "bytes":
if let bytes = rowFieldValue as? Array<UInt8> {
// Assume this is actually a String. Some Text fields come back this way.
if let str = String(bytes: bytes, encoding: String.Encoding.utf8) {
rowFieldValue = str
}
}
default:
Log.error("Unknown field type: \(String(describing: self.fieldTypes[fieldNumber])); fieldNumber: \(fieldNumber)")
if !ignoreErrors {
self.forEachRowStatus = .unknownFieldType
failure = true
return
}
}
if let converter = rowModel.typeConvertersToModel(propertyName: fieldName) {
let value = converter(rowFieldValue)
if value == nil {
if ignoreErrors! {
continue
}
else {
let message = "Problem with converting: \(String(describing: self.fieldTypes[fieldNumber])); fieldNumber: \(fieldNumber)"
Log.error(message)
self.forEachRowStatus = .problemConvertingFieldValueToModel(message)
failure = true
return
}
}
else {
rowFieldValue = value!
}
}
rowModel[fieldName] = rowFieldValue
} // end for
callback(rowModel)
}
if !returnCode {
self.forEachRowStatus = .failedRowIterator
}
}
enum SingleValueResult {
case success(Any?)
case error
}
// Returns a single value from a single row result. E.g., for SELECT GET_LOCK.
func getSingleRowValue() -> SingleValueResult {
let stmtResults = self.stmt.results()
guard stmtResults.numRows == 1, stmtResults.numFields == 1 else {
return .error
}
var result: Any?
let returnCode = stmtResults.forEachRow { row in
result = row[0]
}
if !returnCode {
return .error
}
return .success(result)
}
}
extension Database {
// This intended for a one-off insert of a row, or row updates.
class PreparedStatement {
enum ValueType {
case null
case int(Int)
case int64(Int64)
case string(String)
case bool(Bool)
}
enum Errors : Error {
case failedOnPreparingStatement
case executionError
}
private var stmt:MySQLStmt!
private var repo: RepositoryBasics!
private var statementType: StatementType!
private var valueTypes = [ValueType]()
private var fieldNames = [String]()
private var whereValueTypes = [ValueType]()
private var whereFieldNames = [String]()
enum StatementType {
case insert
case update
}
init(repo: RepositoryBasics, type: StatementType) {
self.repo = repo
self.stmt = MySQLStmt(repo.db.connection)
self.statementType = type
}
// For an insert, these are the fields and values for the row you are inserting. For an update, these are the fields and values for the updated row.
func add(fieldName: String, value: ValueType) {
fieldNames += [fieldName]
valueTypes += [value]
}
// For an update only, provide the (conjoined) parts of the where clause.
func `where`(fieldName: String, value: ValueType) {
assert(statementType == .update)
whereFieldNames += [fieldName]
whereValueTypes += [value]
}
// Returns the id of the inserted row for an insert. For an update, returns the number of rows updated.
@discardableResult
func run() throws -> Int64 {
// The insert query has `?` where values would be. See also https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection
var query:String
switch statementType! {
case .insert:
var formattedFieldNames = ""
var bindParams = ""
fieldNames.forEach { fieldName in
if formattedFieldNames.count > 0 {
formattedFieldNames += ","
bindParams += ","
}
formattedFieldNames += fieldName
bindParams += "?"
}
query = "INSERT INTO \(repo.tableName) (\(formattedFieldNames)) VALUES (\(bindParams))"
case .update:
var setValues = ""
fieldNames.forEach { fieldName in
if setValues.count > 0 {
setValues += ","
}
setValues += "\(fieldName)=?"
}
var whereClause = ""
if whereFieldNames.count > 0 {
whereClause = "WHERE "
var count = 0
whereFieldNames.forEach { whereFieldName in
if count > 0 {
whereClause += " and "
}
count += 1
whereClause += "\(whereFieldName)=?"
}
}
query = "UPDATE \(repo.tableName) SET \(setValues) \(whereClause)"
}
Log.debug("Preparing query: \(query)")
DBLog.query(query)
guard self.stmt.prepare(statement: query) else {
Log.error("Failed on preparing statement: \(query)")
throw Errors.failedOnPreparingStatement
}
for valueType in valueTypes + whereValueTypes {
switch valueType {
case .null:
self.stmt.bindParam()
case .int(let intValue):
self.stmt.bindParam(intValue)
case .int64(let int64Value):
self.stmt.bindParam(int64Value)
case .string(let stringValue):
self.stmt.bindParam(stringValue)
case .bool(let boolValue):
// Bool is TINYINT(1), which is Int8; https://dev.mysql.com/doc/refman/8.0/en/numeric-type-overview.html
self.stmt.bindParam(Int8(boolValue ? 1 : 0))
}
}
guard self.stmt.execute() else {
throw Errors.executionError
}
switch statementType! {
case .insert:
return repo.db.connection.lastInsertId()
case .update:
return repo.db.connection.numberAffectedRows()
}
}
}
}
| mit |
vmanot/swift-package-manager | Fixtures/Miscellaneous/-DSWIFT_PACKAGE/Package.swift | 4 | 79 | import PackageDescription
let package = Package(name: "PackageManagerDefine")
| apache-2.0 |
yonadev/yona-app-ios | Yona/YonaTests/BuddyAPITests.swift | 1 | 3127 | //
// BuddyAPITests.swift
// Yona
//
// Created by Ben Smith on 11/05/16.
// Copyright © 2016 Yona. All rights reserved.
//
import Foundation
import XCTest
@testable import Yona
class BuddyAPITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
func testPostBuddy(){
let expectation = self.expectation(description: "Waiting to respond")
var randomPhoneNumber = String(Int(arc4random_uniform(9999999)))
let body =
["firstName": "Richard",
"lastName": "Quin",
"mobileNumber": "+31999" + randomPhoneNumber,
"nickname": "RQ"]
UserRequestManager.sharedInstance.postUser(body, confirmCode: nil) { (success, message, code, user) in
print("PASSWORD: " + KeychainManager.sharedInstance.getYonaPassword()!)
print("USER ID: " + KeychainManager.sharedInstance.getUserID()!)
UserRequestManager.sharedInstance.confirmMobileNumber(["code":YonaConstants.testKeys.otpTestCode], onCompletion: { (success, message, code) in
randomPhoneNumber = String(Int(arc4random_uniform(9999999)))
let postBuddyBody: [String:AnyObject] = [
postBuddyBodyKeys.sendingStatus.rawValue: buddyRequestStatus.REQUESTED.rawValue,
postBuddyBodyKeys.receivingStatus.rawValue: buddyRequestStatus.REQUESTED.rawValue,
postBuddyBodyKeys.message.rawValue: "Hi there, would you want to become my buddy?",
postBuddyBodyKeys.embedded.rawValue: [
postBuddyBodyKeys.yonaUser.rawValue: [ //this is the details of the person you are adding
addUserKeys.emailAddress.rawValue: "richard@quin.net",
addUserKeys.firstNameKey.rawValue: "Richard",
addUserKeys.lastNameKeys.rawValue: "Quin",
addUserKeys.mobileNumberKeys.rawValue: "+31999" + randomPhoneNumber //this is the number of the person you are adding as a buddy
]
]
]
BuddyRequestManager.sharedInstance.requestNewbuddy(postBuddyBody, onCompletion: { (success, message, code, buddy, buddies) in
XCTAssert(success, message!)
if success {
expectation.fulfill()
}
})
})
}
waitForExpectations(timeout: 100.0, handler:nil)
}
}
| mpl-2.0 |
YevhenHerasymenko/SwiftGroup1 | Classes.playground/Contents.swift | 1 | 1913 | //: Playground - noun: a place where people can play
import UIKit
for i in 1...100 {
if i%2 == 0 {
continue
}
if i == 51 {
break
}
i
}
class Pupil {
var str: String!
func myOpenFunc() {
myTestFunc()
}
private func myTestFunc() {
}
}
class School {
var pupil: Pupil!
func myFunc() {
pupil.myOpenFunc()
}
}
class Human {
var name: String!
func testFunc() {
}
func call() {
print("I am a Human")
}
}
class Worker: Human, MyProtocol {
var variable: Int!
func myFunc() {
name
testFunc()
call()
}
override func call() {
super.call()
print("I am a Worker")
}
func myProtocolFunc() {
}
}
class PlantWorker: Worker {
// var _plantName: String!
private var plantName: String! {
// willSet {
//
// }
didSet {
}
// get {
// return _plantName
// }
// set {
// _plantName = newValue
// }
}
func plantFunc() {
plantName = "Google"
}
}
class MyClass {
var whatever: Any! = "sdfsd"
var variable: Int!
}
extension MyClass: MyProtocol {
func myProtocolFunc() {
whatever = MyTestClass()
}
}
struct MyStruct {
}
class MyTestClass {
}
extension MyClass {
//var str: String!
func myExtensionFunc() {
}
}
protocol MyProtocol {
var variable: Int! { get set }
func myProtocolFunc()
func secondProtocolFunc()
}
extension MyProtocol where Self: Worker {
func secondProtocolFunc() {
name
}
}
extension MyProtocol {
func secondProtocolFunc() {
}
}
| apache-2.0 |
natmark/SlideStock | SlideStock/ViewModels/ImportViewModel.swift | 1 | 3271 | //
// ImportViewModel.swift
// SlideStock
//
// Created by AtsuyaSato on 2017/05/03.
// Copyright © 2017年 Atsuya Sato. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import Kanna
import RealmSwift
class ImportViewModel {
init() {
bindSearchRequest()
}
let error = PublishSubject<Error>()
let urlString = PublishSubject<String>()
let slideId = PublishSubject<String>()
let slideTitle = PublishSubject<String>()
let slideAuthor = PublishSubject<String>()
let pdfURL = PublishSubject<String>()
var loading: Observable<Bool> {
return isLoading.asObservable()
}
var componentsHidden: Observable<Bool> {
return Observable
.combineLatest(slideTitle, slideAuthor, slideId) { slideTitle, slideAuthor, slideId -> Bool in
return slideTitle.isEmpty || slideAuthor.isEmpty || slideId.isEmpty
}
.startWith(true)
}
var importSlide: Observable<Void> {
return Observable
.zip(slideTitle, slideAuthor, slideId, pdfURL, importTrigger) { slideTitle, slideAuthor, slideId, pdfURL, importTrigger -> Void in
let slide = Slide()
slide.title = slideTitle
slide.author = slideAuthor
slide.id = slideId
slide.pdfURL = pdfURL
let realm = try! Realm()
try? realm.write {
realm.add(slide, update: true)
}
}
}
fileprivate let disposeBag = DisposeBag()
fileprivate let isLoading: Variable<Bool> = Variable(false)
let importTrigger = PublishSubject<Void>()
let requestCompleted = PublishSubject<Slide>()
fileprivate func bindSearchRequest() {
let backgroundScheduler = SerialDispatchQueueScheduler(qos: .default)
urlString
.observeOn(backgroundScheduler)
.subscribe(onNext: { path in
do {
print(path)
let data = try FetchSlideRequest.getHTML(path: path.replacingOccurrences(of: "https://speakerdeck.com/", with: ""))
let doc = HTML(html: data, encoding: String.Encoding.utf8)
guard let details = doc?.body?.css("div#talk-details").first else { return }
guard let title = details.css("h1").first?.innerHTML else { return }
guard let author = details.css("a").first?.innerHTML else { return }
guard let pdfURL = doc?.body?.css("#share_pdf").first?["href"] else { return }
guard let slidesContainer = doc?.body?.css("div#slides_container").first?.innerHTML else { return }
var ans: [String] = []
if !slidesContainer.pregMatche(pattern: "data-id=\"([a-z0-9]+)\"", matches: &ans) || ans.count < 2 {
return
}
let id = ans[1]
self.slideId.onNext(id)
self.slideAuthor.onNext(author)
self.slideTitle.onNext(title)
self.pdfURL.onNext(pdfURL)
} catch {
}
})
.addDisposableTo(disposeBag)
}
}
| mit |
maxbritto/cours-ios11-swift4 | Maitriser/Objectif 1/realm_demo/realm_demo/ViewController.swift | 1 | 1242 | //
// ViewController.swift
// realm_demo
//
// Created by Maxime Britto on 12/09/2017.
// Copyright © 2017 Maxime Britto. All rights reserved.
//
import UIKit
import RealmSwift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
listObjects()
}
func listObjects() {
let realm = try! Realm()
let playerList = realm.objects(Player.self)
for player in playerList {
print(player.name)
}
}
func addObject() {
let p1 = Player()
p1.name = "Sheldon"
p1.score = -1
print("Score p1 : \(p1.score)")
let realm = try! Realm()
realm.beginWrite()
realm.add(p1)
p1.name = "Toto"
try? realm.commitWrite()
realm.beginWrite()
p1.name = "Tata"
try! realm.commitWrite()
/*
try? realm.write {
realm.delete(p1)
}
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 |
dropbox/SwiftyDropbox | Source/SwiftyDropbox/Shared/Handwritten/DropboxTransportClient.swift | 1 | 28730 | ///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
import Foundation
import Alamofire
/// Constants used to make API requests. e.g. server addresses and default user agent to be used.
enum ApiClientConstants {
static let apiHost = "https://api.dropbox.com"
static let contentHost = "https://api-content.dropbox.com"
static let notifyHost = "https://notify.dropboxapi.com"
static let defaultUserAgent = "OfficialDropboxSwiftSDKv2/\(Constants.versionSDK)"
}
open class DropboxTransportClient {
struct SwiftyArgEncoding: ParameterEncoding {
fileprivate let rawJsonRequest: Data
init(rawJsonRequest: Data) {
self.rawJsonRequest = rawJsonRequest
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = urlRequest.urlRequest
urlRequest!.httpBody = rawJsonRequest
return urlRequest!
}
}
public let manager: Session
public let longpollManager: Session
public var accessTokenProvider: AccessTokenProvider
open var selectUser: String?
open var pathRoot: Common.PathRoot?
var baseHosts: [String: String]
var userAgent: String
public convenience init(accessToken: String,
selectUser: String? = nil,
pathRoot: Common.PathRoot? = nil) {
self.init(accessToken: accessToken,
baseHosts: nil,
userAgent: nil,
selectUser: selectUser,
pathRoot: pathRoot)
}
public convenience init(
accessToken: String,
baseHosts: [String: String]?,
userAgent: String?,
selectUser: String?,
sessionDelegate: SessionDelegate? = nil,
longpollSessionDelegate: SessionDelegate? = nil,
serverTrustPolicyManager: ServerTrustManager? = nil,
sharedContainerIdentifier: String? = nil,
pathRoot: Common.PathRoot? = nil
) {
self.init(
accessTokenProvider: LongLivedAccessTokenProvider(accessToken: accessToken),
baseHosts: baseHosts,
userAgent: userAgent,
selectUser: selectUser,
sessionDelegate: sessionDelegate,
longpollSessionDelegate: longpollSessionDelegate,
serverTrustPolicyManager: serverTrustPolicyManager,
sharedContainerIdentifier: sharedContainerIdentifier,
pathRoot: pathRoot
)
}
public convenience init(
accessTokenProvider: AccessTokenProvider, selectUser: String? = nil, pathRoot: Common.PathRoot? = nil
) {
self.init(
accessTokenProvider: accessTokenProvider, baseHosts: nil,
userAgent: nil, selectUser: selectUser, pathRoot: pathRoot
)
}
public init(
accessTokenProvider: AccessTokenProvider,
baseHosts: [String: String]?,
userAgent: String?,
selectUser: String?,
sessionDelegate: SessionDelegate? = nil,
longpollSessionDelegate: SessionDelegate? = nil,
serverTrustPolicyManager: ServerTrustManager? = nil,
sharedContainerIdentifier: String? = nil,
pathRoot: Common.PathRoot? = nil
) {
let config = URLSessionConfiguration.default
let delegate = sessionDelegate ?? SessionDelegate()
let serverTrustPolicyManager = serverTrustPolicyManager ?? nil
let manager = Session(configuration: config,
delegate: delegate,
startRequestsImmediately: false,
serverTrustManager: serverTrustPolicyManager)
let longpollConfig = URLSessionConfiguration.default
longpollConfig.timeoutIntervalForRequest = 480.0
let longpollSessionDelegate = longpollSessionDelegate ?? SessionDelegate()
let longpollManager = Session(configuration: longpollConfig,
delegate: longpollSessionDelegate,
serverTrustManager: serverTrustPolicyManager)
let defaultBaseHosts = [
"api": "\(ApiClientConstants.apiHost)/2",
"content": "\(ApiClientConstants.contentHost)/2",
"notify": "\(ApiClientConstants.notifyHost)/2",
]
let defaultUserAgent = ApiClientConstants.defaultUserAgent
self.manager = manager
self.longpollManager = longpollManager
self.accessTokenProvider = accessTokenProvider
self.selectUser = selectUser
self.pathRoot = pathRoot;
self.baseHosts = baseHosts ?? defaultBaseHosts
if let userAgent = userAgent {
let customUserAgent = "\(userAgent)/\(defaultUserAgent)"
self.userAgent = customUserAgent
} else {
self.userAgent = defaultUserAgent
}
}
open func request<ASerial, RSerial, ESerial>(
_ route: Route<ASerial, RSerial, ESerial>, serverArgs: ASerial.ValueType? = nil
) -> RpcRequest<RSerial, ESerial> {
let requestCreation = { self.createRpcRequest(route: route, serverArgs: serverArgs) }
let request = RequestWithTokenRefresh(requestCreation: requestCreation, tokenProvider: accessTokenProvider)
return RpcRequest(
request: request,
responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer
)
}
open func request<ASerial, RSerial, ESerial>(
_ route: Route<ASerial, RSerial, ESerial>, serverArgs: ASerial.ValueType, input: UploadBody
) -> UploadRequest<RSerial, ESerial> {
let requestCreation = { self.createUploadRequest(route: route, serverArgs: serverArgs, input: input) }
let request = RequestWithTokenRefresh(
requestCreation: requestCreation, tokenProvider: accessTokenProvider
)
return UploadRequest(
request: request,
responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer
)
}
open func request<ASerial, RSerial, ESerial>(
_ route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType,
overwrite: Bool,
destination: @escaping (URL, HTTPURLResponse) -> URL
) -> DownloadRequestFile<RSerial, ESerial> {
weak var weakDownloadRequest: DownloadRequestFile<RSerial, ESerial>!
let destinationWrapper: DownloadRequest.Destination = { url, resp in
var finalUrl = destination(url, resp)
if 200 ... 299 ~= resp.statusCode {
if FileManager.default.fileExists(atPath: finalUrl.path) {
if overwrite {
do {
try FileManager.default.removeItem(at: finalUrl)
} catch let error as NSError {
print("Error: \(error)")
}
} else {
print("Error: File already exists at \(finalUrl.path)")
}
}
} else {
weakDownloadRequest.errorMessage = try! Data(contentsOf: url)
// Alamofire will "move" the file to the temporary location where it already resides,
// and where it will soon be automatically deleted
finalUrl = url
}
weakDownloadRequest.urlPath = finalUrl
return (finalUrl, [])
}
let requestCreation = {
self.createDownloadFileRequest(
route: route, serverArgs: serverArgs,
overwrite: overwrite, downloadFileDestination: destinationWrapper
)
}
let request = RequestWithTokenRefresh(requestCreation: requestCreation, tokenProvider: accessTokenProvider)
let downloadRequest = DownloadRequestFile(
request: request,
responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer
)
weakDownloadRequest = downloadRequest
return downloadRequest
}
public func request<ASerial, RSerial, ESerial>(_ route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType) -> DownloadRequestMemory<RSerial, ESerial> {
let requestCreation = {
self.createDownloadMemoryRequest(route: route, serverArgs: serverArgs)
}
let request = RequestWithTokenRefresh(requestCreation: requestCreation, tokenProvider: accessTokenProvider)
return DownloadRequestMemory(
request: request, responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer
)
}
private func getHeaders(_ routeStyle: RouteStyle, jsonRequest: Data?, host: String) -> HTTPHeaders {
var headers = ["User-Agent": userAgent]
let noauth = (host == "notify")
if (!noauth) {
headers["Authorization"] = "Bearer \(accessTokenProvider.accessToken)"
if let selectUser = selectUser {
headers["Dropbox-Api-Select-User"] = selectUser
}
if let pathRoot = pathRoot {
let obj = Common.PathRootSerializer().serialize(pathRoot)
headers["Dropbox-Api-Path-Root"] = utf8Decode(SerializeUtil.dumpJSON(obj)!)
}
}
if (routeStyle == RouteStyle.Rpc) {
headers["Content-Type"] = "application/json"
} else if (routeStyle == RouteStyle.Upload) {
headers["Content-Type"] = "application/octet-stream"
if let jsonRequest = jsonRequest {
let value = asciiEscape(utf8Decode(jsonRequest))
headers["Dropbox-Api-Arg"] = value
}
} else if (routeStyle == RouteStyle.Download) {
if let jsonRequest = jsonRequest {
let value = asciiEscape(utf8Decode(jsonRequest))
headers["Dropbox-Api-Arg"] = value
}
}
return headers.toHTTPHeaders()
}
private func createRpcRequest<ASerial, RSerial, ESerial>(
route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType? = nil
) -> Alamofire.DataRequest {
let host = route.attrs["host"]! ?? "api"
var routeName = route.name
if route.version > 1 {
routeName = String(format: "%@_v%d", route.name, route.version)
}
let url = "\(baseHosts[host]!)/\(route.namespace)/\(routeName)"
let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)!
var rawJsonRequest: Data?
rawJsonRequest = nil
if let serverArgs = serverArgs {
let jsonRequestObj = route.argSerializer.serialize(serverArgs)
rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj)
} else {
let voidSerializer = route.argSerializer as! VoidSerializer
let jsonRequestObj = voidSerializer.serialize(())
rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj)
}
let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host)
let customEncoding = SwiftyArgEncoding(rawJsonRequest: rawJsonRequest!)
let managerToUse = { () -> Session in
// longpoll requests have a much longer timeout period than other requests
if type(of: route) == type(of: Files.listFolderLongpoll) {
return self.longpollManager
}
return self.manager
}()
let request = managerToUse.request(
url, method: .post, parameters: ["jsonRequest": rawJsonRequest!],
encoding: customEncoding, headers: headers
)
request.task?.priority = URLSessionTask.highPriority
return request
}
private func createUploadRequest<ASerial, RSerial, ESerial>(
route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType, input: UploadBody
) -> Alamofire.UploadRequest {
let host = route.attrs["host"]! ?? "api"
var routeName = route.name
if route.version > 1 {
routeName = String(format: "%@_v%d", route.name, route.version)
}
let url = "\(baseHosts[host]!)/\(route.namespace)/\(routeName)"
let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)!
let jsonRequestObj = route.argSerializer.serialize(serverArgs)
let rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj)
let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host)
let request: Alamofire.UploadRequest
switch input {
case let .data(data):
request = manager.upload(data, to: url, method: .post, headers: headers)
case let .file(file):
request = manager.upload(file, to: url, method: .post, headers: headers)
case let .stream(stream):
request = manager.upload(stream, to: url, method: .post, headers: headers)
}
return request
}
private func createDownloadFileRequest<ASerial, RSerial, ESerial>(
route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType,
overwrite: Bool,
downloadFileDestination: @escaping DownloadRequest.Destination
) -> DownloadRequest {
let host = route.attrs["host"]! ?? "api"
var routeName = route.name
if route.version > 1 {
routeName = String(format: "%@_v%d", route.name, route.version)
}
let url = "\(baseHosts[host]!)/\(route.namespace)/\(routeName)"
let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)!
let jsonRequestObj = route.argSerializer.serialize(serverArgs)
let rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj)
let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host)
return manager.download(url, method: .post, headers: headers, to: downloadFileDestination)
}
private func createDownloadMemoryRequest<ASerial, RSerial, ESerial>(
route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType
) -> DataRequest {
let host = route.attrs["host"]! ?? "api"
let url = "\(baseHosts[host]!)/\(route.namespace)/\(route.name)"
let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)!
let jsonRequestObj = route.argSerializer.serialize(serverArgs)
let rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj)
let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host)
return manager.request(url, method: .post, headers: headers)
}
}
open class Box<T> {
public let unboxed: T
init (_ v: T) { self.unboxed = v }
}
public enum DropboxTransportClientError: Error {
case objectAlreadyDeinit
}
public enum CallError<EType>: CustomStringConvertible {
case internalServerError(Int, String?, String?)
case badInputError(String?, String?)
case rateLimitError(Auth.RateLimitError, String?, String?, String?)
case httpError(Int?, String?, String?)
case authError(Auth.AuthError, String?, String?, String?)
case accessError(Auth.AccessError, String?, String?, String?)
case routeError(Box<EType>, String?, String?, String?)
case clientError(Error?)
public var description: String {
switch self {
case let .internalServerError(code, message, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "Internal Server Error \(code)"
if let m = message {
ret += ": \(m)"
}
return ret
case let .badInputError(message, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "Bad Input"
if let m = message {
ret += ": \(m)"
}
return ret
case let .authError(error, _, _, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "API auth error - \(error)"
return ret
case let .accessError(error, _, _, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "API access error - \(error)"
return ret
case let .httpError(code, message, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "HTTP Error"
if let c = code {
ret += "\(c)"
}
if let m = message {
ret += ": \(m)"
}
return ret
case let .routeError(box, _, _, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "API route error - \(box.unboxed)"
return ret
case let .rateLimitError(error, _, _, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "API rate limit error - \(error)"
return ret
case let .clientError(err):
if let e = err {
return "\(e)"
}
return "An unknown system error"
}
}
}
func utf8Decode(_ data: Data) -> String {
return NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
}
func asciiEscape(_ s: String) -> String {
var out: String = ""
for char in s.unicodeScalars {
var esc = "\(char)"
if !char.isASCII {
esc = NSString(format:"\\u%04x", char.value) as String
} else {
esc = "\(char)"
}
out += esc
}
return out
}
public enum RouteStyle: String {
case Rpc = "rpc"
case Upload = "upload"
case Download = "download"
case Other
}
public enum UploadBody {
case data(Data)
case file(URL)
case stream(InputStream)
}
/// These objects are constructed by the SDK; users of the SDK do not need to create them manually.
///
/// Pass in a closure to the `response` method to handle a response or error.
open class Request<RSerial: JSONSerializer, ESerial: JSONSerializer> {
let responseSerializer: RSerial
let errorSerializer: ESerial
fileprivate let request: ApiRequest
private var selfRetain: AnyObject?
init(request: ApiRequest, responseSerializer: RSerial, errorSerializer: ESerial) {
self.errorSerializer = errorSerializer
self.responseSerializer = responseSerializer
self.request = request
self.selfRetain = self
request.setCleanupHandler { [weak self] in
self?.cleanupSelfRetain()
}
}
public func cancel() {
request.cancel()
}
func handleResponseError(_ response: HTTPURLResponse?, data: Data?, error: Error?) -> CallError<ESerial.ValueType> {
let requestId = response?.allHeaderFields["X-Dropbox-Request-Id"] as? String
if let code = response?.statusCode {
switch code {
case 500...599:
var message = ""
if let d = data {
message = utf8Decode(d)
}
return .internalServerError(code, message, requestId)
case 400:
var message = ""
if let d = data {
message = utf8Decode(d)
}
return .badInputError(message, requestId)
case 401:
let json = SerializeUtil.parseJSON(data!)
switch json {
case .dictionary(let d):
return .authError(Auth.AuthErrorSerializer().deserialize(d["error"]!), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"), requestId)
default:
fatalError("Failed to parse error type")
}
case 403:
let json = SerializeUtil.parseJSON(data!)
switch json {
case .dictionary(let d):
return .accessError(Auth.AccessErrorSerializer().deserialize(d["error"]!), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"),requestId)
default:
fatalError("Failed to parse error type")
}
case 409:
let json = SerializeUtil.parseJSON(data!)
switch json {
case .dictionary(let d):
return .routeError(Box(self.errorSerializer.deserialize(d["error"]!)), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"), requestId)
default:
fatalError("Failed to parse error type")
}
case 429:
let json = SerializeUtil.parseJSON(data!)
switch json {
case .dictionary(let d):
return .rateLimitError(Auth.RateLimitErrorSerializer().deserialize(d["error"]!), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"), requestId)
default:
fatalError("Failed to parse error type")
}
case 200:
return .clientError(error)
default:
return .httpError(code, "An error occurred.", requestId)
}
} else if response == nil {
return .clientError(error)
} else {
var message = ""
if let d = data {
message = utf8Decode(d)
}
return .httpError(nil, message, requestId)
}
}
func getStringFromJson(json: [String : JSON], key: String) -> String {
if let jsonStr = json[key] {
switch jsonStr {
case .str(let str):
return str;
default:
break;
}
}
return "";
}
private func cleanupSelfRetain() {
self.selfRetain = nil
}
}
/// An "rpc-style" request
open class RpcRequest<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> {
@discardableResult
public func response(
queue: DispatchQueue? = nil,
completionHandler: @escaping (RSerial.ValueType?, CallError<ESerial.ValueType>?) -> Void
) -> Self {
request.setCompletionHandler(queue: queue, completionHandler: .dataCompletionHandler({ [weak self] response in
guard let strongSelf = self else {
completionHandler(nil, .clientError(DropboxTransportClientError.objectAlreadyDeinit))
return
}
if let error = response.error {
completionHandler(nil, strongSelf.handleResponseError(response.response, data: response.data, error: error))
} else {
completionHandler(strongSelf.responseSerializer.deserialize(SerializeUtil.parseJSON(response.data!)), nil)
}
}))
return self
}
}
/// An "upload-style" request
open class UploadRequest<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> {
@discardableResult
public func progress(_ progressHandler: @escaping ((Progress) -> Void)) -> Self {
request.setProgressHandler(progressHandler)
return self
}
@discardableResult
public func response(
queue: DispatchQueue? = nil,
completionHandler: @escaping (RSerial.ValueType?, CallError<ESerial.ValueType>?) -> Void
) -> Self {
request.setCompletionHandler(queue: queue, completionHandler: .dataCompletionHandler({ [weak self] response in
guard let strongSelf = self else {
completionHandler(nil, .clientError(DropboxTransportClientError.objectAlreadyDeinit))
return
}
if let error = response.error {
completionHandler(nil, strongSelf.handleResponseError(response.response, data: response.data, error: error))
} else {
completionHandler(strongSelf.responseSerializer.deserialize(SerializeUtil.parseJSON(response.data!)), nil)
}
}))
return self
}
}
/// A "download-style" request to a file
open class DownloadRequestFile<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> {
var urlPath: URL?
var errorMessage: Data
override init(request: ApiRequest, responseSerializer: RSerial, errorSerializer: ESerial) {
urlPath = nil
errorMessage = Data()
super.init(request: request, responseSerializer: responseSerializer, errorSerializer: errorSerializer)
}
@discardableResult
public func progress(_ progressHandler: @escaping ((Progress) -> Void)) -> Self {
request.setProgressHandler(progressHandler)
return self
}
@discardableResult
public func response(
queue: DispatchQueue? = nil,
completionHandler: @escaping ((RSerial.ValueType, URL)?, CallError<ESerial.ValueType>?) -> Void
) -> Self {
request.setCompletionHandler(queue: queue, completionHandler: .downloadFileCompletionHandler({ [weak self] response in
guard let strongSelf = self else {
completionHandler(nil, .clientError(DropboxTransportClientError.objectAlreadyDeinit))
return
}
if let error = response.error {
completionHandler(
nil, strongSelf.handleResponseError(response.response, data: strongSelf.errorMessage, error: error)
)
} else {
let headerFields: [AnyHashable : Any] = response.response!.allHeaderFields
let result = caseInsensitiveLookup("Dropbox-Api-Result", dictionary: headerFields)!
let resultData = result.data(using: .utf8, allowLossyConversion: false)
let resultObject = strongSelf.responseSerializer.deserialize(SerializeUtil.parseJSON(resultData!))
completionHandler((resultObject, strongSelf.urlPath!), nil)
}
}))
return self
}
}
/// A "download-style" request to memory
open class DownloadRequestMemory<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> {
@discardableResult
public func progress(_ progressHandler: @escaping ((Progress) -> Void)) -> Self {
request.setProgressHandler(progressHandler)
return self
}
@discardableResult
public func response(
queue: DispatchQueue? = nil,
completionHandler: @escaping ((RSerial.ValueType, Data)?, CallError<ESerial.ValueType>?) -> Void
) -> Self {
request.setCompletionHandler(queue: queue, completionHandler: .dataCompletionHandler({ [weak self] response in
guard let strongSelf = self else {
completionHandler(nil, .clientError(DropboxTransportClientError.objectAlreadyDeinit))
return
}
if let error = response.error {
completionHandler(nil, strongSelf.handleResponseError(response.response, data: response.data, error: error))
} else {
let headerFields: [AnyHashable : Any] = response.response!.allHeaderFields
let result = caseInsensitiveLookup("Dropbox-Api-Result", dictionary: headerFields)!
let resultData = result.data(using: .utf8, allowLossyConversion: false)
let resultObject = strongSelf.responseSerializer.deserialize(SerializeUtil.parseJSON(resultData!))
// An empty file can cause the response data to be nil.
// If nil is encountered, we convert to an empty Data object.
completionHandler((resultObject, response.data ?? Data()), nil)
}
}))
return self
}
}
func caseInsensitiveLookup(_ lookupKey: String, dictionary: [AnyHashable : Any]) -> String? {
for key in dictionary.keys {
let keyString = key as! String
if (keyString.lowercased() == lookupKey.lowercased()) {
return dictionary[key] as? String
}
}
return nil
}
| mit |
lemonkey/iOS | WatchKit/_Apple/ListerforAppleWatchiOSandOSX/Swift/Common/List.swift | 1 | 4687 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `List` class manages a list of items and the color of the list.
*/
import Foundation
/**
The `List` class manages the color of a list and each `ListItem` object. `List` objects are copyable and
archivable. `List` objects are normally associated with an object that conforms to `ListPresenterType`.
This object manages how the list is presented, archived, and manipulated. To ensure that the `List` class
is unarchivable from an instance that was archived in the Objective-C version of Lister, the `List` class
declaration is annotated with @objc(AAPLList). This annotation ensures that the runtime name of the `List`
class is the same as the `AAPLList` class defined in the Objective-C version of the app. It also allows
the Objective-C version of Lister to unarchive a `List` instance that was archived in the Swift version.
*/
@objc(AAPLList)
final public class List: NSObject, NSCoding, NSCopying, DebugPrintable {
// MARK: Types
/**
String constants that are used to archive the stored properties of a `List`. These constants
are used to help implement `NSCoding`.
*/
private struct SerializationKeys {
static let items = "items"
static let color = "color"
}
/**
The possible colors a list can have. Because a list's color is specific to a `List` object,
it is represented by a nested type. The `Printable` representation of the enumeration is
the name of the value. For example, .Gray corresponds to "Gray".
- Gray (default)
- Blue
- Green
- Yellow
- Orange
- Red
*/
public enum Color: Int, Printable {
case Gray, Blue, Green, Yellow, Orange, Red
// MARK: Properties
public var name: String {
switch self {
case .Gray: return "Gray"
case .Blue: return "Blue"
case .Green: return "Green"
case .Orange: return "Orange"
case .Yellow: return "Yellow"
case .Red: return "Red"
}
}
// MARK: Printable
public var description: String {
return name
}
}
// MARK: Properties
/// The list's color. This property is stored when it is archived and read when it is unarchived.
public var color: Color
/// The list's items.
public var items = [ListItem]()
// MARK: Initializers
/**
Initializes a `List` instance with the designated color and items. The default color of a `List` is
gray.
:param: color The intended color of the list.
:param: items The items that represent the underlying list. The `List` class copies the items
during initialization.
*/
public init(color: Color = .Gray, items: [ListItem] = []) {
self.color = color
self.items = items.map { $0.copy() as! ListItem }
}
// MARK: NSCoding
public required init(coder aDecoder: NSCoder) {
items = aDecoder.decodeObjectForKey(SerializationKeys.items) as! [ListItem]
color = Color(rawValue: aDecoder.decodeIntegerForKey(SerializationKeys.color))!
}
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(items, forKey: SerializationKeys.items)
aCoder.encodeInteger(color.rawValue, forKey: SerializationKeys.color)
}
// MARK: NSCopying
public func copyWithZone(zone: NSZone) -> AnyObject {
return List(color: color, items: items)
}
// MARK: Equality
/**
Overrides NSObject's isEqual(_:) instance method to return whether the list is equal to
another list. A `List` is considered to be equal to another `List` if its color and items
are equal.
:param: object Any object, or nil.
:returns: `true` if the object is a `List` and it has the same color and items as the receiving
instance. `false` otherwise.
*/
override public func isEqual(object: AnyObject?) -> Bool {
if let list = object as? List {
if color != list.color {
return false
}
return items == list.items
}
return false
}
// MARK: DebugPrintable
public override var debugDescription: String {
return "{color: \(color), items: \(items)}"
}
}
| mit |
leonljy/PerfectLunch | Sources/App/Models/Restaurant.swift | 1 | 2096 | //
// Restaurant.swift
// Perfectlunch
//
// Created by Jeong-Uk Lee on 2017. 10. 10..
//
import Vapor
import FluentProvider
import HTTP
final class Restaurant: Model {
var storage = Storage()
var name: String
/// The column names for `id` and `content` in the database
struct Keys {
static let id = "id"
static let name = "name"
}
init(name: String) {
self.name = name
}
func makeRow() throws -> Row {
var row = Row()
try row.set(Restaurant.Keys.name, name)
return row
}
init(row: Row) throws {
name = try row.get(Restaurant.Keys.name)
}
}
extension Restaurant: Preparation {
/// Prepares a table/collection in the database
/// for storing Posts
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
builder.id()
builder.string(Restaurant.Keys.name)
}
}
/// Undoes what was done in `prepare`
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
extension Restaurant: Equatable, CustomStringConvertible, Hashable {
public static func ==(lhs: Restaurant, rhs: Restaurant) -> Bool {
return lhs.name == rhs.name
}
public var hashValue: Int {
return self.name.hashValue
}
public var description: String {
return self.name
}
}
extension Restaurant: JSONConvertible {
convenience init(json: JSON) throws {
self.init(
name: try json.get(Restaurant.Keys.name)
)
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set(Restaurant.Keys.name, name)
try json.set(Restaurant.Keys.id, id)
return json
}
}
extension Restaurant: Updateable {
public static var updateableKeys: [UpdateableKey<Restaurant>] {
return [
UpdateableKey(Restaurant.Keys.name, String.self) { restaurant, name in
restaurant.name = name
}
]
}
}
| mit |
PodBuilder/XcodeKit | SwiftXcodeKit/Resources/BuildPhase.swift | 1 | 4354 | /*
* The sources in the "XcodeKit" directory are based on the Ruby project Xcoder.
*
* Copyright (c) 2012 cisimple
*
* MIT License
*
* 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
// Note: BuildPhase is an abstract class; use one of its subclasses instead.
public class BuildPhase: Resource {
public var buildFileReferences: [BuildFile]? {
get {
if let arrayObject: AnyObject = properties["files"] {
if let array = arrayObject as? [AnyObject] {
var retval = [BuildFile]()
for item in array {
if let oid = item as? OID {
let buildFile: BuildFile? = registry.findObject(identifier: oid)
if let actualFile = buildFile {
retval.append(actualFile)
}
} else if let oid = item as? String {
let buildFile: BuildFile? = registry.findObject(identifier: OID(key: oid))
if let actualFile = buildFile {
retval.append(actualFile)
}
}
}
return retval
}
}
return nil
}
}
public func findBuildFileWithName(name: String) -> BuildFile? {
if let arrayObject: AnyObject = properties["files"] {
if let array = arrayObject as? [AnyObject] {
if let oids = array as? [OID] {
for ident in oids {
let file: BuildFile? = registry.findObject(identifier: ident)
if file?.fileReference?.name == name {
return file
}
}
}
}
}
return nil
}
public func findBuildFileWithPath(path: String) -> BuildFile? {
if let arrayObject: AnyObject = properties["files"] {
if let array = arrayObject as? [AnyObject] {
if let oids = array as? [OID] {
for ident in oids {
let file: BuildFile? = registry.findObject(identifier: ident)
if file?.fileReference?.path == path {
return file
}
}
}
}
}
return nil
}
public func addBuildFileWithReference(reference: FileReference, buildSettings: [String: AnyObject]?) -> Bool {
if findBuildFileWithName(reference.name) != nil {
return false
}
if findBuildFileWithPath(reference.path) != nil {
return false
}
let file = BuildFile.create(fileReference: reference, buildSettings: buildSettings, inRegistry: ®istry)
registry.putResource(file)
if let arrayObject: AnyObject = properties["files"] {
if var array = arrayObject as? [AnyObject] {
array.append(file.identifier)
}
}
save()
return true
}
}
| mit |
BridgeTheGap/KRStackView | Example/KRStackView/ViewController.swift | 1 | 6670 | //
// ViewController.swift
// KRStackView
//
// Created by Joshua Park on 07/13/2016.
// Copyright (c) 2016 Joshua Park. All rights reserved.
//
import UIKit
import KRStackView
private var Screen: UIScreen {
return UIScreen.main
}
private var DEFAULT_FRAME = CGRect(x: 20.0, y: 20.0, width: 148.0, height: 400.0)
class ViewController: UIViewController {
@IBOutlet weak var stackView: KRStackView!
@IBOutlet weak var viewRed: UIView!
@IBOutlet weak var viewYellow: UIView!
@IBOutlet weak var viewBlue: UIView!
@IBOutlet weak var viewControls: UIView!
@IBOutlet weak var switchEnabled: UISwitch!
@IBOutlet weak var controlDirection: UISegmentedControl!
@IBOutlet weak var switchShouldWrap: UISwitch!
@IBOutlet weak var controlAlignment: UISegmentedControl!
@IBOutlet weak var sliderTop: UISlider!
@IBOutlet weak var sliderRight: UISlider!
@IBOutlet weak var sliderBottom: UISlider!
@IBOutlet weak var sliderLeft: UISlider!
@IBOutlet weak var switchIndividual: UISwitch!
@IBOutlet weak var controlView: UISegmentedControl!
@IBOutlet weak var sliderWidth: UISlider!
@IBOutlet weak var sliderHeight: UISlider!
@IBOutlet weak var sliderSpacing: UISlider!
@IBOutlet weak var sliderOffset: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
stackView.enabled = false
viewControls.frame.origin.x = Screen.bounds.width
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backgroundAction(_ sender: AnyObject) {
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 300.0, initialSpringVelocity: 4.0, options: [], animations: {
if self.viewControls.frame.origin.x == Screen.bounds.width {
self.viewControls.frame.origin.x = 401.0
} else {
self.viewControls.frame.origin.x = Screen.bounds.width
}
}, completion: nil)
}
// MARK: - Controls
@IBAction func enabledAction(_ sender: AnyObject) {
let enabled = (sender as! UISwitch).isOn
stackView.enabled = enabled
if !enabled {
switchIndividual.isOn = false
switchIndividual.sendActions(for: .valueChanged)
}
for view in viewControls.subviews {
if [switchEnabled, controlView, sliderWidth, sliderHeight, sliderSpacing, sliderOffset].contains(view) { continue }
if let control = view as? UIControl { control.isEnabled = enabled }
}
stackView.setNeedsLayout()
}
@IBAction func directionAction(_ sender: AnyObject) {
stackView.frame = DEFAULT_FRAME
if stackView.direction == .vertical { stackView.direction = .horizontal }
else { stackView.direction = .vertical }
stackView.setNeedsLayout()
}
@IBAction func wrapAction(_ sender: AnyObject) {
stackView.frame = DEFAULT_FRAME
stackView.shouldWrap = (sender as! UISwitch).isOn
stackView.setNeedsLayout()
}
@IBAction func alignmentAction(_ sender: AnyObject) {
stackView.frame = DEFAULT_FRAME
guard let control = sender as? UISegmentedControl else { return }
switch control.selectedSegmentIndex {
case 0: stackView.alignment = .origin
case 1: stackView.alignment = .center
default: stackView.alignment = .endPoint
}
stackView.setNeedsLayout()
}
@IBAction func topInsetAction(_ sender: AnyObject) {
stackView.frame = DEFAULT_FRAME
stackView.insets.top = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
@IBAction func rightInsetAction(_ sender: AnyObject) {
stackView.frame = DEFAULT_FRAME
stackView.insets.right = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
@IBAction func bottomInsetAction(_ sender: AnyObject) {
stackView.frame = DEFAULT_FRAME
stackView.insets.bottom = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
@IBAction func leftInsetAction(_ sender: AnyObject) {
stackView.frame = DEFAULT_FRAME
stackView.insets.left = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
@IBAction func individualAction(_ sender: AnyObject) {
let enabled = (sender as! UISwitch).isOn
controlView.isEnabled = enabled
sliderWidth.isEnabled = enabled
sliderHeight.isEnabled = enabled
sliderSpacing.isEnabled = enabled && controlView.selectedSegmentIndex != 2
sliderOffset.isEnabled = enabled
stackView.itemSpacing = enabled ? [8.0, 8.0] : nil
stackView.itemOffset = enabled ? [0.0, 0.0, 0.0] : nil
}
@IBAction func viewSelectAction(_ sender: AnyObject) {
let index = (sender as! UISegmentedControl).selectedSegmentIndex
let view = [viewRed, viewYellow, viewBlue][index]!
sliderWidth.value = Float(view.frame.width)
sliderHeight.value = Float(view.frame.height)
sliderSpacing.isEnabled = switchIndividual.isOn && controlView.selectedSegmentIndex != 2
sliderSpacing.value = index != 2 ? Float(stackView.itemSpacing![index]) : sliderSpacing.value
sliderOffset.value = Float(stackView.itemOffset![index])
}
@IBAction func widthAction(_ sender: AnyObject) {
let index = controlView.selectedSegmentIndex
let view = [viewRed, viewYellow, viewBlue][index]!
view.frame.size.width = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
@IBAction func heightAction(_ sender: AnyObject) {
let index = controlView.selectedSegmentIndex
let view = [viewRed, viewYellow, viewBlue][index]
view?.frame.size.height = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
@IBAction func spacingAction(_ sender: AnyObject) {
let index = controlView.selectedSegmentIndex
stackView.itemSpacing![index] = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
@IBAction func offsetAction(_ sender: AnyObject) {
let index = controlView.selectedSegmentIndex
stackView.itemOffset![index] = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
}
| mit |
sudiptasahoo/IVP-Luncheon | IVP Luncheon/ExploreVenueResponse.swift | 1 | 4113 | /*
Copyright (c) 2017 Swift Models Generated from JSON powered by http://www.json4swift.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 Foundation
/* For support, please feel free to contact me at https://www.linkedin.com/in/syedabsar */
public class ExploreVenueResponse {
public var suggestedFilters : SuggestedFilters?
public var suggestedRadius : Int?
public var headerLocation : String?
public var headerFullLocation : String?
public var headerLocationGranularity : String?
public var query : String?
public var totalResults : Int?
public var suggestedBounds : SuggestedBounds?
public var groups : Array<Group>?
/**
Returns an array of models based on given dictionary.
Sample usage:
let response_list = Response.modelsFromDictionaryArray(someDictionaryArrayFromJSON)
- parameter array: NSArray from JSON dictionary.
- returns: Array of Response Instances.
*/
public class func modelsFromDictionaryArray(array:NSArray) -> [ExploreVenueResponse]
{
var models:[ExploreVenueResponse] = []
for item in array
{
models.append(ExploreVenueResponse(dictionary: item as! NSDictionary)!)
}
return models
}
/**
Constructs the object based on the given dictionary.
Sample usage:
let response = Response(someDictionaryFromJSON)
- parameter dictionary: NSDictionary from JSON.
- returns: Response Instance.
*/
required public init?(dictionary: NSDictionary) {
if (dictionary["suggestedFilters"] != nil) { suggestedFilters = SuggestedFilters(dictionary: dictionary["suggestedFilters"] as! NSDictionary) }
suggestedRadius = dictionary["suggestedRadius"] as? Int
headerLocation = dictionary["headerLocation"] as? String
headerFullLocation = dictionary["headerFullLocation"] as? String
headerLocationGranularity = dictionary["headerLocationGranularity"] as? String
query = dictionary["query"] as? String
totalResults = dictionary["totalResults"] as? Int
if (dictionary["suggestedBounds"] != nil) { suggestedBounds = SuggestedBounds(dictionary: dictionary["suggestedBounds"] as! NSDictionary) }
if (dictionary["groups"] != nil) { groups = Group.modelsFromDictionaryArray(array: dictionary["groups"] as! NSArray) }
}
/**
Returns the dictionary representation for the current instance.
- returns: NSDictionary.
*/
public func dictionaryRepresentation() -> NSDictionary {
let dictionary = NSMutableDictionary()
dictionary.setValue(self.suggestedFilters?.dictionaryRepresentation(), forKey: "suggestedFilters")
dictionary.setValue(self.suggestedRadius, forKey: "suggestedRadius")
dictionary.setValue(self.headerLocation, forKey: "headerLocation")
dictionary.setValue(self.headerFullLocation, forKey: "headerFullLocation")
dictionary.setValue(self.headerLocationGranularity, forKey: "headerLocationGranularity")
dictionary.setValue(self.query, forKey: "query")
dictionary.setValue(self.totalResults, forKey: "totalResults")
dictionary.setValue(self.suggestedBounds?.dictionaryRepresentation(), forKey: "suggestedBounds")
return dictionary
}
}
| apache-2.0 |
loudnate/LoopKit | LoopKitUI/Views/OverrideSelectionFooterView.swift | 2 | 313 | //
// OverrideSelectionFooterView.swift
// LoopKitUI
//
// Created by Michael Pangburn on 1/27/19.
// Copyright © 2019 LoopKit Authors. All rights reserved.
//
import UIKit
final class OverrideSelectionFooterView: UICollectionReusableView, IdentifiableClass {
@IBOutlet weak var textLabel: UILabel!
}
| mit |
ccloveswift/CLSCommon | Classes/VideoCoder/class_videoDecoder.swift | 1 | 9384 | //
// class_videoDecoder.swift
// Pods
//
// Created by TT on 2021/11/23.
// Copyright © 2021年 TT. All rights reserved.
//
import Foundation
import AVFoundation
import MetalKit
public class class_videoDecoder {
private var _uri: URL
private var _asset: AVURLAsset?
private var _track: AVAssetTrack?
private var _reader: AVAssetReader?
private var _readerTrackOutput: AVAssetReaderTrackOutput?
private var _cacheMTLTexture: MTLTexture?
private var _cacheCVMetalTextureCache: CVMetalTextureCache?
private var _cacheCMSampleBuffer: CMSampleBuffer?
private var _cacheCVMetalTexture: CVMetalTexture?
/// 缓存的那一buff的时间对应的帧下标
private var _cacheSampleBufferFrameIndex: Int
/// 缓存 buffer 的时间
private var _cacheSampleBufferTime: Double
/// 希望的时间
private var _wantTime: Double
private var _wantSize: CGSize
private var _width: Int
private var _height: Int
/// 1帧时间
private var _oneFrameTime: Double
/// 半帧时间
private var _oneFrameTimeHalf: Double
private var _fps: Double
public init(_ uri: URL, _ size: CGSize) {
_uri = uri
_wantSize = size
_width = 0;
_height = 0;
_wantTime = -1
_cacheSampleBufferFrameIndex = -1
_cacheSampleBufferTime = -1
_oneFrameTime = 0
_oneFrameTimeHalf = 0
_fps = 0
createAsset()
recalculateSize()
}
deinit {
CLSLogInfo("deinit")
_asset = nil
_track = nil
_reader = nil
_readerTrackOutput = nil
_cacheMTLTexture = nil
_cacheCVMetalTextureCache = nil
_cacheCMSampleBuffer = nil
_cacheCVMetalTexture = nil
}
private func createAsset() {
_asset = AVURLAsset.init(url: _uri, options: [AVURLAssetPreferPreciseDurationAndTimingKey : true])
guard let asset = _asset else {
assert(false)
return
}
_track = asset.tracks(withMediaType: .video).first
guard let track = _track else {
assert(false)
return
}
_fps = Double(track.nominalFrameRate)
_oneFrameTime = 1.0 / _fps
_oneFrameTimeHalf = _oneFrameTime / 2.0
}
private func releaseAsset() {
_reader?.cancelReading()
_reader = nil
_asset?.cancelLoading()
_asset = nil
}
private func recalculateSize() {
let w = getWidth()
let h = getHeight()
var rW = Double(w);
var rH = Double(h);
if rW > _wantSize.width {
let s = _wantSize.width / Double(w)
rW *= s;
rH *= s;
}
if rH > _wantSize.height {
let s = _wantSize.height / Double(h)
rW *= s;
rH *= s;
}
_width = Int(rW)
_height = Int(rH)
}
private func createAssetReader(_ startTime: Double)
{
guard let asset = _asset else {
assert(false)
return
}
guard let track = _track else {
assert(false)
return
}
do {
_reader?.cancelReading()
_reader = try AVAssetReader.init(asset: asset)
}
catch {
CLSLogError("createAssetReader \(error)")
assert(false)
return
}
let pos = CMTimeMakeWithSeconds(startTime, preferredTimescale: asset.duration.timescale)
let duration = CMTime.positiveInfinity
_reader?.timeRange = CMTimeRangeMake(start: pos, duration: duration)
_readerTrackOutput = AVAssetReaderTrackOutput.init(track: track,
outputSettings:[
kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_32BGRA),
kCVPixelBufferWidthKey as String : OSType(_width),
kCVPixelBufferHeightKey as String : OSType(_height)
])
guard let rto = _readerTrackOutput else {
assert(false)
return
}
rto.alwaysCopiesSampleData = false
if _reader?.canAdd(rto) ?? false {
_reader?.add(rto)
_reader?.startReading()
}
}
private func getFrameIndex(_ time: Double) -> Int {
var index = Int(time / _oneFrameTime)
let diff = time - (Double(index) * _oneFrameTime);
let diffP = diff / _oneFrameTime;
if (diffP > 0.5) {
index += 1
}
return index
}
private func getMTLTexture(_ buffer: CMSampleBuffer) -> MTLTexture? {
let oimgBuff = CMSampleBufferGetImageBuffer(buffer)
guard let imgBuff = oimgBuff else {
assert(false)
return nil
}
guard let device = MTLCreateSystemDefaultDevice() else {
assert(false)
return nil
}
_cacheCVMetalTextureCache = nil
_cacheCVMetalTextureCache = withUnsafeMutablePointer(to: &_cacheCVMetalTextureCache, { Ptr in
let ret = CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, device, nil, Ptr)
if ret != kCVReturnSuccess {
assert(false)
return nil
}
return Ptr.pointee
})
guard let textureCache = _cacheCVMetalTextureCache else {
assert(false)
return nil
}
let w = CVPixelBufferGetWidth(imgBuff)
let h = CVPixelBufferGetHeight(imgBuff)
_cacheCVMetalTexture = nil
_cacheCVMetalTexture = withUnsafeMutablePointer(to: &_cacheCVMetalTexture) { Ptr in
let ret = CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, textureCache, imgBuff, nil, .bgra8Unorm, w, h, 0, Ptr)
if ret != kCVReturnSuccess {
assert(false)
return nil
}
return Ptr.pointee
}
guard let texture = _cacheCVMetalTexture else {
assert(false)
return nil
}
return CVMetalTextureGetTexture(texture)
}
public func getTexture(time: Double) -> MTLTexture? {
var ctime = time
// 范围是 【 0 ~ 视频时长 】
if ctime < 0 {
ctime = 0;
}
else if ctime > getDuration() {
ctime = getDuration()
}
// 判定是否直接返回纹理
let isCopy0 = { abs(ctime - self._cacheSampleBufferTime) < self._oneFrameTimeHalf } // 是否在半帧内
if isCopy0() {
return _cacheMTLTexture
}
// 判定是否需要使用seek
let isSeek0 = { self._wantTime == -1 } // 初始情况要seek一次
let isSeek1 = { self._wantTime > ctime } // 往前拖动,想要的时间比我现在的时候小时,需要seek
let isSeek2 = { abs(ctime - self._wantTime) > 5 }// 时间跨度达到了5秒,需要seek
if isSeek0() || isSeek1() || isSeek2() {
createAssetReader(ctime);
_cacheSampleBufferFrameIndex = -1;
}
_wantTime = ctime
// 获取纹理
guard let rd = _reader else {
assert(false)
return nil
}
guard let rto = _readerTrackOutput else {
assert(false)
return nil
}
let wantFrameIndex = getFrameIndex(_wantTime)
while rd.status == .reading {
// 如果是一样的就直接返回
if wantFrameIndex == _cacheSampleBufferFrameIndex {
break
}
// 可以读取
let obuffer = rto.copyNextSampleBuffer()
guard let buffer = obuffer else {
break
}
let frameCMTime = CMSampleBufferGetOutputPresentationTimeStamp(buffer)
if CMTIME_IS_INVALID(frameCMTime) {
continue
}
let frameTime = CMTimeGetSeconds(frameCMTime);
let frameIndex = getFrameIndex(frameTime);
// ___ AAA ---
_cacheCMSampleBuffer = buffer;
_cacheSampleBufferFrameIndex = frameIndex;
// ___ AAA ---
if _cacheSampleBufferFrameIndex >= wantFrameIndex {
// 需要返回这帧数据
_cacheMTLTexture = getMTLTexture(buffer)
break
}
}
return _cacheMTLTexture
}
public func getDuration() -> Double {
return _asset?.duration.seconds ?? 0
}
public func getWidth() -> Int {
return Int(_track?.naturalSize.width ?? 0)
}
public func getHeight() -> Int {
return Int(_track?.naturalSize.height ?? 0)
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.