repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
codefellows/sea-b19-ios
Projects/Week2Day1ImageDownload/urldemo/ViewController.swift
1
1483
// // ViewController.swift // urldemo // // Created by Bradley Johnson on 7/28/14. // Copyright (c) 2014 learnswift. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var imageVIew: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet weak var downloadImage: UIButton! @IBAction func download(sender: AnyObject) { //setup url var url = NSURL(string: "http://blogimages.thescore.com/nfl/files/2014/02/russell-Wilson-again.jpg") var myQueue = NSOperationQueue() myQueue.maxConcurrentOperationCount = 1 myQueue.addOperationWithBlock( {() -> Void in var data = NSData(contentsOfURL: url) NSOperationQueue.mainQueue().addOperationWithBlock( {() -> Void in var myImage = UIImage(data: data) self.imageVIew.image = myImage }) }) var imageOperation = NSOperation() var blockOperation = NSBlockOperation({() -> Void in //do something }) myQueue.addOperation(blockOperation) } }
gpl-2.0
38eb85a922ae29a01c723877d466cd2a
27.519231
108
0.5853
5.221831
false
false
false
false
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
0fbf80c30e14cd6c9608938c692fd9ec
43.600423
149
0.539202
5.909244
false
true
false
false
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
218d4fd9b3a569acc464da2abf035eb9
42.891089
127
0.674036
4.406561
false
false
false
false
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
037e912d963172d6e9196e1ef9ef7d92
22.869565
85
0.648452
2.639423
false
false
false
false
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
b581a1d081f098e62971ed8319a175ea
22.842105
164
0.717881
3.731466
false
false
false
false
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
53d434346345ec273335937a1e7a1f25
31.236111
95
0.601465
4.756148
false
false
false
false
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
881f61649eaedcf2cfb1933b4d8bbfa1
23.145833
59
0.584987
4.080986
false
false
false
false
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
dae499ff155afa92379a0aa9154b303a
26.051282
75
0.592417
3.38141
false
false
false
false
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
cbd91d50813eba5f90841f39e2c89e38
30.43662
134
0.616487
3.193133
false
true
false
false
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
502277a2361b29e88809558b39903537
26.636364
78
0.606908
2.776256
false
false
false
false
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
4753b5991b249bafd1699c6c84c86aee
39.555556
147
0.651142
4.419778
false
false
false
false
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
72c4aec50b898751201d74b0ffdd4168
27.396226
132
0.671096
5.171821
false
false
false
false
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
ca438311b58cfc0a71541f74c1f0f7b6
32.636364
79
0.738739
2.788945
false
false
false
false
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
cd17d191f6b17e1a3aa05183add5c34c
34.232456
98
0.697622
5.165916
false
false
false
false
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
4f42dfda863de1dbc81882405ec39e12
30.576923
105
0.605847
5.042998
false
false
false
false
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
1d6e1cfb509f1bd17b7c29dee5cabbc9
36.623762
91
0.585526
4.481132
false
false
false
false
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
070b33f5bced5482ed30882c8cff3da3
44.769231
133
0.590196
4.547771
false
false
false
false
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
092972049af766399c7e7eb3e6629808
26.917526
137
0.750739
3.936047
false
false
false
false
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
7b7b9025cf7e8432755a6b734c4e9b01
28.308571
218
0.690973
3.581704
false
false
false
false
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
27ddb6c5fc0c5003d34a1227c3c0becb
34.026087
107
0.654916
5.085859
false
false
false
false
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
faf920599e566a1d14bce9e89862aec5
32.084211
146
0.622494
4.068608
false
false
false
false
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
fb599305cfaf9f2991985d4f256b34c4
37.148936
164
0.619632
4.878912
false
false
false
false
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
9089a87e161cd968440900f9367b7c4f
27.111111
91
0.709881
5.382979
false
false
false
false
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
9897d39d69074a80af5f4476ca3a11ec
32.3379
132
0.634434
4.247237
false
false
false
false
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
09dd3ef5e1b6430852b0b6d2e84a8a49
34.227273
118
0.65106
4.76295
false
true
false
false
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
65690dd7ab8ae893ae4df62117ac58bb
20.190476
72
0.530337
4.12037
false
false
false
false
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
95232fe97e42d220b5826026ac7b8827
46.677419
280
0.725304
4.284058
false
false
false
false
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
86b7070bf96f322d792260f0f7d24180
35.119403
102
0.46157
4.4
false
false
false
false
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
672c6d476ca34f044752f7bfc23ea0f1
33.362205
298
0.540101
3.162319
false
false
false
false
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
7e55580303757bbaecbefd9cdbb9fc26
32.809524
152
0.729577
5.657371
false
false
false
false
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
68e9b05d3720e5951f9fb27a632dd89e
34.984848
82
0.595789
4.248658
false
false
false
false
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
7ee0eb113508d2471b77029486923a00
38.20418
213
0.647529
5.202688
false
false
false
false
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
e40e09596bd5871aced8d94f89471c4e
31.724638
100
0.613818
4.32567
false
false
false
false
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
4f9c3139a676d3c03c1c99370d80c76b
31.148148
146
0.658218
5.40249
false
false
false
false
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
f76ad1a8a4cc5e0cb4e6a0a8604f6aca
35.201493
179
0.698825
5.227371
false
false
false
false
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
bfa12a17471b10ee100a31cef0687b63
32.268908
112
0.608487
4.068859
false
true
false
false
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
17482b47fcf63c79b7ebbef4c5791e33
36.022727
79
0.695826
4.379032
false
false
false
false
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
2a8492d17853fb96bfee68d7ea7a4f75
26.913043
131
0.642523
3.962963
false
false
false
false
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
ca7152b8e4685b6f5dc24e98c70257af
32.016949
148
0.548511
5.479606
false
false
false
false
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
39c83d5b1a2e614ba94f383d3da17460
30.481481
86
0.648529
4
false
false
false
false
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
a57d598af572e37612619bfbfa4d2e23
25.5
103
0.554327
3.96134
false
false
false
false
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
6de4ee0f6148a1e9bf1cef4afb6882fe
38.637838
169
0.636438
5.234118
false
false
false
false
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
d3d1db6e81c15610cef313abe7efa2c9
32.795699
110
0.657861
4.573508
false
false
false
false
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
8a4a426dc5b4247b2bc3881eb834d4de
25.754386
175
0.60918
4.919355
false
false
false
false
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
17732b1c89a8b92adf965c457b533a07
33.835793
203
0.539802
5.070086
false
false
false
false
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: "[email protected]", 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
050b83afd32990a4983e0df7a31e2975
42.416667
161
0.580934
5.175497
false
true
false
false
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
86cb9fe187f4cf642332c74511be39d1
11.422078
52
0.464192
3.985417
false
false
false
false
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
c7789a11cf443df46f776c37561cad99
36.136364
142
0.567625
4.756914
false
false
false
false
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
a6b7b39d9933ed5be15e99fef326875f
20.396552
80
0.545528
4.264605
false
false
false
false
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
ff15176ac76bc89b09739f97d732f373
38.68232
210
0.600696
5.248447
false
false
false
false
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
5564e94c96fe861d45a84ee245912466
32.705036
110
0.605763
4.780612
false
false
false
false
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
d318297ab7d504de0f43c806c3c81a69
21.063158
82
0.586355
4.260163
false
false
false
false
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: &registry) registry.putResource(file) if let arrayObject: AnyObject = properties["files"] { if var array = arrayObject as? [AnyObject] { array.append(file.identifier) } } save() return true } }
mit
6a8623bd84265b911d595dce6bf91a5c
36.86087
114
0.538126
5.355474
false
false
false
false
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
3e9a15efd1abdc783394e297d561cb3d
33.739583
140
0.647826
4.900808
false
false
false
false
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
0fd5ce2ffbf3f2a73a25896da56625e1
28.891803
139
0.517166
4.798421
false
false
false
false
Limon-O-O/Convex
Convex/TabBar.swift
1
3262
// // TabBar.swift // Example // // Created by Limon on 3/19/16. // Copyright © 2016 Convex. All rights reserved. // import UIKit class TabBar: UITabBar { override init(frame: CGRect) { super.init(frame: frame) if let upwrappedPlusButton = TabBarController.plusButton { addSubview(upwrappedPlusButton) } backgroundImage = getImageWithColor(UIColor.whiteColor()) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() guard let unwrappedPlusButton = TabBarController.plusButton where TabBarController.plusButton is protocol<PlusButton> else { return } let barWidth = frame.size.width let barHeight: CGFloat = frame.size.height let barButtonWidth: CGFloat = barWidth / CGFloat(TabBarController.tabbarItemsCount + 1) var multiplerInCenterY: CGFloat = 0.0 var buttonIndex: Int = 0 multiplerInCenterY = (unwrappedPlusButton as! PlusButton).multiplerInCenterY unwrappedPlusButton.center = CGPoint(x: barWidth * 0.5, y: barHeight * multiplerInCenterY) let plusButtonIndex = (unwrappedPlusButton as! PlusButton).indexOfPlusButtonInTabBar unwrappedPlusButton.frame = CGRect(x: CGFloat(plusButtonIndex) * barButtonWidth, y: CGRectGetMinY(unwrappedPlusButton.frame), width: CGRectGetWidth(unwrappedPlusButton.frame), height: CGRectGetHeight(unwrappedPlusButton.frame)) let sortedSubviews = subviews.sort { (view1, view2) -> Bool in return view1.frame.origin.x < view2.frame.origin.x } // 调整加号按钮后面的 UITabBarItem 的位置 sortedSubviews.forEach { childView in guard "\(childView.dynamicType)" == "UITabBarButton" else { return } if buttonIndex == plusButtonIndex { buttonIndex += 1 } childView.frame = CGRect(x: CGFloat(buttonIndex) * barButtonWidth, y: CGRectGetMinY(childView.frame), width: barButtonWidth, height: CGRectGetHeight(childView.frame)) buttonIndex += 1 } bringSubviewToFront(unwrappedPlusButton) } // Capturing touches on a subview outside the frame of its superview override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { if !clipsToBounds && !hidden && alpha > 0.0 { if let result = super.hitTest(point, withEvent: event) { return result } else { for (_, subview) in subviews.reverse().enumerate() { let subPoint = subview.convertPoint(point, fromView: self) return subview.hitTest(subPoint, withEvent: event) } } } return nil } private func getImageWithColor(color: UIColor) -> UIImage { let rect = CGRect(origin: CGPointZero, size: CGSize(width: 1, height: 1)) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
mit
cea9f35559a50a6fea3d341b81988493
32.371134
235
0.649058
4.853073
false
false
false
false
zhixingxi/JJA_Swift
JJA_Swift/JJA_Swift/Modules/Main/NewFeatures/JJANewFeatureView.swift
1
2765
// // JJANewFeatureView.swift // JJA_Swift // // Created by MQL-IT on 2017/8/8. // Copyright © 2017年 MQL-IT. All rights reserved. // 引导图界面 import UIKit private let SCREEN_WIDTH: Double = Double(UIScreen.main.bounds.size.width) private let SCREEN_HEIGHT: Double = Double(UIScreen.main.bounds.size.height) class JJANewFeatureView: UIView { fileprivate lazy var scrollView: UIScrollView = { let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)) scrollView.backgroundColor = UIColor.clear scrollView.bounces = false scrollView.isPagingEnabled = true scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false scrollView.delegate = self return scrollView }() fileprivate lazy var enterBtn: UIButton = { let btn = UIButton(type: UIButtonType.custom) btn.backgroundColor = UIColor.clear btn.frame = CGRect(x: 0, y: SCREEN_HEIGHT - ql_autoHeight(70), width: SCREEN_WIDTH, height: ql_autoHeight(70)) btn.addTarget(self, action: #selector(enterHome), for: .touchUpInside) btn.isHidden = true return btn }() fileprivate let imageArray = ["new_feature_1", "new_feature_2", "new_feature_3", "new_feature_4"] override init(frame: CGRect) { super.init(frame: frame) self.frame = UIScreen.main.bounds setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func enterHome(btn: UIButton) { removeFromSuperview() } } //MARK: - 界面 extension JJANewFeatureView { func setupUI() { let count = imageArray.count let rect = UIScreen.main.bounds for i in 0 ..< count { let iv = UIImageView(image: UIImage(named: imageArray[i])) //设置大小 iv.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0) iv.isUserInteractionEnabled = true scrollView.addSubview(iv) } scrollView.contentSize = CGSize(width: Double(count + 1) * SCREEN_WIDTH, height: SCREEN_HEIGHT) } } // MARK: - 代理 extension JJANewFeatureView: UIScrollViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { // 1.滚动到最后一屏, 视图删除 let page = Int(scrollView.contentOffset.x / scrollView.bounds.width) // 2. 判断是否是最后一页 if page == scrollView.subviews.count { removeFromSuperview() } if page == scrollView.subviews.count - 1 { enterBtn.isHidden = false } } }
mit
b3bc3a4e07c07854181989b5e4652d90
30.717647
118
0.633902
4.179845
false
false
false
false
lllyyy/LY
U17-master/U17/Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQToolbar.swift
2
9708
// // IQToolbar.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // 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 /** @abstract IQToolbar for IQKeyboardManager. */ open class IQToolbar: UIToolbar , UIInputViewAudioFeedback { private static var _classInitialize: Void = classInitialize() private class func classInitialize() { let appearanceProxy = self.appearance() appearanceProxy.barTintColor = nil let positions : [UIBarPosition] = [.any,.bottom,.top,.topAttached]; for position in positions { appearanceProxy.setBackgroundImage(nil, forToolbarPosition: position, barMetrics: .default) appearanceProxy.setShadowImage(nil, forToolbarPosition: .any) } //Background color appearanceProxy.backgroundColor = nil } /** Previous bar button of toolbar. */ private var privatePreviousBarButton: IQBarButtonItem? open var previousBarButton : IQBarButtonItem { get { if privatePreviousBarButton == nil { privatePreviousBarButton = IQBarButtonItem(image: nil, style: .plain, target: nil, action: nil) privatePreviousBarButton?.accessibilityLabel = "Toolbar Previous Button" } return privatePreviousBarButton! } set (newValue) { privatePreviousBarButton = newValue } } /** Next bar button of toolbar. */ private var privateNextBarButton: IQBarButtonItem? open var nextBarButton : IQBarButtonItem { get { if privateNextBarButton == nil { privateNextBarButton = IQBarButtonItem(image: nil, style: .plain, target: nil, action: nil) privateNextBarButton?.accessibilityLabel = "Toolbar Next Button" } return privateNextBarButton! } set (newValue) { privateNextBarButton = newValue } } /** Title bar button of toolbar. */ private var privateTitleBarButton: IQTitleBarButtonItem? open var titleBarButton : IQTitleBarButtonItem { get { if privateTitleBarButton == nil { privateTitleBarButton = IQTitleBarButtonItem(title: nil) privateTitleBarButton?.accessibilityLabel = "Toolbar Title Button" } return privateTitleBarButton! } set (newValue) { privateTitleBarButton = newValue } } /** Done bar button of toolbar. */ private var privateDoneBarButton: IQBarButtonItem? open var doneBarButton : IQBarButtonItem { get { if privateDoneBarButton == nil { privateDoneBarButton = IQBarButtonItem(title: nil, style: .done, target: nil, action: nil) privateDoneBarButton?.accessibilityLabel = "Toolbar Done Button" } return privateDoneBarButton! } set (newValue) { privateDoneBarButton = newValue } } override init(frame: CGRect) { _ = IQToolbar._classInitialize super.init(frame: frame) sizeToFit() autoresizingMask = UIViewAutoresizing.flexibleWidth self.isTranslucent = true } required public init?(coder aDecoder: NSCoder) { _ = IQToolbar._classInitialize super.init(coder: aDecoder) sizeToFit() autoresizingMask = UIViewAutoresizing.flexibleWidth self.isTranslucent = true } override open func sizeThatFits(_ size: CGSize) -> CGSize { var sizeThatFit = super.sizeThatFits(size) sizeThatFit.height = 44 return sizeThatFit } override open var tintColor: UIColor! { didSet { if let unwrappedItems = items { for item in unwrappedItems { item.tintColor = tintColor } } } } override open var barStyle: UIBarStyle { didSet { if barStyle == .default { titleBarButton.selectableTextColor = UIColor.init(red: 0.0, green: 0.5, blue: 1.0, alpha: 1) } else { titleBarButton.selectableTextColor = UIColor.yellow } } } override open func layoutSubviews() { super.layoutSubviews() //If running on Xcode9 (iOS11) only then we'll validate for iOS version, otherwise for older versions of Xcode (iOS10 and below) we'll just execute the tweak #if swift(>=3.2) if #available(iOS 11, *) { return } else { var leftRect = CGRect.null var rightRect = CGRect.null var isTitleBarButtonFound = false let sortedSubviews = self.subviews.sorted(by: { (view1 : UIView, view2 : UIView) -> Bool in let x1 = view1.frame.minX let y1 = view1.frame.minY let x2 = view2.frame.minX let y2 = view2.frame.minY if x1 != x2 { return x1 < x2 } else { return y1 < y2 } }) for barButtonItemView in sortedSubviews { if isTitleBarButtonFound == true { rightRect = barButtonItemView.frame break } else if type(of: barButtonItemView) === UIView.self { isTitleBarButtonFound = true //If it's UIToolbarButton or UIToolbarTextButton (which actually UIBarButtonItem) } else if barButtonItemView.isKind(of: UIControl.self) == true { leftRect = barButtonItemView.frame } } var x : CGFloat = 16 if (leftRect.isNull == false) { x = leftRect.maxX + 16 } let width : CGFloat = self.frame.width - 32 - (leftRect.isNull ? 0 : leftRect.maxX) - (rightRect.isNull ? 0 : self.frame.width - rightRect.minX) if let unwrappedItems = items { for item in unwrappedItems { if let newItem = item as? IQTitleBarButtonItem { let titleRect = CGRect(x: x, y: 0, width: width, height: self.frame.size.height) newItem.customView?.frame = titleRect break } } } } #else var leftRect = CGRect.null var rightRect = CGRect.null var isTitleBarButtonFound = false let sortedSubviews = self.subviews.sorted(by: { (view1 : UIView, view2 : UIView) -> Bool in let x1 = view1.frame.minX let y1 = view1.frame.minY let x2 = view2.frame.minX let y2 = view2.frame.minY if x1 != x2 { return x1 < x2 } else { return y1 < y2 } }) for barButtonItemView in sortedSubviews { if isTitleBarButtonFound == true { rightRect = barButtonItemView.frame break } else if type(of: barButtonItemView) === UIView.self { isTitleBarButtonFound = true //If it's UIToolbarButton or UIToolbarTextButton (which actually UIBarButtonItem) } else if barButtonItemView.isKind(of: UIControl.self) == true { leftRect = barButtonItemView.frame } } var x : CGFloat = 16 if (leftRect.isNull == false) { x = leftRect.maxX + 16 } let width : CGFloat = self.frame.width - 32 - (leftRect.isNull ? 0 : leftRect.maxX) - (rightRect.isNull ? 0 : self.frame.width - rightRect.minX) if let unwrappedItems = items { for item in unwrappedItems { if let newItem = item as? IQTitleBarButtonItem { let titleRect = CGRect(x: x, y: 0, width: width, height: self.frame.size.height) newItem.customView?.frame = titleRect break } } } #endif } open var enableInputClicksWhenVisible: Bool { return true } }
mit
8f78a0bbe0f0957c82508a8cb819db2f
32.475862
165
0.561084
5.281828
false
false
false
false
DanielFulton/ImageLibraryTests
Pods/ImageLoader/ImageLoader/Manager.swift
1
4755
// // Manager.swift // ImageLoader // // Created by Hirohisa Kawasaki on 12/7/15. // Copyright © 2015 Hirohisa Kawasaki. All rights reserved. // import Foundation import UIKit /** Responsible for creating and managing `Loader` objects and controlling of `NSURLSession` and `ImageCache` */ public class Manager { let session: NSURLSession let cache: ImageLoaderCache let delegate: SessionDataDelegate = SessionDataDelegate() public var automaticallyAdjustsSize = true public var automaticallyAddTransition = true public var automaticallySetImage = true /** Use to kill or keep a fetching image loader when it's blocks is to empty by imageview or anyone. */ public var shouldKeepLoader = false let decompressingQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) public init(configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(), cache: ImageLoaderCache = Disk() ) { session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) self.cache = cache } // MARK: state var state: State { return delegate.isEmpty ? .Ready : .Running } // MARK: loading func load(URL: URLLiteralConvertible) -> Loader { if let loader = delegate[URL.imageLoaderURL] { loader.resume() return loader } let request = NSMutableURLRequest(URL: URL.imageLoaderURL) request.setValue("image/*", forHTTPHeaderField: "Accept") let task = session.dataTaskWithRequest(request) let loader = Loader(task: task, delegate: self) delegate[URL.imageLoaderURL] = loader return loader } func suspend(URL: URLLiteralConvertible) -> Loader? { if let loader = delegate[URL.imageLoaderURL] { loader.suspend() return loader } return nil } func cancel(URL: URLLiteralConvertible, block: Block? = nil) -> Loader? { return cancel(URL, identifier: block?.identifier) } func cancel(URL: URLLiteralConvertible, identifier: Int?) -> Loader? { if let loader = delegate[URL.imageLoaderURL] { if let identifier = identifier { loader.remove(identifier) } if !shouldKeepLoader && loader.blocks.isEmpty { loader.cancel() delegate.remove(URL.imageLoaderURL) } return loader } return nil } class SessionDataDelegate: NSObject, NSURLSessionDataDelegate { let _ioQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) var loaders: [NSURL: Loader] = [:] subscript (URL: NSURL) -> Loader? { get { var loader : Loader? dispatch_sync(_ioQueue) { loader = self.loaders[URL] } return loader } set { if let newValue = newValue { dispatch_barrier_async(_ioQueue) { self.loaders[URL] = newValue } } } } var isEmpty: Bool { var isEmpty = false dispatch_sync(_ioQueue) { isEmpty = self.loaders.isEmpty } return isEmpty } private func remove(URL: NSURL) -> Loader? { if let loader = loaders[URL] { loaders[URL] = nil return loader } return nil } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if let URL = dataTask.originalRequest?.URL, loader = self[URL] { loader.receive(data) } } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { completionHandler(.Allow) } func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let URL = task.originalRequest?.URL, loader = loaders[URL] { loader.complete(error) { [unowned self] in self.remove(URL) } } } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: (NSCachedURLResponse?) -> Void) { completionHandler(nil) } } deinit { session.invalidateAndCancel() } }
mit
c56b3c3d72162e6a02255bbb266b111e
29.677419
188
0.592133
5.371751
false
false
false
false
VadimPavlov/SMVC
PerfectProject/Classes/Flow/AppFlow.swift
1
1560
// // AppFlow.swift // PerfectProject // // Created by Vadim Pavlov on 10/7/16. // Copyright © 2016 Vadim Pavlov. All rights reserved. // import UIKit class AppFlow { let session: Session let navigationController: UINavigationController init(session: Session, navigationController: UINavigationController) { self.session = session self.navigationController = navigationController } } extension AppFlow { func showLogin(animated: Bool) { let login = LoginFlow(session: session) { user in if let user = user { self.showUserScreen(user: user) } } if let login = login { navigationController.present(login.navigationController, animated: animated, completion: nil) login.showSignInScreen() } } func showUserScreen(user: User) { let actions = UserController.Actions() let controller = UserController(actions: actions, user: user) // let completion = { // // let view = UserView() //... somehow from storyboard // controller.view = view // self.navigationController.pushViewController(view, animated: true) // } // // if self.navigationController.presentedViewController != nil { // self.navigationController.dismiss(animated: true, completion: completion) // } else { // completion() // } } func showMainScreen() { } }
mit
a1a766a0da19ca85c9e16a03e53b3355
25.87931
105
0.585632
4.826625
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/DiscoveryV2/Models/Enrichment.swift
1
2192
/** * (C) Copyright IBM Corp. 2022. * * 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 /** Information about a specific enrichment. */ public struct Enrichment: Codable, Equatable { /** The type of this enrichment. */ public enum TypeEnum: String { case partOfSpeech = "part_of_speech" case sentiment = "sentiment" case naturalLanguageUnderstanding = "natural_language_understanding" case dictionary = "dictionary" case regularExpression = "regular_expression" case uimaAnnotator = "uima_annotator" case ruleBased = "rule_based" case watsonKnowledgeStudioModel = "watson_knowledge_studio_model" case classifier = "classifier" } /** The unique identifier of this enrichment. */ public var enrichmentID: String? /** The human readable name for this enrichment. */ public var name: String? /** The description of this enrichment. */ public var description: String? /** The type of this enrichment. */ public var type: String? /** An object that contains options for the current enrichment. Starting with version `2020-08-30`, the enrichment options are not included in responses from the List Enrichments method. */ public var options: EnrichmentOptions? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case enrichmentID = "enrichment_id" case name = "name" case description = "description" case type = "type" case options = "options" } }
apache-2.0
d5c5fcbc37218c8cb8860acf1f28bc77
28.621622
115
0.670164
4.419355
false
false
false
false
vandilsonlima/VLPin
VLPin/Classes/UIView+VLPin_Size.swift
1
1815
// // UIView+VLPin_Size.swift // Pods-VLPin_Example // // Created by Vandilson Lima on 09/07/17. // import UIKit public extension UIView { @discardableResult public func makeWidth(equalTo width: CGFloat, withPriority priority: UILayoutPriority = UILayoutPriorityRequired) -> NSLayoutConstraint { translatesAutoresizingMaskIntoConstraints = false let constraint = widthAnchor.constraint(equalToConstant: width) constraint.priority = priority constraint.isActive = true return constraint } @discardableResult public func makeWidth(equalTo view: UIView, multiplier: CGFloat = 1, withPriority priority: UILayoutPriority = UILayoutPriorityRequired) -> NSLayoutConstraint { let constraint = widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: multiplier) return make(view: view, constraint: constraint, priority: priority) } @discardableResult public func makeHeight(equalTo height: CGFloat, withPriority priority: UILayoutPriority = UILayoutPriorityRequired) -> NSLayoutConstraint { translatesAutoresizingMaskIntoConstraints = false let constraint = heightAnchor.constraint(equalToConstant: height) constraint.priority = priority constraint.isActive = true return constraint } @discardableResult public func makeHeight(equalTo view: UIView, multiplier: CGFloat = 1, withPriority priority: UILayoutPriority = UILayoutPriorityRequired) -> NSLayoutConstraint { let constraint = heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: multiplier) return make(view: view, constraint: constraint, priority: priority) } }
mit
4177bb82b9b270dddd6d10a2fe1f424b
40.25
117
0.692562
5.970395
false
false
false
false
theisegeberg/BasicJSON
BasicJSON/PureJSON.swift
1
650
// // BasicJSON.swift // BasicJSON // // Created by Theis Egeberg on 20/04/2017. // Copyright © 2017 Theis Egeberg. All rights reserved. // import Foundation public typealias RawJSON = [String:Any] public typealias PureJSONValue = [String:JSONRepresentable] public struct PureJSON { public let value: PureJSONValue init() { value = PureJSONValue() } init(raw: RawJSON) { value = JSON.purify(raw: raw) } public subscript(key: String) -> JSONRepresentable { get { if let value = self.value[key] { return value } return "" } } }
mit
4e515ed2ee7676c10b84f7c01125b416
18.088235
59
0.587057
3.840237
false
false
false
false
itouch2/LeetCode
LeetCode/H-Index.swift
1
1331
// // H-Index.swift // LeetCode // // Created by You Tu on 2017/5/24. // Copyright © 2017年 You Tu. All rights reserved. // /* Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each." For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3. Note: If there are several possible values for h, the maximum one is taken as the h-index. */ import Cocoa class H_Index: NSObject { func hIndex(_ citations: [Int]) -> Int { if citations.count == 0 { return 0; } let sorted = citations.sorted{ $0 > $1 } var t = 0 for i in 0 ..< sorted.count { if (i + 1) >= sorted[i] { return max(sorted[i], t) } else { t = i + 1 } } return t } }
mit
4ab471fc992965227afe205b1f4f757a
33
306
0.612368
3.632877
false
false
false
false
cxpyear/ZSZQApp
spdbapp/spdbapp/AppDelegate.swift
1
2938
// // AppDelegate.swift // spdbapp // // Created by tommy on 15/5/7. // Copyright (c) 2015年 shgbit. All rights reserved. // import UIKit var server = Server() var current = GBCurrent() var totalMembers = NSArray() var member = GBMember() var bNeedLogin = true var appManager = AppManager() @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var backgroundTransferCompletionHandler:(() -> Void)? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { UIApplication.sharedApplication().idleTimerDisabled = true return true } func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) { self.backgroundTransferCompletionHandler = completionHandler } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. // NSNotificationCenter.defaultCenter().addObserver(self, selector: "defaultsSettingsChanged", name: NSUserDefaultsDidChangeNotification, object: nil) } func applicationWillEnterForeground(application: UIApplication) { // var defaults = NSUserDefaults.standardUserDefaults() // defaults.synchronize() // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. UIApplication.sharedApplication().idleTimerDisabled = false } }
bsd-3-clause
910a9d901c3c05291306d5b07a324888
39.777778
285
0.739101
5.560606
false
false
false
false
mapsme/omim
iphone/Chart/Chart/Views/ChartXAxisView.swift
5
2792
import UIKit fileprivate class ChartXAxisInnerView: UIView { var lowerBound = 0 var upperBound = 0 var steps: [String] = [] var labels: [UILabel] = [] var font: UIFont = UIFont.systemFont(ofSize: 12, weight: .regular) { didSet { labels.forEach { $0.font = font } } } var textColor: UIColor = UIColor(white: 0, alpha: 0.3) { didSet { labels.forEach { $0.textColor = textColor } } } override var frame: CGRect { didSet { if upperBound > 0 { updateLabels() } } } func makeLabel(text: String) -> UILabel { let label = UILabel() label.font = font label.textColor = textColor label.text = text label.frame = CGRect(x: 0, y: 0, width: 50, height: 15) return label } func setBounds(lower: Int, upper: Int, steps: [String]) { lowerBound = lower upperBound = upper self.steps = steps labels.forEach { $0.removeFromSuperview() } labels.removeAll() for i in 0..<steps.count { let step = steps[i] let label = makeLabel(text: step) if i == 0 { label.textAlignment = .left } else if i == steps.count - 1 { label.textAlignment = .right } else { label.textAlignment = .center } labels.append(label) addSubview(label) } updateLabels() } func updateLabels() { let step = CGFloat(upperBound - lowerBound) / CGFloat(labels.count - 1) for i in 0..<labels.count { let x = bounds.width * step * CGFloat(i) / CGFloat(upperBound - lowerBound) let l = labels[i] var f = l.frame let adjust = bounds.width > 0 ? x / bounds.width : 0 f.origin = CGPoint(x: x - f.width * adjust, y: 0) l.frame = f.integral } } } class ChartXAxisView: UIView { var lowerBound = 0 var upperBound = 0 var values: [String] = [] var font: UIFont = UIFont.systemFont(ofSize: 12, weight: .regular) { didSet { labelsView?.font = font } } var textColor: UIColor = UIColor(white: 0, alpha: 0.3) { didSet { labelsView?.textColor = textColor } } private var labelsView: ChartXAxisInnerView? func setBounds(lower: Int, upper: Int) { lowerBound = lower upperBound = upper let step = CGFloat(upper - lower) / 5 var steps: [String] = [] for i in 0..<5 { let x = lower + Int(round(step * CGFloat(i))) steps.append(values[x]) } steps.append(values[upper]) let lv = ChartXAxisInnerView() lv.frame = bounds lv.textColor = textColor lv.autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(lv) if let labelsView = labelsView { labelsView.removeFromSuperview() } lv.setBounds(lower: lower, upper: upper, steps: steps) labelsView = lv } }
apache-2.0
a95e1fdb0473d50cdbfc267c9438cc42
22.07438
81
0.599928
3.84044
false
false
false
false
BoltApp/bolt-ios
BoltExample/BoltExample/BoltAPI/BLTApiIManger.swift
1
7518
// // BLTNetworkManager.swift // BoltAPI // // Created by Bolt. // Copyright © 2018 Bolt. All rights reserved. // import Foundation enum BLTApiManagerError: Error, LocalizedError { case responseError(error: String) case responseErrors(errors: [String]) case tokenNotFound case badRequestData case badResponseData case createOrderFail var errorDescription: String? { switch self { case .responseError(let error): return NSLocalizedString(error, comment: "") case .responseErrors(let errors): return NSLocalizedString("\(errors)", comment: "") case .tokenNotFound: return NSLocalizedString("Token not found", comment: "") case .badRequestData: return NSLocalizedString("Bad request data", comment: "") case .createOrderFail: return NSLocalizedString("Create order fail", comment: "") case .badResponseData: return NSLocalizedString("Bad response data", comment: "") } } } class BLTNetworkService { /// fileprivate enum BLTEndpoint { case createOrder var path: String { switch self { case .createOrder: return "/v1/merchant/orders" } } } /// enum BLTApiUrl: String { case sandbox = "https://api-sandbox.bolt.com" case production = "https://api.bolt.com" } /// This is issued to process voids, captures and refunds from backoffice. let apiKey: String /// This is the URL used to communicate with Bolt's backend. let apiURL: String fileprivate func requestUrl(endpoint: BLTEndpoint) -> String { return apiURL + endpoint.path } // MARK: Initialization /** . - Parameter apiKey: . - Parameter apiUrl: . - Returns: */ internal init(apiKey: String, apiUrl: BLTApiUrl) { self.apiKey = apiKey self.apiURL = apiUrl.rawValue } // MARK: Request /** Create order with order data. - Parameter order: Order info. - Parameter successHandler: Returns orderID for checkout process */ public func createOrder(_ order: BLTOrder, successHandler: @escaping ((_ orderID: String) -> Swift.Void), errorHandler: @escaping ((_ error: Error) -> Swift.Void)) { guard let orderParameters = try? order.asDictionary(), let encodedOrder = try? JSONEncoder().encode(order), let jsonStringOrder = String(data: encodedOrder, encoding: .utf8), let postData = try? JSONSerialization.data(withJSONObject: orderParameters, options: []) else { errorHandler(BLTApiManagerError.badRequestData) return } let contentLength = "\(jsonStringOrder.count)" let xNonce = generateXNonce() let apiKey = self.apiKey let headers: [String : String] = ["Content-Type" : "application/json", "X-Api-Key" : apiKey, "Content-Length" : contentLength, "X-Nonce" : xNonce, "cache-control" : "no-cache"] let url = URL(string: requestUrl(endpoint: .createOrder))! var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.httpBody = postData as Data DispatchQueue.global(qos: .background).async { let task = URLSession.shared.dataTask(with: request) { (data, response, error) in DispatchQueue.main.async { guard error == nil else { errorHandler(error!) return } guard let httpResponse = response as? HTTPURLResponse else { errorHandler(BLTApiManagerError.createOrderFail) return } guard let data = data else { errorHandler(BLTApiManagerError.badResponseData) return } if let responseError = self.getErrorFromResponse(data: data, response: httpResponse) { errorHandler(responseError) return } guard let decodedJson = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : AnyObject], let decodedData = decodedJson else { errorHandler(BLTApiManagerError.badResponseData) return } if let errors = decodedData["errors"] as? [String] { errorHandler(BLTApiManagerError.responseErrors(errors: errors)) return } else { if let token = decodedData["token"] as? String { successHandler(token) } else { errorHandler(BLTApiManagerError.tokenNotFound) return } } } } task.resume() } } // MARK: Helper public func getErrorFromResponse(data: Data, response: HTTPURLResponse) -> Error? { let statusCode = String(response.statusCode) let errorMessage = "Error: \(statusCode)" if response.statusCode != 200 && response.statusCode != 201 { print("statusCode should be 200, but is \(response.statusCode)") print("response = \(String(describing: response))") do { guard let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else { return BLTApiManagerError.responseError(error: errorMessage) } if let errors = json["errors"] as? [String] { return BLTApiManagerError.responseErrors(errors: errors) } else if let errorMessage = json["error"] as? String { return BLTApiManagerError.responseError(error: errorMessage) } } catch let error as NSError { return error } return BLTApiManagerError.responseError(error: errorMessage) } return nil } /// A unique 12-16 digit for every request. Generated by the merchant. func generateXNonce() -> String { func random(digits: Int) -> Int { let min = Int(pow(Double(10), Double(digits-1))) - 1 let max = Int(pow(Double(10), Double(digits))) - 1 return Int.random(in: min...max) } let digitsCount = Int.random(in: 12...16) let value = random(digits: digitsCount) let nonce = "\(value)" return nonce } } extension Encodable { func asDictionary() throws -> [String: Any] { let data = try JSONEncoder().encode(self) guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else { throw NSError() } return dictionary } }
mit
27c0196a0a272d6b51a0f74e2049de3a
35.490291
169
0.541838
5.342573
false
false
false
false
gcba/usig-normalizador-ios
Example/ViewController.swift
1
4298
// // ViewController.swift // Example // // Created by Rita Zerrizuela on 9/28/17. // Copyright © 2017 GCBA. All rights reserved. // import UIKit import CoreLocation import USIGNormalizador class ViewController: UIViewController { fileprivate var currentAddress: USIGNormalizadorAddress? fileprivate let locationManager = CLLocationManager() fileprivate var showPin = true fileprivate var forceNormalization = true fileprivate var includePlaces = true fileprivate var cabaOnly = true // MARK: - Outlets @IBOutlet weak var searchLabel: UILabel! @IBOutlet weak var searchButton: UIButton! @IBOutlet weak var geoLabel: UILabel! @IBOutlet weak var geoButton: UIButton! @IBOutlet weak var pinSwitch: UISwitch! @IBOutlet weak var mandatorySwitch: UISwitch! @IBOutlet weak var placesSwitch: UISwitch! @IBOutlet weak var cabaSwitch: UISwitch! // MARK: - Actions @IBAction func pinSwitchValueChanged(_ sender: Any) { showPin = pinSwitch.isOn } @IBAction func mandatorySwitchValueChanged(_ sender: Any) { forceNormalization = mandatorySwitch.isOn } @IBAction func placesSwitchValueChanged(_ sender: Any) { includePlaces = placesSwitch.isOn } @IBAction func cabaSwitchValueChanged(_ sender: Any) { cabaOnly = cabaSwitch.isOn } @IBAction func searchButtonTapped(sender: UIButton) { let searchController = USIGNormalizador.searchController() let navigationController = UINavigationController(rootViewController: searchController) searchController.delegate = self searchController.edit = searchLabel.text present(navigationController, animated: true, completion: nil) } @IBAction func geoButtonTapped(sender: UIButton) { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() requestLocation() } // MARK: - Overrides override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } override func viewDidLoad() { super.viewDidLoad() searchLabel.sizeToFit() geoLabel.sizeToFit() } // MARK: - Location fileprivate func requestLocation() { guard CLLocationManager.authorizationStatus() == .authorizedWhenInUse, let currentLocation = locationManager.location else { return } USIGNormalizador.location(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude) { result, error in DispatchQueue.main.async { self.geoLabel.text = result?.address ?? error?.message } } } } extension ViewController: USIGNormalizadorControllerDelegate { func exclude(_ searchController: USIGNormalizadorController) -> String { return cabaOnly ? USIGNormalizadorExclusions.AMBA.rawValue : "" } func shouldShowPin(_ searchController: USIGNormalizadorController) -> Bool { return showPin } func shouldForceNormalization(_ searchController: USIGNormalizadorController) -> Bool { return forceNormalization } func shouldIncludePlaces(_ searchController: USIGNormalizadorController) -> Bool { return includePlaces } func didSelectValue(_ searchController: USIGNormalizadorController, value: USIGNormalizadorAddress) { currentAddress = value DispatchQueue.main.async { self.searchLabel.text = value.address } } func didSelectPin(_ searchController: USIGNormalizadorController) { DispatchQueue.main.async { self.searchLabel.text = "PIN" } } func didSelectUnnormalizedAddress(_ searchController: USIGNormalizadorController, value: String) { DispatchQueue.main.async { self.searchLabel.text = value } } func didCancelSelection(_ searchController: USIGNormalizadorController) { DispatchQueue.main.async { self.searchLabel.text = "CANCELADO" } } } extension ViewController: CLLocationManagerDelegate { public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { requestLocation() } }
mit
1f9a0ae5a5156228dc6cc59fb4001ef5
32.053846
148
0.707703
5.127685
false
false
false
false
radazzouz/firefox-ios
Storage/SQL/BrowserTable.swift
1
40868
/* 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 XCGLogger let BookmarksFolderTitleMobile: String = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.") let BookmarksFolderTitleMenu: String = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.") let BookmarksFolderTitleToolbar: String = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.") let BookmarksFolderTitleUnsorted: String = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.") let _TableBookmarks = "bookmarks" // Removed in v12. Kept for migration. let TableBookmarksMirror = "bookmarksMirror" // Added in v9. let TableBookmarksMirrorStructure = "bookmarksMirrorStructure" // Added in v10. let TableBookmarksBuffer = "bookmarksBuffer" // Added in v12. bookmarksMirror is renamed to bookmarksBuffer. let TableBookmarksBufferStructure = "bookmarksBufferStructure" // Added in v12. let TableBookmarksLocal = "bookmarksLocal" // Added in v12. Supersedes 'bookmarks'. let TableBookmarksLocalStructure = "bookmarksLocalStructure" // Added in v12. let TableFavicons = "favicons" let TableHistory = "history" let TableCachedTopSites = "cached_top_sites" let TableDomains = "domains" let TableVisits = "visits" let TableFaviconSites = "favicon_sites" let TableQueuedTabs = "queue" let TableActivityStreamBlocklist = "activity_stream_blocklist" let TablePageMetadata = "page_metadata" let ViewBookmarksBufferOnMirror = "view_bookmarksBuffer_on_mirror" let ViewBookmarksBufferStructureOnMirror = "view_bookmarksBufferStructure_on_mirror" let ViewBookmarksLocalOnMirror = "view_bookmarksLocal_on_mirror" let ViewBookmarksLocalStructureOnMirror = "view_bookmarksLocalStructure_on_mirror" let ViewAllBookmarks = "view_all_bookmarks" let ViewAwesomebarBookmarks = "view_awesomebar_bookmarks" let ViewAwesomebarBookmarksWithIcons = "view_awesomebar_bookmarks_with_favicons" let ViewHistoryVisits = "view_history_visits" let ViewWidestFaviconsForSites = "view_favicons_widest" let ViewHistoryIDsWithWidestFavicons = "view_history_id_favicon" let ViewIconForURL = "view_icon_for_url" let IndexHistoryShouldUpload = "idx_history_should_upload" let IndexVisitsSiteIDDate = "idx_visits_siteID_date" // Removed in v6. let IndexVisitsSiteIDIsLocalDate = "idx_visits_siteID_is_local_date" // Added in v6. let IndexBookmarksMirrorStructureParentIdx = "idx_bookmarksMirrorStructure_parent_idx" // Added in v10. let IndexBookmarksLocalStructureParentIdx = "idx_bookmarksLocalStructure_parent_idx" // Added in v12. let IndexBookmarksBufferStructureParentIdx = "idx_bookmarksBufferStructure_parent_idx" // Added in v12. let IndexBookmarksMirrorStructureChild = "idx_bookmarksMirrorStructure_child" // Added in v14. let IndexPageMetadataCacheKey = "idx_page_metadata_cache_key_uniqueindex" // Added in v19 private let AllTables: [String] = [ TableDomains, TableFavicons, TableFaviconSites, TableHistory, TableVisits, TableCachedTopSites, TableBookmarksBuffer, TableBookmarksBufferStructure, TableBookmarksLocal, TableBookmarksLocalStructure, TableBookmarksMirror, TableBookmarksMirrorStructure, TableQueuedTabs, TableActivityStreamBlocklist, TablePageMetadata, ] private let AllViews: [String] = [ ViewHistoryIDsWithWidestFavicons, ViewWidestFaviconsForSites, ViewIconForURL, ViewBookmarksBufferOnMirror, ViewBookmarksBufferStructureOnMirror, ViewBookmarksLocalOnMirror, ViewBookmarksLocalStructureOnMirror, ViewAllBookmarks, ViewAwesomebarBookmarks, ViewAwesomebarBookmarksWithIcons, ViewHistoryVisits ] private let AllIndices: [String] = [ IndexHistoryShouldUpload, IndexVisitsSiteIDIsLocalDate, IndexBookmarksBufferStructureParentIdx, IndexBookmarksLocalStructureParentIdx, IndexBookmarksMirrorStructureParentIdx, IndexBookmarksMirrorStructureChild, IndexPageMetadataCacheKey ] private let AllTablesIndicesAndViews: [String] = AllViews + AllIndices + AllTables private let log = Logger.syncLogger /** * The monolithic class that manages the inter-related history etc. tables. * We rely on SQLiteHistory having initialized the favicon table first. */ open class BrowserTable: Table { static let DefaultVersion = 21 // Bug 1253656. // TableInfo fields. var name: String { return "BROWSER" } var version: Int { return BrowserTable.DefaultVersion } let sqliteVersion: Int32 let supportsPartialIndices: Bool public init() { let v = sqlite3_libversion_number() self.sqliteVersion = v self.supportsPartialIndices = v >= 3008000 // 3.8.0. let ver = String(cString: sqlite3_libversion()) log.info("SQLite version: \(ver) (\(v)).") } func run(_ db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool { let err = db.executeChange(sql, withArgs: args) if err != nil { log.error("Error running SQL in BrowserTable. \(err?.localizedDescription)") log.error("SQL was \(sql)") } return err == nil } // TODO: transaction. func run(_ db: SQLiteDBConnection, queries: [(String, Args?)]) -> Bool { for (sql, args) in queries { if !run(db, sql: sql, args: args) { return false } } return true } func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool { for sql in queries { if !run(db, sql: sql) { return false } } return true } func runValidQueries(_ db: SQLiteDBConnection, queries: [(String?, Args?)]) -> Bool { for (sql, args) in queries { if let sql = sql { if !run(db, sql: sql, args: args) { return false } } } return true } func runValidQueries(_ db: SQLiteDBConnection, queries: [String?]) -> Bool { return self.run(db, queries: optFilter(queries)) } func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool { let type = BookmarkNodeType.folder.rawValue let now = Date.nowNumber() let status = SyncStatus.new.rawValue let localArgs: Args = [ BookmarkRoots.RootID, BookmarkRoots.RootGUID, type, BookmarkRoots.RootGUID, status, now, BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, BookmarkRoots.RootGUID, status, now, BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, BookmarkRoots.RootGUID, status, now, BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, BookmarkRoots.RootGUID, status, now, BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, BookmarkRoots.RootGUID, status, now, ] // Compute these args using the sequence in RootChildren, rather than hard-coding. var idx = 0 var structureArgs = Args() structureArgs.reserveCapacity(BookmarkRoots.RootChildren.count * 3) BookmarkRoots.RootChildren.forEach { guid in structureArgs.append(BookmarkRoots.RootGUID) structureArgs.append(guid) structureArgs.append(idx) idx += 1 } // Note that we specify an empty title and parentName for these records. We should // never need a parentName -- we don't use content-based reconciling or // reparent these -- and we'll use the current locale's string, retrieved // via titleForSpecialGUID, if necessary. let local = "INSERT INTO \(TableBookmarksLocal) " + "(id, guid, type, parentid, title, parentName, sync_status, local_modified) VALUES " + Array(repeating: "(?, ?, ?, ?, '', '', ?, ?)", count: BookmarkRoots.RootChildren.count + 1).joined(separator: ", ") let structure = "INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) VALUES " + Array(repeating: "(?, ?, ?)", count: BookmarkRoots.RootChildren.count).joined(separator: ", ") return self.run(db, queries: [(local, localArgs), (structure, structureArgs)]) } let topSitesTableCreate = "CREATE TABLE IF NOT EXISTS \(TableCachedTopSites) (" + "historyID INTEGER, " + "url TEXT NOT NULL, " + "title TEXT NOT NULL, " + "guid TEXT NOT NULL UNIQUE, " + "domain_id INTEGER, " + "domain TEXT NO NULL, " + "localVisitDate REAL, " + "remoteVisitDate REAL, " + "localVisitCount INTEGER, " + "remoteVisitCount INTEGER, " + "iconID INTEGER, " + "iconURL TEXT, " + "iconDate REAL, " + "iconType INTEGER, " + "iconWidth INTEGER, " + "frecencies REAL" + ")" let domainsTableCreate = "CREATE TABLE IF NOT EXISTS \(TableDomains) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "domain TEXT NOT NULL UNIQUE, " + "showOnTopSites TINYINT NOT NULL DEFAULT 1" + ")" let queueTableCreate = "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" + "url TEXT NOT NULL UNIQUE, " + "title TEXT" + ") " let activityStreamBlocklistCreate = "CREATE TABLE IF NOT EXISTS \(TableActivityStreamBlocklist) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "url TEXT NOT NULL UNIQUE, " + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP " + ") " let pageMetadataCreate = "CREATE TABLE IF NOT EXISTS \(TablePageMetadata) (" + "id INTEGER PRIMARY KEY, " + "cache_key LONGVARCHAR UNIQUE, " + "site_url TEXT, " + "media_url LONGVARCHAR, " + "title TEXT, " + "type VARCHAR(32), " + "description TEXT, " + "provider_name TEXT, " + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, " + "expired_at LONG" + ") " let indexPageMetadataCreate = "CREATE UNIQUE INDEX IF NOT EXISTS \(IndexPageMetadataCacheKey) ON page_metadata (cache_key)" let iconColumns = ", faviconID INTEGER REFERENCES \(TableFavicons)(id) ON DELETE SET NULL" let mirrorColumns = ", is_overridden TINYINT NOT NULL DEFAULT 0" let serverColumns = ", server_modified INTEGER NOT NULL" + // Milliseconds. ", hasDupe TINYINT NOT NULL DEFAULT 0" // Boolean, 0 (false) if deleted. let localColumns = ", local_modified INTEGER" + // Can be null. Client clock. In extremis only. ", sync_status TINYINT NOT NULL" // SyncStatus enum. Set when changed or created. func getBookmarksTableCreationStringForTable(_ table: String, withAdditionalColumns: String="") -> String { // The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry. // For now we have the simplest possible schema: everything in one. let sql = "CREATE TABLE IF NOT EXISTS \(table) " + // Shared fields. "( id INTEGER PRIMARY KEY AUTOINCREMENT" + ", guid TEXT NOT NULL UNIQUE" + ", type TINYINT NOT NULL" + // Type enum. // Record/envelope metadata that'll allow us to do merges. ", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean ", parentid TEXT" + // GUID ", parentName TEXT" + // Type-specific fields. These should be NOT NULL in many cases, but we're going // for a sparse schema, so this'll do for now. Enforce these in the application code. ", feedUri TEXT, siteUri TEXT" + // LIVEMARKS ", pos INT" + // SEPARATORS ", title TEXT, description TEXT" + // FOLDERS, BOOKMARKS, QUERIES ", bmkUri TEXT, tags TEXT, keyword TEXT" + // BOOKMARKS, QUERIES ", folderName TEXT, queryId TEXT" + // QUERIES withAdditionalColumns + ", CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1)" + ", CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1)" + ")" return sql } /** * We need to explicitly store what's provided by the server, because we can't rely on * referenced child nodes to exist yet! */ func getBookmarksStructureTableCreationStringForTable(_ table: String, referencingMirror mirror: String) -> String { let sql = "CREATE TABLE IF NOT EXISTS \(table) " + "( parent TEXT NOT NULL REFERENCES \(mirror)(guid) ON DELETE CASCADE" + ", child TEXT NOT NULL" + // Should be the GUID of a child. ", idx INTEGER NOT NULL" + // Should advance from 0. ")" return sql } fileprivate let bufferBookmarksView = "CREATE VIEW \(ViewBookmarksBufferOnMirror) AS " + "SELECT" + " -1 AS id" + ", mirror.guid AS guid" + ", mirror.type AS type" + ", mirror.is_deleted AS is_deleted" + ", mirror.parentid AS parentid" + ", mirror.parentName AS parentName" + ", mirror.feedUri AS feedUri" + ", mirror.siteUri AS siteUri" + ", mirror.pos AS pos" + ", mirror.title AS title" + ", mirror.description AS description" + ", mirror.bmkUri AS bmkUri" + ", mirror.keyword AS keyword" + ", mirror.folderName AS folderName" + ", null AS faviconID" + ", 0 AS is_overridden" + // LEFT EXCLUDING JOIN to get mirror records that aren't in the buffer. // We don't have an is_overridden flag to help us here. " FROM \(TableBookmarksMirror) mirror LEFT JOIN" + " \(TableBookmarksBuffer) buffer ON mirror.guid = buffer.guid" + " WHERE buffer.guid IS NULL" + " UNION ALL " + "SELECT" + " -1 AS id" + ", guid" + ", type" + ", is_deleted" + ", parentid" + ", parentName" + ", feedUri" + ", siteUri" + ", pos" + ", title" + ", description" + ", bmkUri" + ", keyword" + ", folderName" + ", null AS faviconID" + ", 1 AS is_overridden" + " FROM \(TableBookmarksBuffer) WHERE is_deleted IS 0" // TODO: phrase this without the subselect… fileprivate let bufferBookmarksStructureView = // We don't need to exclude deleted parents, because we drop those from the structure // table when we see them. "CREATE VIEW \(ViewBookmarksBufferStructureOnMirror) AS " + "SELECT parent, child, idx, 1 AS is_overridden FROM \(TableBookmarksBufferStructure) " + "UNION ALL " + // Exclude anything from the mirror that's present in the buffer -- dynamic is_overridden. "SELECT parent, child, idx, 0 AS is_overridden FROM \(TableBookmarksMirrorStructure) " + "LEFT JOIN \(TableBookmarksBuffer) ON parent = guid WHERE guid IS NULL" fileprivate let localBookmarksView = "CREATE VIEW \(ViewBookmarksLocalOnMirror) AS " + "SELECT -1 AS id, guid, type, is_deleted, parentid, parentName, feedUri," + " siteUri, pos, title, description, bmkUri, folderName, faviconID, NULL AS local_modified, server_modified, 0 AS is_overridden " + "FROM \(TableBookmarksMirror) WHERE is_overridden IS NOT 1 " + "UNION ALL " + "SELECT -1 AS id, guid, type, is_deleted, parentid, parentName, feedUri, siteUri, pos, title, description, bmkUri, folderName, faviconID," + " local_modified, NULL AS server_modified, 1 AS is_overridden " + "FROM \(TableBookmarksLocal) WHERE is_deleted IS NOT 1" // TODO: phrase this without the subselect… fileprivate let localBookmarksStructureView = "CREATE VIEW \(ViewBookmarksLocalStructureOnMirror) AS " + "SELECT parent, child, idx, 1 AS is_overridden FROM \(TableBookmarksLocalStructure) " + "WHERE " + "((SELECT is_deleted FROM \(TableBookmarksLocal) WHERE guid = parent) IS NOT 1) " + "UNION ALL " + "SELECT parent, child, idx, 0 AS is_overridden FROM \(TableBookmarksMirrorStructure) " + "WHERE " + "((SELECT is_overridden FROM \(TableBookmarksMirror) WHERE guid = parent) IS NOT 1) " // This view exists only to allow for text searching of URLs and titles in the awesomebar. // As such, we cheat a little: we include buffer, non-overridden mirror, and local. // Usually this will be indistinguishable from a more sophisticated approach, and it's way // easier. fileprivate let allBookmarksView = "CREATE VIEW \(ViewAllBookmarks) AS " + "SELECT guid, bmkUri AS url, title, description, faviconID FROM " + "\(TableBookmarksMirror) WHERE " + "type = \(BookmarkNodeType.bookmark.rawValue) AND is_overridden IS 0 AND is_deleted IS 0 " + "UNION ALL " + "SELECT guid, bmkUri AS url, title, description, faviconID FROM " + "\(TableBookmarksLocal) WHERE " + "type = \(BookmarkNodeType.bookmark.rawValue) AND is_deleted IS 0 " + "UNION ALL " + "SELECT guid, bmkUri AS url, title, description, -1 AS faviconID FROM " + "\(TableBookmarksBuffer) WHERE " + "type = \(BookmarkNodeType.bookmark.rawValue) AND is_deleted IS 0" // This smushes together remote and local visits. So it goes. fileprivate let historyVisitsView = "CREATE VIEW \(ViewHistoryVisits) AS " + "SELECT h.url AS url, MAX(v.date) AS visitDate, h.domain_id AS domain_id FROM " + "\(TableHistory) h JOIN \(TableVisits) v ON v.siteID = h.id " + "GROUP BY h.id" // Join all bookmarks against history to find the most recent visit. // visits. fileprivate let awesomebarBookmarksView = "CREATE VIEW \(ViewAwesomebarBookmarks) AS " + "SELECT b.guid AS guid, b.url AS url, b.title AS title, " + "b.description AS description, b.faviconID AS faviconID, " + "h.visitDate AS visitDate " + "FROM \(ViewAllBookmarks) b " + "LEFT JOIN " + "\(ViewHistoryVisits) h ON b.url = h.url" fileprivate let awesomebarBookmarksWithIconsView = "CREATE VIEW \(ViewAwesomebarBookmarksWithIcons) AS " + "SELECT b.guid AS guid, b.url AS url, b.title AS title, " + "b.description AS description, b.visitDate AS visitDate, " + "f.id AS iconID, f.url AS iconURL, f.date AS iconDate, " + "f.type AS iconType, f.width AS iconWidth " + "FROM \(ViewAwesomebarBookmarks) b " + "LEFT JOIN " + "\(TableFavicons) f ON f.id = b.faviconID" func create(_ db: SQLiteDBConnection) -> Bool { let favicons = "CREATE TABLE IF NOT EXISTS \(TableFavicons) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "url TEXT NOT NULL UNIQUE, " + "width INTEGER, " + "height INTEGER, " + "type INTEGER NOT NULL, " + "date REAL NOT NULL" + ") " let history = "CREATE TABLE IF NOT EXISTS \(TableHistory) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's. "url TEXT UNIQUE, " + // May only be null for deleted records. "title TEXT NOT NULL, " + "server_modified INTEGER, " + // Can be null. Integer milliseconds. "local_modified INTEGER, " + // Can be null. Client clock. In extremis only. "is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted. "should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added. "domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " + "CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" + ")" // Right now we don't need to track per-visit deletions: Sync can't // represent them! See Bug 1157553 Comment 6. // We flip the should_upload flag on the history item when we add a visit. // If we ever want to support logic like not bothering to sync if we added // and then rapidly removed a visit, then we need an 'is_new' flag on each visit. let visits = "CREATE TABLE IF NOT EXISTS \(TableVisits) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " + "date REAL NOT NULL, " + // Microseconds since epoch. "type INTEGER NOT NULL, " + "is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. "UNIQUE (siteID, date, type) " + ") " let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " + "ON \(TableVisits) (siteID, is_local, date)" let faviconSites = "CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " + "faviconID INTEGER NOT NULL REFERENCES \(TableFavicons)(id) ON DELETE CASCADE, " + "UNIQUE (siteID, faviconID) " + ") " let widestFavicons = "CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " + "SELECT " + "\(TableFaviconSites).siteID AS siteID, " + "\(TableFavicons).id AS iconID, " + "\(TableFavicons).url AS iconURL, " + "\(TableFavicons).date AS iconDate, " + "\(TableFavicons).type AS iconType, " + "MAX(\(TableFavicons).width) AS iconWidth " + "FROM \(TableFaviconSites), \(TableFavicons) WHERE " + "\(TableFaviconSites).faviconID = \(TableFavicons).id " + "GROUP BY siteID " let historyIDsWithIcon = "CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " + "SELECT \(TableHistory).id AS id, " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM \(TableHistory) " + "LEFT OUTER JOIN " + "\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID " let iconForURL = "CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " + "SELECT history.url AS url, icons.iconID AS iconID FROM " + "\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " + "\(TableHistory).id = icons.siteID " // Locally we track faviconID. // Local changes end up in the mirror, so we track it there too. // The buffer and the mirror additionally track some server metadata. let bookmarksLocal = getBookmarksTableCreationStringForTable(TableBookmarksLocal, withAdditionalColumns: self.localColumns + self.iconColumns) let bookmarksLocalStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksLocalStructure, referencingMirror: TableBookmarksLocal) let bookmarksBuffer = getBookmarksTableCreationStringForTable(TableBookmarksBuffer, withAdditionalColumns: self.serverColumns) let bookmarksBufferStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksBufferStructure, referencingMirror: TableBookmarksBuffer) let bookmarksMirror = getBookmarksTableCreationStringForTable(TableBookmarksMirror, withAdditionalColumns: self.serverColumns + self.mirrorColumns + self.iconColumns) let bookmarksMirrorStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksMirrorStructure, referencingMirror: TableBookmarksMirror) let indexLocalStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksLocalStructureParentIdx) " + "ON \(TableBookmarksLocalStructure) (parent, idx)" let indexBufferStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksBufferStructureParentIdx) " + "ON \(TableBookmarksBufferStructure) (parent, idx)" let indexMirrorStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " + "ON \(TableBookmarksMirrorStructure) (parent, idx)" let indexMirrorStructureChild = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureChild) " + "ON \(TableBookmarksMirrorStructure) (child)" let queries: [String] = [ self.domainsTableCreate, history, favicons, visits, bookmarksBuffer, bookmarksBufferStructure, bookmarksLocal, bookmarksLocalStructure, bookmarksMirror, bookmarksMirrorStructure, indexBufferStructureParentIdx, indexLocalStructureParentIdx, indexMirrorStructureParentIdx, indexMirrorStructureChild, faviconSites, indexShouldUpload, indexSiteIDDate, widestFavicons, historyIDsWithIcon, iconForURL, pageMetadataCreate, indexPageMetadataCreate, self.queueTableCreate, self.topSitesTableCreate, self.localBookmarksView, self.localBookmarksStructureView, self.bufferBookmarksView, self.bufferBookmarksStructureView, allBookmarksView, historyVisitsView, awesomebarBookmarksView, awesomebarBookmarksWithIconsView, activityStreamBlocklistCreate ] assert(queries.count == AllTablesIndicesAndViews.count, "Did you forget to add your table, index, or view to the list?") log.debug("Creating \(queries.count) tables, views, and indices.") return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } func updateTable(_ db: SQLiteDBConnection, from: Int) -> Bool { let to = BrowserTable.DefaultVersion if from == to { log.debug("Skipping update from \(from) to \(to).") return true } if from == 0 { // This is likely an upgrade from before Bug 1160399. log.debug("Updating browser tables from zero. Assuming drop and recreate.") return drop(db) && create(db) } if from > to { // This is likely an upgrade from before Bug 1160399. log.debug("Downgrading browser tables. Assuming drop and recreate.") return drop(db) && create(db) } log.debug("Updating browser tables from \(from) to \(to).") if from < 4 && to >= 4 { return drop(db) && create(db) } if from < 5 && to >= 5 { if !self.run(db, sql: self.queueTableCreate) { return false } } if from < 6 && to >= 6 { if !self.run(db, queries: [ "DROP INDEX IF EXISTS \(IndexVisitsSiteIDDate)", "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) ON \(TableVisits) (siteID, is_local, date)", self.domainsTableCreate, "ALTER TABLE \(TableHistory) ADD COLUMN domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE", ]) { return false } let urls = db.executeQuery("SELECT DISTINCT url FROM \(TableHistory) WHERE url IS NOT NULL", factory: { $0["url"] as! String }) if !fillDomainNamesFromCursor(urls, db: db) { return false } } if from < 8 && to == 8 { // Nothing to do: we're just shifting the favicon table to be owned by this class. return true } if from < 9 && to >= 9 { if !self.run(db, sql: getBookmarksTableCreationStringForTable(TableBookmarksMirror)) { return false } } if from < 10 && to >= 10 { if !self.run(db, sql: getBookmarksStructureTableCreationStringForTable(TableBookmarksMirrorStructure, referencingMirror: TableBookmarksMirror)) { return false } let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " + "ON \(TableBookmarksMirrorStructure) (parent, idx)" if !self.run(db, sql: indexStructureParentIdx) { return false } } if from < 11 && to >= 11 { if !self.run(db, sql: self.topSitesTableCreate) { return false } } if from < 12 && to >= 12 { let bookmarksLocal = getBookmarksTableCreationStringForTable(TableBookmarksLocal, withAdditionalColumns: self.localColumns + self.iconColumns) let bookmarksLocalStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksLocalStructure, referencingMirror: TableBookmarksLocal) let bookmarksMirror = getBookmarksTableCreationStringForTable(TableBookmarksMirror, withAdditionalColumns: self.serverColumns + self.mirrorColumns + self.iconColumns) let bookmarksMirrorStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksMirrorStructure, referencingMirror: TableBookmarksMirror) let indexLocalStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksLocalStructureParentIdx) " + "ON \(TableBookmarksLocalStructure) (parent, idx)" let indexBufferStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksBufferStructureParentIdx) " + "ON \(TableBookmarksBufferStructure) (parent, idx)" let indexMirrorStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " + "ON \(TableBookmarksMirrorStructure) (parent, idx)" let prep = [ // Drop indices. "DROP INDEX IF EXISTS idx_bookmarksMirrorStructure_parent_idx", // Rename the old mirror tables to buffer. // The v11 one is the same shape as the current buffer table. "ALTER TABLE \(TableBookmarksMirror) RENAME TO \(TableBookmarksBuffer)", "ALTER TABLE \(TableBookmarksMirrorStructure) RENAME TO \(TableBookmarksBufferStructure)", // Create the new mirror and local tables. bookmarksLocal, bookmarksMirror, bookmarksLocalStructure, bookmarksMirrorStructure, ] // Only migrate bookmarks. The only folders are our roots, and we'll create those later. // There should be nothing else in the table, and no structure. // Our old bookmarks table didn't have creation date, so we use the current timestamp. let modified = Date.now() let status = SyncStatus.new.rawValue // We don't specify a title, expecting it to be generated on the fly, because we're smarter than Android. // We also don't migrate the 'id' column; we'll generate new ones that won't conflict with our roots. let migrateArgs: Args = [BookmarkRoots.MobileFolderGUID] let migrateLocal = "INSERT INTO \(TableBookmarksLocal) " + "(guid, type, bmkUri, title, faviconID, local_modified, sync_status, parentid, parentName) " + "SELECT guid, type, url AS bmkUri, title, faviconID, " + "\(modified) AS local_modified, \(status) AS sync_status, ?, '' " + "FROM \(_TableBookmarks) WHERE type IS \(BookmarkNodeType.bookmark.rawValue)" // Create structure for our migrated bookmarks. // In order to get contiguous positions (idx), we first insert everything we just migrated under // Mobile Bookmarks into a temporary table, then use rowid as our idx. let temporaryTable = "CREATE TEMPORARY TABLE children AS " + "SELECT guid FROM \(_TableBookmarks) WHERE " + "type IS \(BookmarkNodeType.bookmark.rawValue) ORDER BY id ASC" let createStructure = "INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) " + "SELECT ? AS parent, guid AS child, (rowid - 1) AS idx FROM children" let migrate: [(String, Args?)] = [ (migrateLocal, migrateArgs), (temporaryTable, nil), (createStructure, migrateArgs), // Drop the temporary table. ("DROP TABLE children", nil), // Drop the old bookmarks table. ("DROP TABLE \(_TableBookmarks)", nil), // Create indices for each structure table. (indexBufferStructureParentIdx, nil), (indexLocalStructureParentIdx, nil), (indexMirrorStructureParentIdx, nil) ] if !self.run(db, queries: prep) || !self.prepopulateRootFolders(db) || !self.run(db, queries: migrate) { return false } // TODO: trigger a sync? } // Add views for the overlays. if from < 14 && to >= 14 { let indexMirrorStructureChild = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureChild) " + "ON \(TableBookmarksMirrorStructure) (child)" if !self.run(db, queries: [ self.bufferBookmarksView, self.bufferBookmarksStructureView, self.localBookmarksView, self.localBookmarksStructureView, indexMirrorStructureChild]) { return false } } if from == 14 && to >= 15 { // We screwed up some of the views. Recreate them. if !self.run(db, queries: [ "DROP VIEW IF EXISTS \(ViewBookmarksBufferStructureOnMirror)", "DROP VIEW IF EXISTS \(ViewBookmarksLocalStructureOnMirror)", "DROP VIEW IF EXISTS \(ViewBookmarksBufferOnMirror)", "DROP VIEW IF EXISTS \(ViewBookmarksLocalOnMirror)", self.bufferBookmarksView, self.bufferBookmarksStructureView, self.localBookmarksView, self.localBookmarksStructureView]) { return false } } if from < 16 && to >= 16 { if !self.run(db, queries: [ allBookmarksView, historyVisitsView, awesomebarBookmarksView, awesomebarBookmarksWithIconsView]) { return false } } if from < 17 && to >= 17 { if !self.run(db, queries: [ // Adds the local_modified, server_modified times to the local bookmarks view "DROP VIEW IF EXISTS \(ViewBookmarksLocalOnMirror)", self.localBookmarksView]) { return false } } if from < 18 && to >= 18 { if !self.run(db, queries: [ // Adds the Activity Stream blocklist table activityStreamBlocklistCreate]) { return false } } if from < 19 && to >= 19 { if !self.run(db, queries: [ // Adds tables/indicies for metadata content pageMetadataCreate, indexPageMetadataCreate]) { return false } } if from < 20 && to >= 20 { if !self.run(db, queries: [ "DROP VIEW IF EXISTS \(ViewBookmarksBufferOnMirror)", self.bufferBookmarksView]) { return false } } if from < 21 && to >= 21 { if !self.run(db, queries: [ "DROP VIEW IF EXISTS \(ViewHistoryVisits)", self.historyVisitsView]) { return false } } return true } fileprivate func fillDomainNamesFromCursor(_ cursor: Cursor<String>, db: SQLiteDBConnection) -> Bool { if cursor.count == 0 { return true } // URL -> hostname, flattened to make args. var pairs = Args() pairs.reserveCapacity(cursor.count * 2) for url in cursor { if let url = url, let host = url.asURL?.normalizedHost { pairs.append(url) pairs.append(host) } } cursor.close() let tmpTable = "tmp_hostnames" let table = "CREATE TEMP TABLE \(tmpTable) (url TEXT NOT NULL UNIQUE, domain TEXT NOT NULL, domain_id INT)" if !self.run(db, sql: table, args: nil) { log.error("Can't create temporary table. Unable to migrate domain names. Top Sites is likely to be broken.") return false } // Now insert these into the temporary table. Chunk by an even number, for obvious reasons. let chunks = chunk(pairs, by: BrowserDB.MaxVariableNumber - (BrowserDB.MaxVariableNumber % 2)) for chunk in chunks { let ins = "INSERT INTO \(tmpTable) (url, domain) VALUES " + Array<String>(repeating: "(?, ?)", count: chunk.count / 2).joined(separator: ", ") if !self.run(db, sql: ins, args: Array(chunk)) { log.error("Couldn't insert domains into temporary table. Aborting migration.") return false } } // Now make those into domains. let domains = "INSERT OR IGNORE INTO \(TableDomains) (domain) SELECT DISTINCT domain FROM \(tmpTable)" // … and fill that temporary column. let domainIDs = "UPDATE \(tmpTable) SET domain_id = (SELECT id FROM \(TableDomains) WHERE \(TableDomains).domain = \(tmpTable).domain)" // Update the history table from the temporary table. let updateHistory = "UPDATE \(TableHistory) SET domain_id = (SELECT domain_id FROM \(tmpTable) WHERE \(tmpTable).url = \(TableHistory).url)" // Clean up. let dropTemp = "DROP TABLE \(tmpTable)" // Now run these. if !self.run(db, queries: [domains, domainIDs, updateHistory, dropTemp]) { log.error("Unable to migrate domains.") return false } return true } /** * The Table mechanism expects to be able to check if a 'table' exists. In our (ab)use * of Table, that means making sure that any of our tables and views exist. * We do that by fetching all tables from sqlite_master with matching names, and verifying * that we get back more than one. * Note that we don't check for views -- trust to luck. */ func exists(_ db: SQLiteDBConnection) -> Bool { return db.tablesExist(AllTables) } func drop(_ db: SQLiteDBConnection) -> Bool { log.debug("Dropping all browser tables.") let additional = [ "DROP TABLE IF EXISTS faviconSites" // We renamed it to match naming convention. ] let views = AllViews.map { "DROP VIEW IF EXISTS \($0)" } let indices = AllIndices.map { "DROP INDEX IF EXISTS \($0)" } let tables = AllTables.map { "DROP TABLE IF EXISTS \($0)" } let queries = Array([views, indices, tables, additional].joined()) return self.run(db, queries: queries) } }
mpl-2.0
cbaeffc855f48a2d0e25ccbbfb458440
42.937634
246
0.620136
4.799953
false
false
false
false
jindulys/Leetcode_Solutions_Swift
Sources/Tree/105_ConstructBinaryTreeFromPreorderAndInorderTraversal.swift
1
2420
// // 105_ConstructBinaryTreeFromPreorderAndInorderTraversal.swift // HRSwift // // Created by yansong li on 2016-08-06. // Copyright © 2016 yansong li. All rights reserved. // import Foundation /** Title:105 Construct Binary Tree From Preorder and Ignorer Traversal URL: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ Space: O(n) Time: O(n) */ class TreeBuildPreorderInorder_Solution { func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? { guard preorder.count > 0 && inorder.count > 0 && preorder.count == inorder.count else { return nil } return treeBuildHelper(preorder, preStartIndex: 0, preEndIndex: preorder.count - 1, inorder: inorder, inorderStartIndex: 0, inorderEndIndex: inorder.count - 1) } func treeBuildHelper(_ preorder: [Int], preStartIndex: Int, preEndIndex: Int, inorder: [Int], inorderStartIndex: Int, inorderEndIndex: Int) -> TreeNode? { guard preStartIndex <= preEndIndex && inorderStartIndex <= inorderEndIndex else { return nil } let rootVal = preorder[preStartIndex] let currentRoot = TreeNode(rootVal) var mid: Int = 0 for i in inorderStartIndex...inorderEndIndex { if inorder[i] == rootVal { mid = i break } } currentRoot.left = treeBuildHelper(preorder, preStartIndex: preStartIndex + 1, preEndIndex: preStartIndex + mid - inorderStartIndex, inorder: inorder, inorderStartIndex: inorderStartIndex, inorderEndIndex: mid - 1) currentRoot.right = treeBuildHelper(preorder, preStartIndex: preStartIndex + mid - inorderStartIndex + 1, preEndIndex: preEndIndex, inorder: inorder, inorderStartIndex: mid + 1, inorderEndIndex: inorderEndIndex) return currentRoot } }
mit
13d5d503154748b4c92193874b742b16
36.215385
99
0.522117
4.799603
false
false
false
false
xeo-it/zipbooks-invoices-swift
zipbooks-ios/Models/Expense.swift
1
2490
// // User.swift // zipbooks-ios // // Created by Francesco Pretelli on 11/01/16. // Copyright © 2016 Francesco Pretelli. All rights reserved. // import RealmSwift import ObjectMapper import Foundation class Expense: Object,Mappable { dynamic var id: Int = 0 dynamic var name: String? dynamic var created_at: String? dynamic var billed: Int = 0 dynamic var plaid_transaction_id: String? dynamic var customer_id: Int = 0 dynamic var category: String? dynamic var date: String? dynamic var customer: Customer? dynamic var bank_account_id: Int = 0 dynamic var image_filename: String? dynamic var meta: String? dynamic var type: String? dynamic var deleted_at: String? dynamic var pending: String? dynamic var note: String? dynamic var updated_at: String? dynamic var line_item_id: Int = 0 dynamic var account_id: Int = 0 dynamic var archived_at: String? dynamic var amount: String? dynamic var currency_code: String? dynamic var category_id: String? override static func primaryKey() -> String? { return "id" } // MARK: Mappable required convenience init?(map: Map) { self.init() } func mapping(map: Map) { id <- map["id"] name <- map["name"] created_at <- map["created_at"] billed <- map["billed"] plaid_transaction_id <- map["plaid_transaction_id"] customer_id <- map["customer_id"] category <- map["category"] date <- map["date"] customer <- map["customer"] bank_account_id <- map["bank_account_id"] image_filename <- map["image_filename"] meta <- map["meta"] type <- map["type"] deleted_at <- map["deleted_at"] pending <- map["pending"] note <- map["note"] updated_at <- map["updated_at"] line_item_id <- map["line_item_id"] account_id <- map["account_id"] archived_at <- map["archived_at"] amount <- map["amount"] currency_code <- map["currency_code"] category_id <- map["category_id"] } } class ExpensePost: Object,Mappable { dynamic var amount: Double = 0 dynamic var date: String? dynamic var customer_id: Int = 0 dynamic var name: String? dynamic var category: String? dynamic var note: String? // MARK: Mappable required convenience init?(map: Map) { self.init() } func mapping(map: Map) { amount <- map["amount"] date <- map["date"] customer_id <- map["customer_id"] name <- map["name"] category <- map["category"] note <- map["note"] } }
mit
6cd01374972618b80eae304dacf7ef1d
24.927083
61
0.641221
3.428375
false
false
false
false
behoernchen/IcnsComposer
Icns Composer/NSImageExtensions.swift
1
4433
// // NSImageExtensions.swift // Icns Composer // https://github.com/raphaelhanneken/icnscomposer // import Cocoa extension NSImage { /// The height of the image. var height: CGFloat { return size.height } /// The width of the image. var width: CGFloat { return size.width } /// A PNG representation of the image. var PNGRepresentation: Data? { if let tiff = self.tiffRepresentation, let tiffData = NSBitmapImageRep(data: tiff) { return tiffData.representation(using: .png, properties: [:]) } return nil } // MARK: Resizing /// Resize the image to the given size. /// /// - Parameter size: The size to resize the image to. /// - Returns: The resized image. func resize(toSize size: NSSize) -> NSImage? { // Create a new rect with given width and height let frame = NSRect(x: 0, y: 0, width: size.width, height: size.height) // Get the best representation for the given size. guard let rep = self.bestRepresentation(for: frame, context: nil, hints: nil) else { return nil } // Create an empty image with the given size. let img = NSImage(size: size, flipped: false, drawingHandler: { (_) -> Bool in if rep.draw(in: frame) { return true } return false }) return img } /// Copy the image and resize it to the supplied size, while maintaining it's /// original aspect ratio. /// /// - Parameter size: The target size of the image. /// - Returns: The resized image. func resizeMaintainingAspectRatio(withSize size: NSSize) -> NSImage? { let newSize: NSSize let widthRatio = size.width / width let heightRatio = size.height / height if widthRatio > heightRatio { newSize = NSSize(width: floor(width * widthRatio), height: floor(height * widthRatio)) } else { newSize = NSSize(width: floor(width * heightRatio), height: floor(height * heightRatio)) } return resize(toSize: newSize) } // MARK: Cropping /// Resize the image, to nearly fit the supplied cropping size /// and return a cropped copy the image. /// /// - Parameter size: The size of the new image. /// - Returns: The cropped image. func crop(toSize: NSSize) -> NSImage? { // Resize the current image, while preserving the aspect ratio. guard let resized = self.resizeMaintainingAspectRatio(withSize: size) else { return nil } // Get some points to center the cropping area. let x = floor((resized.width - size.width) / 2) let y = floor((resized.height - size.height) / 2) // Create the cropping frame. let frame = NSRect(x: x, y: y, width: width, height: height) // Get the best representation of the image for the given cropping frame. guard let rep = resized.bestRepresentation(for: frame, context: nil, hints: nil) else { return nil } // Create a new image with the new size let img = NSImage(size: size) defer { img.unlockFocus() } img.lockFocus() if rep.draw(in: NSRect(x: 0, y: 0, width: width, height: height), from: frame, operation: NSCompositingOperation.copy, fraction: 1.0, respectFlipped: false, hints: [:]) { // Return the cropped image. return img } // Return nil in case anything fails. return nil } // MARK: Saving /// Save the images PNG representation to the supplied file URL. /// /// - Parameter url: The file URL to save the png file to. /// - Throws: An NSImageExtension Error. func savePngTo(url: URL) throws { if let png = self.PNGRepresentation { try png.write(to: url, options: .atomicWrite) } else { throw NSImageExtensionError.creatingPngRepresentationFailed } } } /// Exceptions for the image extension class. /// /// - creatingPngRepresentationFailed: Is thrown when the creation of the png representation failed. enum NSImageExtensionError: Error { case creatingPngRepresentationFailed }
mit
089da67f20ca388ec0be46d6cc968c30
31.123188
100
0.587187
4.551335
false
false
false
false
Raizlabs/ios-template
{{ cookiecutter.project_name | replace(' ', '') }}/app/Services/API/APIEndpoint+Codable.swift
1
604
// // APIEndpoint+Codable.swift // Services // // Created by {{ cookiecutter.lead_dev }} on {% now 'utc', '%D' %}. // Copyright © {% now 'utc', '%Y' %} {{ cookiecutter.company_name }}. All rights reserved. // import Foundation extension JSONDecoder { static let `default`: JSONDecoder = { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 return decoder }() } extension JSONEncoder { static let `default`: JSONEncoder = { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 return encoder }() }
mit
56344f8f330ceffc9217415e77a94259
20.535714
91
0.613599
4.276596
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/AccountBuilder.swift
2
1212
import Foundation @testable import WordPress /// Builds an Account for use with testing /// @objc class AccountBuilder: NSObject { private let coreDataStack: CoreDataStack private var account: WPAccount @objc init(_ coreDataStack: CoreDataStack) { self.coreDataStack = coreDataStack account = NSEntityDescription.insertNewObject(forEntityName: WPAccount.entityName(), into: coreDataStack.mainContext) as! WPAccount account.uuid = UUID().uuidString super.init() } @objc func with(id: Int64) -> AccountBuilder { account.userID = NSNumber(value: id) return self } @objc func with(uuid: String) -> AccountBuilder { account.uuid = uuid return self } @objc func with(username: String) -> AccountBuilder { account.username = username return self } @objc func with(email: String) -> AccountBuilder { account.email = email return self } @objc func with(blogs: [Blog]) -> AccountBuilder { account.blogs = Set(blogs) return self } @objc @discardableResult func build() -> WPAccount { account } }
gpl-2.0
2d39542e9ecdef3bfc3f69aaffa1f4a5
20.263158
139
0.622112
4.679537
false
false
false
false
mrommel/TreasureDungeons
TreasureDungeons/Source/Utils/Array2D.swift
1
1898
// // Array2D.swift // TreasureDungeons // // Created by Michael Rommel on 22.06.17. // Copyright © 2017 BurtK. All rights reserved. // import Foundation public class Array2D <T: Equatable> { fileprivate var columns: Int = 0 fileprivate var rows: Int = 0 fileprivate var array: Array<T?> = Array<T?>() public init(columns: Int, rows: Int) { self.columns = columns self.rows = rows self.array = Array<T?>(repeating: nil, count: rows * columns) } public subscript(column: Int, row: Int) -> T? { get { return array[(row * columns) + column] } set(newValue) { array[(row * columns) + column] = newValue } } public func columnCount() -> Int { return columns } public func rowCount() -> Int { return rows } } extension Array2D { subscript(point: Point) -> T? { get { return array[(point.y * columns) + point.x] } set(newValue) { array[(point.y * columns) + point.x] = newValue } } } extension Array2D { public func fill(with value: T) { for x in 0..<columns { for y in 0..<rows { self[x, y] = value } } } } extension Array2D: Sequence { public func makeIterator() -> Array2DIterator<T> { return Array2DIterator<T>(self) } } public struct Array2DIterator<T: Equatable>: IteratorProtocol { let array: Array2D<T> var index = 0 init(_ array: Array2D<T>) { self.array = array } mutating public func next() -> T? { let nextNumber = self.array.array.count - index guard nextNumber > 0 else { return nil } index += 1 return self.array.array[nextNumber] } }
apache-2.0
a18b2df6de6d216ed153f7efde6372bf
19.619565
69
0.523985
3.935685
false
false
false
false
whiteshadow-gr/HatForIOS
HAT/Objects/HATNotificationNotice.swift
1
2081
/** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * 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 SwiftyJSON // MARK: Struct public struct HATNotificationNotice { // MARK: - Coding Keys /** The JSON fields used by the hat The Fields are the following: * `noticeID` in JSON is `id` * `dateCreated` in JSON is `dateCreated` * `message` in JSON is `message` */ private enum CodingKeys: String, CodingKey { case noticeID = "id" case dateCreated = "dateCreated" case message = "message" } // MARK: - Variables /// The notification ID public var noticeID: Int = -1 /// The message of the notification public var message: String = "" /// The date the notification was created public var dateCreated: Date = Date() // MARK: - Initialisers /** The default initialiser. Initialises everything to default values. */ public init() { noticeID = -1 message = "" dateCreated = Date() } /** It initialises everything from the received JSON file from the HAT - dictionary: The JSON file received from the HAT */ public init(dictionary: Dictionary<String, JSON>) { if let tempNoticeID: Int = dictionary[CodingKeys.noticeID.rawValue]?.int { noticeID = tempNoticeID } if let tempMessage: String = dictionary[CodingKeys.message.rawValue]?.string { message = tempMessage } if let tempDateCreated: Int = dictionary[CodingKeys.dateCreated.rawValue]?.intValue { dateCreated = Date(timeIntervalSince1970: TimeInterval(tempDateCreated / 1000)) } } }
mpl-2.0
7a1a126134d131545dd5744fde373616
25.341772
93
0.594426
4.686937
false
false
false
false
bsmith11/ScoreReporter
ScoreReporterCore/ScoreReporterCore/Models/Cluster.swift
1
1621
// // Cluster.swift // ScoreReporter // // Created by Bradley Smith on 7/18/16. // Copyright © 2016 Brad Smith. All rights reserved. // import Foundation import CoreData public class Cluster: NSManagedObject { } // MARK: - Public public extension Cluster { func add(team: Team) { guard let games = games.allObjects as? [Game] else { return } games.forEach { $0.add(team: team) } } } // MARK: - Fetchable extension Cluster: Fetchable { public static var primaryKey: String { return #keyPath(Cluster.clusterID) } } // MARK: - CoreDataImportable extension Cluster: CoreDataImportable { public static func object(from dictionary: [String: Any], context: NSManagedObjectContext) -> Cluster? { guard let clusterID = dictionary[APIConstants.Response.Keys.clusterID] as? NSNumber else { return nil } guard let cluster = object(primaryKey: clusterID, context: context, createNew: true) else { return nil } cluster.clusterID = clusterID cluster.name = dictionary <~ APIConstants.Response.Keys.name let games = dictionary[APIConstants.Response.Keys.games] as? [[String: AnyObject]] ?? [] let gamesArray = Game.objects(from: games, context: context) for (index, game) in gamesArray.enumerated() { game.sortOrder = index as NSNumber } cluster.games = NSSet(array: gamesArray) if !cluster.hasPersistentChangedValues { context.refresh(cluster, mergeChanges: false) } return cluster } }
mit
883e003a21fd0057106b9530998d439d
23.545455
108
0.637654
4.274406
false
false
false
false
Zewo/HashedPassword
Sources/HashedPassword.swift
1
4881
// HashedPassword.swift // // The MIT License (MIT) // // Copyright (c) 2016 Zewo // // 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, INCLUDINbG BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import CryptoSwift public enum HashedPasswordError: Error { case invalidString } public enum HashMethod: Equatable { case hash(variant: HMAC.Variant) case hmac(variant: HMAC.Variant) case pbkdf2(variant: HMAC.Variant, iterations: Int) internal init?(string: String) { let comps = string.components(separatedBy: "_") guard let methodStr = comps.first else { return nil } switch methodStr { case "hash": guard comps.count == 2, let hashType = HMAC.Variant(string: comps[1]) else { return nil } self = .hash(variant: hashType) case "hmac": guard comps.count == 2, let hashType = HMAC.Variant(string: comps[1]) else { return nil } self = .hmac(variant: hashType) case "pbkdf2": guard comps.count == 3, let hashType = HMAC.Variant(string: comps[1]), let iterations = Int(comps[2]) else { return nil } self = .pbkdf2(variant: hashType, iterations: iterations) default: return nil } } internal var string: String { switch self { case .hash(let variant): return "hash_" + variant.string case .hmac(let variant): return "hmac_" + variant.string case .pbkdf2(let variant, let iterations): return "pbkdf2_" + variant.string + "_" + String(iterations) } } internal func calculate(password: String, salt: String) throws -> String { guard let saltData = salt.data(using: .utf8)?.bytes, let passwordData = password.data(using: .utf8)?.bytes else { throw HashedPasswordError.invalidString } let data: [UInt8] switch self { case .hash(let variant): data = variant.calculateHash(saltData+passwordData) case .hmac(let variant): data = try HMAC(key: saltData, variant: variant).authenticate(passwordData) case .pbkdf2(let variant, let iterations): data = try PKCS5.PBKDF2(password: passwordData, salt: saltData, iterations: iterations, variant: variant).calculate() } return data.reduce("", { $0 + String(format: "%02x", $1) }) } public static func ==(lhs: HashMethod, rhs: HashMethod) -> Bool { return true } } public struct HashedPassword: Equatable, CustomStringConvertible { public let hash: String public let method: HashMethod public let salt: String public init(hash: String, method: HashMethod, salt: String) { self.hash = hash self.method = method self.salt = salt } public init(string: String) throws { let passwordComps = string.components(separatedBy: "$") guard passwordComps.count == 3, let method = HashMethod(string: passwordComps[1]) else { throw HashedPasswordError.invalidString } self.init(hash: passwordComps[0], method: method, salt: passwordComps[2]) } public init(password: String, method: HashMethod = .pbkdf2(variant: .sha256, iterations: 4096), saltLen: Int = 30) throws { let pool = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] var salt = "" for _ in 0 ..< saltLen { let i = Random.number(max: pool.count - 1) salt += pool[i] } self.method = method self.salt = salt self.hash = try method.calculate(password: password, salt: salt) } public var description: String { return "\(hash)$\(method.string)$\(salt)" } public static func ==(lhs: HashedPassword, rhs: HashedPassword) -> Bool { return lhs.hash == rhs.hash && lhs.method == rhs.method && lhs.salt == rhs.salt } } public func ==(lhs: HashedPassword, rhs: String) -> Bool { return (try? lhs.method.calculate(password: rhs, salt: lhs.salt)) == lhs.hash.lowercased() } public func ==(lhs: String, rhs: HashedPassword) -> Bool { return rhs == lhs }
mit
f45a76ac3b70c3d09a0bb8ac306a285f
35.977273
273
0.681623
3.327198
false
false
false
false
openHPI/xikolo-ios
iOS/Data/Model/Actions/Course+Actions.swift
1
4557
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Common import UIKit extension Course { func shareAction(handler: @escaping () -> Void) -> Action { let title = NSLocalizedString("course.action-menu.share", comment: "Title for course item share action") return Action(title: title, image: Action.Image.share, handler: handler) } func showCourseDatesAction(handler: @escaping () -> Void) -> Action? { guard self.hasEnrollment && Brand.default.features.showCourseDates else { return nil } let title = NSLocalizedString("course.action-menu.show-course-dates", comment: "Title for show course dates action") return Action(title: title, image: Action.Image.calendar, handler: handler) } func openHelpdeskAction(handler: @escaping () -> Void) -> Action { let title = NSLocalizedString("settings.cell-title.app-helpdesk", comment: "cell title for helpdesk") return Action(title: title, image: Action.Image.helpdesk, handler: handler) } func automatedDownloadAction(handler: @escaping () -> Void) -> Action? { guard self.offersNotificationsForNewContent else { return nil } let title = NSLocalizedString("automated-downloads.setup.action.title", comment: "Automated Downloads: Action title for managing notifications for new content") return Action(title: title, image: Action.Image.notification, handler: handler) } @available(iOS 13.0, *) var unenrollAction: UIAction? { guard let enrollment = self.enrollment else { return nil } let unenrollActionTitle = NSLocalizedString("enrollment.options-alert.unenroll-action.title", comment: "title for unenroll action") return UIAction(title: unenrollActionTitle, image: Action.Image.unenroll, attributes: .destructive) { _ in EnrollmentHelper.delete(enrollment) } } @available(iOS 13.0, *) var markAsCompletedMenu: UIMenu? { // For this, we require the subtitle of the confirm action. The subtitle is only available on iOS 15 and later. guard #available(iOS 15, *) else { return nil } guard let enrollment = self.enrollment, !enrollment.completed else { return nil } let cancelActionTitle = NSLocalizedString("global.alert.cancel", comment: "title to cancel alert") let cancelAction = UIAction(title: cancelActionTitle, image: Action.Image.cancel) { _ in } let confirmActionTitle = NSLocalizedString("global.alert.ok", comment: "title to confirm alert") let confirmActionSubtitle = NSLocalizedString("enrollment.mark-as-completed.message.no-undo", comment: "message for the mark as completed action that this action can not be undone") let markAsCompletedAction = UIAction(title: confirmActionTitle, subtitle: confirmActionSubtitle, image: Action.Image.ok) { _ in EnrollmentHelper.markAsCompleted(self) } let completedActionTitle = NSLocalizedString("enrollment.options-alert.mask-as-completed-action.title", comment: "title for 'mask as completed' action") return UIMenu(title: completedActionTitle, image: Action.Image.markAsCompleted, children: [markAsCompletedAction, cancelAction]) } @available(iOS 13.0, *) var manageEnrollmentMenu: UIMenu? { let enrollmentActions: [UIMenuElement] = [ self.markAsCompletedMenu, self.unenrollAction, ].compactMap { $0 } if enrollmentActions.isEmpty { return nil } else { return UIMenu(title: "", options: .displayInline, children: enrollmentActions) } } var isEligibleForContentNotifications: Bool { guard #available(iOS 13, *) else { return false } guard self.hasEnrollment else { return false } guard self.endsAt?.inFuture ?? false else { return false } return true } var offersNotificationsForNewContent: Bool { guard self.isEligibleForContentNotifications else { return false } return FeatureHelper.hasFeature(.newContentNotification, for: self) } var offersAutomatedBackgroundDownloads: Bool { guard self.offersNotificationsForNewContent else { return false } return FeatureHelper.hasFeature(.newContentBackgroundDownload, for: self) } }
gpl-3.0
fc0818b3e63cf4675ea177f9df64f0b5
46.458333
141
0.665716
4.668033
false
false
false
false
GenerallyHelpfulSoftware/Scalar2D
Font/Sources/CoreText+FontDescription.swift
1
18499
// // CoreText+FontDescription.swift // Scalar2D // // Created by Glenn Howes on 9/8/17. // Copyright © 2017-2019 Generally Helpful Software. All rights reserved. // // // // // The MIT License (MIT) // Copyright (c) 2016-2019 Generally Helpful Software // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // import Foundation import CoreText import Scalar2D_Utils #if os(iOS) || os(tvOS) || os(watchOS) import UIKit // for NSAttributedString.Key.underlineStyle #elseif os(OSX) import AppKit // for NSAttributedString.Key.underlineStyle #endif fileprivate let gSystemFontProperties : [AnyHashable : Any] = {return createSystemFontProperties()}() fileprivate let gFontMappings = {return ["Arial" : "ArialMT", "Times New Roman" : "TimesNewRomanPSMT", "Times" : "TimesNewRomanPSMT", "Courier New" : "CourierNewPSMT", "Palatino": "Palatino-Roman"]}() fileprivate let fontAttributesCache : NSCache<AnyObject, AnyObject> = { let result = NSCache<AnyObject, AnyObject>() result.name = "com.genhelp.scalard2d.fontcache" return result }() public protocol FontContext { var initial : Dictionary<AnyHashable, Any> {get} var inherited : Dictionary<AnyHashable, Any> {get} var defaultFontSize : CGFloat {get} var baseFontSize : CGFloat {get} } public protocol CoreTextProperty : InheritableProperty { func merge(properties: inout Dictionary<AnyHashable, Any>, withContext context: FontContext) } extension FontWeight : CoreTextProperty { public func merge(properties: inout Dictionary<AnyHashable, Any>, withContext context: FontContext) { var existingTraits : [AnyHashable : Any] = (properties[kCTFontTraitsAttribute] as? [AnyHashable:Any]) ?? [AnyHashable:Any]() var explicitWeight = (existingTraits[kCTFontWeightTrait] as? NSNumber)?.intValue let fontTraitMaskRaw : UInt32 = UInt32((properties[kCTFontSymbolicTrait] as? Int) ?? 0) var symbolicTraits = CTFontSymbolicTraits(rawValue: fontTraitMaskRaw) switch self { case .bold: symbolicTraits.formUnion(.boldTrait) explicitWeight = nil case .lighter, .bolder, .custom(_): let startWeight = (explicitWeight ?? (symbolicTraits.contains(.boldTrait) ? 700 : 400)) explicitWeight = self.equivalentWeight(forStartWeight: startWeight) if explicitWeight == FontWeight.boldWeight { explicitWeight = nil symbolicTraits.formUnion(.boldTrait) } else if explicitWeight == FontWeight.normalWeight { explicitWeight = nil symbolicTraits.remove(.boldTrait) } case .normal: explicitWeight = nil symbolicTraits.remove(.boldTrait) case .inherit: return case .initial: explicitWeight = nil } if let weightToSet = explicitWeight { existingTraits[kCTFontWeightTrait] = weightToSet properties[kCTFontTraitsAttribute] = existingTraits symbolicTraits.remove(.boldTrait) } else { existingTraits.removeValue(forKey: kCTFontWeightTrait) if existingTraits.isEmpty { properties.removeValue(forKey: kCTFontTraitsAttribute) } else { properties[kCTFontTraitsAttribute] = existingTraits } } if symbolicTraits.rawValue == 0 { properties.removeValue(forKey: kCTFontSymbolicTrait) } else { properties[kCTFontSymbolicTrait] = NSNumber(value: symbolicTraits.rawValue) } } } public extension FontFamily { var stylisticTraits : CTFontStylisticClass { switch self { case .cursive: return .scriptsClass case .fantasy: return .ornamentalsClass case .serif: return .modernSerifsClass case .sansSerif: return .sansSerifClass default: return CTFontStylisticClass(rawValue: 0) } } var symbolicTraits : CTFontSymbolicTraits { switch self { case .monospace: return .traitMonoSpace default: return CTFontSymbolicTraits(rawValue: 0) } } } extension TextDecoration : CoreTextProperty { public func merge(properties: inout Dictionary<AnyHashable, Any>, withContext context: FontContext) { switch self { case .noDecoration, .initial: properties.removeValue(forKey: NSAttributedString.Key.underlineStyle) case .inherit: return case .underline: properties[NSAttributedString.Key.underlineStyle] = NSNumber(value: 1) case .lineThrough: properties[NSAttributedString.Key.strikethroughStyle] = NSNumber(value: 1) case .overline: // don't know how to render this break } } } extension FontVariant { public func add(toDescriptor descriptor: CTFontDescriptor, withContext context: FontContext ) -> CTFontDescriptor { var result = descriptor switch self { case .smallCaps: result = CTFontDescriptorCreateCopyWithFeature(result, 3 as CFNumber, 3 as CFNumber) default: break } return result } } extension FontStretch : CoreTextProperty { public func merge(properties: inout Dictionary<AnyHashable, Any>, withContext context: FontContext) { switch self { case .normal, .initial: properties.removeValue(forKey: kCTFontWidthTrait) case .inherit: return default: guard let width = self.normalizedWidth else { properties.removeValue(forKey: kCTFontWidthTrait) return } properties[kCTFontWidthTrait] = NSNumber(value: width) } } var normalizedWidth : Double? { switch self { case .condensed: return -0.5 case .expanded: return 0.5 case .extraCondensed: return -0.75 case .extraExpanded: return 0.75 case .semiCondensed: return -0.25 case .semiExpanded: return 0.25 case .ultraExpanded: return 1.0 case .ultraCondensed: return -1.0 default: return nil } } } public extension FontContext { var initial : Dictionary<AnyHashable, Any> { return Dictionary<AnyHashable, Any>() } var inherited : Dictionary<AnyHashable, Any> { return self.initial } var defaultFont : CTFont { guard let result = CTFontCreateUIFontForLanguage(.user, 0.0, nil) else { return CTFontCreateWithName("Helvetica" as CFString, 14.0, nil) } return result } var defaultFontSize : CGFloat { let defaultFontRef = self.defaultFont return CTFontGetSize(defaultFontRef) } var defaultAttributes : [AnyHashable : Any] { let fontDescriptor = CTFontCopyFontDescriptor(self.defaultFont) return CTFontDescriptorCopyAttributes(fontDescriptor) as! [AnyHashable : Any] } var baseFontSize : CGFloat { return defaultFontSize } func fontSize(fromFontSize fontSize: FontSize) -> CGFloat { let standardScaling: CGFloat = 1.2 switch fontSize { case .inherit, .initial, .medium: return baseFontSize case .small: return defaultFontSize / standardScaling case .large: return defaultFontSize * standardScaling case .xSmall: return defaultFontSize / (standardScaling*standardScaling) case .xLarge: return defaultFontSize * standardScaling * standardScaling case .xxSmall: return defaultFontSize / (standardScaling*standardScaling*standardScaling) case .xxLarge: return defaultFontSize * standardScaling * standardScaling * standardScaling case .larger: return baseFontSize * standardScaling case .smaller: return baseFontSize / standardScaling case .pixel(let value): return CGFloat(value) // have to re-examine this later with a mechanism to get the pixel height case .point(let value): return CGFloat(value) case .percentage(let percent): return baseFontSize * CGFloat(percent / 100.0) case .em(let scaling): return baseFontSize * CGFloat(scaling) case .rem(let scaling): return defaultFontSize * CGFloat(scaling) case .dynamic: return baseFontSize // TODO support dynamic sizing case .ch(_): return baseFontSize // TODO support ch sizing case .ex(_): return baseFontSize // TODO support ex sizing case .viewPortH(_), .viewPortW(_): return baseFontSize // TODO support viewport based sizing } } private static func map(fontName: String) -> String { guard let mappedName = gFontMappings[fontName] else { return fontName } return mappedName } private static func createFontAttributes(forName name: String) -> [AnyHashable : Any]? { let testFont = CTFontCreateWithName(name as CFString, 0.0, nil) let descriptor = CTFontCopyFontDescriptor(testFont) var fontAttributes = CTFontDescriptorCopyAttributes(descriptor) as! [AnyHashable : Any] if !fontAttributes.isEmpty { fontAttributes.removeValue(forKey: kCTFontSizeAttribute) return fontAttributes } return nil } private static func fontAttributes(forName name: String) -> [AnyHashable : Any]? { let realName = self.map(fontName: name) if realName.isEmpty { return nil } if let savedProperties = fontAttributesCache.object(forKey: realName as NSString) { if savedProperties is NSNull { return nil } else if let result = savedProperties as? [AnyHashable : Any] { return result } } else { if let createdProperties = createFontAttributes(forName: realName) { fontAttributesCache.setObject(createdProperties as AnyObject, forKey: realName as NSString, cost: 100) return createdProperties } else { fontAttributesCache.setObject(NSNull(), forKey: realName as NSString, cost: 100) } } return nil } func fontFamilyProperties(from fontDescriptor: FontDescription) -> [AnyHashable : Any] { let fontFamilies = fontDescriptor.families if fontFamilies.isEmpty { return self.defaultAttributes } else { var result = self.defaultAttributes var looped = false var fallbacks : [[AnyHashable : Any]]? fontFamilies.forEach { aFamily in var symbolicTraits: CTFontSymbolicTraits? = nil var stylisticTraits: CTFontStylisticClass? = nil if looped { fallbacks = [[AnyHashable : Any]]() } looped = true switch aFamily { case .system: if fallbacks != nil { fallbacks!.append(gSystemFontProperties) } else { result = gSystemFontProperties } return case .cursive: stylisticTraits = .scriptsClass case .fantasy: stylisticTraits = .ornamentalsClass case .monospace: symbolicTraits = .monoSpaceTrait case .sansSerif: stylisticTraits = .sansSerifClass case .serif: stylisticTraits = .classModernSerifs case .named(let name): if let attributes = Self.fontAttributes(forName: name) { if fallbacks != nil { fallbacks!.append(attributes) } else { result = attributes } return } case .initial: break case .inherit: break } let rawTraits = (symbolicTraits?.rawValue ?? 0) + (stylisticTraits?.rawValue ?? 0) if rawTraits != 0 { let symbolRecord = [kCTFontSymbolicTrait : rawTraits] if fallbacks != nil { fallbacks!.append([kCTFontTraitsAttribute : symbolRecord]) } else { result[kCTFontTraitsAttribute] = symbolRecord } } } if (fallbacks?.count ?? 0) > 0 { result[kCTFontCascadeListAttribute] = fallbacks } return result } } var baseFontAttributes : [AnyHashable : Any] { return [AnyHashable : Any]() } } public class DefaultFontContext : FontContext { public static var shared : DefaultFontContext = { return DefaultFontContext() }() } public extension FontDescription { var symbolicTraits : CTFontSymbolicTraits { var result = CTFontSymbolicTraits(rawValue: 0) switch self.weight { case .bold: result = .boldTrait default: break } switch self.stretch { case .condensed: result.insert(.condensedTrait) case .expanded: result.insert(.expandedTrait) default: break } return result } var ctDescriptor : CTFontDescriptor { return self.coreTextDescriptor() } private func mergeParagraphStyles(properties: inout Dictionary<AnyHashable, Any>, withContext context: FontContext) { // let existingParagraphStyles = properties[kCTParagraphStyleAttributeName] as? [CTParagraphStyleSetting] ?? [CTParagraphStyleSetting]() } func coreTextDescriptor(context: FontContext = DefaultFontContext.shared) -> CTFontDescriptor { var record = context.baseFontAttributes let familyProperties = context.fontFamilyProperties(from: self) record = record.merging(familyProperties, uniquingKeysWith:{(_, new) in new}) self.weight.merge(properties: &record, withContext: context) self.stretch.merge(properties: &record, withContext: context) self.decorations.forEach{$0.merge(properties:&record, withContext: context)} record[kCTFontSizeAttribute as String] = context.fontSize(fromFontSize: self.size) let keySet = Set(record.keys) var coreTextDescriptor = CTFontDescriptorCreateWithAttributes(record as CFDictionary) if let missSizedResult = CTFontDescriptorCreateMatchingFontDescriptor(coreTextDescriptor, keySet as CFSet) { coreTextDescriptor = CTFontDescriptorCreateCopyWithAttributes(missSizedResult, record as CFDictionary) } let coreTextDescriptorWithVariant = self.variant.add(toDescriptor: coreTextDescriptor, withContext: context) return coreTextDescriptorWithVariant } } fileprivate func createSystemFontProperties() -> [AnyHashable : Any] { let defaultFontRef = CTFontCreateUIFontForLanguage(CTFontUIFontType.system, 0.0, nil)! let postscriptNameCF = CTFontCopyPostScriptName(defaultFontRef) let fontTraits = CTFontCopyTraits(defaultFontRef) var mutableResult = fontTraits as! [String : Any] mutableResult[kCTFontNameAttribute as String] = postscriptNameCF return mutableResult }
mit
8c5e2d5541f903dc3c2f1f9c402e30de
32.269784
200
0.568494
5.413521
false
false
false
false
PANDA-Guide/PandaGuideApp
Pods/ActionCableClient/Source/Classes/JSONSerializer.swift
2
7048
// // Copyright (c) 2016 Daniel Rhodes <[email protected]> // // 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 internal class JSONSerializer { static let nonStandardMessageTypes: [MessageType] = [.ping, .welcome] static func serialize(_ channel : Channel, command: Command, data: ActionPayload?) throws -> String { do { var identifierDict : ChannelIdentifier if let identifier = channel.identifier { identifierDict = identifier } else { identifierDict = Dictionary() } identifierDict["channel"] = "\(channel.name)" let JSONData = try JSONSerialization.data(withJSONObject: identifierDict, options: JSONSerialization.WritingOptions(rawValue: 0)) guard let identifierString = NSString(data: JSONData, encoding: String.Encoding.utf8.rawValue) else { throw SerializationError.json } var commandDict = [ "command" : command.string, "identifier" : identifierString ] as [String : Any] if let _ = data { let JSONData = try JSONSerialization.data(withJSONObject: data!, options: JSONSerialization.WritingOptions(rawValue: 0)) guard let dataString = NSString(data: JSONData, encoding: String.Encoding.utf8.rawValue) else { throw SerializationError.json } commandDict["data"] = dataString } let CmdJSONData = try JSONSerialization.data(withJSONObject: commandDict, options: JSONSerialization.WritingOptions(rawValue: 0)) guard let JSONString = NSString(data: CmdJSONData, encoding: String.Encoding.utf8.rawValue) else { throw SerializationError.json } return JSONString as String } catch { throw SerializationError.json } } static func deserialize(_ string: String) throws -> Message { do { guard let JSONData = string.data(using: String.Encoding.utf8) else { throw SerializationError.json } guard let JSONObj = try JSONSerialization.jsonObject(with: JSONData, options: .allowFragments) as? Dictionary<String, AnyObject> else { throw SerializationError.json } var messageType: MessageType = .unrecognized if let typeObj = JSONObj["type"], let typeString = typeObj as? String { messageType = MessageType(string: typeString) } var channelName: String? if let idObj = JSONObj["identifier"] { var idJSON: Dictionary<String, AnyObject> if let idString = idObj as? String { guard let JSONIdentifierData = idString.data(using: String.Encoding.utf8) else { throw SerializationError.json } if let JSON = try JSONSerialization.jsonObject(with: JSONIdentifierData, options: .allowFragments) as? Dictionary<String, AnyObject> { idJSON = JSON } else { throw SerializationError.json } } else if let idJSONObj = idObj as? Dictionary<String, AnyObject> { idJSON = idJSONObj } else { throw SerializationError.protocolViolation } if let nameStr = idJSON["channel"], let name = nameStr as? String { channelName = name } } switch messageType { // Subscriptions case .confirmSubscription, .rejectSubscription, .cancelSubscription, .hibernateSubscription: guard let _ = channelName else { throw SerializationError.protocolViolation } return Message(channelName: channelName, actionName: nil, messageType: messageType, data: nil, error: nil) // Welcome/Ping messages case .welcome, .ping: return Message(channelName: nil, actionName: nil, messageType: messageType, data: nil, error: nil) case .message, .unrecognized: var messageActionName : String? var messageValue : AnyObject? var messageError : Swift.Error? do { // No channel name was extracted from identifier guard let _ = channelName else { throw SerializationError.protocolViolation } // No message was extracted from identifier guard let messageObj = JSONObj["message"] else { throw SerializationError.protocolViolation } if let actionObj = messageObj["action"], let actionStr = actionObj as? String { messageActionName = actionStr } messageValue = messageObj } catch { messageError = error } return Message(channelName: channelName!, actionName: messageActionName, messageType: MessageType.message, data: messageValue, error: messageError) } } catch { throw error } } }
gpl-3.0
16aff5e4fb25adb5350170432ee51411
43.607595
154
0.547106
5.937658
false
false
false
false
RevenueCat/purchases-ios
Sources/Misc/FatalErrorUtil.swift
1
1030
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // FatalErrorUtil.swift // // Created by Andrés Boedo on 9/16/21. import Foundation #if DEBUG enum FatalErrorUtil { fileprivate static var fatalErrorClosure: (String, StaticString, UInt) -> Never = defaultFatalErrorClosure private static let defaultFatalErrorClosure = { Swift.fatalError($0, file: $1, line: $2) } static func replaceFatalError(closure: @escaping (String, StaticString, UInt) -> Never) { fatalErrorClosure = closure } static func restoreFatalError() { fatalErrorClosure = defaultFatalErrorClosure } } func fatalError(_ message: @autoclosure () -> String = "", file: StaticString = #fileID, line: UInt = #line) -> Never { FatalErrorUtil.fatalErrorClosure(message(), file, line) } #endif
mit
1495b57e0e920cec4cce8de69a62a017
26.810811
119
0.696793
4.083333
false
false
false
false
pyromobile/nubomedia-ouatclient-src
ios/LiveTales/uoat/Utils.swift
1
7569
// // Utils.swift // uoat // // Created by Pyro User on 17/5/16. // Copyright © 2016 Zed. All rights reserved. // import Foundation class Utils { static func md5( string string: String ) -> String { var digest = [UInt8](count: Int( CC_MD5_DIGEST_LENGTH ), repeatedValue: 0) if let data = string.dataUsingEncoding(NSUTF8StringEncoding) { CC_MD5( data.bytes, CC_LONG( data.length ), &digest ) } var digestHex = "" for index in 0..<Int( CC_MD5_DIGEST_LENGTH ) { digestHex += String( format: "%02x", digest[index] ) } return digestHex } static func alertMessage(viewController:UIViewController, title:String, message:String, onAlertClose:((action:UIAlertAction)->Void)?) { if let _ = viewController.presentedViewController { return } let alert = UIAlertController( title:title, message:message, preferredStyle:.Alert ) //options. let actionOk = UIAlertAction( title:"Ok", style:.Default, handler:onAlertClose) alert.addAction( actionOk ) //viewController.presentViewController( alert, animated: true, completion:nil ) if let _ = viewController.parentViewController { viewController.parentViewController!.presentViewController( alert, animated: true, completion:nil ) } else { viewController.presentViewController( alert, animated: true, completion:nil ) } } static func blurEffectView(view:UIView, radius:Int) -> UIVisualEffectView { let customBlurClass: AnyObject.Type = NSClassFromString("_UICustomBlurEffect")! let customBlurObject: NSObject.Type = customBlurClass as! NSObject.Type let blurEffect = customBlurObject.init() as! UIBlurEffect blurEffect.setValue(radius, forKeyPath: "blurRadius") let blurEffectView = UIVisualEffectView( effect: blurEffect ) blurEffectView.frame = view.bounds blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] return blurEffectView } static func flipImage( named name:String, orientation:UIImageOrientation ) -> UIImage { let image:UIImage = UIImage( named: name )! //Filp arrow image. let imageFlip:UIImage = UIImage( CGImage: image.CGImage!, scale: image.scale, orientation: orientation ) return imageFlip } static func randomString(length:Int) -> String { let baseString:NSString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let randomString:NSMutableString = NSMutableString( capacity:length ) for _:Int in 0...length { let len = UInt32( baseString.length ) let rand = arc4random_uniform( len ) randomString.appendFormat( "%C", baseString.characterAtIndex( Int( rand ) ) ) } return String(randomString) } /* RELOCATED INTO MODELS/USER/USERMODEL.SWIFT static func loadUserFriends(userId:String,callback:(friends:[(id:String,nick:String)]?)->Void) { let criteria:[String:AnyObject] = ["me":"pub_\(userId)"] let query = KuasarsQuery( criteria, retrievingFields: nil ) as KuasarsQuery KuasarsEntity.query( query, entityType: "friends", occEnabled: false, completion:{ (response:KuasarsResponse!, error:KuasarsError!) -> Void in if( error != nil ) { print( "Error from kuasars: \(error.description)" ) } else { let batch = KuasarsBatch() let entities = response.contentObjects as! [KuasarsEntity] for entity:KuasarsEntity in entities { let friendId:String = (entity.customData!["friend"])! as! String print("Amigo encontrado:\(friendId)") let criteria:[String:AnyObject] = ["id":"\(friendId)"] let query = KuasarsQuery( criteria, retrievingFields: nil ) as KuasarsQuery let request:KuasarsRequest = KuasarsServices.queryEntities(query, type: "users", occEnabled: false) batch.addRequest(request) } batch.performRequests({ (response:KuasarsResponse!, error:KuasarsError!) in if( error != nil ) { print( "Error from kuasars: \(error.description)" ) callback(friends:nil) } else { var friends:[(id:String,nick:String)] = [(id:String,nick:String)]() let responses = response.contentObjects as! [NSDictionary] for index in 0 ..< responses.count { let rsp:NSDictionary = responses[index] as NSDictionary let body:[NSDictionary] = rsp["body"] as! [NSDictionary] let friendNick = body[0]["nick"] as! String /* print("Amigo :\(friendNick)") let usr = UILabel( frame: CGRectMake( 0, CGFloat(0 + 42*index), self.friendsScrollView.frame.width, 40 ) ); usr.text = friendNick usr.backgroundColor = UIColor.whiteColor() usr.textColor = UIColor.grayColor() self.friendsScrollView.addSubview( usr ) self.friendsScrollView.contentSize = CGSize( width:self.friendsScrollView.frame.width, height: CGFloat( 42 * index) ) */ let id:String = entities[index].customData["friend"] as! String friends.append( (id:id, nick:friendNick) ) } callback(friends: friends) } }) } }) } */ static func saveImageFromView(view:UIView)->Bool { UIGraphicsBeginImageContextWithOptions( view.bounds.size, true, 0 ) view.drawViewHierarchyInRect( view.bounds, afterScreenUpdates:true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() //Save image in device. //.:Generate image name. let today:NSDate = NSDate() let formatter = NSDateFormatter() formatter.dateFormat = "yyyyMMddHHmmss" let strDateFormat = formatter.stringFromDate( today ) let fileName:String = "ouat-snapshot-\(strDateFormat).jpg" //.:Get path to save. let documentsURL:NSURL = NSFileManager.defaultManager().URLsForDirectory( .DocumentDirectory, inDomains:.UserDomainMask )[0] let fileURL:NSURL = documentsURL.URLByAppendingPathComponent( fileName ) let imagePath:String = fileURL.path! print("PATH to save image:\(imagePath)") //.:Save image as jpg file. let jpgImageData:NSData = UIImageJPEGRepresentation( image, 1.0 )! let isSavedOk:Bool = jpgImageData.writeToFile( imagePath, atomically:true ) return isSavedOk; } }
apache-2.0
b51773d240e2ed249192a61818206abb
40.360656
150
0.559329
5.344633
false
false
false
false
nervousnet/nervousnet-iOS
nervous/Controllers/AccelerometerController.swift
1
3271
// // AccelerometerController.swift // nervousnet-iOS // // Created by Sid on 03 Mar 2016. // Copyright (c) 2016 ETHZ . All rights reserved. import Foundation import CoreMotion import CoreData import UIKit private let _ACC = AccelerometerController() class AccelerometerController : NSObject, SensorProtocol { private var auth: Int = 0 private var manager: CMMotionManager private let VM = VMController.sharedInstance internal var timestamp: UInt64 = 0 internal var x: Float = 0.0 internal var y: Float = 0.0 internal var z: Float = 0.0 override init() { self.manager = CMMotionManager() } class var sharedInstance: AccelerometerController { return _ACC } func requestAuthorization() { print("requesting authorization for acc") let val1 = self.VM.defaults.boolForKey("kill") //objectForKey("kill") as! Bool let val2 = self.VM.defaults.boolForKey("switchAcc") //objectForKey("switchAcc") as! Bool if !val1 && val2 { if self.manager.accelerometerAvailable { self.auth = 1 } } else { self.auth = 0 } } func initializeUpdate(freq: Double) { self.manager.accelerometerUpdateInterval = freq self.manager.startAccelerometerUpdates() } // requestAuthorization must be before this is function is called func startSensorUpdates() { if self.auth == 0 { return } let queue = NSOperationQueue() let currentTimeA :NSDate = NSDate() self.manager.startAccelerometerUpdatesToQueue(queue,withHandler: {data, error in self.timestamp = UInt64(currentTimeA.timeIntervalSince1970*1000) // time to timestamp //if let data = self.manager.accelerometerData { guard let data = data else { return } self.x = Float(data.acceleration.x) self.y = Float(data.acceleration.y) self.z = Float(data.acceleration.z) //print("accelerometer") //print(self.x) // store the current data in the CoreData database let val = self.VM.defaults.objectForKey("logAcc") as! Bool if val { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let entity = NSEntityDescription.entityForName("Accelerometer", inManagedObjectContext: managedContext) let acc = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) acc.setValue(NSNumber(unsignedLongLong: self.timestamp) , forKey: "timestamp") acc.setValue(self.x, forKey: "x") acc.setValue(self.y, forKey: "y") acc.setValue(self.z, forKey: "z") } }) } func stopSensorUpdates() { self.manager.stopAccelerometerUpdates() self.auth = 0 } }
gpl-3.0
89036ea37eee967fb775521d1d8c01a4
29.018349
106
0.576582
5.183835
false
false
false
false
BrainDDump/Extractor
Extractor/AppDelegate.swift
1
4234
// // AppDelegate.swift // Extractor // // Created by Кирилл on 2/27/16. // Copyright © 2016 BrainDump. All rights reserved. // import UIKit import Parse import ParseFacebookUtilsV4 @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let storyboard = UIStoryboard(name: "Main", bundle: nil) // MARK: - Application delegate func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { User.initialize() Node.initialize() List.initialize() Parse.setApplicationId("K3iaNav9TphE8eopgbHoJUjWf7yNT5KGOsNG0Fb2", clientKey: "rVacb4z5iexRmUubmtdQtRY72KX2N0B6g5BuYQj3") PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions) FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) // Push notifications let settings = UIUserNotificationSettings(forTypes: [.Sound, .Badge], categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() if let launchOptions = launchOptions as? [String : AnyObject] { if let notificationDictionary = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as? [NSObject : AnyObject] { self.application(application, didReceiveRemoteNotification: notificationDictionary) } } tryToLoadMainApp() // Setup appearance configureView() return true } func applicationDidBecomeActive(application: UIApplication) { FBSDKAppEvents.activateApp() } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } // MARK: - Help methods func configureView() { UINavigationBar.appearance().barTintColor = UIColor(red: 237/255.0, green: 174/255.0, blue: 47/255.0, alpha: 1) UINavigationBar.appearance().translucent = false UINavigationBar.appearance().tintColor = UIColor.whiteColor() if let barFont = UIFont(name: "Avenir-Light", size: 24.0) { UINavigationBar.appearance().titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: barFont ] } } // MARK: - Push notifications func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { if PFUser.currentUser() != nil { let installation = PFInstallation.currentInstallation() installation["user"] = PFUser.currentUser() installation.setDeviceTokenFromData(deviceToken) installation.saveInBackground() } } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { PFPush.handlePush(userInfo) print(userInfo) NSNotificationCenter.defaultCenter().postNotificationName("refreshChatRoom", object: nil) } // MARK: - Global functions func tryToLoadMainApp() { if PFUser.currentUser() == nil { let loginVC = storyboard.instantiateInitialViewController() window?.rootViewController = loginVC } else { let mainVC = storyboard.instantiateViewControllerWithIdentifier("MainNavigationVC") window?.rootViewController = mainVC } } func logoutUser() { PFUser.logOutInBackgroundWithBlock { (error: NSError?) -> Void in if error != nil { print("Error occured while logging ") return } self.tryToLoadMainApp() } } }
apache-2.0
202dd096ff8b4d2027613466ff5b3146
34.225
161
0.646558
5.658635
false
false
false
false
thomashocking/SimpleGeo
Constants.swift
1
2125
// // Constants.swift // LSGeo // // Created by Thomas Hocking on 11/18/16. // Copyright © 2016 Thomas Hocking. All rights reserved. // import Foundation let NamesResultsKey : String = "NamesResultsKey" let TotalResultsCountKey : String = "TotalResultsCountKey" let AdminCode1Key : String = "AdminCode1Key" let AdminCode2Key : String = "AdminCode2Key" let AdminCode3Key : String = "AdminCode3Key" let AdminName1Key : String = "AdminName1Key" let AdminName2Key : String = "AdminName2Key" let AdminName3Key : String = "AdminName3Key" let AdminName4Key : String = "AdminName4Key" let NameKey : String = "NameKey" let ToponymNameKey : String = "ToponymNameKey" let ContinentCodeKey : String = "ContinentCodeKey" let CountryCodeKey : String = "CountryCodeKey" let CountryNameKey : String = "CountryNameKey" let PopulationKey : String = "PopulationKey" //used for wikipedia requests. let WikiTitleKey : String = "WikiTitleKey" let WikiSummaryKey : String = "WikiSummaryKey" let WikiURLKey : String = "WikiURLKey" let WikiFeatureKey : String = "WikiFeatureKey" let AlternateNamesKey : String = "AlternateNamesKey" let AlternateNameKey : String = "AlternateNameKey" let AlternateLanguageKey : String = "AlternateLanguageKey" let IDKey : String = "IDKey" let FeatureClassKey : String = "FeatureClassKey" let FeatureCodeKey : String = "FeatureCodeKey" let FeatureClassNameKey : String = "FeatureClassNameKey" let FeatureNameKey : String = "FeatureNameKey" let NamesScoreKey : String = "NamesScoreKey" let LatitudeKey : String = "LatitudeKey" let LongitudeKey : String = "LongitudeKey" let DistanceKey : String = "DistanceKey" let ElevationKey : String = "ElevationKey" let LanguageKey : String = "LanguageKey" //Wiki let RankKey : String = "RankKey" //Wiki let TimeZoneInfoKey : String = "TimeZoneInfoKey" let TimeZoneDSTOffsetKey : String = "TimeZoneDSTOffsetKey" let TimeZoneGMTOffsetKey : String = "TimeZoneGMTOffsetKey" let TimeZoneIDKey : String = "TimeZoneIDKey" let ErrorResponseKey : String = "ErrorResponseKey" let ErrorMessageKey : String = "ErrorMessageKey" let ErrorCodeKey : String = "ErrorCodeKey"
gpl-3.0
38a33950c986ae8c0375d0add92bf373
30.235294
58
0.768832
3.726316
false
false
false
false
practicalswift/swift
test/IRGen/generic_types.swift
12
5100
// RUN: %target-swift-frontend %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime // REQUIRES: CPU=x86_64 // CHECK: [[A:%T13generic_types1AC]] = type <{ [[REF:%swift.refcounted]], [[INT:%TSi]] }> // CHECK: [[INT]] = type <{ i64 }> // CHECK: [[B:%T13generic_types1BC]] = type <{ [[REF:%swift.refcounted]], [[UNSAFE:%TSp]] }> // CHECK: [[C:%T13generic_types1CC]] = type // CHECK: [[D:%T13generic_types1DC]] = type // CHECK-LABEL: @"$s13generic_types1ACMI" = internal global [16 x i8*] zeroinitializer, align 8 // CHECK-LABEL: @"$s13generic_types1ACMn" = hidden constant // CHECK-SAME: i32 -2147483440, // CHECK-SAME: @"$s13generic_typesMXM" // <name> // CHECK-SAME: @"$s13generic_types1ACMa" // -- superclass // CHECK-SAME: i32 0, // -- negative size in words // CHECK-SAME: i32 2, // -- positive size in words // CHECK-SAME: i32 17, // -- num immediate members // CHECK-SAME: i32 7, // -- num fields // CHECK-SAME: i32 1, // -- field offset vector offset // CHECK-SAME: i32 11, // -- instantiation cache // CHECK-SAME: @"$s13generic_types1ACMI" // -- instantiation pattern // CHECK-SAME: @"$s13generic_types1ACMP" // -- num generic params // CHECK-SAME: i16 1, // -- num generic requirement // CHECK-SAME: i16 0, // -- num key arguments // CHECK-SAME: i16 1, // -- num extra arguments // CHECK-SAME: i16 0, // -- parameter descriptor 1 // CHECK-SAME: i8 -128, // CHECK-LABEL: @"$s13generic_types1ACMP" = internal constant // -- instantiation function // CHECK-SAME: @"$s13generic_types1ACMi" // -- heap destructor // CHECK-SAME: void ([[A]]*)* @"$s13generic_types1ACfD" // -- ivar destroyer // CHECK-SAME: i32 0, // -- flags // CHECK-SAME: i32 {{3|2}}, // CHECK-SAME: } // CHECK-LABEL: @"$s13generic_types1BCMI" = internal global [16 x i8*] zeroinitializer, align 8 // CHECK-LABEL: @"$s13generic_types1BCMn" = hidden constant // CHECK-SAME: @"$s13generic_types1BCMa" // CHECK-SAME: @"$s13generic_types1BCMI" // CHECK-SAME: @"$s13generic_types1BCMP" // CHECK-LABEL: @"$s13generic_types1BCMP" = internal constant // -- instantiation function // CHECK-SAME: @"$s13generic_types1BCMi" // -- heap destructor // CHECK-SAME: void ([[B]]*)* @"$s13generic_types1BCfD" // -- ivar destroyer // CHECK-SAME: i32 0, // -- class flags // CHECK-SAME: i32 {{3|2}}, // CHECK-SAME: } // CHECK-LABEL: @"$s13generic_types1CCMP" = internal constant // -- instantiation function // CHECK-SAME: @"$s13generic_types1CCMi" // -- heap destructor // CHECK-SAME: void ([[C]]*)* @"$s13generic_types1CCfD" // -- ivar destroyer // CHECK-SAME: i32 0, // -- class flags // CHECK-SAME: i32 {{3|2}}, // CHECK-SAME: } // CHECK-LABEL: @"$s13generic_types1DCMP" = internal constant // -- instantiation function // CHECK-SAME: @"$s13generic_types1DCMi" // -- heap destructor // CHECK-SAME: void ([[D]]*)* @"$s13generic_types1DCfD" // -- ivar destroyer // CHECK-SAME: i32 0, // -- class flags // CHECK-SAME: i32 {{3|2}}, // CHECK-SAME: } class A<T> { var x = 0 func run(_ t: T) {} init(y : Int) {} } class B<T> { var ptr : UnsafeMutablePointer<T> init(ptr: UnsafeMutablePointer<T>) { self.ptr = ptr } deinit { ptr.deinitialize(count: 1) } } class C<T> : A<Int> {} class D<T> : A<Int> { override func run(_ t: Int) {} } struct E<T> { var x : Int func foo() { bar() } func bar() {} } class ClassA {} class ClassB {} // This type is fixed-size across specializations, but it needs to use // a different implementation in IR-gen so that types match up. // It just asserts if we get it wrong. struct F<T: AnyObject> { var value: T } func testFixed() { var a = F(value: ClassA()).value var b = F(value: ClassB()).value } // Checking generic requirement encoding protocol P1 { } protocol P2 { associatedtype A } struct X1: P1 { } struct X2: P2 { typealias A = X1 } // Check for correct generic parameters in the nominal type descriptor // CHECK-LABEL: @"$s13generic_types2X3VMn" = // Root: generic parameter 1 // CHECK-SAME: @"symbolic q_" // U.A (via P2) // CHECK-SAME: @"symbolic 1A_____Qy_ 13generic_types2P2P struct X3<T, U> where U: P2, U.A: P1 { } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} internal %swift.type* @"$s13generic_types1ACMi"(%swift.type_descriptor*, i8**, i8*) {{.*}} { // CHECK: [[T0:%.*]] = bitcast i8** %1 to %swift.type** // CHECK: %T = load %swift.type*, %swift.type** [[T0]], // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_descriptor* %0, i8** %1, i8* %2) // CHECK-NEXT: ret %swift.type* [[METADATA]] // CHECK: } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} internal %swift.type* @"$s13generic_types1BCMi"(%swift.type_descriptor*, i8**, i8*) {{.*}} { // CHECK: [[T0:%.*]] = bitcast i8** %1 to %swift.type** // CHECK: %T = load %swift.type*, %swift.type** [[T0]], // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_descriptor* %0, i8** %1, i8* %2) // CHECK-NEXT: ret %swift.type* [[METADATA]] // CHECK: }
apache-2.0
1557d0cf5c207040f64da95ba829e9c7
28.479769
149
0.624706
2.934407
false
false
false
false
yanif/circator
MetabolicCompass/View Controller/AuthorizationViewControllers/AdditionalInfoViewController.swift
1
2519
// // AdditionalInfoViewController.swift // MetabolicCompass // // Created by Anna Tkach on 4/28/16. // Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved. // import UIKit import MetabolicCompassKit import SwiftyUserDefaults import Crashlytics class AdditionalInfoViewController: BaseViewController { weak var registerViewController: RegisterViewController? var dataSource = AdditionalInfoDataSource() @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() setupScrollViewForKeyboardsActions(collectionView) dataSource.collectionView = self.collectionView configureNavBar() } private func configureNavBar() { let cancelButton = ScreenManager.sharedInstance.appNavButtonWithTitle("Cancel".localized) cancelButton.addTarget(self, action: #selector(cancelAction), forControlEvents: .TouchUpInside) let cancelBarButton = UIBarButtonItem(customView: cancelButton) let nextButton = ScreenManager.sharedInstance.appNavButtonWithTitle("Next".localized) nextButton.addTarget(self, action: #selector(nextAction), forControlEvents: .TouchUpInside) let nextBarButton = UIBarButtonItem(customView: nextButton) self.navigationItem.rightBarButtonItems = [nextBarButton] self.navigationItem.leftBarButtonItems = [cancelBarButton] self.navigationItem.title = NSLocalizedString("PHYSIOLOGICAL DATA", comment: "additional info data") } func cancelAction () { self.dismissViewControllerAnimated(true, completion: { [weak controller = self.registerViewController] in Answers.logCustomEventWithName("Register Additional", customAttributes: ["WithAdditional": false]) controller?.registrationComplete() }); } func nextAction() { startAction() dataSource.model.additionalInfoDict { (error, additionalInfo) in guard error == nil else { UINotifications.genericError(self, msg: error!) return } UserManager.sharedManager.saveAdditionalProfileData(additionalInfo) self.dismissViewControllerAnimated(true, completion: { [weak controller = self.registerViewController] in Answers.logCustomEventWithName("Register Additional", customAttributes: ["WithAdditional": true]) controller?.registrationComplete() }) } } }
apache-2.0
fcb2a5d89003d8bbfa79f165146b36e4
37.738462
117
0.703336
5.788506
false
false
false
false
Authman2/Pix
Pods/Hero/Sources/Array+HeroModifier.swift
1
2186
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit internal extension Array { func get(_ index: Int) -> Element? { if index < count { return self[index] } return nil } func getCGFloat(_ index: Int) -> CGFloat? { if let s = get(index) as? String, let f = Float(s) { return CGFloat(f) } return nil } func getDouble(_ index: Int) -> Double? { if let s = get(index) as? String, let f = Double(s) { return f } return nil } func getFloat(_ index: Int) -> Float? { if let s = get(index) as? String, let f = Float(s) { return f } return nil } func getBool(_ index: Int) -> Bool? { if let s = get(index) as? String, let f = Bool(s) { return f } return nil } mutating func filterInPlace(_ comparator: (Element) -> Bool) -> [Element] { var array2: [Element] = [] self = self.filter { (element) -> Bool in if comparator(element) { return true } else { array2.append(element) return false } } return array2 } }
gpl-3.0
dcd06c29a847f2110d424f8d6be1e122
30.681159
80
0.658737
3.967332
false
false
false
false
Yoloabdo/CS-193P
SmashTag/SmashTag/Reachability.swift
1
985
// // Reachability.swift // SmashTag // // Created by abdelrahman mohamed on 3/8/16. // Copyright © 2016 Abdulrhman dev. All rights reserved. // import Foundation import SystemConfiguration public class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) } var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) { return false } let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) } }
mit
aab818873dfb98c8f75e6d22f208aa43
34.178571
95
0.688008
4.871287
false
false
false
false
lionheart/LionheartExtensions
Pod/Classes/Core/NSDecimalNumber+LionheartExtensions.swift
2
2652
// // NSDecimalNumber.swift // Pods // // Created by Daniel Loewenherz on 3/16/16. // // import Foundation /** - source: https://gist.github.com/mattt/1ed12090d7c89f36fd28 */ extension NSDecimalNumber: Comparable {} public extension NSDecimalNumber { /// Returns `true` if two `NSDecimalNumber` values are equal, `false` otherwise. static func ==(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool { return lhs.compare(rhs) == .orderedSame } /// Returns `true` if the first `NSDecimalNumber` parameter is less than the second, `false` otherwise. static func <(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool { return lhs.compare(rhs) == .orderedAscending } /// Returns `true` if the first `NSDecimalNumber` parameter is greater than the second, `false` otherwise. static func >(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool { return lhs.compare(rhs) == .orderedDescending } /// Returns the [additive inverse](https://en.wikipedia.org/wiki/Additive_inverse) of the provided `NSDecimalNumber`. static prefix func -(value: NSDecimalNumber) -> NSDecimalNumber { return value.multiplying(by: NSDecimalNumber(mantissa: 1, exponent: 0, isNegative: true)) } /// Returns the sum of two `NSDecimalNumber` values. static func +(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber { return lhs.adding(rhs) } /// Returns the difference of two `NSDecimalNumber` values. static func -(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber { return lhs.subtracting(rhs) } /// Returns the product of two `NSDecimalNumber` values. static func *(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber { return lhs.multiplying(by: rhs) } /// Returns the quotient of two `NSDecimalNumber` values. static func /(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber { return lhs.dividing(by: rhs) } /// Returns the result of raising the provided `NSDecimalNumber` to a specified power. static func ^(lhs: NSDecimalNumber, rhs: Int) -> NSDecimalNumber { return lhs.raising(toPower: rhs) } // MARK: - Assignment static func +=(lhs: inout NSDecimalNumber, rhs: NSDecimalNumber) { lhs = lhs + rhs } static func -=(lhs: inout NSDecimalNumber, rhs: NSDecimalNumber) { lhs = lhs - rhs } static func *=(lhs: inout NSDecimalNumber, rhs: NSDecimalNumber) { lhs = lhs * rhs } static func /=(lhs: inout NSDecimalNumber, rhs: NSDecimalNumber) { lhs = lhs / rhs } }
apache-2.0
dce21080b08e1dfd25c43e4346e61984
32.15
121
0.666667
4.464646
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/UI/SnapshotCardCell.swift
1
9567
/* * 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 UIKit /// A cell displaying the results of sensor(s) snapshot in an Experiment. The cell contains one or /// more SnapshotCardViews, a header and an optional caption. class SnapshotCardCell: FrameLayoutMaterialCardCell { // MARK: - Properties weak var delegate: ExperimentCardCellDelegate? private let captionView = ExperimentCardCaptionView() private let headerView = ExperimentCardHeaderView() private var snapshotViews = [SnapshotCardView]() private var snapshotViewsContainer = UIView() private let separator = SeparatorView(direction: .horizontal, style: .dark) private var snapshotNote: DisplaySnapshotNote? // MARK: - Public override init(frame: CGRect) { super.init(frame: frame) configureView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } override func layoutSubviews() { super.layoutSubviews() var nextOriginY: CGFloat = 0 if !headerView.isHidden { headerView.frame = CGRect(x: 0, y: nextOriginY, width: cellContentView.bounds.width, height: ExperimentCardHeaderView.height) nextOriginY = headerView.frame.maxY } separator.frame = CGRect(x: 0, y: nextOriginY, width: cellContentView.bounds.width, height: SeparatorView.Metrics.dimension) if let snapshots = snapshotNote?.snapshots { let snapshotViewsHeight = ceil(SnapshotCardCell.height(forSnapshots: snapshots, inWidth: cellContentView.bounds.width)) snapshotViewsContainer.frame = CGRect(x: 0, y: separator.frame.maxY, width: cellContentView.bounds.width, height: snapshotViewsHeight) for (index, snapshotView) in snapshotViews.enumerated() { let snapshotViewHeight = snapshotViewsHeight / CGFloat(snapshotViews.count) snapshotView.frame = CGRect(x: 0, y: snapshotViewHeight * CGFloat(index), width: cellContentView.bounds.width, height: snapshotViewHeight) } } if let caption = snapshotNote?.caption { let captionViewHeight = ceil(ExperimentCardCaptionView.heightWithCaption(caption, inWidth: cellContentView.bounds.width)) captionView.frame = CGRect(x: 0, y: snapshotViewsContainer.frame.maxY, width: cellContentView.bounds.width, height: captionViewHeight) } } override func prepareForReuse() { super.prepareForReuse() snapshotNote = nil } /// Sets the snapshot note to show in the cell and whether or not to show the header and /// inline timestamp. /// /// - Parameters: /// - snapshotNote: The snapshot note to show in the cell. /// - shouldShowHeader: Whether or not to show the header. /// - shouldShowInlineTimestamp: Whether or not to show the inline timestamp. /// - shouldShowCaptionButton: Whether or not to show the caption button. func setSnapshotNote(_ snapshotNote: DisplaySnapshotNote, showHeader shouldShowHeader: Bool, showInlineTimestamp shouldShowInlineTimestamp: Bool, showCaptionButton shouldShowCaptionButton: Bool, experimentDisplay: ExperimentDisplay = .normal) { self.snapshotNote = snapshotNote // Remove any snapshot views that are not needed. if snapshotViews.count > snapshotNote.snapshots.count { let rangeOfSnapshotViewsToRemove = snapshotNote.snapshots.count..<snapshotViews.count snapshotViews[rangeOfSnapshotViewsToRemove].forEach { $0.removeFromSuperview() } snapshotViews.removeSubrange(rangeOfSnapshotViewsToRemove) } // Add any snapshot views that are needed. for _ in snapshotViews.count..<snapshotNote.snapshots.count { let snapshotCardView = SnapshotCardView(preferredMaxLayoutWidth: bounds.width, showTimestamp: shouldShowInlineTimestamp) snapshotViews.append(snapshotCardView) snapshotViewsContainer.addSubview(snapshotCardView) } // Update snapshot views with snapshots. for (index, snapshot) in snapshotNote.snapshots.enumerated() { let snapshotView = snapshotViews[index] snapshotView.showTimestamp = shouldShowInlineTimestamp snapshotView.snapshot = snapshot } // Header. headerView.isHidden = !shouldShowHeader // Timestamp. headerView.headerTimestampLabel.text = snapshotNote.timestamp.string headerView.accessibilityLabel = snapshotNote.timestamp.string headerView.isTimestampRelative = snapshotNote.timestamp.isRelative // Caption and add caption button. if let caption = snapshotNote.caption { headerView.showCaptionButton = false captionView.isHidden = false captionView.captionLabel.text = caption } else { headerView.showCaptionButton = shouldShowCaptionButton captionView.isHidden = true } headerView.showMenuButton = experimentDisplay.showMenuButton setNeedsLayout() } /// Calculates the height required to display this view, given the data provided in `snapshots`. /// /// - Parameters: /// - width: Maximum width for this view, used to constrain measurements. /// - snapshotNote: The snapshot note to measure. /// - showingHeader: Whether or not the cell will be showing the header. /// - Returns: The total height of this view. Ideally, controllers would cache this value as it /// will not change for different instances of this view type. static func height(inWidth width: CGFloat, snapshotNote: DisplaySnapshotNote, showingHeader: Bool) -> CGFloat { // Measure the height of the snapshots. var totalHeight = SnapshotCardCell.height(forSnapshots: snapshotNote.snapshots, inWidth: width) // Add the separator height. totalHeight += SeparatorView.Metrics.dimension if showingHeader { // Add the header stack view's height. totalHeight += ExperimentCardHeaderView.height } // The caption, if necessary. if let caption = snapshotNote.caption { totalHeight += ExperimentCardCaptionView.heightWithCaption(caption, inWidth: width) } return totalHeight } // MARK: - Private private func configureView() { // Header view. cellContentView.addSubview(headerView) headerView.timestampButton.addTarget(self, action: #selector(timestampButtonPressed), for: .touchUpInside) headerView.commentButton.addTarget(self, action: #selector(commentButtonPressed), for: .touchUpInside) headerView.menuButton.addTarget(self, action: #selector(menuButtonPressed(sender:)), for: .touchUpInside) // Separator view. cellContentView.addSubview(separator) // Snapshot views container. cellContentView.addSubview(snapshotViewsContainer) // Caption view. cellContentView.addSubview(captionView) // Accessibility wrapping view, which sits behind all other elements to allow a user to "grab" // a cell by tapping anywhere in the empty space of a cell. let accessibilityWrappingView = UIView() cellContentView.configureAccessibilityWrappingView( accessibilityWrappingView, withLabel: String.noteContentDescriptionSnapshot, hint: String.doubleTapToViewDetails) // Set the order of elements to be the wrapping view first, then the header. accessibilityElements = [accessibilityWrappingView, headerView, snapshotViewsContainer] } private static func height(forSnapshots snapshots: [DisplaySnapshotValue], inWidth width: CGFloat) -> CGFloat { return snapshots.reduce(0) { (result, snapshot) in result + SnapshotCardView.heightForSnapshot(snapshot, inWidth: width) } } // MARK: - User actions @objc private func commentButtonPressed() { delegate?.experimentCardCellCommentButtonPressed(self) } @objc private func menuButtonPressed(sender: MenuButton) { delegate?.experimentCardCellMenuButtonPressed(self, button: sender) } @objc private func timestampButtonPressed() { delegate?.experimentCardCellTimestampButtonPressed(self) } }
apache-2.0
71ff37579b36b936b2cee15d35efd3e3
39.029289
100
0.653392
5.326837
false
false
false
false
yscode001/YSExtension
YSExtension/YSExtension/YSExtension/UIViewController/UIViewController+ysExtension.swift
1
3135
import UIKit extension UIViewController{ /// push public func ys_pushTo(_ viewController:UIViewController, animated:Bool){ navigationController?.pushViewController(viewController, animated: animated) } /// pop public func ys_pop(animated:Bool){ navigationController?.popViewController(animated: animated) } public func ys_popToVC(_ viewController:UIViewController, animated:Bool){ navigationController?.popToViewController(viewController, animated: animated) } public func ys_popToRootVC(animated:Bool){ navigationController?.popToRootViewController(animated: animated) } /// 添加子控制器 public func ys_addChildViewController(childViewController:UIViewController, intoView:UIView, childViewFrame:CGRect? = nil){ addChild(childViewController) childViewController.view.frame = childViewFrame == nil ? intoView.bounds : childViewFrame! intoView.addSubview(childViewController.view) childViewController.didMove(toParent: self) } /// 弹出框 public func ys_alert(title:String?, message:String?, confirm:String, confirmClosure:@escaping(()->())){ let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert) let confirmAction = UIAlertAction(title: confirm, style: .default) { (_) in confirmClosure() } alertVC.addAction(confirmAction) present(alertVC, animated: true, completion: nil) } public func ys_alert(title:String?,message:String?,title1:String,title2:String,titleClosure1:@escaping(()->()),titleClosure2:@escaping(()->())) { let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert) let action1 = UIAlertAction(title: title1, style: .default) { (_) in titleClosure1() } let action2 = UIAlertAction(title: title2, style: .default) { (_) in titleClosure2() } alertVC.addAction(action1) alertVC.addAction(action2) present(alertVC, animated: true, completion: nil) } public func ys_confirm(title:String?, message:String?, cancel:String, confirm:String, cancelClosure:@escaping(()->()),confirmClosure:@escaping(()->())){ let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert) let cancelAction = UIAlertAction(title: cancel, style: .cancel) { (_) in cancelClosure() } let confirmAction = UIAlertAction(title: confirm, style: .default) { (_) in confirmClosure() } alertVC.addAction(cancelAction) alertVC.addAction(confirmAction) present(alertVC, animated: true, completion: nil) } public var ys_vcName:String{ // 示例:"<period.ArticleListVC: 0x7f818dc2b390>" let descString = self.description if let startRange = descString.range(of: "."),let endRange = descString.range(of: ":"){ return String(descString[startRange.upperBound..<endRange.lowerBound]) } return "" } }
mit
339987019dda32c596dfbcf7a5ae6246
41.616438
156
0.661845
4.800926
false
false
false
false
rporzuc/FindFriends
FindFriends/FindFriends/MyAccount/Edit User Data/EditUserNameViewController.swift
1
3445
// // EditUserNameViewController.swift // FindFriends // // Created by MacOSXRAFAL on 3/23/17. // Copyright © 2017 MacOSXRAFAL. All rights reserved. // import UIKit var editUserNameViewController :EditUserNameViewController! class EditUserNameViewController: UIViewController, UITextFieldDelegate { static var delegate : DelegateProtocolSendDataToMyAccount! var userImage = UIImage(named: "ImagePersonRounded") var firstName = "" var lastName = "" @IBOutlet var userImageView: UIImageView! @IBOutlet var textFieldFirstName: UITextField! @IBOutlet var textFieldLastName: UITextField! @IBOutlet var btnSave: UIButton! @IBOutlet var backgroundView: UIView! @IBAction func btnReturnClicked(_ sender: UIButton) { _ = self.navigationController?.popViewController(animated: true) editUserNameViewController = nil } @IBAction func btnSaveClicked(_ sender: Any) { let name_RegEx = "^[A-Za-z.ąęćółżźńś]{2,25}$" let nameTest = NSPredicate(format: "SELF MATCHES %@", name_RegEx) if (textFieldFirstName.text != "" && textFieldLastName.text != "" && nameTest.evaluate(with: textFieldFirstName.text) == true && nameTest.evaluate(with: textFieldLastName.text) == true) { EditUserNameViewController.delegate.saveValueFromEditUserNameViewController(firstName: textFieldFirstName.text!, lastName: textFieldLastName.text!, userImage: self.userImage!) _ = self.navigationController?.popViewController(animated: true) }else { self.showInformationAlertView(message: "Incorrect First or Last Name. Please enter a correct data.") } } @IBAction func editUserImageClicked(_ sender: UIButton) { self.performSegue(withIdentifier: "segueEditUserImage", sender: nil) } override func viewDidLoad() { super.viewDidLoad() userImageView.image = userImage userImageView.layer.cornerRadius = userImageView.frame.width / 2 textFieldFirstName.text = firstName textFieldLastName.text = lastName for txtField in [textFieldFirstName, textFieldLastName] { txtField?.setBottomBorderWithoutPlaceholder(viewColor: UIColor.white, borderColor: UIColor.lightGray, borderSize: 1) } backgroundView.layer.borderColor = UIColor.gray.cgColor backgroundView.layer.borderWidth = 1 editUserNameViewController = self } override func viewWillAppear(_ animated: Bool) { self.userImageView.image = self.userImage! } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let tagTouch = touches.first?.view?.tag if tagTouch == 99 { self.view.endEditing(true) } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return true } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "segueEditUserImage" { let destination = segue.destination as! EditUserImageViewController destination.modalPresentationStyle = .overCurrentContext destination.userImage = self.userImage! } } }
gpl-3.0
2d66b5a763f11ca4927893d01c1ce925
30.805556
194
0.652402
5.05891
false
false
false
false
PerrchicK/swift-app
SomeApp/SomeApp/Data/CloudUser.swift
1
1182
// // CloudUser.swift // SomeApp // // Created by Perry on 12/01/2018. // Copyright © 2018 PerrchicK. All rights reserved. // import Foundation import FirebaseAuth import Firebase //protocol FirebaseDictionaryConveratable { // func toFirebaseDictionary() //} // //extension FirebaseDictionaryConveratable { // /// https://stackoverflow.com/questions/25463146/iterate-over-object-class-attributes-in-swift // func toFirebaseDictionary() -> [String:Any] { // let mirrored_object = Mirror(reflecting: self) // var firebaseDictionary = [String:Any]() // for (index, attr) in mirrored_object.children.enumerated() { // if let propertyName = attr.label { // let propertyValue = attr.value // print("Attr \(index): \(propertyName) = \(propertyValue)") // firebaseDictionary[propertyName] = propertyValue // } // } // // return firebaseDictionary // } //} class CloudUser: DictionaryConvertible { private(set) var uid: String var fcmToken: String? init(from user: User, fcmToken: String?) { uid = user.uid self.fcmToken = fcmToken } }
apache-2.0
74f536e7d256bc4a310556ec160ce5a2
27.119048
100
0.632515
3.989865
false
false
false
false
king7532/TaylorSource
examples/Gallery/Pods/HanekeSwift/Haneke/Haneke.swift
48
1367
// // Haneke.swift // Haneke // // Created by Hermes Pique on 9/9/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit public struct HanekeGlobals { public static let Domain = "io.haneke" } public struct Shared { public static var imageCache : Cache<UIImage> { struct Static { static let name = "shared-images" static let cache = Cache<UIImage>(name: name) } return Static.cache } public static var dataCache : Cache<NSData> { struct Static { static let name = "shared-data" static let cache = Cache<NSData>(name: name) } return Static.cache } public static var stringCache : Cache<String> { struct Static { static let name = "shared-strings" static let cache = Cache<String>(name: name) } return Static.cache } public static var JSONCache : Cache<JSON> { struct Static { static let name = "shared-json" static let cache = Cache<JSON>(name: name) } return Static.cache } } func errorWithCode(code : Int, #description : String) -> NSError { let userInfo = [NSLocalizedDescriptionKey: description] return NSError(domain: HanekeGlobals.Domain, code: code, userInfo: userInfo) }
mit
61015998287519015221975d26c7922c
23.854545
80
0.589612
4.38141
false
false
false
false
DarthStrom/BlackBox
Black Box/Models/Board.swift
1
1937
struct Board { var slots = [Location: Bool]() var entries = [Location: Int]() init() { clearSlots() populateEntries() } mutating func clearSlots() { for y in 0...7 { for x in 0...7 { slots[Location(x, y)] = false } } } mutating func populateEntries() { for n in 1...8 { entries[Location(-1, n-1)] = n } for n in 9...16 { entries[Location(n-9, 8)] = n } for n in 17...24 { entries[Location(8, 24-n)] = n } for n in 25...32 { entries[Location(32-n, -1)] = n } } mutating func placeAt(column: Int, andRow row: Int) { slots[Location(column, row)] = true } func getEntryPointAt(column: Int, andRow row: Int) -> Int? { return entries[Location(column, row)] } func getSlotAt(column: Int, andRow row: Int) -> Bool { if let result = slots[Location(column, row)] { return result } return false } func getLocationFor(entry: Int) -> Location? { switch entry { case 1...8: return Location(-1, entry - 1) case 9...16: return Location(entry - 9, 8) case 17...24: return Location(8, 24 - entry) case 25...32: return Location(32 - entry, -1) default: return nil } } func getDirectionFor(entry: Int) -> Direction? { switch entry { case 1...8: return .right case 9...16: return .up case 17...24: return .left case 25...32: return .down default: return nil } } func isInBox(position: Location) -> Bool { if slots[position] != nil { return true } return false } }
mit
f2e82f29d9cb66429d28d0ad6a3ec9dc
21.788235
64
0.45999
4.060797
false
false
false
false
ykws/yomblr
yomblr/ViewController.swift
1
8395
// // ViewController.swift // yomblr // // Created by Yoshiyuki Kawashima on 2017/06/21. // Copyright © 2017 ykws. All rights reserved. // import UIKit import TMTumblrSDK import SDWebImage import MBProgressHUD import ChameleonFramework class ViewController: UITableViewController { // MARK: - Properties private let limit: Int = 20 var user: User! var posts: [PhotoPost] = Array() var offset: Int = 0 var ignoreLikes: Int = 0 // MARK: - Actions @IBAction func dashboard(_ sender: Any) { TMTumblrAppClient.viewDashboard() } // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() setApplicationColor() refreshControl = UIRefreshControl() refreshControl?.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControl?.addTarget(self, action: #selector(requestLikes), for: UIControlEvents.valueChanged) tableView.addSubview(refreshControl!) guard let oAuthToken = UserDefaults.standard.string(forKey: "OAuthToken"), let oAuthTokenSecret = UserDefaults.standard.string(forKey: "OAuthTokenSecret") else { requestAuthenticate() return } TMAPIClient.sharedInstance().oAuthToken = oAuthToken TMAPIClient.sharedInstance().oAuthTokenSecret = oAuthTokenSecret requestUserInfo() } override func viewWillAppear(_ animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: animated) super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { navigationController?.setNavigationBarHidden(false, animated: animated) super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - TableView override func numberOfSections(in tableView: UITableView) -> Int { return posts.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return posts[section].photos.count } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 0 ? 0 : 20 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let screenWidth = UIScreen.main.bounds.size.width guard let altSize = posts[indexPath.section].photos[indexPath.row].altSizes.first else { return screenWidth } let scale = screenWidth / CGFloat(altSize.width) return CGFloat(altSize.height) * scale } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = UIView() header.backgroundColor = UIColor.clear return header } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == (offset + limit - 1) { refreshView(withOffset: offset + limit) } let cell: CustomCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell guard let url = posts[indexPath.section].photos[indexPath.row].altSizes.first?.url else { showMessage("Can't retrieve url.") return cell } cell.photo.sd_setShowActivityIndicatorView(true) cell.photo.sd_setIndicatorStyle(.gray) cell.photo.sd_setImage(with: URL(string: url), placeholderImage: nil) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { logEvent(title: "Photo", type: "Image") let cell: CustomCell = tableView.cellForRow(at: indexPath) as! CustomCell crop(postIndex: indexPath.section, photoIndex: indexPath.row, image: cell.photo.image!) } // MARK: - Tumblr func requestAuthenticate() { TMAPIClient.sharedInstance().authenticate("yomblr", from: self, callback: { error in if (error != nil) { self.showError(error!) return } guard let oAuthToken = TMAPIClient.sharedInstance().oAuthToken, let oAuthTokenSecret = TMAPIClient.sharedInstance().oAuthTokenSecret else { self.showMessage("Can't retrieve OAuthToken or OAuthTokenSecret") return } UserDefaults.standard.set(oAuthToken, forKey: "OAuthToken") UserDefaults.standard.set(oAuthTokenSecret, forKey: "OAuthTokenSecret") self.requestUserInfo() }) } func requestUserInfo() { let hud = showProgress(withMessage: "Requesting user's information...") TMAPIClient.sharedInstance().userInfo({ response, error in self.hideProgress(hud: hud) if (error != nil) { self.showError(error!) return } do { self.user = try User.init(json: response!) } catch { self.showError(error) return } self.refreshView() }) } func requestDashboard(withOffset offset: Int = 0) { let hud = showProgress(withMessage: "Requesting dashboard...") TMAPIClient.sharedInstance().dashboard(["offset": offset, "type": "photo"], callback: { response, error in self.hideProgress(hud: hud) if (error != nil) { self.showError(error!) return } do { let dashboard = try Dashboard.init(json: response!) self.updatePosts(posts: dashboard.posts, offset: self.offset) } catch { self.showError(error) return } }) } func requestLikes(sender: AnyObject /*withOffset offset: Int = 0*/) { let hud = showProgress(withMessage: "Requesting likes...") TMAPIClient.sharedInstance().likes(user.blogs.first?.name, parameters: ["offset": offset], callback: { response, error in self.hideProgress(hud: hud) if (error != nil) { self.refreshControl?.endRefreshing() self.showError(error!) return } do { let likes = try Likes.init(json: response!) // Cancel displaying previous photo if no more previous likes photo if likes.likedPosts.count == 0 { self.refreshControl?.endRefreshing() self.showMessage("No more likes") return } self.updatePosts(posts: likes.likedPosts, offset: self.offset) self.ignoreLikes += likes.ignoreCount self.refreshControl?.endRefreshing() } catch { self.refreshControl?.endRefreshing() self.showError(error) return } }) } // MARK: - View func refreshView(withOffset offset: Int = 0) { self.offset = offset == 0 ? offset : offset + ignoreLikes requestLikes(sender: refreshControl!) } func updatePosts(posts: [PhotoPost], offset: Int) { if offset == 0 { self.posts = posts } else { posts.forEach { post in self.posts.append(post) } } self.offset = offset == 0 ? offset : offset - ignoreLikes tableView.reloadData() } // MARK: - Controller func browse(postIndex: Int) { let webViewController: WebViewController = storyboard?.instantiateViewController(withIdentifier: "web") as! WebViewController initWebViewController(webViewController, postIndex: postIndex) navigationController?.pushViewController(webViewController, animated: true) } func crop(postIndex: Int, photoIndex: Int, image: UIImage) { let cropViewController: CropViewController = storyboard?.instantiateViewController(withIdentifier: "crop") as! CropViewController cropViewController.blogName = user.blogs.first?.name cropViewController.image = image cropViewController.postUrl = posts[postIndex].photos[photoIndex].altSizes.first?.url navigationController?.pushViewController(cropViewController, animated: true) } // MARK: - Initializer func initWebViewController(_ webViewController: WebViewController, postIndex: Int) { webViewController.blogName = user.blogs.first?.name let targetString = posts[postIndex].sourceUrl ?? posts[postIndex].postUrl if targetString.contains("%") { webViewController.urlString = targetString return } let encodedString = targetString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) webViewController.urlString = encodedString } }
mit
edde819aae2027b102db5bff1d66911d
29.635036
133
0.677389
4.753114
false
false
false
false
crashoverride777/Swift-2-iAds-AdMob-CustomAds-Helper
Sources/Internal/SwiftyAdsBanner.swift
2
12842
// The MIT License (MIT) // // Copyright (c) 2015-2021 Dominik Ringler // // 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 GoogleMobileAds final class SwiftyAdsBanner: NSObject { // MARK: - Types private enum Configuration { static let visibleConstant: CGFloat = 0 static let hiddenConstant: CGFloat = 400 } // MARK: - Properties private let environment: SwiftyAdsEnvironment private let isDisabled: () -> Bool private let hasConsent: () -> Bool private let request: () -> GADRequest private var onOpen: (() -> Void)? private var onClose: (() -> Void)? private var onError: ((Error) -> Void)? private var onWillPresentScreen: (() -> Void)? private var onWillDismissScreen: (() -> Void)? private var onDidDismissScreen: (() -> Void)? private var bannerView: GADBannerView? private var position: SwiftyAdsBannerAdPosition = .bottom(isUsingSafeArea: true) private var animation: SwiftyAdsBannerAdAnimation = .none private var bannerViewConstraint: NSLayoutConstraint? private var animator: UIViewPropertyAnimator? // MARK: - Initialization init(environment: SwiftyAdsEnvironment, isDisabled: @escaping () -> Bool, hasConsent: @escaping () -> Bool, request: @escaping () -> GADRequest) { self.environment = environment self.isDisabled = isDisabled self.hasConsent = hasConsent self.request = request super.init() } // MARK: - Methods func prepare(withAdUnitId adUnitId: String, in viewController: UIViewController, position: SwiftyAdsBannerAdPosition, animation: SwiftyAdsBannerAdAnimation, onOpen: (() -> Void)?, onClose: (() -> Void)?, onError: ((Error) -> Void)?, onWillPresentScreen: (() -> Void)?, onWillDismissScreen: (() -> Void)?, onDidDismissScreen: (() -> Void)?) { self.position = position self.animation = animation self.onOpen = onOpen self.onClose = onClose self.onError = onError self.onWillPresentScreen = onWillPresentScreen self.onWillDismissScreen = onWillDismissScreen self.onDidDismissScreen = onDidDismissScreen // Create banner view let bannerView = GADBannerView() // Keep reference to created banner view self.bannerView = bannerView // Set ad unit id bannerView.adUnitID = adUnitId // Set the root view controller that will display the banner view bannerView.rootViewController = viewController // Set the banner view delegate bannerView.delegate = self // Add banner view to view controller add(bannerView, to: viewController) // Hide banner without animation hide(bannerView, from: viewController, skipAnimation: true) } } // MARK: - SwiftyAdsBannerType extension SwiftyAdsBanner: SwiftyAdsBannerType { func show(isLandscape: Bool) { guard !isDisabled() else { return } guard hasConsent() else { return } guard let bannerView = bannerView else { return } guard let currentView = bannerView.rootViewController?.view else { return } // Determine the view width to use for the ad width. let frame = { () -> CGRect in switch position { case .top(let isUsingSafeArea), .bottom(let isUsingSafeArea): if isUsingSafeArea { return currentView.frame.inset(by: currentView.safeAreaInsets) } else { return currentView.frame } } }() // Get Adaptive GADAdSize and set the ad view. if isLandscape { bannerView.adSize = GADLandscapeAnchoredAdaptiveBannerAdSizeWithWidth(frame.size.width) } else { bannerView.adSize = GADPortraitAnchoredAdaptiveBannerAdSizeWithWidth(frame.size.width) } // Create an ad request and load the adaptive banner ad. bannerView.load(request()) } func hide() { guard let bannerView = bannerView else { return } guard let rootViewController = bannerView.rootViewController else { return } hide(bannerView, from: rootViewController) } func remove() { guard bannerView != nil else { return } bannerView?.delegate = nil bannerView?.removeFromSuperview() bannerView = nil bannerViewConstraint = nil onClose?() } } // MARK: - GADBannerViewDelegate extension SwiftyAdsBanner: GADBannerViewDelegate { // Request lifecycle events func bannerViewDidRecordImpression(_ bannerView: GADBannerView) { if case .development = environment { print("SwiftyAdsBanner did record impression for banner ad") } } func bannerViewDidReceiveAd(_ bannerView: GADBannerView) { show(bannerView, from: bannerView.rootViewController) if case .development = environment { print("SwiftyAdsBanner did receive ad from: \(bannerView.responseInfo?.adNetworkClassName ?? "not found")") } } func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) { hide(bannerView, from: bannerView.rootViewController) onError?(error) } // Click-Time lifecycle events func bannerViewWillPresentScreen(_ bannerView: GADBannerView) { onWillPresentScreen?() } func bannerViewWillDismissScreen(_ bannerView: GADBannerView) { onWillDismissScreen?() } func bannerViewDidDismissScreen(_ bannerView: GADBannerView) { onDidDismissScreen?() } } // MARK: - Private Methods private extension SwiftyAdsBanner { func add(_ bannerView: GADBannerView, to viewController: UIViewController) { // Add banner view to view controller bannerView.translatesAutoresizingMaskIntoConstraints = false viewController.view.addSubview(bannerView) // Add constraints // We don't give the banner a width or height constraint, as the provided ad size will give the banner // an intrinsic content size switch position { case .top(let isUsingSafeArea): if isUsingSafeArea { bannerViewConstraint = bannerView.topAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.topAnchor) } else { bannerViewConstraint = bannerView.topAnchor.constraint(equalTo: viewController.view.topAnchor) } case .bottom(let isUsingSafeArea): if let tabBarController = viewController as? UITabBarController { bannerViewConstraint = bannerView.bottomAnchor.constraint(equalTo: tabBarController.tabBar.topAnchor) } else { if isUsingSafeArea { bannerViewConstraint = bannerView.bottomAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.bottomAnchor) } else { bannerViewConstraint = bannerView.bottomAnchor.constraint(equalTo: viewController.view.bottomAnchor) } } } // Activate constraints NSLayoutConstraint.activate([ bannerView.centerXAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.centerXAnchor), bannerViewConstraint ].compactMap { $0 }) } func show(_ bannerAd: GADBannerView, from viewController: UIViewController?) { // Stop current animations stopCurrentAnimatorAnimations() // Show banner incase it was hidden bannerAd.isHidden = false // Animate if needed switch animation { case .none: animator = nil case .fade(let duration): animator = UIViewPropertyAnimator(duration: duration, curve: .easeOut) { [weak bannerView] in bannerView?.alpha = 1 } case .slide(let duration): /// We can only animate the banner to its on-screen position with a valid view controller guard let viewController = viewController else { return } /// We can only animate the banner to its on-screen position if it has a constraint guard let bannerViewConstraint = bannerViewConstraint else { return } /// We can only animate the banner to its on-screen position if its not already visible guard bannerViewConstraint.constant != Configuration.visibleConstant else { return } /// Set banner constraint bannerViewConstraint.constant = Configuration.visibleConstant /// Animate constraint changes animator = UIViewPropertyAnimator(duration: duration, curve: .easeOut) { viewController.view.layoutIfNeeded() } } // Add animation completion if needed animator?.addCompletion { [weak self] _ in self?.onOpen?() } // Start animation if needed animator?.startAnimation() } func hide(_ bannerAd: GADBannerView, from viewController: UIViewController?, skipAnimation: Bool = false) { // Stop current animations stopCurrentAnimatorAnimations() // Animate if needed switch animation { case .none: animator = nil bannerAd.isHidden = true case .fade(let duration): if skipAnimation { bannerView?.alpha = 0 } else { animator = UIViewPropertyAnimator(duration: duration, curve: .easeOut) { [weak bannerView] in bannerView?.alpha = 0 } } case .slide(let duration): /// We can only animate the banner to its off-screen position with a valid view controller guard let viewController = viewController else { return } /// We can only animate the banner to its off-screen position if it has a constraint guard let bannerViewConstraint = bannerViewConstraint else { return } /// We can only animate the banner to its off-screen position if its already visible guard bannerViewConstraint.constant == Configuration.visibleConstant else { return } /// Get banner off-screen constant var newConstant: CGFloat { switch position { case .top: return -Configuration.hiddenConstant case .bottom: return Configuration.hiddenConstant } } /// Set banner constraint bannerViewConstraint.constant = newConstant /// Animate constraint changes if !skipAnimation { animator = UIViewPropertyAnimator(duration: duration, curve: .easeOut) { viewController.view.layoutIfNeeded() } } } // Add animation completion if needed animator?.addCompletion { [weak self, weak bannerAd] _ in bannerAd?.isHidden = true self?.onClose?() } // Start animation if needed animator?.startAnimation() } func stopCurrentAnimatorAnimations() { animator?.stopAnimation(false) animator?.finishAnimation(at: .current) } } // MARK: - Deprecated extension SwiftyAdsBanner { @available(*, deprecated, message: "Please use new hide method without animated parameter") func hide(animated: Bool) { hide() } }
mit
bea3caeb9518206f083377e55eaaf2df
35.482955
140
0.630276
5.552097
false
false
false
false
kesun421/firefox-ios
Storage/SQL/SQLiteMetadata.swift
7
2337
/* 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 Deferred import Shared /// The sqlite-backed implementation of the metadata protocol containing images and content for pages. open class SQLiteMetadata { let db: BrowserDB required public init(db: BrowserDB) { self.db = db } } extension SQLiteMetadata: Metadata { // A cache key is a conveninent, readable identifier for a site in the metadata database which helps // with deduping entries for the same page. typealias CacheKey = String /// Persists the given PageMetadata object to browser.db in the page_metadata table. /// /// - parameter metadata: Metadata object /// - parameter pageURL: URL of page metadata was fetched from /// - parameter expireAt: Expiration/TTL interval for when this metadata should expire at. /// /// - returns: Deferred on success public func storeMetadata(_ metadata: PageMetadata, forPageURL pageURL: URL, expireAt: UInt64) -> Success { guard let cacheKey = pageURL.displayURL?.absoluteString else { return succeed() } // Replace any matching cache_key entries if they exist let selectUniqueCacheKey = "COALESCE((SELECT cache_key FROM \(TablePageMetadata) WHERE cache_key = ?), ?)" let args: Args = [cacheKey, cacheKey, metadata.siteURL, metadata.mediaURL, metadata.title, metadata.type, metadata.description, metadata.providerName, expireAt] let insert = "INSERT OR REPLACE INTO \(TablePageMetadata)" + "(cache_key, site_url, media_url, title, type, description, provider_name, expired_at) " + "VALUES ( \(selectUniqueCacheKey), ?, ?, ?, ?, ?, ?, ?)" return self.db.run(insert, withArgs: args) } /// Purges any metadata items living in page_metadata that are expired. /// /// - returns: Deferred on success public func deleteExpiredMetadata() -> Success { let sql = "DELETE FROM page_metadata WHERE expired_at <= (CAST(strftime('%s', 'now') AS LONG)*1000)" return self.db.run(sql) } }
mpl-2.0
bdbd52d39a8aa9d51763aa266b8d6e86
39.293103
114
0.652546
4.520309
false
false
false
false