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
nickswalker/ASCIIfy
Pod/Classes/LuminanceLookupTable.swift
1
3179
// // Copyright for portions of ASCIIfy are held by Barış Koç, 2014 as part of // project BKAsciiImage and Amy Dyer, 2012 as part of project Ascii. All other copyright // for ASCIIfy are held by Nick Walker, 2016. // // 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. // // BlockGrid class and block struct are adapted from // https://github.com/oxling/iphone-ascii/blob/master/ASCII/BlockGrid.h // import Foundation import KDTree extension Float: KDTreePoint { public static var dimensions: Int = 1 // MARK: KDTreePoint public func squaredDistance(to otherPoint: Float) -> Double { return Double(pow(self - otherPoint, 2)) } public func kdDimension(_ dimension: Int) -> Double { return Double(self) } } open class LuminanceLookupTable: LookupTable { // MARK: Properties open var invertLuminance = true fileprivate let tree: KDTree<KDTreeEntry<Float, String>> static let defaultMapping = [1.0: " ", 0.95: "`", 0.92: ".", 0.9: ",", 0.8: "-", 0.75: "~", 0.7: "+", 0.65: "<", 0.6: ">", 0.55: "o", 0.5: "=", 0.35: "*", 0.3: "%", 0.1: "X", 0.0: "@"] // MARK: Initialization public convenience init() { self.init(luminanceToStringMapping: LuminanceLookupTable.defaultMapping) } public init(luminanceToStringMapping: [Double: String]) { let entries = luminanceToStringMapping.map{KDTreeEntry<Float, String>(key: Float($0.0),value: $0.1)} tree = KDTree(values: entries) } open func lookup(_ block: BlockGrid.Block) -> String? { let luminance = LuminanceLookupTable.luminance(block, invert: invertLuminance) let nearest = tree.nearest(to: KDTreeEntry<Float, String>(key: luminance, value: "")) return nearest?.value } open static func luminance(_ block: BlockGrid.Block, invert: Bool = false) -> Float { // See Wikipedia's article on relative luminance: // https://en.wikipedia.org/wiki/Relative_luminance var result = 0.2126 * block.r + 0.7152 * block.g + 0.0722 * block.b if invert { result = (1.0 - result) } return result } }
mit
e88dfcb9bcbc0af962406a9a46f9468b
38.7
188
0.678526
3.950249
false
false
false
false
zzycami/firefox-ios
ClientTests/ClientTests.swift
3
3581
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import UIKit import XCTest class ClientTests: XCTestCase { func testFavicons() { var fav : Favicons = BasicFavicons(); var url = NSURL(string: "http://www.example.com"); var expectation = expectationWithDescription("asynchronous request") fav.getForUrl(url!, options: nil, callback: { (data: Favicon) -> Void in XCTAssertEqual(data.siteUrl!, url!, "Site url is correct"); XCTAssertEqual(data.sourceUrl!, FaviconConsts.DefaultFaviconUrl, "Source url is correct"); expectation.fulfill() }); waitForExpectationsWithTimeout(10.0, handler:nil) expectation = expectationWithDescription("asynchronous request") var urls = [url!, url!, url!]; fav.getForUrls(urls, options: nil, callback: { (data: ArrayCursor<Favicon>) -> Void in XCTAssertTrue(data.count == urls.count, "At least one favicon was returned for each url requested"); var favicon : Favicon = data[0]!; XCTAssertEqual(favicon.siteUrl!, url!, "Site url is correct"); XCTAssertEqual(favicon.sourceUrl!, FaviconConsts.DefaultFaviconUrl, "Favicon url is correct"); XCTAssertNotNil(favicon.img!, "Favicon image is not null"); expectation.fulfill() }); waitForExpectationsWithTimeout(10.0, handler:nil) } func testArrayCursor() { let data = ["One", "Two", "Three"]; let t = ArrayCursor<String>(data: data); // Test subscript access XCTAssertNil(t[-1], "Subscript -1 returns nil"); XCTAssertEqual(t[0]!, "One", "Subscript zero returns the correct data"); XCTAssertEqual(t[1]!, "Two", "Subscript one returns the correct data"); XCTAssertEqual(t[2]!, "Three", "Subscript two returns the correct data"); XCTAssertNil(t[3], "Subscript three returns nil"); // Test status data with default initializer XCTAssertEqual(t.status, CursorStatus.Success, "Cursor as correct status"); XCTAssertEqual(t.statusMessage, "Success", "Cursor as correct status message"); XCTAssertEqual(t.count, 3, "Cursor as correct size"); // Test generator access var i = 0; for s in t { XCTAssertEqual(s, data[i], "Subscript zero returns the correct data"); i++; } // Test creating a failed cursor let t2 = ArrayCursor<String>(data: data, status: CursorStatus.Failure, statusMessage: "Custom status message"); XCTAssertEqual(t2.status, CursorStatus.Failure, "Cursor as correct status"); XCTAssertEqual(t2.statusMessage, "Custom status message", "Cursor as correct status message"); XCTAssertEqual(t2.count, 0, "Cursor as correct size"); // Test subscript access return nil for a failed cursor XCTAssertNil(t2[0], "Subscript zero returns nil if failure"); XCTAssertNil(t2[1], "Subscript one returns nil if failure"); XCTAssertNil(t2[2], "Subscript two returns nil if failure"); XCTAssertNil(t2[3], "Subscript three returns nil if failure"); // Test that generator doesn't work with failed cursors var ran = false; for s in t2 { println("Got \(s)") ran = true; } XCTAssertFalse(ran, "for...in didn't run for failed cursor"); } }
mpl-2.0
e004d8031467495e449a52af9fdd940d
44.329114
119
0.636135
4.650649
false
true
false
false
midoks/Swift-Learning
GitHubStar/GitHubStar/GitHubStar/Controllers/common/events/GsEventsViewController_bak.swift
1
17104
// // GsEventsViewController.swift // GitHubStar // // Created by midoks on 16/3/17. // Copyright © 2016年 midoks. All rights reserved. // import UIKit class GsEventsViewController: GsListViewController { var current = NSDate() override func viewDidLoad() { self.showSearch = false self.delegate = self super.viewDidLoad() } func updateData(){ self.startPull() GitHubApi.instance.urlGet(_fixedUrl) { (data, response, error) -> Void in self.pullingEnd() self._tableData = Array<JSON>() if data != nil { let _dataJson = self.gitJsonParse(data) for i in _dataJson { self._tableData.append(i.1) } let rep = response as! NSHTTPURLResponse if rep.allHeaderFields["Link"] != nil { self.pageInfo = self.gitParseLink(rep.allHeaderFields["Link"] as! String) } } self._tableView?.reloadData() } } override func refreshUrl(){ super.refreshUrl() if _fixedUrl != "" { updateData() } } func setUrlData(url:String){ _fixedUrl = url } } extension GsEventsViewController { func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var default_h:CGFloat = 70 let indexData = self.getSelectTableData(indexPath) let cell = GsEventsCell(style: .Default, reuseIdentifier: cellIdentifier) //let cell = tableView.cellForRowAtIndexPath(indexPath) // if indexData["type"].stringValue == "PushEvent" { // let s = cell.getCommitHeight() // default_h += s.height // } if indexData["type"].stringValue == "CommitCommentEvent" { let v = UILabel(frame: CGRectZero) v.text = indexData["payload"]["comment"]["body"].stringValue let size = cell.getSize(v) default_h += size.height if default_h > 140 { default_h = 140 } } else if indexData["type"].stringValue == "CreateEvent"{ } else if indexData["type"].stringValue == "DeleteEvent" { } else if indexData["type"].stringValue == "DeploymentEvent" { } else if indexData["type"].stringValue == "DeploymentStatusEvent" { } else if indexData["type"].stringValue == "DownloadEvent" { } else if indexData["type"].stringValue == "FollowEvent" { } else if indexData["type"].stringValue == "ForkEvent" { } else if indexData["type"].stringValue == "ForkApplyEvent" { } else if indexData["type"].stringValue == "GistEvent" { } else if indexData["type"].stringValue == "GollumEvent" { let c = indexData["payload"]["pages"].count * 15 default_h += CGFloat(c) }else if indexData["type"].stringValue == "IssueCommentEvent" { //print("2") //print(indexData["payload"]["comment"]["body"].stringValue) let v = UILabel(frame: CGRectZero) v.text = indexData["payload"]["comment"]["body"].stringValue //print(v.text) let size = cell.getSize(v) default_h += size.height //default_h += 40 //print(ceil(size.height)) } else if indexData["type"].stringValue == "IssuesEvent" { let v = UILabel(frame: CGRectZero) v.text = indexData["payload"]["issue"]["title"].stringValue let size = cell.getSize(v) default_h += size.height } else if indexData["type"].stringValue == "MemberEvent"{ } else if indexData["type"].stringValue == "MembershipEvent"{ } else if indexData["type"].stringValue == "PageBuildEvent"{ } else if indexData["type"].stringValue == "PublicEvent"{ } else if indexData["type"].stringValue == "PullRequestEvent" { let v = UILabel(frame: CGRectZero) v.text = indexData["payload"]["pull_request"]["title"].stringValue let size = cell.getSize(v) default_h += size.height } else if indexData["type"].stringValue == "PullRequestReviewCommentEvent"{ let v = UILabel(frame: CGRectZero) v.text = indexData["payload"]["comment"]["body"].stringValue let size = cell.getSize(v) default_h += size.height } else if indexData["type"].stringValue == "PushEvent" { let c = indexData["payload"]["commits"].count * 15 default_h += CGFloat(c) } else if indexData["type"].stringValue == "ReleaseEvent"{ } else if indexData["type"].stringValue == "RepositoryEvent"{ } else if indexData["type"].stringValue == "StatusEvent"{ } else if indexData["type"].stringValue == "TeamAddEvent"{ } else if indexData["type"].stringValue == "WatchEvent" { } print(indexPath, default_h) return default_h } } extension GsEventsViewController:GsListViewDelegate { //event name private func actionName(type:String) -> String { //print(type) switch(type){ case "CommitCommentEvent": return "CommitCommentEvent" case "CreateEvent": return "created branch" case "DeleteEvent": return "DeleteEvent" case "DeploymentEvent": return "DeploymentEvent" case "DeploymentStatusEvent": return "DeploymentStatusEvent" case "DownloadEvent": return "DownloadEvent" case "FollowEvent": return "FollowEvent" case "ForkEvent": return "ForkEvent" case "ForkApplyEvent": return "ForkApplyEvent" case "GistEvent": return "GistEvent" case "GollumEvent": return "GollumEvent" case "IssueCommentEvent": return "IssueCommentEvent" case "IssuesEvent": return "IssuesEvent" case "MemberEvent": return "MemberEvent" case "MembershipEvent": return "MembershipEvent" case "PageBuildEvent": return "PageBuildEvent" case "PublicEvent": return "PublicEvent" case "PullRequestEvent": return "PullRequestEvent" case "PullRequestReviewCommentEvent": return "PullRequestReviewCommentEvent" case "PushEvent": return "pushed to" case "ReleaseEvent": return "ReleaseEvent" case "RepositoryEvent": return "RepositoryEvent" case "StatusEvent": return "StatusEvent" case "TeamAddEvent": return "TeamAddEvent" case "WatchEvent": return "starred" default:return "" } } func listTableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let indexData = self.getSelectTableData(indexPath) let cell = GsEventsCell(style: .Default, reuseIdentifier: cellIdentifier) cell.authorIcon.MDCacheImage(indexData["actor"]["avatar_url"].stringValue, defaultImage: "avatar_default") cell.eventTime.text = gitNowBeforeTime(indexData["created_at"].stringValue) let author = indexData["actor"]["login"].stringValue let repo = indexData["repo"]["name"].stringValue if indexData["type"].stringValue == "CommitCommentEvent" { //计算高度有问题 var commitCommentEvent = author commitCommentEvent += " commented on commit " + indexData["payload"]["comment"]["commit_id"].stringValue.substring(0, end: 5) commitCommentEvent += " in " + repo cell.actionContent.text = commitCommentEvent let v = UILabel(frame: CGRectZero) v.text = indexData["payload"]["comment"]["body"].stringValue //v. cell.nextContent = v } else if indexData["type"].stringValue == "CreateEvent"{ var createEvent = author createEvent += " created " + indexData["payload"]["ref_type"].stringValue createEvent += " " + indexData["payload"]["ref"].stringValue + " in " createEvent += repo cell.actionContent.text = createEvent } else if indexData["type"].stringValue == "DeleteEvent"{ var createEvent = author createEvent += " deleted " + indexData["payload"]["ref_type"].stringValue createEvent += " " + indexData["payload"]["ref"].stringValue createEvent += " " + repo cell.actionContent.text = createEvent } else if indexData["type"].stringValue == "DeploymentEvent"{ print(indexData) } else if indexData["type"].stringValue == "DeploymentStatusEvent"{ print(indexData) } else if indexData["type"].stringValue == "DownloadEvent"{ print(indexData) } else if indexData["type"].stringValue == "FollowEvent"{ print(indexData) } else if indexData["type"].stringValue == "ForkEvent" { var forkevent = author forkevent += " forked " + indexData["repo"]["name"].stringValue forkevent += " to " + indexData["payload"]["forkee"]["full_name"].stringValue cell.actionContent.text = forkevent } else if indexData["type"].stringValue == "ForkApplyEvent"{ print(indexData) } else if indexData["type"].stringValue == "GistEvent"{ print(indexData) } else if indexData["type"].stringValue == "GollumEvent" { var gollumEventContent = author gollumEventContent += " modified the wiki the in " + repo cell.actionContent.text = gollumEventContent for i in indexData["payload"]["pages"] { let v = i.1 let msg = v["page_name"].stringValue + " - " + v["action"].stringValue let labelList = UILabel() labelList.text = msg cell.nextList.append(labelList) } cell.showList() } else if indexData["type"].stringValue == "IssueCommentEvent" { var issueCommentEvent = author if indexData["payload"]["issue"].count > 0 { issueCommentEvent += " commented on issue #" } else { issueCommentEvent += " commented on pull request #" } issueCommentEvent += indexData["payload"]["issue"]["number"].stringValue + " " issueCommentEvent += repo cell.actionContent.text = issueCommentEvent let v = UILabel(frame: CGRectZero) v.text = indexData["payload"]["comment"]["body"].stringValue cell.nextContent = v } else if indexData["type"].stringValue == "IssuesEvent" { var issueCommentEvent = author if indexData["payload"]["action"].stringValue == "reopened" { issueCommentEvent += " reopened issue #" } else if indexData["payload"]["action"].stringValue == "opened"{ issueCommentEvent += " opened issue #" } else { issueCommentEvent += " closed issue #" } issueCommentEvent += indexData["payload"]["issue"]["number"].stringValue + " " issueCommentEvent += repo cell.actionContent.text = issueCommentEvent //print("1") //print(indexData["payload"]["comment"]["body"].stringValue) let v = UILabel(frame: CGRectZero) v.text = indexData["payload"]["issue"]["title"].stringValue cell.nextContent = v } else if indexData["type"].stringValue == "MemberEvent"{ print(indexData) } else if indexData["type"].stringValue == "MembershipEvent"{ print(indexData) } else if indexData["type"].stringValue == "PageBuildEvent" { print(indexData) } else if indexData["type"].stringValue == "PublicEvent" { print(indexData) } else if indexData["type"].stringValue == "PullRequestEvent" { var pullRequestEventContent = author if indexData["payload"]["action"].stringValue == "closed" { pullRequestEventContent += " " + "closed pull request" } else { pullRequestEventContent += " " + "opened pull request" } pullRequestEventContent += " #" + indexData["payload"]["number"].stringValue pullRequestEventContent += " " + repo cell.actionContent.text = pullRequestEventContent let v = UILabel(frame: CGRectZero) v.text = indexData["payload"]["pull_request"]["title"].stringValue cell.nextContent = v } else if indexData["type"].stringValue == "PullRequestReviewCommentEvent"{ var pullRequestReviewCommentEvent = author pullRequestReviewCommentEvent += " commented on pull request in " pullRequestReviewCommentEvent += repo cell.actionContent.text = pullRequestReviewCommentEvent let v = UILabel(frame: CGRectZero) v.text = indexData["payload"]["comment"]["body"].stringValue cell.nextContent = v } else if indexData["type"].stringValue == "PushEvent" { var content = author content += " " + actionName(indexData["type"].stringValue) let ref = indexData["payload"]["ref"].stringValue let refs = ref.componentsSeparatedByString("/") content += " " + refs[refs.count - 1] content += " " + repo cell.actionContent.text = content for i in indexData["payload"]["commits"] { let v = i.1 let msg = v["sha"].stringValue.substring(0, end: 5) + " - " + v["message"].stringValue.componentsSeparatedByString("\n\n")[0] let labelList = UILabel() labelList.text = msg cell.nextList.append(labelList) } cell.showList() } else if indexData["type"].stringValue == "ReleaseEvent"{ var releaseEvent = author releaseEvent += " published release" cell.actionContent.text = releaseEvent } else if indexData["type"].stringValue == "RepositoryEvent"{ print(indexData) } else if indexData["type"].stringValue == "StatusEvent"{ print(indexData) } else if indexData["type"].stringValue == "TeamAddEvent"{ print(indexData) } else if indexData["type"].stringValue == "WatchEvent" { var content = author content += " " + actionName(indexData["type"].stringValue) let ref = indexData["payload"]["ref"].stringValue let refs = ref.componentsSeparatedByString("/") content += " " + refs[refs.count - 1] content += " " + repo cell.actionContent.text = content cell.actionContent.addLinkToURL(NSURL(string: "scheme://?type=1&business_id=2"), withRange: NSRange(location: 0, length: author.length)) } return cell } func listTableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } func applyFilter(searchKey:String, data:JSON) -> Bool { return false } func pullUrlLoad(url: String){ GitHubApi.instance.webGet(url) { (data, response, error) -> Void in self.pullingEnd() if data != nil { let _dataJson = self.gitJsonParse(data) for i in _dataJson { self._tableData.append(i.1) } self._tableView?.reloadData() let rep = response as! NSHTTPURLResponse if rep.allHeaderFields["Link"] != nil { let r = self.gitParseLink(rep.allHeaderFields["Link"] as! String) self.pageInfo = r } } } } }
apache-2.0
a3029050a205f903377391ac12938bd8
38.192661
148
0.540586
5.571242
false
false
false
false
HongliYu/firefox-ios
Sync/Synchronizers/Bookmarks/Merging.swift
1
10857
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Deferred import Foundation import Shared import Storage import XCGLogger private let log = Logger.syncLogger // Because generic protocols in Swift are a pain in the ass. public protocol BookmarkStorer: AnyObject { // TODO: this should probably return a timestamp. func applyUpstreamCompletionOp(_ op: UpstreamCompletionOp, itemSources: ItemSources, trackingTimesInto local: LocalOverrideCompletionOp) -> Deferred<Maybe<POSTResult>> } open class UpstreamCompletionOp: PerhapsNoOp { // Upload these records from the buffer, but with these child lists. open var amendChildrenFromBuffer: [GUID: [GUID]] = [:] // Upload these records from the mirror, but with these child lists. open var amendChildrenFromMirror: [GUID: [GUID]] = [:] // Upload these records from local, but with these child lists. open var amendChildrenFromLocal: [GUID: [GUID]] = [:] // Upload these records as-is. open var records: [Record<BookmarkBasePayload>] = [] public let ifUnmodifiedSince: Timestamp? open var isNoOp: Bool { return records.isEmpty } public init(ifUnmodifiedSince: Timestamp?=nil) { self.ifUnmodifiedSince = ifUnmodifiedSince } } open class BookmarksMergeResult: PerhapsNoOp { let uploadCompletion: UpstreamCompletionOp let overrideCompletion: LocalOverrideCompletionOp let bufferCompletion: BufferCompletionOp let itemSources: ItemSources open var isNoOp: Bool { return self.uploadCompletion.isNoOp && self.overrideCompletion.isNoOp && self.bufferCompletion.isNoOp } func applyToClient(_ client: BookmarkStorer, storage: SyncableBookmarks, buffer: BookmarkBufferStorage) -> Success { return client.applyUpstreamCompletionOp(self.uploadCompletion, itemSources: self.itemSources, trackingTimesInto: self.overrideCompletion) >>> { storage.applyLocalOverrideCompletionOp(self.overrideCompletion, itemSources: self.itemSources) } >>> { buffer.applyBufferCompletionOp(self.bufferCompletion, itemSources: self.itemSources) } } init(uploadCompletion: UpstreamCompletionOp, overrideCompletion: LocalOverrideCompletionOp, bufferCompletion: BufferCompletionOp, itemSources: ItemSources) { self.uploadCompletion = uploadCompletion self.overrideCompletion = overrideCompletion self.bufferCompletion = bufferCompletion self.itemSources = itemSources } static func NoOp(_ itemSources: ItemSources) -> BookmarksMergeResult { return BookmarksMergeResult(uploadCompletion: UpstreamCompletionOp(), overrideCompletion: LocalOverrideCompletionOp(), bufferCompletion: BufferCompletionOp(), itemSources: itemSources) } } // MARK: - Errors. open class BookmarksMergeError: MaybeErrorType, SyncPingFailureFormattable { fileprivate let error: Error? init(error: Error?=nil) { self.error = error } open var description: String { return "Merge error: \(self.error ??? "nil")" } open var failureReasonName: SyncPingFailureReasonName { return .otherError } } open class BookmarksMergeConsistencyError: BookmarksMergeError { override open var description: String { return "Merge consistency error" } } open class BookmarksMergeErrorTreeIsUnrooted: BookmarksMergeConsistencyError { public let roots: Set<GUID> public init(roots: Set<GUID>) { self.roots = roots } override open var description: String { return "Tree is unrooted: roots are \(self.roots)" } } enum MergeState<T: Equatable>: Equatable { case unknown // Default state. case unchanged // Nothing changed: no work needed. case remote // Take the associated remote value. case local // Take the associated local value. case new(value: T) // Take this synthesized value. var isUnchanged: Bool { if case .unchanged = self { return true } return false } var isUnknown: Bool { if case .unknown = self { return true } return false } var label: String { switch self { case .unknown: return "Unknown" case .unchanged: return "Unchanged" case .remote: return "Remote" case .local: return "Local" case .new: return "New" } } static func ==(lhs: MergeState, rhs: MergeState) -> Bool { switch (lhs, rhs) { case (.unknown, .unknown), (.unchanged, .unchanged), (.remote, .remote), (.local, .local): return true case let (.new(lh), .new(rh)): return lh == rh default: return false } } } /** * Using this: * * You get one for the root. Then you give it children for the roots * from the mirror. * * Then you walk those, populating the remote and local nodes by looking * at the left/right trees. * * By comparing left and right, and doing value-based comparisons if necessary, * a merge state is decided and assigned for both value and structure. * * One then walks both left and right child structures (both to ensure that * all nodes on both left and right will be visited!) recursively. */ class MergedTreeNode { let guid: GUID let mirror: BookmarkTreeNode? var remote: BookmarkTreeNode? var local: BookmarkTreeNode? var hasLocal: Bool { return self.local != nil } var hasMirror: Bool { return self.mirror != nil } var hasRemote: Bool { return self.remote != nil } var valueState: MergeState<BookmarkMirrorItem> = MergeState.unknown var structureState: MergeState<BookmarkTreeNode> = MergeState.unknown var hasDecidedChildren: Bool { return !self.structureState.isUnknown } var mergedChildren: [MergedTreeNode]? // One-sided constructors. static func forRemote(_ remote: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) -> MergedTreeNode { let n = MergedTreeNode(guid: remote.recordGUID, mirror: mirror, structureState: MergeState.remote) n.remote = remote n.valueState = MergeState.remote return n } static func forLocal(_ local: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) -> MergedTreeNode { let n = MergedTreeNode(guid: local.recordGUID, mirror: mirror, structureState: MergeState.local) n.local = local n.valueState = MergeState.local return n } static func forUnchanged(_ mirror: BookmarkTreeNode) -> MergedTreeNode { let n = MergedTreeNode(guid: mirror.recordGUID, mirror: mirror, structureState: MergeState.unchanged) n.valueState = MergeState.unchanged return n } init(guid: GUID, mirror: BookmarkTreeNode?, structureState: MergeState<BookmarkTreeNode>) { self.guid = guid self.mirror = mirror self.structureState = structureState } init(guid: GUID, mirror: BookmarkTreeNode?) { self.guid = guid self.mirror = mirror } // N.B., you cannot recurse down `decidedStructure`: you'll depart from the // merged tree. You need to use `mergedChildren` instead. fileprivate var decidedStructure: BookmarkTreeNode? { switch self.structureState { case .unknown: return nil case .unchanged: return self.mirror case .remote: return self.remote case .local: return self.local case let .new(node): return node } } func asUnmergedTreeNode() -> BookmarkTreeNode { return self.decidedStructure ?? BookmarkTreeNode.unknown(guid: self.guid) } // Recursive. Starts returning Unknown when nodes haven't been processed. func asMergedTreeNode() -> BookmarkTreeNode { guard let decided = self.decidedStructure, let merged = self.mergedChildren else { return BookmarkTreeNode.unknown(guid: self.guid) } if case .folder = decided { let children = merged.map { $0.asMergedTreeNode() } return BookmarkTreeNode.folder(guid: self.guid, children: children) } return decided } var isFolder: Bool { return self.mergedChildren != nil } func dump(_ indent: Int) { precondition(indent < 200) let r: Character = "R" let l: Character = "L" let m: Character = "M" let ind = indenting(indent) print(ind, "[V: ", box(self.remote, r), box(self.mirror, m), box(self.local, l), self.guid, self.valueState.label, "]") guard self.isFolder else { return } print(ind, "[S: ", self.structureState.label, "]") if let children = self.mergedChildren { print(ind, " ..") for child in children { child.dump(indent + 2) } } } } private func box<T>(_ x: T?, _ c: Character) -> Character { if x == nil { return "□" } return c } private func indenting(_ by: Int) -> String { return String(repeating: " ", count: by) } class MergedTree { var root: MergedTreeNode var deleteLocally: Set<GUID> = Set() var deleteRemotely: Set<GUID> = Set() var deleteFromMirror: Set<GUID> = Set() var acceptLocalDeletion: Set<GUID> = Set() var acceptRemoteDeletion: Set<GUID> = Set() var allGUIDs: Set<GUID> { var out = Set<GUID>([self.root.guid]) func acc(_ node: MergedTreeNode) { guard let children = node.mergedChildren else { return } out.formUnion(Set(children.map { $0.guid })) children.forEach(acc) } acc(self.root) return out } init(mirrorRoot: BookmarkTreeNode) { self.root = MergedTreeNode(guid: mirrorRoot.recordGUID, mirror: mirrorRoot, structureState: MergeState.unchanged) self.root.valueState = MergeState.unchanged } func dump() { print("Deleted locally: \(self.deleteLocally.joined(separator: ", "))") print("Deleted remotely: \(self.deleteRemotely.joined(separator: ", "))") print("Deleted from mirror: \(self.deleteFromMirror.joined(separator: ", "))") print("Accepted local deletions: \(self.acceptLocalDeletion.joined(separator: ", "))") print("Accepted remote deletions: \(self.acceptRemoteDeletion.joined(separator: ", "))") print("Root: ") self.root.dump(0) } }
mpl-2.0
f68a0df1465b9941616b9991294347bb
31.597598
192
0.644219
4.740175
false
false
false
false
joutwate/jenkins_notifier
PasteableNSTextField.swift
1
1922
// // PasteableNSTextField.swift // JenkinsNotifier // // Created by Josh Outwater. // // import AppKit import Foundation /** */ class PasteableNSTextField : NSTextField { /** Overridden method of NSView. */ override func performKeyEquivalent(with theEvent: NSEvent) -> Bool { if (theEvent.type == .keyDown) && ((theEvent.modifierFlags.rawValue & NSEventModifierFlags.command.rawValue) != 0) { if let textView = self.window?.firstResponder as? NSTextView { let range = textView.selectedRange() let bHasSelectedTexts = range.length > 0 let keyCode: UInt16 = theEvent.keyCode var bHandled = false //0 A, 6 Z, 7 X, 8 C, 9 V if keyCode == 0 { textView.selectAll(self) bHandled = true } else if keyCode == 6 { if textView.undoManager?.canUndo ?? false { textView.undoManager?.undo() bHandled = true } } else if keyCode == 7 && bHasSelectedTexts { textView.cut(self) bHandled = true } else if keyCode == 8 && bHasSelectedTexts { textView.copy(self) bHandled = true } else if keyCode == 9 { textView.paste(self) bHandled = true } if bHandled { return true } } } return false } }
unlicense
22468700352ad1b1617240d2288f4883
25.328767
95
0.402185
5.987539
false
false
false
false
asynchrony/Re-Lax
ReLaxExample/JaggedEdgeViewController.swift
1
1898
import UIKit import ReLax class JaggedEdgeViewController: UIViewController { override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) tabBarItem = UITabBarItem(title: "Jagged Edge", image: nil, tag: 0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { let example = ParallaxView<DefaultContainer>(layerContainer: DefaultContainer(views: [ExampleView()])) guard let standard = UIImage(contentsOfFile: Bundle.main.path(forResource: "walle", ofType: "lcr")!) else { fatalError("standard LCR missing") } let parallaxParent = JaggedEdgeParentButton(standardLCR: standard, exampleView: example) view = parallaxParent view.backgroundColor = .darkGray } private var images: [UIImage] { return (1...5) .map { "\($0)" } .map { UIImage(contentsOfFile: Bundle.main.path(forResource: $0, ofType: "png")!)! } } private func generateLCR() -> UIImage? { let parallaxImage = ParallaxImage(images: Array(images.reversed())) return parallaxImage.image() } } class ExampleView: UIView { let border = UIView() let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) guard let image = UIImage(contentsOfFile: Bundle.main.path(forResource: "walle", ofType: "lcr")!) else { fatalError("walle LCR missing") } border.backgroundColor = .white imageView.backgroundColor = .black imageView.image = image imageView.adjustsImageWhenAncestorFocused = false addSubview(border) addSubview(imageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() border.frame = bounds.insetBy(dx: 1, dy: 1) imageView.frame = bounds.insetBy(dx: 4, dy: 4) } }
mit
6fed30d75bbe686461ce5122a79842c3
29.612903
146
0.722339
3.714286
false
false
false
false
buscarini/miscel
Miscel/Classes/Extensions/NSDate.swift
2
425
// // NSDate.swift // Miscel // // Created by Jose Manuel Sánchez Peñarroja on 29/3/16. // Copyright © 2016 vitaminew. All rights reserved. // import Foundation //public func ==(lhs: Date, rhs: Date) -> Bool { // return lhs === rhs || lhs.compare(rhs) == .OrderedSame //} // //public func <(lhs: Date, rhs: Date) -> Bool { // return lhs.compare(rhs) == .OrderedAscending //} //extension Date: Comparable { }
mit
eec852196f9f65a18a3515a309090bdc
20.1
60
0.625592
3.19697
false
false
false
false
lorentey/swift
test/expr/cast/dictionary_coerce.swift
29
1232
// RUN: %target-typecheck-verify-swift class C : Hashable { var x = 0 func hash(into hasher: inout Hasher) { hasher.combine(x) } } func == (x: C, y: C) -> Bool { return true } class D : C {} // Test dictionary upcasts var dictCC = Dictionary<C, C>() var dictCD = Dictionary<C, D>() var dictDC = Dictionary<D, C>() var dictDD = Dictionary<D, D>() dictCC = dictCD dictCC = dictDC dictCC = dictDD dictCD = dictDD dictCD = dictCC // expected-error{{cannot assign value of type '[C : C]' to type '[C : D]'}} // expected-note@-1 {{arguments to generic parameter 'Value' ('C' and 'D') are expected to be equal}} dictDC = dictDD dictDC = dictCD // expected-error {{cannot assign value of type '[C : D]' to type '[D : C]'}} // expected-note@-1 {{arguments to generic parameter 'Key' ('C' and 'D') are expected to be equal}} // expected-note@-2 {{arguments to generic parameter 'Value' ('D' and 'C') are expected to be equal}} dictDD = dictCC // expected-error{{cannot assign value of type '[C : C]' to type '[D : D]'}} // expected-note@-1 {{arguments to generic parameter 'Key' ('C' and 'D') are expected to be equal}} // expected-note@-2 {{arguments to generic parameter 'Value' ('C' and 'D') are expected to be equal}}
apache-2.0
9d67265fb4a99ad8fb04c5f131507431
31.421053
101
0.653409
3.233596
false
false
false
false
lorentey/swift
test/IRGen/objc_class_export.swift
8
6054
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend -sdk %S/Inputs -I %t -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop // CHECK-DAG: %swift.refcounted = type // CHECK-DAG: [[HOOZIT:%T17objc_class_export6HoozitC]] = type <{ [[REF:%swift.refcounted]] }> // CHECK-DAG: [[FOO:%T17objc_class_export3FooC]] = type <{ [[REF]], %TSi }> // CHECK-DAG: [[INT:%TSi]] = type <{ i64 }> // CHECK-DAG: [[DOUBLE:%TSd]] = type <{ double }> // CHECK-DAG: [[NSRECT:%TSo6NSRectV]] = type <{ %TSo7NSPointV, %TSo6NSSizeV }> // CHECK-DAG: [[NSPOINT:%TSo7NSPointV]] = type <{ %TSd, %TSd }> // CHECK-DAG: [[NSSIZE:%TSo6NSSizeV]] = type <{ %TSd, %TSd }> // CHECK: @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" = hidden global %objc_class { // CHECK-SAME: %objc_class* @"OBJC_METACLASS_$_{{(_TtCs12_)?}}SwiftObject", // CHECK-SAME: %objc_class* @"OBJC_METACLASS_$_{{(_TtCs12_)?}}SwiftObject", // CHECK-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-SAME: %swift.opaque* null, // CHECK-SAME: i64 ptrtoint ({{.*}}* @_METACLASS_DATA__TtC17objc_class_export3Foo to i64) // CHECK-SAME: } // CHECK: [[FOO_NAME:@.*]] = private unnamed_addr constant [28 x i8] c"_TtC17objc_class_export3Foo\00" // CHECK: @_METACLASS_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } { // CHECK-SAME: i32 129, // CHECK-SAME: i32 40, // CHECK-SAME: i32 40, // CHECK-SAME: i32 0, // CHECK-SAME: i8* null, // CHECK-SAME: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0), // CHECK-SAME: @_CLASS_METHODS__TtC17objc_class_export3Foo, // CHECK-SAME: i8* null, // CHECK-SAME: i8* null, // CHECK-SAME: i8* null, // CHECK-SAME: i8* null // CHECK-SAME: }, section "__DATA, __objc_const", align 8 // CHECK: @_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } { // CHECK-SAME: i32 128, // CHECK-SAME: i32 16, // CHECK-SAME: i32 24, // CHECK-SAME: i32 0, // CHECK-SAME: i8* null, // CHECK-SAME: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0), // CHECK-SAME: { i32, i32, [6 x { i8*, i8*, i8* }] }* @_INSTANCE_METHODS__TtC17objc_class_export3Foo, // CHECK-SAME: i8* null, // CHECK-SAME: @_IVARS__TtC17objc_class_export3Foo, // CHECK-SAME: i8* null, // CHECK-SAME: _PROPERTIES__TtC17objc_class_export3Foo // CHECK-SAME: }, section "__DATA, __objc_const", align 8 // CHECK: @"$s17objc_class_export3FooCMf" = internal global <{{.*}} }> <{ // CHECK-SAME: void ([[FOO]]*)* @"$s17objc_class_export3FooCfD", // CHECK-SAME: i8** @"$sBOWV", // CHECK-SAME: i64 ptrtoint (%objc_class* @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" to i64), // CHECK-SAME: %objc_class* @"OBJC_CLASS_$_{{(_TtCs12_)?}}SwiftObject", // CHECK-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-SAME: %swift.opaque* null, // CHECK-SAME: i64 add (i64 ptrtoint ({{.*}}* @_DATA__TtC17objc_class_export3Foo to i64), i64 {{1|2}}), // CHECK-SAME: [[FOO]]* (%swift.type*)* @"$s17objc_class_export3FooC6createACyFZ", // CHECK-SAME: void (double, double, double, double, [[FOO]]*)* @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tF" // CHECK-SAME: }>, section "__DATA,__objc_data, regular" // -- TODO: The OBJC_CLASS symbol should reflect the qualified runtime name of // Foo. // CHECK: @"$s17objc_class_export3FooCN" = hidden alias %swift.type, bitcast (i64* getelementptr inbounds ({{.*}} @"$s17objc_class_export3FooCMf", i32 0, i32 2) to %swift.type*) // CHECK: @"OBJC_CLASS_$__TtC17objc_class_export3Foo" = hidden alias %swift.type, %swift.type* @"$s17objc_class_export3FooCN" import gizmo class Hoozit {} struct BigStructWithNativeObjects { var x, y, w : Double var h : Hoozit } @objc class Foo { @objc var x = 0 @objc class func create() -> Foo { return Foo() } @objc func drawInRect(dirty dirty: NSRect) { } // CHECK: define internal void @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tFTo"([[OPAQUE:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE]]* %0 to [[FOO]]* // CHECK: call swiftcc void @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]]) // CHECK: } @objc func bounds() -> NSRect { return NSRect(origin: NSPoint(x: 0, y: 0), size: NSSize(width: 0, height: 0)) } // CHECK: define internal void @"$s17objc_class_export3FooC6boundsSo6NSRectVyFTo"([[NSRECT]]* noalias nocapture sret, [[OPAQUE4:%.*]]*, i8*) unnamed_addr {{.*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE4]]* %1 to [[FOO]]* // CHECK: call swiftcc { double, double, double, double } @"$s17objc_class_export3FooC6boundsSo6NSRectVyF"([[FOO]]* swiftself [[CAST]]) @objc func convertRectToBacking(r r: NSRect) -> NSRect { return r } // CHECK: define internal void @"$s17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tFTo"([[NSRECT]]* noalias nocapture sret, [[OPAQUE5:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE5]]* %1 to [[FOO]]* // CHECK: call swiftcc { double, double, double, double } @"$s17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]]) func doStuffToSwiftSlice(f f: [Int]) { } // This function is not representable in Objective-C, so don't emit the objc entry point. // CHECK-NOT: @"$s17objc_class_export3FooC19doStuffToSwiftSlice1fySaySiG_tcAAFTo" func doStuffToBigSwiftStruct(f f: BigStructWithNativeObjects) { } // This function is not representable in Objective-C, so don't emit the objc entry point. // CHECK-NOT: @_TToFC17objc_class_export3Foo23doStuffToBigSwiftStruct1ffS_FTV17objc_class_export27BigStructWithNativeObjects_T_ @objc init() { } }
apache-2.0
3e400ff1e736386362270baef42ef3d5
51.189655
219
0.641394
3.09351
false
false
false
false
DanielAsher/VIPER-SWIFT
VIPER-SWIFT/Classes/AppDependencies.swift
1
3707
// // AppDependencies.swift // VIPER TODO // // Created by Conrad Stoll on 6/4/14. // Copyright (c) 2014 Mutual Mobile. All rights reserved. // import Foundation import UIKit import RxSwift public class AppDependencies { public var listWireframe : ListWireframe var disposeBag = DisposeBag() init() { let coreDataStore = CoreDataStore() let clock = DeviceClock() let listDataManager = ListDataManager(coreDataStore: coreDataStore) let listInteractor = ListInteractor(dataManager: listDataManager, clock: clock) let listPresenter = ListPresenter(listInteractor: listInteractor) let addDataManager = AddDataManager(dataStore: coreDataStore) let addInteractor = AddInteractor(addDataManager: addDataManager) let addPresenter = AddPresenter(addInteractor: addInteractor, addModuleDelegate: listPresenter) //addPresenter //.events //.subscribeNext { event in //switch event { //case .DidSave: //listPresenter.addModuleDidSaveAddAction() //case .DidCancel: //listPresenter.addModuleDidCancelAddAction() //} //}.addDisposableTo(disposeBag) let rootWireframe = RootWireframe() let addWireframe = AddWireframe(addPresenter: addPresenter) listWireframe = ListWireframe(rootWireframe: rootWireframe, addWireframe: addWireframe, listPresenter: listPresenter) //addWireframe.addPresenter = addPresenter //listPresenter.listInteractor = listInteractor //listWireframe.addWireframe = addWireframe //addPresenter.addWireframe = addWireframe //listWireframe.rootWireframe = RootWireframe() //listDataManager.coreDataStore = coreDataStore //addInteractor.addDataManager = addDataManager //addPresenter.addModuleDelegate = listPresenter //addPresenter.addInteractor = addInteractor //addDataManager.dataStore = coreDataStore //configureDependencies() } func installRootViewControllerIntoWindow(window: UIWindow) { listWireframe.presentListInterfaceFromWindow(window) } func configureDependencies() { //let coreDataStore = CoreDataStore() //let clock = DeviceClock() //let rootWireframe = RootWireframe() //let listDataManager = ListDataManager() //let listInteractor = ListInteractor(dataManager: listDataManager, clock: clock) //let listPresenter = ListPresenter(listInteractor: listInteractor) //listPresenter.listWireframe = listWireframe //let addWireframe = AddWireframe() //let addInteractor = AddInteractor() //let addPresenter = AddPresenter() //let addDataManager = AddDataManager() ////listInteractor.listPresenter = listPresenter ////listPresenter.listInteractor = listInteractor //listWireframe.addWireframe = addWireframe //listWireframe.listPresenter = listPresenter //listWireframe.rootWireframe = rootWireframe //listDataManager.coreDataStore = coreDataStore //addInteractor.addDataManager = addDataManager //addWireframe.addPresenter = addPresenter //addPresenter.addWireframe = addWireframe //addPresenter.addModuleDelegate = listPresenter //addPresenter.addInteractor = addInteractor //addDataManager.dataStore = coreDataStore } }
mit
24106087760bd2993abb8feabf869a88
33.018349
125
0.646345
6.679279
false
false
false
false
Juan-Sanchez/Supporting_Classes
TempCoreDataStack.swift
1
1088
// // TempCoreDataStack.swift // Created by juan sanchez on 4/12/17. // import Foundation import CoreData class TempCoreDataStack { fileprivate var context: NSManagedObjectContext? init() { context = nil let managedObjectModel = NSManagedObjectModel.mergedModel(from: [Bundle.main])! let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) do { try persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil) context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context?.persistentStoreCoordinator = persistentStoreCoordinator print("TempCoreDataStack successfully created in memory store") } catch { print("ERROR: TempCoreDataStack failed to create in memory store") } } func getContext() -> NSManagedObjectContext? { return self.context } }
mit
330f175350a136a1045568f1c15625f8
29.222222
137
0.660846
6.325581
false
false
false
false
jkolb/Asheron
Sources/Asheron/Region.swift
1
23455
/* The MIT License (MIT) Copyright (c) 2020 Justin Kolb 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. */ public final class Region : Identifiable { public var id: Identifier public var regionNumber: UInt32 public var version: UInt32 public var regionName: String // ReadPString "Dereth" align if needed afterwards public var landDefs: LandDefs public var gameTime: GameTime public var partsMask: PartsMask // 0x21F = 10 0001 1111 // public var minimizePal: UInt32 public var fileInfo: FileNameDesc = FileNameDesc() public var skyInfo: SkyDesc? public var soundInfo: SoundDesc? public var sceneInfo: SceneDesc? public var terrainInfo: TerrainDesc? public var encounterInfo: EncounterDesc? public var waterInfo: WaterDesc? public var fogInfo: FogDesc? public var distFogInfo: DistanceFogDesc? public var regionMapInfo: RegionMapDesc? public var regionMisc: RegionMisc? public struct PartsMask : OptionSet, Packable { public static let hasSound = PartsMask(rawValue: 0b0000000001) public static let hasScene = PartsMask(rawValue: 0b0000000010) public static let hasTerrain = PartsMask(rawValue: 0b0000000100) public static let hasEncounter = PartsMask(rawValue: 0b0000001000) public static let hasSky = PartsMask(rawValue: 0b0000010000) public static let hasWater = PartsMask(rawValue: 0b0000100000) public static let hasFog = PartsMask(rawValue: 0b0001000000) public static let hasDistFog = PartsMask(rawValue: 0b0010000000) public static let hasRegionMap = PartsMask(rawValue: 0b0100000000) public static let hasMisc = PartsMask(rawValue: 0b1000000000) public let rawValue: UInt32 public init(rawValue: UInt32) { self.rawValue = rawValue } } public init(from dataStream: DataStream, id: Identifier) { let diskId = Identifier(from: dataStream) precondition(diskId == id) self.id = id self.regionNumber = UInt32(from: dataStream) self.version = UInt32(from: dataStream) self.regionName = String(from: dataStream) self.landDefs = LandDefs(from: dataStream) self.gameTime = GameTime(from: dataStream) self.partsMask = PartsMask(from: dataStream) self.skyInfo = partsMask.contains(.hasSky) ? SkyDesc(from: dataStream) : nil self.soundInfo = partsMask.contains(.hasSound) ? SoundDesc(from: dataStream) : nil self.sceneInfo = partsMask.contains(.hasScene) ? SceneDesc(from: dataStream) : nil self.terrainInfo = partsMask.contains(.hasTerrain) ? TerrainDesc(from: dataStream) : nil self.encounterInfo = partsMask.contains(.hasEncounter) ? EncounterDesc(from: dataStream) : nil self.waterInfo = partsMask.contains(.hasWater) ? WaterDesc(from: dataStream) : nil self.fogInfo = partsMask.contains(.hasFog) ? FogDesc(from: dataStream) : nil self.distFogInfo = partsMask.contains(.hasDistFog) ? DistanceFogDesc(from: dataStream) : nil self.regionMapInfo = partsMask.contains(.hasRegionMap) ? RegionMapDesc(from: dataStream) : nil self.regionMisc = partsMask.contains(.hasMisc) ? RegionMisc(from: dataStream) : nil } } // 0x00012692 public struct SkyDesc : Packable { //public var presentDayGroup: UInt32 public var tickSize: Float64 public var lightTickSize: Float64 public var dayGroups: [DayGroup] public init(from dataStream: DataStream) { self.tickSize = Float64(from: dataStream) self.lightTickSize = Float64(from: dataStream) self.dayGroups = [DayGroup](from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct SkyTimeOfDay : Packable { public var begin: Float32 public var dirBright: Float32 public var dirHeading: Float32 public var dirPitch: Float32 public var dirColor: ARGB8888 public var ambBright: Float32 public var ambColor: ARGB8888 public var minWorldFog: Float32 public var maxWorldFog: Float32 public var worldFogColor: ARGB8888 public var worldFog: UInt32 public var skyObjReplace: [SkyObjectReplace] public init(from dataStream: DataStream) { self.begin = Float32(from: dataStream) self.dirBright = Float32(from: dataStream) self.dirHeading = Float32(from: dataStream) self.dirPitch = Float32(from: dataStream) self.dirColor = ARGB8888(from: dataStream) self.ambBright = Float32(from: dataStream) self.ambColor = ARGB8888(from: dataStream) self.minWorldFog = Float32(from: dataStream) self.maxWorldFog = Float32(from: dataStream) self.worldFogColor = ARGB8888(from: dataStream) self.worldFog = UInt32(from: dataStream) self.skyObjReplace = [SkyObjectReplace](from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct SkyObject : Packable { //public var objectName: String = "" // Not in file public var beginTime: Float32 public var endTime: Float32 public var beginAngle: Float32 public var endAngle: Float32 public var texVelocity: Vector3 public var defaultGFXObject: Identifier public var defaultPesObject: Identifier public var properties: UInt32 public init(from dataStream: DataStream) { self.beginTime = Float32(from: dataStream) self.endTime = Float32(from: dataStream) self.beginAngle = Float32(from: dataStream) self.endAngle = Float32(from: dataStream) let texVelocityX = Float32(from: dataStream) let texVelocityY = Float32(from: dataStream) self.texVelocity = Vector3(x: texVelocityX, y: texVelocityY, z: 0.0) self.defaultGFXObject = Identifier(from: dataStream) self.defaultPesObject = Identifier(from: dataStream) self.properties = UInt32(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct SkyObjectReplace : Packable { public var objectIndex: UInt32 public var gfxObjID: Identifier public var rotate: Float32 public var transparent: Float32 public var luminosity: Float32 public var maxBright: Float32 //public var object: UInt32 // Temp public init(from dataStream: DataStream) { self.objectIndex = UInt32(from: dataStream) self.gfxObjID = Identifier(from: dataStream) self.rotate = Float32(from: dataStream) self.transparent = Float32(from: dataStream) self.luminosity = Float32(from: dataStream) self.maxBright = Float32(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct TMTerrainDesc : Packable { public var terrainType: LandDefs.TerrainType public var terrainTex: TerrainTex // PDB says -> [TerrainTex], but there isn't a count public init(from dataStream: DataStream) { self.terrainType = LandDefs.TerrainType(from: dataStream) self.terrainTex = TerrainTex(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct TexMerge : Packable { public var baseTexSize: UInt32 public var cornerTerrainMaps: [TerrainAlphaMap] public var sideTerrainMaps: [TerrainAlphaMap] public var roadMaps: [RoadAlphaMap] public var terrainDesc: [TMTerrainDesc] public init(from dataStream: DataStream) { self.baseTexSize = UInt32(from: dataStream) self.cornerTerrainMaps = [TerrainAlphaMap](from: dataStream) self.sideTerrainMaps = [TerrainAlphaMap](from: dataStream) self.roadMaps = [RoadAlphaMap](from: dataStream) self.terrainDesc = [TMTerrainDesc](from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct TerrainTex : Packable { public var tex: Identifier // These two are in PDB but not file? // public let baseTexture: UInt32 // type = 0x7920 // public let minSlope: Float32 public var texTiling: UInt32 public var maxVertBright: UInt32 public var minVertBright: UInt32 public var maxVertSaturate: UInt32 public var minVertSaturate: UInt32 public var maxVertHue: UInt32 public var minVertHue: UInt32 public var detailTexTiling: UInt32 public var detailTex: Identifier public init(from dataStream: DataStream) { self.tex = Identifier(from: dataStream) self.texTiling = UInt32(from: dataStream) self.maxVertBright = UInt32(from: dataStream) self.minVertBright = UInt32(from: dataStream) self.maxVertSaturate = UInt32(from: dataStream) self.minVertSaturate = UInt32(from: dataStream) self.maxVertHue = UInt32(from: dataStream) self.minVertHue = UInt32(from: dataStream) self.detailTexTiling = UInt32(from: dataStream) self.detailTex = Identifier(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public enum RCode : UInt32, Packable { case corner = 8 case straight = 9 case diagonal = 10 } public enum TCode : UInt32, Packable { case corner = 8 case straight = 9 case diagonal = 10 } public struct TerrainAlphaMap : Packable { public var tcode: TCode public var tex: Identifier public init(from dataStream: DataStream) { self.tcode = TCode(from: dataStream) self.tex = Identifier(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct RoadAlphaMap : Packable { public var rcode: RCode public var roadTex: Identifier public init(from dataStream: DataStream) { self.rcode = RCode(from: dataStream) self.roadTex = Identifier(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } // 0x0001269d public struct RegionMisc : Packable { public var version: UInt32 public var gameMap: Identifier public var autotestMap: Identifier public var autotestMapSize: UInt32 public var clearCell: UInt32 // identifier? public var clearMonster: UInt32 // identifier? public init(from dataStream: DataStream) { self.version = UInt32(from: dataStream) self.gameMap = Identifier(from: dataStream) self.autotestMap = Identifier(from: dataStream) self.autotestMapSize = UInt32(from: dataStream) self.clearCell = UInt32(from: dataStream) self.clearMonster = UInt32(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } // Empty definitions in PDB public struct RegionMapDesc : Packable { public init() {} public init(from dataStream: DataStream) { self.init() } @inlinable public func encode(to dataStream: DataStream) { } } // Empty definition in PDB public struct WaterDesc : Packable { public init() {} public init(from dataStream: DataStream) { self.init() } @inlinable public func encode(to dataStream: DataStream) { } } // 0x00012507 public struct TerrainDesc : Packable { public var terrainTypes: [TerrainType] public var landSurfaces: LandSurf public init(from dataStream: DataStream) { self.terrainTypes = [TerrainType](from: dataStream) self.landSurfaces = LandSurf(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public enum LandSurf : Packable { case palShift(PalShift) case texMerge(TexMerge) public init(from dataStream: DataStream) { let isPalShift = Bool(from: dataStream) if isPalShift { let palShift = PalShift(from: dataStream) self = .palShift(palShift) } else { let texMerge = TexMerge(from: dataStream) self = .texMerge(texMerge) } } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } // Not defining as it is not in the files I have public struct PalShift : Packable { public init() {} public init(from dataStream: DataStream) { self.init() } @inlinable public func encode(to dataStream: DataStream) { } } public struct TerrainType : Packable { public var terrainName: String public var terrainColor: ARGB8888 public var sceneTypeIndex: [Int32] public init(from dataStream: DataStream) { self.terrainName = String(from: dataStream) self.terrainColor = ARGB8888(from: dataStream) self.sceneTypeIndex = [Int32](from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct GameTime : Packable { public var zeroTimeOfYear: Float64 public var zeroYear: UInt32 public var dayLength: Float32 public var daysPerYear: UInt32 public var yearSpec: String // ?? PString public var timesOfDay: [TimeOfDay] // ?? public var daysOfTheWeek: [WeekDay] // ?? public var seasons: [Season] // ?? // public var yearLength: Float64 = day_length * days_per_year // public var presentTimeOfDay: Float32 // public var timeOfDayBegin: Float64 // public var timeOfNextEvent: Float64 // more public init(from dataStream: DataStream) { self.zeroTimeOfYear = Float64(from: dataStream) self.zeroYear = UInt32(from: dataStream) self.dayLength = Float32(from: dataStream) self.daysPerYear = UInt32(from: dataStream) self.yearSpec = String(from: dataStream) self.timesOfDay = [TimeOfDay](from: dataStream) self.daysOfTheWeek = [WeekDay](from: dataStream) self.seasons = [Season](from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct TimeOfDay : Packable { public var begin: Float32 public var isNight: Bool public var timeOfDayName: String public init(from dataStream: DataStream) { self.begin = Float32(from: dataStream) self.isNight = Bool(from: dataStream) self.timeOfDayName = String(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct WeekDay : Packable { public let weekDayName: String public init(from dataStream: DataStream) { self.weekDayName = String(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct Season : Packable { public let begin: UInt32 public let seasonName: String public init(from dataStream: DataStream) { self.begin = UInt32(from: dataStream) self.seasonName = String(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } // Empty definition in PDB public struct FogDesc : Packable { public init() {} public init(from dataStream: DataStream) { self.init() } @inlinable public func encode(to dataStream: DataStream) { } } public struct FileNameDesc : Packable { // 0x00015f96 public init() {} public init(from dataStream: DataStream) { self.init() } @inlinable public func encode(to dataStream: DataStream) { } } public struct LandDefs : Packable { public enum Direction : UInt32, Packable { case inViewerBlock = 0 case northOfViewer = 1 case southOfViewer = 2 case eastOfViewer = 3 case westOfViewer = 4 case northWestOfViewer = 5 case southWestOfViewer = 6 case northEastOfViewer = 7 case southEastOfViewer = 8 case unknown = 9 } public enum Rotation : UInt32, Packable { case rot0 = 0 case rot90 = 1 case rot180 = 2 case rot270 = 3 } public enum PalType : UInt32, Packable { case swTerrain = 0 case seTerrain = 1 case neTerrain = 2 case nwTerrain = 3 case road = 4 } public enum WaterType : UInt32, Packable { case notWater = 0 case partiallyWater = 1 case entirelyWater = 2 } public enum TerrainType : UInt32, Packable { case barrenRock = 0 case grassland = 1 case ice = 2 case lushGrass = 3 case marshSparseSwamp = 4 case mudRichDirt = 5 case obsidianPlain = 6 case packedDirt = 7 case patchyDirt = 8 case patchyGrassland = 9 case sandYellow = 10 case sandGrey = 11 case sandRockStrewn = 12 case sedimentaryRock = 13 case semiBarrenRock = 14 case snow = 15 case waterRunning = 16 case waterStandingFresh = 17 case waterShallowSea = 18 case waterShallowStillSea = 19 case waterDeepSea = 20 case reserved21 = 21 case reserved22 = 22 case reserved23 = 23 case reserved24 = 24 case reserved25 = 25 case reserved26 = 26 case reserved27 = 27 case reserved28 = 28 case reserved29 = 29 case reserved30 = 30 case reserved31 = 31 case roadType = 32 } public let numBlockLength: UInt32 // 255 (0-254) public let numBlockWidth: UInt32 // 255 (0-254) public let squareLength: Float32 // 24.0 public let lblockSide: UInt32 // 8 (8 * 24.0 = 192.0) public let vertexPerCell: UInt32 // 1 (overlap??) public let maxObjHeight: Float32 // 200.0 public let skyHeight: Float32 // 1000.0 public let roadWidth: Float32 // 5.0 public let landHeightTable: [Float32] // 256 values public init(from dataStream: DataStream) { self.numBlockLength = UInt32(from: dataStream) self.numBlockWidth = UInt32(from: dataStream) self.squareLength = Float32(from: dataStream) self.lblockSide = UInt32(from: dataStream) self.vertexPerCell = UInt32(from: dataStream) self.maxObjHeight = Float32(from: dataStream) self.skyHeight = Float32(from: dataStream) self.roadWidth = Float32(from: dataStream) self.landHeightTable = [Float32](from: dataStream, count: 256) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct EncounterDesc : Packable { // 0x00015fa7 public init() {} public init(from dataStream: DataStream) { self.init() } @inlinable public func encode(to dataStream: DataStream) { } } public struct DayGroup : Packable { public var chanceOfOccur: Float public var dayName: String public var skyObjects: [SkyObject] public var skyTime: [SkyTimeOfDay] public init(from dataStream: DataStream) { self.chanceOfOccur = Float32(from: dataStream) self.dayName = String(from: dataStream) self.skyObjects = [SkyObject](from: dataStream) self.skyTime = [SkyTimeOfDay](from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } // Empty definition in PDB public struct DistanceFogDesc : Packable { public init() {} public init(from dataStream: DataStream) { self.init() } @inlinable public func encode(to dataStream: DataStream) { } } public struct SceneDesc : Packable { public var sceneTypes: [SceneType] public init(from dataStream: DataStream) { self.sceneTypes = [SceneType](from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct SceneType : Packable { // public var sceneName: String public var stbIndex: UInt32 public var scenes: [Identifier] // public var soundTableDesc: AmbientSTBDesc? public init(from dataStream: DataStream) { self.stbIndex = UInt32(from: dataStream) self.scenes = [Identifier](from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct SoundDesc : Packable { public var stbDesc: [AmbientSTBDesc] public init(from dataStream: DataStream) { self.stbDesc = [AmbientSTBDesc](from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct AmbientSoundDesc : Packable { public var stype: SoundType public var volume: Float32 public var baseChance: Float32 public var isContinuous: Bool { return baseChance == 0.0 } public var minRate: Float32 public var maxRate: Float32 public init(from dataStream: DataStream) { self.stype = SoundType(from: dataStream) self.volume = Float32(from: dataStream) self.baseChance = Float32(from: dataStream) self.minRate = Float32(from: dataStream) self.maxRate = Float32(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct AmbientSTBDesc : Packable { public var stbId: Identifier public var ambientSounds: [AmbientSoundDesc] public init(from dataStream: DataStream) { self.stbId = Identifier(from: dataStream) self.ambientSounds = [AmbientSoundDesc](from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } }
mit
962e20feca7703a45a6f48e4e5dc3163
31.531207
102
0.666169
4.30604
false
false
false
false
LYM-mg/DemoTest
其他功能/SwiftyDemo/SwiftyDemo/MGImageCompressTool.swift
1
4393
// // MGImageCompressTool.swift // SwiftyDemo // // Created by newunion on 2020/3/2. // Copyright © 2020 firestonetmt. All rights reserved. // import UIKit class MGImageCompressTool: NSObject { // MARK: - 降低质量 func resetSizeOfImageData(source_image: UIImage!, maxSize: Int) -> NSData { //先判断当前质量是否满足要求,不满足再进行压缩 var finallImageData = source_image.jpegData(compressionQuality: 1.0) let sizeOrigin = finallImageData?.count let sizeOriginKB = sizeOrigin! / 1024 if sizeOriginKB <= maxSize { return finallImageData! as NSData } //先调整分辨率 var defaultSize = CGSize(width: 1024, height: 1024) let newImage = self.newSizeImage(size: defaultSize, source_image: source_image) finallImageData = newImage.jpegData(compressionQuality: 1.0); //保存压缩系数 let compressionQualityArr = NSMutableArray() let avg = CGFloat(1.0/250) var value = avg var i = 250 repeat { i -= 1 value = CGFloat(i)*avg compressionQualityArr.add(value) } while i >= 1 /* 调整大小 说明:压缩系数数组compressionQualityArr是从大到小存储。 */ //思路:使用二分法搜索 finallImageData = self.halfFuntion(arr: compressionQualityArr.copy() as! [CGFloat], image: newImage, sourceData: finallImageData!, maxSize: maxSize) //如果还是未能压缩到指定大小,则进行降分辨率 while finallImageData?.count == 0 { //每次降100分辨率 if defaultSize.width-100 <= 0 || defaultSize.height-100 <= 0 { break } defaultSize = CGSize(width: defaultSize.width-100, height: defaultSize.height-100) let image = self.newSizeImage(size: defaultSize, source_image: UIImage.init(data: newImage.jpegData(compressionQuality: compressionQualityArr.lastObject as! CGFloat)!)!) finallImageData = self.halfFuntion(arr: compressionQualityArr.copy() as! [CGFloat], image: image, sourceData: image.jpegData(compressionQuality: 1.0)!, maxSize: maxSize) } return finallImageData! as NSData } // MARK: - 调整图片分辨率/尺寸(等比例缩放) func newSizeImage(size: CGSize, source_image: UIImage) -> UIImage { var newSize = CGSize(width: source_image.size.width, height: source_image.size.height) let tempHeight = newSize.height / size.height let tempWidth = newSize.width / size.width if tempWidth > 1.0 && tempWidth > tempHeight { newSize = CGSize(width: source_image.size.width / tempWidth, height: source_image.size.height / tempWidth) } else if tempHeight > 1.0 && tempWidth < tempHeight { newSize = CGSize(width: source_image.size.width / tempHeight, height: source_image.size.height / tempHeight) } UIGraphicsBeginImageContext(newSize) source_image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } // MARK: - 二分法 func halfFuntion(arr: [CGFloat], image: UIImage, sourceData finallImageData: Data, maxSize: Int) -> Data? { var tempFinallImageData = finallImageData var tempData = Data.init() var start = 0 var end = arr.count - 1 var index = 0 var difference = Int.max while start <= end { index = start + (end - start)/2 tempFinallImageData = image.jpegData(compressionQuality: arr[index])! let sizeOrigin = tempFinallImageData.count let sizeOriginKB = sizeOrigin / 1024 print("当前降到的质量:\(sizeOriginKB)\n\(index)----\(arr[index])") if sizeOriginKB > maxSize { start = index + 1 } else if sizeOriginKB < maxSize { if maxSize-sizeOriginKB < difference { difference = maxSize-sizeOriginKB tempData = tempFinallImageData } end = index - 1 } else { break } } return tempData } }
mit
a7f1008955e364c4c42e3fdd5b8786e1
41.742268
181
0.611674
4.458065
false
false
false
false
sora0077/qiita-app-infra
QiitaInfra/src/Repository/User/UserListRepository.swift
1
5809
// // UserListRepository.swift // QiitaInfra // // Created by 林達也 on 2015/11/28. // Copyright © 2015年 jp.sora0077. All rights reserved. // import Foundation import QiitaKit import BrightFutures import RealmSwift import QueryKit import QiitaDomainInterface final class UserListRepositoryUtil<Entity: RefUserListEntityProtocol, Token: QiitaRequestToken where Entity: Object, Token: LinkProtocol, Token.Response == ([User], LinkMeta<Token>)> { private let session: QiitaSession private let query: NSPredicate private let versionProvider: Realm -> Int private let entityProvider: (Realm, Token.Response) -> Entity private let tokenProvider: Int? -> Token private var running: Future<[UserProtocol], QiitaInfraError>? init(session: QiitaSession, query: NSPredicate, versionProvider: Realm -> Int, entityProvider: (Realm, Token.Response) -> Entity, tokenProvider: Int? -> Token) { self.session = session self.query = query self.versionProvider = versionProvider self.entityProvider = entityProvider self.tokenProvider = tokenProvider } func values() throws -> [UserProtocol] { let realm = try GetRealm() guard let list = realm.objects(Entity).filter(query).first else { return [] } var ret: [UserEntity] = [] for p in list.pages { for u in p.users { if !ret.contains(u) { ret.append(u) } } } return ret } func update(force: Bool) -> Future<[UserProtocol], QiitaInfraError> { func future() -> Future<[UserProtocol], QiitaInfraError> { let update = _update return running.map { $0.flatMap { _ in update(force) } } ?? update(force) } let f = future() running = f return f } private func _update(force: Bool) -> Future<[UserProtocol], QiitaInfraError> { let query = self.query let version = self.versionProvider let entityProvider = self.entityProvider let tokenProvider = self.tokenProvider func check() -> Future<(Token, Bool)?, QiitaInfraError> { return realm { let realm = try GetRealm() let results = realm.objects(Entity).filter(query) guard let list = results.filter(Entity.ttl > Entity.ttlLimit || Entity.version == version(realm)).first else { return (tokenProvider(nil), true) } guard let page = list.pages.last?.next_page.value else { return nil } return (tokenProvider(page), false) } } func fetch(token: Token, isNew: Bool) -> Future<[UserProtocol], QiitaInfraError> { return session.request(token) .mapError(QiitaInfraError.QiitaAPIError) .flatMap { res in realm { let realm = try GetRealm() realm.beginWrite() let results = realm.objects(Entity).filter(query) if isNew { realm.delete(results.flatMap { $0.pages.map { $0 } }) realm.delete(results) } let entity: Entity if let list = results.first where !isNew { entity = list let page = RefUserListPageEntity.create(realm, res) realm.add(page) entity.pages.append(page) entity.ttl = NSDate() realm.add(entity, update: true) } else { entity = entityProvider(realm, res) realm.add(entity, update: true) } entity.version = version(realm) try realm.commitWrite() var ret: [UserEntity] = [] for p in entity.pages { for u in p.users { if !ret.contains(u) { ret.append(u) } } } return ret } } } func get(_: [UserProtocol] = []) -> Future<[UserProtocol], QiitaInfraError> { return Realm.read() .mapError(QiitaInfraError.RealmError) .map { realm in guard let page = realm.objects(Entity).filter(query).first?.pages.last else { return [] } var ret: [UserEntity] = [] for u in page.users { if !ret.contains(u) { ret.append(u) } } return ret } } if force { return fetch(tokenProvider(nil), isNew: true).flatMap(get) } return check().flatMap { res -> Future<[UserProtocol], QiitaInfraError> in guard let (token, isNew) = res else { return Future(value: []) } return fetch(token, isNew: isNew) }.flatMap(get) } }
mit
d0036750522a1ed9fdee9cf180a0fee1
34.365854
184
0.464138
5.587669
false
false
false
false
kdawgwilk/vapor
Sources/Vapor/Session/MemorySessionDriver.swift
1
1867
import libc import class Base.Lock /** The `MemorySessionDriver` stores session data in a Swift `Dictionary`. This means all session data will be purged if the server is restarted. */ public class MemorySessions: Sessions { var sessions = [String: [String: String]]() private var sessionsLock = Lock() public var hash: Hash public init(hash: Hash) { self.hash = hash } /** Loads value for session id at given key */ public func value(for key: String, identifier: String) -> String? { var value: String? sessionsLock.locked { value = sessions[identifier]?[key] } return value } /** Sets value for session id at given key */ public func set(_ value: String?, for key: String, identifier: String) { sessionsLock.locked { if sessions[identifier] == nil { sessions[identifier] = [String: String]() } sessions[identifier]?[key] = value } } /** Returns true if the identifier is in use. */ public func contains(identifier: String) -> Bool { return sessions[identifier] != nil } /** Create new unique session id */ public func makeIdentifier() -> String { var identifier = String(time(nil)) identifier += "v@p0r" identifier += String(Int.random(min: 0, max: 9999)) identifier += "s3sS10n" identifier += String(Int.random(min: 0, max: 9999)) identifier += "k3y" identifier += String(Int.random(min: 0, max: 9999)) return hash.make(identifier) } /** Destroys session with associated identifier */ public func destroy(_ identifier: String) { sessionsLock.locked { sessions[identifier] = nil } } }
mit
345d99bd5796a14fab719666ce59400d
24.930556
76
0.574719
4.413712
false
false
false
false
ahoppen/swift
SwiftCompilerSources/Sources/Optimizer/PassManager/PassContext.swift
1
8090
//===--- PassContext.swift - defines the PassContext type -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SIL import OptimizerBridging public typealias BridgedFunctionPassCtxt = OptimizerBridging.BridgedFunctionPassCtxt public typealias BridgedInstructionPassCtxt = OptimizerBridging.BridgedInstructionPassCtxt struct PassContext { let _bridged: BridgedPassContext func continueWithNextSubpassRun(for inst: Instruction? = nil) -> Bool { let bridgedInst = OptionalBridgedInstruction(obj: inst?.bridged.obj) return PassContext_continueWithNextSubpassRun(_bridged, bridgedInst) != 0 } //===--------------------------------------------------------------------===// // Analysis //===--------------------------------------------------------------------===// var aliasAnalysis: AliasAnalysis { let bridgedAA = PassContext_getAliasAnalysis(_bridged) return AliasAnalysis(bridged: bridgedAA) } var calleeAnalysis: CalleeAnalysis { let bridgeCA = PassContext_getCalleeAnalysis(_bridged) return CalleeAnalysis(bridged: bridgeCA) } var deadEndBlocks: DeadEndBlocksAnalysis { let bridgeDEA = PassContext_getDeadEndBlocksAnalysis(_bridged) return DeadEndBlocksAnalysis(bridged: bridgeDEA) } var dominatorTree: DominatorTree { let bridgedDT = PassContext_getDomTree(_bridged) return DominatorTree(bridged: bridgedDT) } var postDominatorTree: PostDominatorTree { let bridgedPDT = PassContext_getPostDomTree(_bridged) return PostDominatorTree(bridged: bridgedPDT) } //===--------------------------------------------------------------------===// // Interaction with AST and the SIL module //===--------------------------------------------------------------------===// func getContextSubstitutionMap(for type: Type) -> SubstitutionMap { SubstitutionMap(PassContext_getContextSubstitutionMap(_bridged, type.bridged)) } func loadFunction(name: StaticString) -> Function? { return name.withUTF8Buffer { (nameBuffer: UnsafeBufferPointer<UInt8>) in PassContext_loadFunction(_bridged, BridgedStringRef(data: nameBuffer.baseAddress, length: nameBuffer.count)).function } } //===--------------------------------------------------------------------===// // Modify SIL //===--------------------------------------------------------------------===// /// Splits the basic block, which contains `inst`, before `inst` and returns the /// new block. /// /// `inst` and all subsequent instructions are moved to the new block, while all /// instructions _before_ `inst` remain in the original block. func splitBlock(at inst: Instruction) -> BasicBlock { notifyBranchesChanged() return PassContext_splitBlock(inst.bridged).block } enum EraseMode { case onlyInstruction, includingDebugUses } func erase(instruction: Instruction, _ mode: EraseMode = .onlyInstruction) { switch mode { case .onlyInstruction: break case .includingDebugUses: for result in instruction.results { for use in result.uses { assert(use.instruction is DebugValueInst) PassContext_eraseInstruction(_bridged, use.instruction.bridged) } } } if instruction is FullApplySite { notifyCallsChanged() } if instruction is TermInst { notifyBranchesChanged() } notifyInstructionsChanged() PassContext_eraseInstruction(_bridged, instruction.bridged) } func fixStackNesting(function: Function) { PassContext_fixStackNesting(_bridged, function.bridged) } func modifyEffects(in function: Function, _ body: (inout FunctionEffects) -> ()) { function._modifyEffects(body) // TODO: do we need to notify any changes? } //===--------------------------------------------------------------------===// // Private utilities //===--------------------------------------------------------------------===// fileprivate func notifyInstructionsChanged() { PassContext_notifyChanges(_bridged, instructionsChanged) } fileprivate func notifyCallsChanged() { PassContext_notifyChanges(_bridged, callsChanged) } fileprivate func notifyBranchesChanged() { PassContext_notifyChanges(_bridged, branchesChanged) } } //===----------------------------------------------------------------------===// // Builder initialization //===----------------------------------------------------------------------===// extension Builder { /// Creates a builder which inserts _before_ `insPnt`, using a custom `location`. init(at insPnt: Instruction, location: Location, _ context: PassContext) { self.init(insertAt: .before(insPnt), location: location, passContext: context._bridged) } /// Creates a builder which inserts _before_ `insPnt`, using the location of `insPnt`. init(at insPnt: Instruction, _ context: PassContext) { self.init(insertAt: .before(insPnt), location: insPnt.location, passContext: context._bridged) } /// Creates a builder which inserts _after_ `insPnt`, using the location of `insPnt`. init(after insPnt: Instruction, _ context: PassContext) { if let nextInst = insPnt.next { self.init(insertAt: .before(nextInst), location: insPnt.location, passContext: context._bridged) } else { self.init(insertAt: .atEndOf(insPnt.block), location: insPnt.location, passContext: context._bridged) } } /// Creates a builder which inserts at the end of `block`, using a custom `location`. init(atEndOf block: BasicBlock, location: Location, _ context: PassContext) { self.init(insertAt: .atEndOf(block), location: location, passContext: context._bridged) } /// Creates a builder which inserts at the begin of `block`, using the location of the first /// instruction of `block`. init(atBeginOf block: BasicBlock, _ context: PassContext) { let firstInst = block.instructions.first! self.init(insertAt: .before(firstInst), location: firstInst.location, passContext: context._bridged) } } //===----------------------------------------------------------------------===// // Modifying the SIL //===----------------------------------------------------------------------===// extension BasicBlock { func addBlockArgument(type: Type, ownership: Ownership, _ context: PassContext) -> BlockArgument { context.notifyInstructionsChanged() return SILBasicBlock_addBlockArgument(bridged, type.bridged, ownership._bridged).blockArgument } func eraseArgument(at index: Int, _ context: PassContext) { context.notifyInstructionsChanged() SILBasicBlock_eraseArgument(bridged, index) } } extension AllocRefInstBase { func setIsStackAllocatable(_ context: PassContext) { context.notifyInstructionsChanged() AllocRefInstBase_setIsStackAllocatable(bridged) } } extension UseList { func replaceAll(with replacement: Value, _ context: PassContext) { for use in self { use.instruction.setOperand(at: use.index, to: replacement, context) } } } extension Instruction { func setOperand(at index : Int, to value: Value, _ context: PassContext) { if self is FullApplySite && index == ApplyOperands.calleeOperandIndex { context.notifyCallsChanged() } context.notifyInstructionsChanged() SILInstruction_setOperand(bridged, index, value.bridged) } } extension RefCountingInst { func setAtomicity(isAtomic: Bool, _ context: PassContext) { context.notifyInstructionsChanged() RefCountingInst_setIsAtomic(bridged, isAtomic) } }
apache-2.0
461a9977732100e4daa676fe22c2fe26
34.955556
123
0.619901
5.120253
false
false
false
false
USAssignmentWarehouse/EnglishNow
EnglishNow/AppDelegate.swift
1
4580
// // AppDelegate.swift // EnglishNow // // Created by Nha T.Tran on 5/18/17. // Copyright © 2017 IceTeaViet. All rights reserved. // import UIKit import CoreData import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FirebaseClient.configure() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. //self.saveContext() } // MARK: - Core Data stack /* lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "EnglishNow") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } }*/ }
apache-2.0
4035bf220100bf9d30a2cd5508a9f683
47.712766
285
0.684647
5.818297
false
false
false
false
katsana/katsana-sdk-ios
KatsanaSDK/Manager/AddressRequest.swift
1
6075
// // AddressRequest.swift // KatsanaSDK // // Created by Wan Ahmad Lutfi on 18/10/2016. // Copyright © 2016 pixelated. All rights reserved. // import CoreLocation /// Class to request address from server. We are not using Siesta API because Siesta cache response in memory. Address may be called multiple times and we need to cache in KMKTCacheManager to save it in hdd class AddressRequest: NSObject { class func requestAddress(for location:CLLocationCoordinate2D, completion: @escaping (KTAddress?, Error?) -> Void) -> Void { KTCacheManager.shared.address(for: location) { (address) in if address != nil{ completion(address, nil) }else{ self.appleGeoAddress(from: location, completion: { (address) in KTCacheManager.shared.cache(address: address) completion(address, nil) let optimizedAddress = address.optimizedAddress() var useAppleAddress = true let comps = optimizedAddress.components(separatedBy: ",") if let first = comps.first{ if first.count < 2{ useAppleAddress = false } } if (optimizedAddress.count) <= 10 || !useAppleAddress, let handler = KatsanaAPI.shared.addressHandler{ handler(location, {googleAddress in if let googleAddress = googleAddress{ KTCacheManager.shared.cache(address: googleAddress) completion(googleAddress, nil) }else{ completion(address, nil) } }) }else{ KTCacheManager.shared.cache(address: address) completion(address, nil) } }, failure: { (error) in if let handler = KatsanaAPI.shared.addressHandler{ handler(location, {address in if let address = address{ completion(address, nil) }else{ completion(nil, error) } }) }else{ completion(nil, error) } }) } } } class func platformGeoAddress(from location:CLLocationCoordinate2D, completion:@escaping (KTAddress) -> Void, failure: @escaping (_ error: Error?) -> Void = {_ in }) -> Void { let path = KatsanaAPI.shared.baseURL().absoluteString + "address/" let latitude = String(format: "%.6f", location.latitude) let longitude = String(format: "%.6f", location.longitude) Just.get( path, params: ["latitude" : latitude, "longitude" : longitude] ) { r in if r.ok { let content = r.content let json = JSON(data: content!) if json != JSON.null{ let address = ObjectJSONTransformer.AddressObject(json: json) DispatchQueue.main.sync{completion(address)} }else{ DispatchQueue.main.sync{failure(nil)} } }else{ DispatchQueue.main.sync{failure(r.APIError())} } } } class func appleGeoAddress(from location:CLLocationCoordinate2D, completion:@escaping (KTAddress) -> Void, failure: @escaping (_ error: Error?) -> Void = {_ in }) -> Void { let geocoder = CLGeocoder() let clLocation = CLLocation(latitude: location.latitude, longitude: location.longitude) geocoder.reverseGeocodeLocation(clLocation, completionHandler: { (placemarks, error) in if let error = error{ failure(error) }else{ if let dicto = placemarks?.first?.addressDictionary{ let address = KTAddress() address.latitude = location.latitude address.longitude = location.longitude address.streetName = dicto["Street"] as? String let postcode = dicto["ZIP"] as? String if let postcode = postcode, let postcodeInt = Int(postcode){ address.postcode = postcodeInt } address.country = dicto["Country"] as? String address.city = dicto["City"] as? String address.state = dicto["State"] as? String address.sublocality = dicto["SubLocality"] as? String address.locality = dicto["Locality"] as? String address.state = dicto["State"] as? String address.subAdministrativeArea = dicto["SubAdministrativeArea"] as? String var addressComps = dicto["FormattedAddressLines"] as? [String] addressComps?.removeLast() let addressStr = addressComps?.joined(separator: ", ") address.address = addressStr completion(address) } } }) } // let address = Address() // address.latitude = json["latitude"].doubleValue // address.longitude = json["longitude"].doubleValue // let streetNumber = json["street_number"].stringValue // address.streetNumber = streetNumber // address.streetName = json["street_name"].stringValue // address.locality = json["locality"].stringValue // address.sublocality = json["sublocality"].stringValue // address.postcode = json["postcode"].intValue // address.country = json["country"].stringValue // address.address = json["address"].stringValue }
apache-2.0
b643a211648e0b1ea955d0903eaf9a05
45.015152
206
0.520086
5.432916
false
false
false
false
mightydeveloper/swift
test/Constraints/generics.swift
10
3960
// RUN: %target-parse-verify-swift infix operator +++ {} protocol ConcatToAnything { func +++ <T>(lhs: Self, other: T) } func min<T : Comparable>(x: T, y: T) -> T { if y < x { return y } return x } func weirdConcat<T : ConcatToAnything, U>(t: T, u: U) { t +++ u t +++ 1 u +++ t // expected-error{{binary operator '+++' cannot be applied to operands of type 'U' and 'T'}} // expected-note @-1 {{expected an argument list of type '(Self, T)'}} } // Make sure that the protocol operators don't get in the way. var b1, b2 : Bool _ = b1 != b2 extension UnicodeScalar { func isAlpha2() -> Bool { return (self >= "A" && self <= "Z") || (self >= "a" && self <= "z") } } protocol P { static func foo(arg: Self) -> Self } struct S : P { static func foo(arg: S) -> S { return arg } } func foo<T : P>(arg: T) -> T { return T.foo(arg) } // Associated types and metatypes protocol SomeProtocol { typealias SomeAssociated } func generic_metatypes<T : SomeProtocol>(x: T) -> (T.Type, T.SomeAssociated.Type) { return (x.dynamicType, x.dynamicType.SomeAssociated.self) } // Inferring a variable's type from a call to a generic. struct Pair<T, U> { } func pair<T, U>(x: T, _ y: U) -> Pair<T, U> { } var i : Int, f : Float var p = pair(i, f) // Conformance constraints on static variables. func f1<S1 : SequenceType>(s1: S1) {} var x : Array<Int> = [1] f1(x) // Inheritance involving generics and non-generics. class X { func f() {} } class Foo<T> : X { func g() { } } class Y<U> : Foo<Int> { } func genericAndNongenericBases(x: Foo<Int>, y: Y<()>) { x.f() y.f() y.g() } func genericAndNongenericBasesTypeParameter<T : Y<()>>(t: T) { t.f() t.g() } protocol P1 {} protocol P2 {} func foo<T : P1>(t: T) -> P2 { return t // expected-error{{return expression of type 'T' does not conform to 'P2'}} } func foo2(p1: P1) -> P2 { return p1 // expected-error{{return expression of type 'P1' does not conform to 'P2'}} } // <rdar://problem/14005696> protocol BinaryMethodWorkaround { typealias MySelf } protocol Squigglable : BinaryMethodWorkaround { } infix operator ~~~ { } func ~~~ <T : Squigglable where T.MySelf == T>(lhs: T, rhs: T) -> Bool { return true } extension UInt8 : Squigglable { typealias MySelf = UInt8 } var rdar14005696 : UInt8 rdar14005696 ~~~ 5 // <rdar://problem/15168483> func f1< S: CollectionType where S.Index: BidirectionalIndexType >(seq: S) { let x = (seq.indices).lazy.reverse() PermutationGenerator(elements: seq, indices: x) // expected-warning{{unused}} PermutationGenerator(elements: seq, indices: seq.indices.reverse()) // expected-warning{{unused}} } // <rdar://problem/16078944> func count16078944<C: CollectionType>(x: C) -> Int { return 0 } func test16078944 <T: ForwardIndexType>(lhs: T, args: T) -> Int { return count16078944(lhs..<args) // don't crash } // <rdar://problem/22409190> QoI: Passing unsigned integer to ManagedBuffer elements.destroy() class r22409190ManagedBuffer<Value, Element> { final var value: Value { get {} set {}} func withUnsafeMutablePointerToElements<R>( body: (UnsafeMutablePointer<Element>)->R) -> R { } } class MyArrayBuffer<Element>: r22409190ManagedBuffer<UInt, Element> { deinit { self.withUnsafeMutablePointerToElements { elems->Void in elems.destroy(self.value) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} } } } // <rdar://problem/22459135> error: 'print' is unavailable: Please wrap your tuple argument in parentheses: 'print((...))' func r22459135() { func h<S: SequenceType where S.Generator.Element: IntegerType> (sequence: S) -> S.Generator.Element { return 0 } func g(x: Any) {} func f(x: Int) { g(h([3])) } func f2<TargetType: AnyObject>(target: TargetType, handler: TargetType -> ()) { let _: AnyObject -> () = { internalTarget in handler(internalTarget as! TargetType) } } }
apache-2.0
3134d55230be5167d28b13e52aed866b
21.890173
122
0.645202
3.201293
false
false
false
false
material-motion/motion-animator-objc
examples/TapToBounceTraitsExample.swift
2
2775
/* Copyright 2017-present The Material Motion Authors. 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 import MotionAnimator // This demo shows how to use animation traits to define the timings for an animation. class TapToBounceTraitsExampleViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let circle = UIButton() circle.bounds = CGRect(x: 0, y: 0, width: 128, height: 128) circle.center = view.center circle.layer.cornerRadius = circle.bounds.width / 2 circle.layer.borderColor = UIColor(red: (CGFloat)(0x88) / 255.0, green: (CGFloat)(0xEF) / 255.0, blue: (CGFloat)(0xAA) / 255.0, alpha: 1).cgColor circle.backgroundColor = UIColor(red: (CGFloat)(0xEF) / 255.0, green: (CGFloat)(0x88) / 255.0, blue: (CGFloat)(0xAA) / 255.0, alpha: 1) view.addSubview(circle) circle.addTarget(self, action: #selector(didFocus), for: [.touchDown, .touchDragEnter]) circle.addTarget(self, action: #selector(didUnfocus), for: [.touchUpInside, .touchUpOutside, .touchDragExit]) } let traits = MDMAnimationTraits(delay: 0, duration: 0.5, timingCurve: MDMSpringTimingCurve(mass: 1, tension: 100, friction: 10)) @objc func didFocus(_ sender: UIButton) { let animator = MotionAnimator() animator.animate(with: traits) { sender.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) // This would normally not be animatable with the UIView animation APIs, but it is animatable // with the motion animator. sender.layer.borderWidth = 10 } } @objc func didUnfocus(_ sender: UIButton) { let animator = MotionAnimator() animator.animate(with: traits) { sender.transform = .identity sender.layer.borderWidth = 0 } } }
apache-2.0
367704bceb51dee6a06053815615031f
37.013699
99
0.594595
4.711375
false
false
false
false
exyte/Macaw
Source/views/ShapeLayer.swift
1
1385
import Foundation #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif class ShapeLayer: CAShapeLayer { weak var renderer: NodeRenderer? var shouldRenderContent = true var isForceRenderingEnabled = true override func draw(in ctx: CGContext) { if !shouldRenderContent { super.draw(in: ctx) return } renderer?.directRender(in: ctx, force: isForceRenderingEnabled) } } extension ShapeLayer { func setupStrokeAndFill(_ shape: Shape) { // Stroke if let stroke = shape.stroke { if let color = stroke.fill as? Color { strokeColor = color.toCG() } else { strokeColor = MColor.black.cgColor } lineWidth = CGFloat(stroke.width) lineCap = MCAShapeLayerLineCap.mapToGraphics(model: stroke.cap) lineJoin = MCAShapeLayerLineJoin.mapToGraphics(model: stroke.join) lineDashPattern = stroke.dashes.map { NSNumber(value: $0) } lineDashPhase = CGFloat(stroke.offset) } else if shape.fill == nil { strokeColor = MColor.black.cgColor lineWidth = 1.0 } // Fill if let color = shape.fill as? Color { fillColor = color.toCG() } else { fillColor = MColor.clear.cgColor } } }
mit
61adab16de3829140c8ba02159c2710c
24.648148
78
0.581949
4.467742
false
false
false
false
MateuszKarwat/Napi
Napi/Extensions/NSMenuItem.swift
1
1567
// // MenuItemFactory.swift // Napi // // Created by Mateusz Karwat on 28/09/2018. // Copyright © 2018 Mateusz Karwat. All rights reserved. // import AppKit extension NSMenuItem { static func downloadSubtitles(target: AnyObject, action: Selector) -> NSMenuItem { let menu = NSMenu() for subtitleProvider in SupportedSubtitleProvider.allValues { let providerMenuItem = NSMenuItem(title: subtitleProvider.instance.name, action: action, keyEquivalent: "") providerMenuItem.target = target providerMenuItem.representedObject = subtitleProvider menu.addItem(providerMenuItem) } let menuItem = NSMenuItem(title: "StatusBar_Download_Subtitles".localized, action: nil, keyEquivalent: "") menuItem.submenu = menu return menuItem } static func showApplication(target: AnyObject, action: Selector) -> NSMenuItem { let menuItem = NSMenuItem(title: "StatusBar_Show_Napi".localized, action: action, keyEquivalent: "") menuItem.target = target return menuItem } static func quitApplication() -> NSMenuItem { return NSMenuItem(title: "StatusBar_Quit_Napi".localized, action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q") } }
mit
f2c439451816d2573d4a6942dd1deb9d
33.8
86
0.560664
5.694545
false
false
false
false
LimCrazy/SwiftProject3.0-Master
SwiftPreject-Master/SwiftPreject-Master/Class/CustomNavigationVC.swift
1
2363
// // CustomNavigationVC.swift // SwiftPreject-Master // // Created by lim on 2016/12/11. // Copyright © 2016年 Lim. All rights reserved. // import UIKit class CustomNavigationVC: UINavigationController { let imageExtension = YM_ImageExtension() override func viewDidLoad() { super.viewDidLoad() // setup(bar: self) } public func setup(bar:UINavigationController) -> () { //黑色导航栏 bar.navigationBar.barTintColor = kNavColor //修改导航栏按钮颜色和文字大小 //bar.navigationBar.tintColor = UIColor.white let dict = [NSForegroundColorAttributeName:UIColor.white,NSFontAttributeName:UIFont.systemFont(ofSize: 20)] //修改导航栏文字颜色 bar.navigationBar.titleTextAttributes = dict //修改状态栏文字白色 UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent } //透明导航栏 public func setTranslucent(bar:UINavigationController) -> () { //设置标题颜色 let dict = [NSForegroundColorAttributeName:UIColor.clear,NSFontAttributeName:UIFont.systemFont(ofSize: 20)] //修改导航栏文字颜色 bar.navigationBar.titleTextAttributes = dict bar.navigationBar.setBackgroundImage(UIImage(), for:.default) //设置导航栏按钮颜色 bar.navigationBar.tintColor = UIColor.black //设置背景空图片 bar.navigationBar.shadowImage = UIImage() //导航栏透明 bar.navigationBar.isTranslucent = true } override func pushViewController(_ viewController: UIViewController, animated: Bool) { viewController.hidesBottomBarWhenPushed = true if self.viewControllers.count > 0 { let vc = self.viewControllers[self.viewControllers.count - 1] print(vc) //自定义返回按钮 let backBtn = UIBarButtonItem(title: "返回", style: .plain, target: nil, action: nil) vc.navigationItem.backBarButtonItem = backBtn } super.pushViewController(viewController, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
106870c8061605ca7efd967b5efd03dd
32.121212
115
0.645471
5.095571
false
false
false
false
uasys/swift
test/SILGen/specialize_attr.swift
4
4852
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -emit-verbose-sil %s | %FileCheck %s // CHECK-LABEL: @_specialize(exported: false, kind: full, where T == Int, U == Float) // CHECK-NEXT: func specializeThis<T, U>(_ t: T, u: U) @_specialize(where T == Int, U == Float) func specializeThis<T, U>(_ t: T, u: U) {} public protocol PP { associatedtype PElt } public protocol QQ { associatedtype QElt } public struct RR : PP { public typealias PElt = Float } public struct SS : QQ { public typealias QElt = Int } public struct GG<T : PP> {} // CHECK-LABEL: public class CC<T> where T : PP { // CHECK-NEXT: @_specialize(exported: false, kind: full, where T == RR, U == SS) // CHECK-NEXT: @inline(never) public func foo<U>(_ u: U, g: GG<T>) -> (U, GG<T>) where U : QQ public class CC<T : PP> { @inline(never) @_specialize(where T == RR, U == SS) public func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) { return (u, g) } } // CHECK-LABEL: sil hidden [_specialize exported: false, kind: full, where T == Int, U == Float] @_T015specialize_attr0A4Thisyx_q_1utr0_lF : $@convention(thin) <T, U> (@in T, @in U) -> () { // CHECK-LABEL: sil [noinline] [_specialize exported: false, kind: full, where T == RR, U == SS] @_T015specialize_attr2CCC3fooqd___AA2GGVyxGtqd___AG1gtAA2QQRd__lF : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) { // ----------------------------------------------------------------------------- // Test user-specialized subscript accessors. public protocol TestSubscriptable { associatedtype Element subscript(i: Int) -> Element { get set } } public class ASubscriptable<Element> : TestSubscriptable { var storage: UnsafeMutablePointer<Element> init(capacity: Int) { storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity) } public subscript(i: Int) -> Element { @_specialize(where Element == Int) get { return storage[i] } @_specialize(where Element == Int) set(rhs) { storage[i] = rhs } } } // ASubscriptable.subscript.getter with _specialize // CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr14ASubscriptableCxSicig : $@convention(method) <Element> (Int, @guaranteed ASubscriptable<Element>) -> @out Element { // ASubscriptable.subscript.setter with _specialize // CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr14ASubscriptableCxSicis : $@convention(method) <Element> (@in Element, Int, @guaranteed ASubscriptable<Element>) -> () { // ASubscriptable.subscript.materializeForSet with no attribute // CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr14ASubscriptableCxSicim : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed ASubscriptable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { public class Addressable<Element> : TestSubscriptable { var storage: UnsafeMutablePointer<Element> init(capacity: Int) { storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity) } public subscript(i: Int) -> Element { @_specialize(where Element == Int) unsafeAddress { return UnsafePointer<Element>(storage + i) } @_specialize(where Element == Int) unsafeMutableAddress { return UnsafeMutablePointer<Element>(storage + i) } } } // Addressable.subscript.getter with no attribute // CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr11AddressableCxSicig : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> @out Element { // Addressable.subscript.unsafeAddressor with _specialize // CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr11AddressableCxSicilu : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafePointer<Element> { // Addressable.subscript.setter with no attribute // CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr11AddressableCxSicis : $@convention(method) <Element> (@in Element, Int, @guaranteed Addressable<Element>) -> () { // Addressable.subscript.unsafeMutableAddressor with _specialize // CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr11AddressableCxSiciau : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafeMutablePointer<Element> { // Addressable.subscript.materializeForSet with no attribute // CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr11AddressableCxSicim : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed Addressable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
apache-2.0
723263f9f17bcfb7499f506a87efc73f
43.925926
277
0.69765
3.814465
false
false
false
false
steryokhin/AsciiArtPlayer
src/AsciiArtPlayer/Pods/DKImagePickerController/DKImagePickerController/DKImagePickerController.swift
1
18378
// // DKImagePickerController.swift // DKImagePickerController // // Created by ZhangAo on 14-10-2. // Copyright (c) 2014年 ZhangAo. All rights reserved. // import UIKit import Photos @objc public protocol DKImagePickerControllerCameraProtocol { func setDidCancel(block: @escaping () -> Void) -> Void func setDidFinishCapturingImage(block: @escaping (_ image: UIImage) -> Void) -> Void func setDidFinishCapturingVideo(block: @escaping (_ videoURL: URL) -> Void) -> Void } @objc public protocol DKImagePickerControllerUIDelegate { /** The picker calls -prepareLayout once at its first layout as the first message to the UIDelegate instance. */ func prepareLayout(_ imagePickerController: DKImagePickerController, vc: UIViewController) /** Returns a custom camera. **Note** If you are using a UINavigationController as the custom camera, you should also set the picker's modalPresentationStyle to .overCurrentContext, like this: ``` pickerController.modalPresentationStyle = .overCurrentContext ``` - Parameter imagePickerController: DKImagePickerController - Returns: The returned `UIViewControlelr` must conform to the `DKImagePickerControllerCameraProtocol`. */ func imagePickerControllerCreateCamera(_ imagePickerController: DKImagePickerController) -> UIViewController @available(*, deprecated: 1.0, message: "Use imagePickerControllerCreateCamera(_:) instead.") @objc optional func imagePickerControllerCreateCamera(_ imagePickerController: DKImagePickerController, didCancel: @escaping (() -> Void), didFinishCapturingImage: @escaping ((_ image: UIImage) -> Void), didFinishCapturingVideo: @escaping ((_ videoURL: URL) -> Void)) -> UIViewController /** The layout is to provide information about the position and visual state of items in the collection view. */ func layoutForImagePickerController(_ imagePickerController: DKImagePickerController) -> UICollectionViewLayout.Type /** Called when the user needs to show the cancel button. */ func imagePickerController(_ imagePickerController: DKImagePickerController, showsCancelButtonForVC vc: UIViewController) /** Called when the user needs to hide the cancel button. */ func imagePickerController(_ imagePickerController: DKImagePickerController, hidesCancelButtonForVC vc: UIViewController) /** Called after the user changes the selection. */ func imagePickerController(_ imagePickerController: DKImagePickerController, didSelectAssets: [DKAsset]) /** Called after the user changes the selection. */ func imagePickerController(_ imagePickerController: DKImagePickerController, didDeselectAssets: [DKAsset]) /** Called when the count of the selectedAssets did reach `maxSelectableCount`. */ func imagePickerControllerDidReachMaxLimit(_ imagePickerController: DKImagePickerController) /** Accessory view below content. default is nil. */ func imagePickerControllerFooterView(_ imagePickerController: DKImagePickerController) -> UIView? /** Set the color of the background of the collection view. */ func imagePickerControllerCollectionViewBackgroundColor() -> UIColor func imagePickerControllerCollectionImageCell() -> DKAssetGroupDetailBaseCell.Type func imagePickerControllerCollectionCameraCell() -> DKAssetGroupDetailBaseCell.Type func imagePickerControllerCollectionVideoCell() -> DKAssetGroupDetailBaseCell.Type } /** - AllPhotos: Get all photos assets in the assets group. - AllVideos: Get all video assets in the assets group. - AllAssets: Get all assets in the group. */ @objc public enum DKImagePickerControllerAssetType : Int { case allPhotos, allVideos, allAssets } @objc public enum DKImagePickerControllerSourceType : Int { case camera, photo, both } // MARK: - Public DKImagePickerController /** * The `DKImagePickerController` class offers the all public APIs which will affect the UI. */ open class DKImagePickerController : UINavigationController { lazy public var UIDelegate: DKImagePickerControllerUIDelegate = { return DKImagePickerControllerDefaultUIDelegate() }() /// Forces deselect of previous selected image public var singleSelect = false /// Auto close picker on single select public var autoCloseOnSingleSelect = true /// The maximum count of assets which the user will be able to select. public var maxSelectableCount = 999 /// Set the defaultAssetGroup to specify which album is the default asset group. public var defaultAssetGroup: PHAssetCollectionSubtype? /// The types of PHAssetCollection to display in the picker. public var assetGroupTypes: [PHAssetCollectionSubtype] = [ .smartAlbumUserLibrary, .smartAlbumFavorites, .albumRegular ] { willSet(newTypes) { getImageManager().groupDataManager.assetGroupTypes = newTypes } } /// Set the showsEmptyAlbums to specify whether or not the empty albums is shown in the picker. public var showsEmptyAlbums = true { didSet { getImageManager().groupDataManager.showsEmptyAlbums = self.showsEmptyAlbums } } public var assetFilter: ((_ asset: PHAsset) -> Bool)? { didSet { getImageManager().groupDataManager.assetFilter = self.assetFilter } } /// The type of picker interface to be displayed by the controller. public var assetType: DKImagePickerControllerAssetType = .allAssets { didSet { getImageManager().groupDataManager.assetFetchOptions = self.createAssetFetchOptions() } } /// The predicate applies to images only. public var imageFetchPredicate: NSPredicate? { didSet { getImageManager().groupDataManager.assetFetchOptions = self.createAssetFetchOptions() } } /// The predicate applies to videos only. public var videoFetchPredicate: NSPredicate? { didSet { getImageManager().groupDataManager.assetFetchOptions = self.createAssetFetchOptions() } } /// If sourceType is Camera will cause the assetType & maxSelectableCount & allowMultipleTypes & defaultSelectedAssets to be ignored. public var sourceType: DKImagePickerControllerSourceType = .both { didSet { /// If source type changed in the scenario of sharing instance, view controller should be reinitialized. if(oldValue != sourceType) { self.hasInitialized = false } } } /// Whether allows to select photos and videos at the same time. public var allowMultipleTypes = true /// If YES, and the requested image is not stored on the local device, the Picker downloads the image from iCloud. public var autoDownloadWhenAssetIsInCloud = true { didSet { getImageManager().autoDownloadWhenAssetIsInCloud = self.autoDownloadWhenAssetIsInCloud } } /// Determines whether or not the rotation is enabled. public var allowsLandscape = false /// The callback block is executed when user pressed the cancel button. public var didCancel: (() -> Void)? public var showsCancelButton = false { didSet { if let rootVC = self.viewControllers.first { self.updateCancelButtonForVC(rootVC) } } } /// The callback block is executed when user pressed the select button. public var didSelectAssets: ((_ assets: [DKAsset]) -> Void)? /// It will have selected the specific assets. public var defaultSelectedAssets: [DKAsset]? { didSet { if let count = self.defaultSelectedAssets?.count, count != self.selectedAssets.count { self.selectedAssets = self.defaultSelectedAssets ?? [] if let rootVC = self.viewControllers.first as? DKAssetGroupDetailVC { rootVC.collectionView.reloadData() } } } } public var selectedAssets = [DKAsset]() public convenience init() { let rootVC = UIViewController() self.init(rootViewController: rootVC) self.preferredContentSize = CGSize(width: 680, height: 600) rootVC.navigationItem.hidesBackButton = true getImageManager().groupDataManager.assetGroupTypes = self.assetGroupTypes getImageManager().groupDataManager.assetFetchOptions = self.createAssetFetchOptions() getImageManager().groupDataManager.showsEmptyAlbums = self.showsEmptyAlbums getImageManager().autoDownloadWhenAssetIsInCloud = self.autoDownloadWhenAssetIsInCloud } deinit { NotificationCenter.default.removeObserver(self) getImageManager().invalidate() } override open func viewDidLoad() { super.viewDidLoad() } private var hasInitialized = false override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !hasInitialized { hasInitialized = true if self.sourceType == .camera { self.isNavigationBarHidden = true let camera = self.createCamera() if camera is UINavigationController { self.present(camera, animated: true, completion: nil) self.setViewControllers([], animated: false) } else { self.setViewControllers([camera], animated: false) } } else { self.isNavigationBarHidden = false let rootVC = DKAssetGroupDetailVC() rootVC.imagePickerController = self self.UIDelegate.prepareLayout(self, vc: rootVC) self.updateCancelButtonForVC(rootVC) self.setViewControllers([rootVC], animated: false) if let count = self.defaultSelectedAssets?.count, count > 0 { self.UIDelegate.imagePickerController(self, didSelectAssets: [self.defaultSelectedAssets!.last!]) } } } } private lazy var assetFetchOptions: PHFetchOptions = { let assetFetchOptions = PHFetchOptions() return assetFetchOptions }() private func createAssetFetchOptions() -> PHFetchOptions? { let createImagePredicate = { () -> NSPredicate in var imagePredicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.image.rawValue) if let imageFetchPredicate = self.imageFetchPredicate { imagePredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [imagePredicate, imageFetchPredicate]) } return imagePredicate } let createVideoPredicate = { () -> NSPredicate in var videoPredicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.video.rawValue) if let videoFetchPredicate = self.videoFetchPredicate { videoPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [videoPredicate, videoFetchPredicate]) } return videoPredicate } var predicate: NSPredicate? switch self.assetType { case .allAssets: predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [createImagePredicate(), createVideoPredicate()]) case .allPhotos: predicate = createImagePredicate() case .allVideos: predicate = createVideoPredicate() } self.assetFetchOptions.predicate = predicate return self.assetFetchOptions } private func updateCancelButtonForVC(_ vc: UIViewController) { if self.showsCancelButton { self.UIDelegate.imagePickerController(self, showsCancelButtonForVC: vc) } else { self.UIDelegate.imagePickerController(self, hidesCancelButtonForVC: vc) } } private func createCamera() -> UIViewController { let didCancel = { [unowned self] () in if self.sourceType == .camera { if (self.presentedViewController != nil) { self.dismiss(animated: false, completion: nil) } self.dismiss(animated: true) } else { self.dismiss(animated: true, completion: nil) } } let didFinishCapturingImage = { [unowned self] (image: UIImage) in var newImageIdentifier: String! PHPhotoLibrary.shared().performChanges({ let assetRequest = PHAssetChangeRequest.creationRequestForAsset(from: image) newImageIdentifier = assetRequest.placeholderForCreatedAsset!.localIdentifier }) { [weak self] (success, error) in DispatchQueue.main.async(execute: { [weak self] in if success { if let newAsset = PHAsset.fetchAssets(withLocalIdentifiers: [newImageIdentifier], options: nil).firstObject { if self?.presentedViewController != nil { self?.dismiss(animated: true, completion: nil) } self?.selectImage(DKAsset(originalAsset: newAsset)) } } else { if self?.sourceType != .camera { self?.dismiss(animated: true, completion: nil) } self?.selectImage(DKAsset(image: image)) } }) } } let didFinishCapturingVideo = { [unowned self] (videoURL: URL) in var newVideoIdentifier: String! PHPhotoLibrary.shared().performChanges({ let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL) newVideoIdentifier = assetRequest?.placeholderForCreatedAsset?.localIdentifier }) { (success, error) in DispatchQueue.main.async(execute: { if success { if let newAsset = PHAsset.fetchAssets(withLocalIdentifiers: [newVideoIdentifier], options: nil).firstObject { if self.sourceType != .camera || self.viewControllers.count == 0 { self.dismiss(animated: true, completion: nil) } self.selectImage(DKAsset(originalAsset: newAsset)) } } else { self.dismiss(animated: true, completion: nil) } }) } } let camera = self.UIDelegate.imagePickerControllerCreateCamera(self) let cameraProtocol = camera as! DKImagePickerControllerCameraProtocol cameraProtocol.setDidCancel(block: didCancel) cameraProtocol.setDidFinishCapturingImage(block: didFinishCapturingImage) cameraProtocol.setDidFinishCapturingVideo(block: didFinishCapturingVideo) return camera } internal func presentCamera() { self.present(self.createCamera(), animated: true, completion: nil) } open func dismiss() { self.dismiss(animated: true) } open func dismiss(animated flag: Bool) { self.presentingViewController?.dismiss(animated: flag, completion: { self.didCancel?() }) } open func done() { self.presentingViewController?.dismiss(animated: true, completion: { self.didSelectAssets?(self.selectedAssets) }) } // MARK: - Selection public func deselectAssetAtIndex(_ index: Int) { let asset = self.selectedAssets[index] self.deselectAsset(asset) } public func deselectAsset(_ asset: DKAsset) { self.deselectImage(asset) if let rootVC = self.viewControllers.first as? DKAssetGroupDetailVC { rootVC.collectionView?.reloadData() } } public func deselectAllAssets() { if self.selectedAssets.count > 0 { let assets = self.selectedAssets self.selectedAssets.removeAll() self.UIDelegate.imagePickerController(self, didDeselectAssets: assets) if let rootVC = self.viewControllers.first as? DKAssetGroupDetailVC { rootVC.collectionView?.reloadData() } } } internal func selectImage(_ asset: DKAsset) { if self.singleSelect { self.deselectAllAssets() self.selectedAssets.append(asset) if autoCloseOnSingleSelect { self.done() } } else { self.selectedAssets.append(asset) if self.sourceType == .camera { self.done() } else { self.UIDelegate.imagePickerController(self, didSelectAssets: [asset]) } } } internal func deselectImage(_ asset: DKAsset) { self.selectedAssets.remove(at: selectedAssets.index(of: asset)!) self.UIDelegate.imagePickerController(self, didDeselectAssets: [asset]) } // MARK: - Handles Orientation open override var shouldAutorotate : Bool { return self.allowsLandscape && self.sourceType != .camera ? true : false } open override var supportedInterfaceOrientations : UIInterfaceOrientationMask { if self.allowsLandscape { return super.supportedInterfaceOrientations } else { return UIInterfaceOrientationMask.portrait } } }
mit
b4bf4a2c1931976c13d5d3b5846ddec6
36.88866
141
0.623476
6.07672
false
false
false
false
HarrisLee/SwiftBook
Swift-ZhihuDaily-master/util/YRHttpRequest.swift
1
1628
// // YRHttpRequest.swift // JokeClient-Swift // // Created by YANGReal on 14-6-5. // Copyright (c) 2014年 YANGReal. All rights reserved. // import UIKit import Foundation //class func connectionWithRequest(request: NSURLRequest!, delegate: AnyObject!) -> NSURLConnection! class YRHttpRequest: NSObject { override init() { super.init(); } class func requestWithURL(urlString:String,completionHandler:(data:AnyObject)->Void) { let URL = NSURL(string:urlString) let req = NSMutableURLRequest(URL:URL!) req.setValue("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:29.0) Gecko/20100101 Firefox/29.0",forHTTPHeaderField:"User-Agent") let queue = NSOperationQueue(); NSURLConnection.sendAsynchronousRequest(req, queue: queue, completionHandler: { response, data, error in if (error != nil) { dispatch_async(dispatch_get_main_queue(), { print(error) completionHandler(data:NSNull()) }) } else { do { let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary dispatch_async(dispatch_get_main_queue(), { completionHandler(data:jsonData) }) } catch { } } }) } }
mit
094fcc48c5c4f7ee8ffbc95c6b925e9a
27.526316
150
0.52583
5.228296
false
false
false
false
nathawes/swift
stdlib/public/Darwin/Foundation/String.swift
9
3811
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module @_spi(Foundation) import Swift //===----------------------------------------------------------------------===// // New Strings //===----------------------------------------------------------------------===// // // Conversion from NSString to Swift's native representation // extension String { public init(_ cocoaString: NSString) { self = String(_cocoaString: cocoaString) } } extension String : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSString { // This method should not do anything extra except calling into the // implementation inside core. (These two entry points should be // equivalent.) return unsafeBitCast(_bridgeToObjectiveCImpl(), to: NSString.self) } public static func _forceBridgeFromObjectiveC( _ x: NSString, result: inout String? ) { result = String(x) } public static func _conditionallyBridgeFromObjectiveC( _ x: NSString, result: inout String? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return result != nil } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC( _ source: NSString? ) -> String { // `nil` has historically been used as a stand-in for an empty // string; map it to an empty string. if _slowPath(source == nil) { return String() } return String(source!) } } extension Substring : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSString { return String(self)._bridgeToObjectiveC() } public static func _forceBridgeFromObjectiveC( _ x: NSString, result: inout Substring? ) { let s = String(x) result = s[...] } public static func _conditionallyBridgeFromObjectiveC( _ x: NSString, result: inout Substring? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return result != nil } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC( _ source: NSString? ) -> Substring { // `nil` has historically been used as a stand-in for an empty // string; map it to an empty substring. if _slowPath(source == nil) { return Substring() } let s = String(source!) return s[...] } } extension String: CVarArg {} /* This is on NSObject so that the stdlib can call it in StringBridge.swift without having to synthesize a receiver (e.g. lookup a class or allocate) In the future (once the Foundation overlay can know about SmallString), we should move the caller of this method up into the overlay and avoid this indirection. */ private extension NSObject { // The ObjC selector has to start with "new" to get ARC to not autorelease @_effects(releasenone) @objc(newTaggedNSStringWithASCIIBytes_:length_:) func createTaggedString(bytes: UnsafePointer<UInt8>, count: Int) -> AnyObject? { //TODO: update this to use _CFStringCreateTaggedPointerString once we can return CFStringCreateWithBytes( kCFAllocatorSystemDefault, bytes, count, CFStringBuiltInEncodings.UTF8.rawValue, false ) as NSString as NSString? //just "as AnyObject" inserts unwanted bridging } }
apache-2.0
8b580c16576582f9d753f1d3eb03439c
29.733871
80
0.63789
4.879641
false
false
false
false
anatoliyv/SMDatePicker
SMDatePicker/SMDatePicker.swift
1
8966
// // SMDatePicker.swift // Countapp // // Created by Anatoliy Voropay on 5/12/15. // Copyright (c) 2015 Smartarium.com. All rights reserved. // import UIKit @objc public protocol SMDatePickerDelegate: class { @objc optional func datePickerWillAppear(_ picker: SMDatePicker) @objc optional func datePickerDidAppear(_ picker: SMDatePicker) @objc optional func datePicker(_ picker: SMDatePicker, didPickDate date: Date) @objc optional func datePickerDidCancel(_ picker: SMDatePicker) @objc optional func datePickerWillDisappear(_ picker: SMDatePicker) @objc optional func datePickerDidDisappear(_ picker: SMDatePicker) } @objc open class SMDatePicker: UIView { /// Picker's delegate that conforms to SMDatePickerDelegate protocol open weak var delegate: SMDatePickerDelegate? /// UIToolbar title open var title: String? open var titleFont: UIFont = UIFont.systemFont(ofSize: 13) open var titleColor: UIColor = UIColor.gray /// You can define your own toolbar height. By default it's 44 pixels. open var toolbarHeight: CGFloat = 44.0 /// Specify different UIDatePicker mode. By default it's UIDatePickerMode.DateAndTime open var pickerMode: UIDatePicker.Mode = UIDatePicker.Mode.dateAndTime { didSet { picker.datePickerMode = pickerMode } } /// You can set up different color for picker and toolbar. open var toolbarBackgroundColor: UIColor? { didSet { toolbar.backgroundColor = toolbarBackgroundColor toolbar.barTintColor = toolbarBackgroundColor } } /// You can set up different color for picker and toolbar. open var pickerBackgroundColor: UIColor? { didSet { picker.backgroundColor = pickerBackgroundColor } } /// Initial picker's date open var pickerDate: Date = Date() { didSet { picker.date = pickerDate } } open var minuteInterval: Int { set { picker.minuteInterval = newValue } get { return picker.minuteInterval } } /// Minimum date selectable open var minimumDate: Date? { set { picker.minimumDate = newValue } get { return picker.minimumDate } } /// Maximum date selectable open var maximumDate: Date? { set { picker.maximumDate = newValue } get { return picker.maximumDate } } /// Array of UIBarButtonItem's that will be placed on left side of UIToolbar. By default it has only 'Cancel' bytton. open var leftButtons: [UIBarButtonItem] = [] /// Array of UIBarButtonItem's that will be placed on right side of UIToolbar. By default it has only 'Done' bytton. open var rightButtons: [UIBarButtonItem] = [] // Privates fileprivate var toolbar: UIToolbar = UIToolbar() fileprivate var picker: UIDatePicker = UIDatePicker() // MARK: Lifecycle public override init(frame: CGRect) { super.init(frame: CGRect.zero) addSubview(picker) addSubview(toolbar) setupDefaultButtons() customize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addSubview(picker) addSubview(toolbar) setupDefaultButtons() customize() } // MARK: Customization fileprivate func setupDefaultButtons() { let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.plain, target: self, action: #selector(SMDatePicker.pressedDone(_:))) let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItem.Style.plain, target: self, action: #selector(SMDatePicker.pressedCancel(_:))) leftButtons = [ cancelButton ] rightButtons = [ doneButton ] } fileprivate func customize() { toolbar.barStyle = UIBarStyle.blackTranslucent toolbar.isTranslucent = false backgroundColor = UIColor.white if let toolbarBackgroundColor = toolbarBackgroundColor { toolbar.backgroundColor = toolbarBackgroundColor } else { toolbar.backgroundColor = backgroundColor } if let pickerBackgroundColor = pickerBackgroundColor { picker.backgroundColor = pickerBackgroundColor } else { picker.backgroundColor = backgroundColor } } fileprivate func toolbarItems() -> [UIBarButtonItem] { var items: [UIBarButtonItem] = [] for button in leftButtons { items.append(button) } if let title = toolbarTitle() { let spaceLeft = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil) let spaceRight = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil) let titleItem = UIBarButtonItem(customView: title) items.append(spaceLeft) items.append(titleItem) items.append(spaceRight) } else { let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil) items.append(space) } for button in rightButtons { items.append(button) } return items } fileprivate func toolbarTitle() -> UILabel? { if let title = title { let label = UILabel() label.text = title label.font = titleFont label.textColor = titleColor label.sizeToFit() return label } return nil } // MARK: Showing and hiding picker /// Shows picker in view with animation if it's required. /// /// - Parameter view: is a UIView where we want to show our picker /// - Parameter animated: will show with animation if it's true open func showPickerInView(_ view: UIView, animated: Bool) { toolbar.items = toolbarItems() toolbar.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: toolbarHeight) picker.frame = CGRect(x: 0, y: toolbarHeight, width: view.frame.size.width, height: picker.frame.size.height) self.frame = CGRect(x: 0, y: view.frame.size.height - picker.frame.size.height - toolbar.frame.size.height, width: view.frame.size.width, height: picker.frame.size.height + toolbar.frame.size.height) view.addSubview(self) becomeFirstResponder() showPickerAnimation(animated) } /// Hide visible picker animated. /// /// - Parameter animated: will hide with animation if `true` open func hidePicker(_ animated: Bool) { hidePickerAnimation(true) } // MARK: Animation fileprivate func hidePickerAnimation(_ animated: Bool) { delegate?.datePickerWillDisappear?(self) if animated { UIView.animate(withDuration: 0.2, animations: { () -> Void in self.frame = self.frame.offsetBy(dx: 0, dy: self.picker.frame.size.height + self.toolbar.frame.size.height) }, completion: { (finished) -> Void in self.delegate?.datePickerDidDisappear?(self) }) } else { self.frame = self.frame.offsetBy(dx: 0, dy: self.picker.frame.size.height + self.toolbar.frame.size.height) delegate?.datePickerDidDisappear?(self) } } fileprivate func showPickerAnimation(_ animated: Bool) { delegate?.datePickerWillAppear?(self) if animated { self.frame = self.frame.offsetBy(dx: 0, dy: self.frame.size.height) UIView.animate(withDuration: 0.2, animations: { () -> Void in self.frame = self.frame.offsetBy(dx: 0, dy: -1 * self.frame.size.height) }, completion: { (finished) -> Void in self.delegate?.datePickerDidAppear?(self) }) } else { delegate?.datePickerDidAppear?(self) } } // MARK: Actions /// Default Done action for picker. It will hide picker with animation and call's delegate datePicker(:didPickDate) method. @objc open func pressedDone(_ sender: AnyObject) { hidePickerAnimation(true) delegate?.datePicker?(self, didPickDate: picker.date) } /// Default Cancel actions for picker. @objc open func pressedCancel(_ sender: AnyObject) { hidePickerAnimation(true) delegate?.datePickerDidCancel?(self) } }
mit
473c6f6ad8687fa74d93ba29171e62dd
31.722628
133
0.609971
5.176674
false
false
false
false
itechline/bonodom_new
SlideMenuControllerSwift/SpinnerUtil.swift
1
3341
// // SpinnerUtil.swift // Bonodom // // Created by Attila Dán on 2016. 06. 14.. // Copyright © 2016. Itechline. All rights reserved. // import SwiftyJSON class SpinnerUtil: NSObject { static let sharedInstance = SpinnerUtil() let baseURL = "https://bonodom.com/api/" func get_list_hirdetestipusa(onCompletion: (JSON) -> Void) { let route = baseURL + "list_hirdetestipusa" makeHTTPGetRequest(route, onCompletion: { json, err in onCompletion(json as JSON) }) } func get_list_ingatlanallapota(onCompletion: (JSON) -> Void) { let route = baseURL + "list_ingatlanallapota" makeHTTPGetRequest(route, onCompletion: { json, err in onCompletion(json as JSON) }) } func get_list_ingatlanenergia(onCompletion: (JSON) -> Void) { let route = baseURL + "list_ingatlanenergia" makeHTTPGetRequest(route, onCompletion: { json, err in onCompletion(json as JSON) }) } func get_list_ingatlanfutes(onCompletion: (JSON) -> Void) { let route = baseURL + "list_ingatlanfutes" makeHTTPGetRequest(route, onCompletion: { json, err in onCompletion(json as JSON) }) } func get_list_ingatlankilatas(onCompletion: (JSON) -> Void) { let route = baseURL + "list_ingatlankilatas" makeHTTPGetRequest(route, onCompletion: { json, err in onCompletion(json as JSON) }) } func get_list_ingatlanparkolas(onCompletion: (JSON) -> Void) { let route = baseURL + "list_ingatlanparkolas" makeHTTPGetRequest(route, onCompletion: { json, err in onCompletion(json as JSON) }) } func get_list_ingatlanszoba(onCompletion: (JSON) -> Void) { let route = baseURL + "list_ingatlanszoba" makeHTTPGetRequest(route, onCompletion: { json, err in onCompletion(json as JSON) }) } func get_list_ingatlantipus(onCompletion: (JSON) -> Void) { let route = baseURL + "list_ingatlantipus" makeHTTPGetRequest(route, onCompletion: { json, err in onCompletion(json as JSON) }) } func get_list_ingatlanemelet(onCompletion: (JSON) -> Void) { let route = baseURL + "list_ingatlanemelet" makeHTTPGetRequest(route, onCompletion: { json, err in onCompletion(json as JSON) }) } //list_statuses func get_list_statuses(onCompletion: (JSON) -> Void) { let route = baseURL + "list_statuses" makeHTTPGetRequest(route, onCompletion: { json, err in onCompletion(json as JSON) }) } // MARK: Perform a GET Request private func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse) { let request = NSMutableURLRequest(URL: NSURL(string: path)!) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in if let jsonData = data { let json:JSON = JSON(data: jsonData) onCompletion(json, error) } else { onCompletion(nil, error) } }) task.resume() } }
mit
db4e8e121f6fba138c0cab837d6e9c3b
30.5
108
0.595088
4.359008
false
false
false
false
migchaves/EGTracker
Example/EGTracker/AppDelegate.swift
1
1143
// // AppDelegate.swift // EGTracker // // Created by Miguel Chaves on 04/01/2016. // Copyright (c) 2016 Miguel Chaves. All rights reserved. // import UIKit import EGTracker // Events struct (Suggestion) struct EGEvents { static let appOpen = "APP_OPEN" static let eventButton = "EVENT_BUTTON" static let viewHome = "VIEW_HOME" } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Init the tracker EGTracker.sharedInstance.initEngine() // Configure with E-Goi information about your App EGTracker.sharedInstance.url = "http://myappname.ios" EGTracker.sharedInstance.clientID = 1234 EGTracker.sharedInstance.listID = 2143 EGTracker.sharedInstance.idsite = 4321 EGTracker.sharedInstance.subscriber = "[email protected]" // Track App Open EGTracker.sharedInstance.trackEvent(EGEvents.appOpen) return true } }
mit
39ef61d4f4a51d2a2b7505c13a99e603
25.581395
127
0.67979
4.665306
false
false
false
false
lyp1992/douyu-Swift
YPTV/Pods/Kingfisher/Sources/Kingfisher.swift
7
2310
// // Kingfisher.swift // Kingfisher // // Created by Wei Wang on 16/9/14. // // Copyright (c) 2018 Wei Wang <[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 import ImageIO #if os(macOS) import AppKit public typealias Image = NSImage public typealias View = NSView public typealias Color = NSColor public typealias ImageView = NSImageView public typealias Button = NSButton #else import UIKit public typealias Image = UIImage public typealias Color = UIColor #if !os(watchOS) public typealias ImageView = UIImageView public typealias View = UIView public typealias Button = UIButton #endif #endif public final class Kingfisher<Base> { public let base: Base public init(_ base: Base) { self.base = base } } /** A type that has Kingfisher extensions. */ public protocol KingfisherCompatible { associatedtype CompatibleType var kf: CompatibleType { get } } public extension KingfisherCompatible { public var kf: Kingfisher<Self> { get { return Kingfisher(self) } } } extension Image: KingfisherCompatible { } #if !os(watchOS) extension ImageView: KingfisherCompatible { } extension Button: KingfisherCompatible { } #endif
mit
33052bd63945aa3a391d0f6346d52701
30.643836
81
0.727706
4.468085
false
false
false
false
rugheid/Swift-MathEagle
MathEagleTests/Protocols/BasicOperationsTests.swift
1
2500
// // BasicOperationsTests.swift // MathEagleTests // // Created by Kelly Roach on 7/31/18. // Copyright © 2018 Jorestha Solutions. All rights reserved. // import XCTest import MathEagle class BasicOperationsTests: XCTestCase { func testNegatable() { // Test protocol Negatable for unsigned integers do { // Expecting -n64 = -1 = 2^64-1 (mod 2^64) etc. let n : UInt = 1 let n8 : UInt8 = 1 let n16 : UInt16 = 1 let n32 : UInt32 = 1 let n64 : UInt64 = 1 XCTAssertEqual(Int(bitPattern:-n),-1) XCTAssertEqual(Int8(bitPattern:-n8),-1) XCTAssertEqual(Int16(bitPattern:-n16),-1) XCTAssertEqual(Int32(bitPattern:-n32),-1) XCTAssertEqual(Int64(bitPattern:-n64),-1) XCTAssertNotEqual(-n,n) XCTAssertNotEqual(-n8,n8) XCTAssertNotEqual(-n16,n16) XCTAssertNotEqual(-n32,n32) XCTAssertNotEqual(-n64,n64) XCTAssertEqual(-(-n),n) XCTAssertEqual(-(-n8),n8) XCTAssertEqual(-(-n16),n16) XCTAssertEqual(-(-n32),n32) XCTAssertEqual(-(-n64),n64) XCTAssert(-n>=0) XCTAssert(-n8>=0) XCTAssert(-n16>=0) XCTAssert(-n32>=0) XCTAssert(-n64>=0) } do { // Expecting -n64 = 1 (mod 2^64) etc. let n : UInt = UInt(bitPattern:-1) let n8 : UInt8 = UInt8(bitPattern:-1) let n16 : UInt16 = UInt16(bitPattern:-1) let n32 : UInt32 = UInt32(bitPattern:-1) let n64 : UInt64 = UInt64(bitPattern:-1) XCTAssertEqual(Int(bitPattern:-n),1) XCTAssertEqual(Int8(bitPattern:-n8),1) XCTAssertEqual(Int16(bitPattern:-n16),1) XCTAssertEqual(Int32(bitPattern:-n32),1) XCTAssertEqual(Int64(bitPattern:-n64),1) XCTAssertNotEqual(-n,n) XCTAssertNotEqual(-n8,n8) XCTAssertNotEqual(-n16,n16) XCTAssertNotEqual(-n32,n32) XCTAssertNotEqual(-n64,n64) XCTAssertEqual(-(-n),n) XCTAssertEqual(-(-n8),n8) XCTAssertEqual(-(-n16),n16) XCTAssertEqual(-(-n32),n32) XCTAssertEqual(-(-n64),n64) XCTAssert(-n>=0) XCTAssert(-n8>=0) XCTAssert(-n16>=0) XCTAssert(-n32>=0) XCTAssert(-n64>=0) } } }
mit
deb16c3921e7d13c9fdf40a32abb1ed3
33.708333
61
0.530612
3.96038
false
true
false
false
neoneye/SwiftyFORM
Source/Specification/Specification.swift
1
4795
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. /// A type that can check whether or not a candidate object satisfy the rules. /// /// Specifications are cheap to write, easy to test and can be combined to /// represent very complex business rules. /// /// More about specification pattern on [Wikipedia](https://en.wikipedia.org/wiki/Specification_pattern). public protocol Specification { /// The central part of a specification is the `isSatisfiedBy()` function, /// which is used to check if an object satisfies the specification. /// /// - parameter candidate: The object to be checked. /// /// - returns: `true` if the candidate satisfies the specification, `false` otherwise. func isSatisfiedBy(_ candidate: Any?) -> Bool } extension Specification { /// Combine two specifications into one. /// /// This is an **AND** operation. The new specification is satisfied /// when both specifications are satisfied. /// /// - parameter other: The other specification that is to be to combine with this specification. /// /// - returns: A combined specification public func and(_ other: Specification) -> Specification { AndSpecification(self, other) } /// Combine two specifications into one. /// /// This is an **OR** operation. The new specification is satisfied /// when either of the specifications are satisfied. /// /// - parameter other: The other specification that is to be to combine with this specification. /// /// - returns: A combined specification public func or(_ other: Specification) -> Specification { OrSpecification(self, other) } /// Invert a specification. /// /// This is a **NOT** operation. The new specification is satisfied /// when the specification is not satisfied. /// /// - returns: An inverted specification public func not() -> Specification { NotSpecification(self) } } /// Check if two specifications are both satisfied. /// /// This is a composite specification that combines two specifications /// into a single specification. public class AndSpecification: Specification { private let one: Specification private let other: Specification public init(_ x: Specification, _ y: Specification) { self.one = x self.other = y } /// Check if both specifications are satisfied. /// /// - parameter candidate: The object to be checked. /// /// - returns: `true` if the candidate satisfies both specifications, `false` otherwise. public func isSatisfiedBy(_ candidate: Any?) -> Bool { one.isSatisfiedBy(candidate) && other.isSatisfiedBy(candidate) } } /// Check if either of the specifications are satisfied. /// /// This is a composite specification that combines two specifications /// into a single specification. public class OrSpecification: Specification { private let one: Specification private let other: Specification public init(_ x: Specification, _ y: Specification) { self.one = x self.other = y } /// Check if either of the specifications are satisfied. /// /// - parameter candidate: The object to be checked. /// /// - returns: `true` if the candidate satisfies either of the specifications, `false` otherwise. public func isSatisfiedBy(_ candidate: Any?) -> Bool { one.isSatisfiedBy(candidate) || other.isSatisfiedBy(candidate) } } /// Check if a specification is not satisfied. /// /// This is a composite specification that wraps another specification. public class NotSpecification: Specification { private let wrapped: Specification public init(_ x: Specification) { self.wrapped = x } /// Check if specification is not satisfied. /// /// - parameter candidate: The object to be checked. /// /// - returns: `true` if the candidate doesn't satisfy the specification, `false` otherwise. public func isSatisfiedBy(_ candidate: Any?) -> Bool { !wrapped.isSatisfiedBy(candidate) } } /// This specification is never satisfied. public class FalseSpecification: Specification { public init() { } /// Doesn't do anything. This specification is never satisfied. /// /// - parameter candidate: The parameter is ignored. /// /// - returns: `false` always. public func isSatisfiedBy(_ candidate: Any?) -> Bool { false } } /// This specification is always satisfied. public class TrueSpecification: Specification { public init() { } /// Doesn't do anything. This specification is always satisfied. /// /// - parameter candidate: The parameter is ignored. /// /// - returns: `true` always. public func isSatisfiedBy(_ candidate: Any?) -> Bool { true } } /// - warning: /// This class will be removed in the future, starting with SwiftyFORM 2.0.0 open class CompositeSpecification: Specification { open func isSatisfiedBy(_ candidate: Any?) -> Bool { // subclass must implement this function false } }
mit
566607e4ce51ef463e30e39ad14829d2
28.782609
105
0.713452
4.098291
false
false
false
false
jindulys/Wikipedia
Wikipedia/Code/SDImageCache+PromiseKit.swift
1
1881
// // SDImageCache+PromiseKit.swift // Wikipedia // // Created by Brian Gerstle on 7/1/15. // Copyright (c) 2015 Wikimedia Foundation. All rights reserved. // import Foundation import PromiseKit import SDWebImage public typealias DiskQueryResult = (cancellable: Cancellable?, promise: Promise<(UIImage, ImageOrigin)>) extension SDImageCache { public func queryDiskCacheForKey(key: String) -> DiskQueryResult { let (promise, fulfill, reject) = Promise<(UIImage, ImageOrigin)>.pendingPromise() // queryDiskCache will return nil if the image is in memory let diskQueryOperation: NSOperation? = self.queryDiskCacheForKey(key, done: { image, cacheType -> Void in if image != nil { fulfill((image, asImageOrigin(cacheType))) } else { reject(WMFImageControllerErrorCode.DataNotFound.error) } }) if let diskQueryOperation = diskQueryOperation { // make sure promise is rejected if the operation is cancelled self.KVOController.observe(diskQueryOperation, keyPath: "isCancelled", options: NSKeyValueObservingOptions.New) { _, _, change in let value = change[NSKeyValueChangeNewKey] as! NSNumber if value.boolValue { reject(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil)) } } // tear down observation when operation finishes self.KVOController.observe(diskQueryOperation, keyPath: "isFinished", options: NSKeyValueObservingOptions()) { [weak self] _, object, _ in self?.KVOController.unobserve(object) } } return (diskQueryOperation, promise) } }
mit
baf21f11b3ae55278a83adced59ffde5
35.882353
113
0.609782
5.548673
false
false
false
false
StanZabroda/Hydra
Hydra/SinglyLinkedList.swift
1
1726
import Foundation struct SinglyLinkedList<T> { var head = HeadNode<SinglyNode<T>>() func findNodeWithKey(key: String) -> SinglyNode<T>? { if var currentNode = head.next { while currentNode.key != key { if let nextNode = currentNode.next { currentNode = nextNode } else { return nil } } return currentNode } else { return nil } } func upsertNodeWithKey(key: String, AndValue val: T) -> SinglyNode<T> { if var currentNode = head.next { while let nextNode = currentNode.next { if currentNode.key == key { break } else { currentNode = nextNode } } if currentNode.key == key { currentNode.value = val return currentNode } else { currentNode.next = SinglyNode<T>(key: key, value: val, nextNode: nil) return currentNode.next! } } else { head.next = SinglyNode<T>(key: key, value: val, nextNode: nil) return head.next! } } func displayNodes() { print("Printing Nodes", terminator: "") if var currentNode = head.next { print("First Node's Value is \(currentNode.value!)", terminator: "") while let nextNode = currentNode.next { currentNode = nextNode print("Next Node's Value is \(currentNode.value!)", terminator: "") } } else { print("List is empty", terminator: "") } } }
mit
66465fa895ccb3227d9cfc753d42bd89
32.211538
85
0.48146
5.152239
false
false
false
false
ChiliLabs/CHIPageControl
Example/Example/ViewController.swift
1
3309
// // ViewController.swift // Example // // Created by Igors Nemenonoks on 13/03/17. // Copyright © 2017 Chili. All rights reserved. // import UIKit import CHIPageControl class ViewController: UIViewController { internal let numberOfPages = 4 @IBOutlet var pageControls: [CHIBasePageControl]! @IBOutlet var coloredPageControls: [CHIBasePageControl]! @IBOutlet weak var verticalPageControl: CHIPageControlJalapeno! override func viewDidLoad() { super.viewDidLoad() self.pageControls.forEach { (control) in control.numberOfPages = self.numberOfPages } // You can insert tint colors to a position (it will replace that position with the selected color) coloredPageControls.forEach { (control) in control.insertTintColor(randomColor(), position: Int(arc4random_uniform(UInt32(numberOfPages)))) control.insertTintColor(randomColor(), position: Int(arc4random_uniform(UInt32(numberOfPages)))) } // You can also initialize the tintColors with an array coloredPageControls.last?.tintColors = [randomColor(), randomColor(), randomColor(), randomColor()] //you can display page control vertical self.verticalPageControl.transform = self.pageControls.last!.transform.rotated(by: .pi/2) //you can activate touch through code self.verticalPageControl.enableTouchEvents = true self.verticalPageControl.delegate = self self.coloredPageControls.forEach({ pager in pager.delegate = self }) } func randomColor() -> UIColor{ return UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0) } } extension ViewController: CHIBasePageControlDelegate { func didTouch(pager: CHIBasePageControl, index: Int) { print(pager, index) } } extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 4 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "aCell", for: indexPath) cell.backgroundColor = self.randomColor() return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return self.view.bounds.size } func scrollViewDidScroll(_ scrollView: UIScrollView) { let total = scrollView.contentSize.width - scrollView.bounds.width let offset = scrollView.contentOffset.x let percent = Double(offset / total) let progress = percent * Double(self.numberOfPages - 1) (self.pageControls + self.coloredPageControls).forEach { (control) in control.progress = progress } } }
mit
2ab28e0cba494a2cedbce61718f02173
34.956522
160
0.670193
5.318328
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/MediaList.swift
1
2487
public struct MediaListItemSource: Codable { public let urlString: String public let scale: String enum CodingKeys: String, CodingKey { case urlString = "src" case scale } public init (urlString: String, scale: String) { self.urlString = urlString self.scale = scale } } public enum MediaListItemType: String { case image case audio case video } public struct MediaListItem: Codable { public let title: String? public let sectionID: Int public let type: String public let showInGallery: Bool public let isLeadImage: Bool public let sources: [MediaListItemSource]? public let audioType: String? enum CodingKeys: String, CodingKey { case title case sectionID = "section_id" case showInGallery case isLeadImage = "leadImage" case sources = "srcset" case type case audioType } public init(title: String?, sectionID: Int, type: String, showInGallery: Bool, isLeadImage: Bool, sources: [MediaListItemSource]?, audioType: String? = nil) { self.title = title self.sectionID = sectionID self.type = type self.showInGallery = showInGallery self.isLeadImage = isLeadImage self.sources = sources self.audioType = audioType } } extension MediaListItem { public var itemType: MediaListItemType? { return MediaListItemType(rawValue: type) } } public struct MediaList: Codable { public let items: [MediaListItem] public init(items: [MediaListItem]) { self.items = items } // This failable initializer is used for a single-image MediaList, given via a URL. public init?(from url: URL?) { guard let imageURL = url, let imageName = WMFParseUnescapedNormalizedImageNameFromSourceURL(imageURL) else { return nil } let filename = "File:" + imageName let urlString = imageURL.absoluteString let sources: [MediaListItemSource] = [ MediaListItemSource(urlString: urlString, scale: "1x"), MediaListItemSource(urlString: urlString, scale: "2x"), MediaListItemSource(urlString: urlString, scale: "1.5x") ] let mediaListItem = MediaListItem(title: filename, sectionID: 0, type: "image", showInGallery: true, isLeadImage: true, sources: sources, audioType: nil) self = MediaList(items: [mediaListItem]) } }
mit
a68a5e6db965e2d50cf6778bf8fc499f
29.703704
162
0.649377
4.728137
false
false
false
false
SrirangaDigital/shankara-android
iOS/Advaita Sharada/Advaita Sharada/BookTOCController.swift
1
6456
// // BookTOCController.swift // Advaita Sharada // // Created by Amiruddin Nagri on 01/08/15. // Copyright (c) 2015 Sriranga Digital Software Technologies Pvt. Ltd. All rights reserved. // import UIKit import CoreData class BookTOCController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var segments: UISegmentedControl! @IBOutlet weak var tableView: UITableView! var currentBook: Link? var currentTableDataSource: LinkBasedDataSource? var selectedLink: Link? lazy var appDelegate: AppDelegate? = { return UIApplication.sharedApplication().delegate as? AppDelegate }() lazy var managedObjectContext: NSManagedObjectContext? = { return self.appDelegate?.managedObjectContext }() lazy var userDataManagedObjectContext: NSManagedObjectContext? = { return self.appDelegate?.userDataManagedObjectContext }() lazy var tocTableDataSource:LinkBasedDataSource? = { [unowned self] in let dataSource = TOCTableDataSource(managedObjectContext: self.managedObjectContext!, book: self.currentBook!) return dataSource }() lazy var bookmarksTableDataSource:LinkBasedDataSource? = { [unowned self] in let dataSource = BookmarkTableDataSource(managedObjectContext: self.managedObjectContext!, userDataManagedObjectContext: self.userDataManagedObjectContext!, book: self.currentBook!) return dataSource }() lazy var ishaTOCDataSource: LinkBasedDataSource? = { [unowned self] in let dataSource = VerseBasedDataSource(managedObjectContext: self.managedObjectContext!, book: self.currentBook!, htmlClass: "versetext") return dataSource }() lazy var brahmasutraSutraniDataSource: LinkBasedDataSource? = { [unowned self] in let dataSource = VerseBasedDataSource(managedObjectContext: self.managedObjectContext!, book: self.currentBook!, htmlClass: "versetext") return dataSource }() lazy var brahmasutraAdhikaraniDataSource: LinkBasedDataSource? = { [unowned self] in let dataSource = VerseBasedDataSource(managedObjectContext: self.managedObjectContext!, book: self.currentBook!, htmlClass: "subsection") return dataSource }() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = currentBook!.displayName() if currentBook?.type != "brahmasutra" { segments.removeSegmentAtIndex(1, animated: false) segments.removeSegmentAtIndex(1, animated: false) } let managedObjectContext: NSManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext! self.currentTableDataSource = defaultTOCDataSource() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { var tracker = GAI.sharedInstance().defaultTracker tracker.set(kGAIScreenName, value: "Book TOC") tracker.set(GAIFields.customDimensionForIndex(1), value: Link.language()) tracker.set(GAIFields.customDimensionForIndex(2), value: currentBook!.name_en) var builder = GAIDictionaryBuilder.createScreenView() tracker.send(builder.build() as [NSObject : AnyObject]) } @IBAction func segmentSelected(sender: AnyObject) { if let from = sender as? UISegmentedControl { if let title = from.titleForSegmentAtIndex(from.selectedSegmentIndex) { switch title { case "अध्यायाः": self.currentTableDataSource = defaultTOCDataSource() case "Bookmarks": self.currentTableDataSource = bookmarksTableDataSource case "सूत्राणि": self.currentTableDataSource = brahmasutraSutraniDataSource case "अधिकरणानि": self.currentTableDataSource = brahmasutraAdhikaraniDataSource default: self.currentTableDataSource = tocTableDataSource } } } self.tableView.reloadData() } func defaultTOCDataSource() -> LinkBasedDataSource? { if currentBook?.name == "ईशावास्योपनिषद्भाष्यम्" { return ishaTOCDataSource } else { return tocTableDataSource } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return currentTableDataSource?.numberOfSectionsInTableView?(tableView) ?? 0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return currentTableDataSource?.tableView(tableView, numberOfRowsInSection: section) ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return currentTableDataSource!.tableView(tableView, cellForRowAtIndexPath: indexPath) } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return currentTableDataSource?.tableView?(tableView, titleForHeaderInSection: section) ?? nil } func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { NSLog("Prepare for segue \(segue.identifier)") if segue.identifier == "segue_toc_to_book" || segue.identifier == "segue_bookmark_to_book" { if let cell = sender as? UITableViewCell, selectedIndex = self.tableView?.indexPathForCell(cell) { self.selectedLink = self.currentTableDataSource?.linkForIndexPath(selectedIndex) } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-2.0
438f5521322f34d586b89e5cc8e54766
39.782051
189
0.67353
5.446918
false
false
false
false
jindulys/GithubPilot
Sources/Models/GithubEvent.swift
2
5101
// // GithubEvent.swift // Pods // // Created by yansong li on 2016-02-21. // // import Foundation /// GithubEventType https://developer.github.com/v3/activity/events/types/ public enum EventType: String { case CreateEvent = "CreateEvent" case CommitCommentEvent = "CommitCommmentEvent" case DeleteEvent = "DeleteEvent" case DeploymentEvent = "DeploymentEvent" case DeploymentStatusEvent = "DeploymentStatusEvent" case DownloadEvent = "DownloadEvent" case FollowEvent = "FollowEvent" case ForkEvent = "ForkEvent" case ForkApplyEvent = "ForkApplyEvent" case GistEvent = "GistEvent" case GollumEvent = "GollumEvent" case IssueCommentEvent = "IssueCommentEvent" case IssuesEvent = "IssuesEvent" case MemberEvent = "MemberEvent" case MembershipEvent = "MembershipEvent" case PageBuildEvent = "PageBuildEvent" case PublicEvent = "PublicEvent" case PullRequestEvent = "PullRequestEvent" case PullRequestReviewCommentEvent = "PullRequestReviewCommentEvent" case PushEvent = "PushEvent" case ReleaseEvent = "ReleaseEvent" case RepositoryEvent = "RepositoryEvent" case StatusEvent = "StatusEvent" case TeamAddEvent = "TeamAddEvent" case WatchEvent = "WatchEvent" init?(event:String) { switch event { case "CreateEvent": self = .CreateEvent case "CommitCommentEvent": self = .CommitCommentEvent case "DeleteEvent": self = .DeleteEvent case "DeploymentEvent": self = .DeploymentEvent case "DeploymentStatusEvent": self = .DeploymentStatusEvent case "DownloadEvent": self = .DownloadEvent case "FollowEvent": self = .FollowEvent case "ForkEvent": self = .ForkEvent case "ForkApplyEvent": self = .ForkApplyEvent case "GistEvent": self = .GistEvent case "GollumEvent": self = .GollumEvent case "IssueCommentEvent": self = .IssueCommentEvent case "IssuesEvent": self = .IssuesEvent case "MemberEvent": self = .MemberEvent case "MembershipEvent": self = .MembershipEvent case "PageBuildEvent": self = .PageBuildEvent case "PublicEvent": self = .PublicEvent case "PullRequestEvent": self = .PullRequestEvent case "PullRequestReviewCommentEvent": self = .PullRequestReviewCommentEvent case "PushEvent": self = .PushEvent case "ReleaseEvent": self = .ReleaseEvent case "RepositoryEvent": self = .RepositoryEvent case "StatusEvent": self = .StatusEvent case "TeamAddEvent": self = .TeamAddEvent case "WatchEvent": self = .WatchEvent default: print("There has \(event)") return nil } } } /// GithubEvent represents a Github Event open class GithubEvent { open let id: String open let type: EventType open let repo: GithubRepo? open let actor: GithubUser? open let createdAt: String init(id: String, type: EventType, repo: GithubRepo? = nil, actor: GithubUser? = nil, createdAt: String) { self.id = id self.type = type self.repo = repo self.actor = actor self.createdAt = createdAt } } /// EventSerializer GithubEvent <---> JSON open class EventSerializer: JSONSerializer { let userSerializer: GithubUserSerializer let repoSerializer: RepoSerializer public init() { self.userSerializer = GithubUserSerializer() self.repoSerializer = RepoSerializer() } /** GithubEvent -> JSON */ open func serialize(_ value: GithubEvent) -> JSON { let retVal = [ "id": Serialization._StringSerializer.serialize(value.id), "type": Serialization._StringSerializer.serialize(value.type.rawValue), "repo": NullableSerializer(self.repoSerializer).serialize(value.repo), "actor": NullableSerializer(self.userSerializer).serialize(value.actor), "created_at": Serialization._StringSerializer.serialize(value.createdAt) ] return .dictionary(retVal) } /** JSON -> GithubEvent */ open func deserialize(_ json: JSON) -> GithubEvent { switch json { case .dictionary(let dict): let id = Serialization._StringSerializer.deserialize(dict["id"] ?? .null) let type = EventType(event: Serialization._StringSerializer.deserialize(dict["type"] ?? .null))! let repo = NullableSerializer(self.repoSerializer).deserialize(dict["repo"] ?? .null) let actor = NullableSerializer(self.userSerializer).deserialize(dict["actor"] ?? .null) let createdAt = Serialization._StringSerializer.deserialize(dict["created_at"] ?? .null) return GithubEvent(id: id, type: type, repo: repo, actor: actor, createdAt: createdAt) default: fatalError("Github Event JSON Type Error") } } } /// Event Array Serializer, which deal with array. open class EventArraySerializer: JSONSerializer { let eventSerializer: EventSerializer init() { self.eventSerializer = EventSerializer() } /** [GithubEvent] -> JSON */ open func serialize(_ value: [GithubEvent]) -> JSON { let users = value.map { self.eventSerializer.serialize($0) } return .array(users) } /** JSON -> [GithubEvent] */ open func deserialize(_ json: JSON) -> [GithubEvent] { switch json { case .array(let users): return users.map { self.eventSerializer.deserialize($0) } default: fatalError("JSON Type should be array") } } }
mit
75c5054ef1fab6c26aec51db87a2331c
26.722826
106
0.721819
3.861469
false
false
false
false
CharlinFeng/Reflect
Reflect/Reflect/Model2Dict/Reflect+Convert.swift
2
2001
// // Reflect+Convert.swift // Reflect // // Created by 成林 on 15/8/23. // Copyright (c) 2015年 冯成林. All rights reserved. // import Foundation extension Reflect{ func toDict() -> [String: Any]{ var dict: [String: Any] = [:] self.properties { (name, type, value) -> Void in if type.isOptional{ if type.isReflect { dict[name] = (value as? Reflect)?.toDict() }else{ dict[name] = "\(value)".replacingOccurrencesOfString(target: "Optional(", withString: "").replacingOccurrencesOfString(target: ")", withString: "").replacingOccurrencesOfString(target: "\"", withString: "") } }else{ if type.isReflect { if type.isArray { var dictM: [[String: Any]] = [] let modelArr = value as! NSArray for item in modelArr { let dict = (item as! Reflect).toDict() dictM.append(dict) } dict[name] = dictM }else{ dict[name] = (value as! Reflect).toDict() } }else{ dict[name] = "\(value)".replacingOccurrencesOfString(target: "Optional(", withString: "").replacingOccurrencesOfString(target: ")", withString: "").replacingOccurrencesOfString(target: "\"", withString: "") } } } return dict } }
mit
2da6ba6cda3dee5734f0873b3f8ee499
30.078125
226
0.371543
6.436893
false
false
false
false
JonMo/Alertmo
Example/Alertmo/ViewController.swift
1
1807
// // ViewController.swift // Alertmo // // Created by JonMo on 06/27/2017. // Copyright (c) 2017 JonMo. All rights reserved. // import UIKit import Alertmo class ViewController: UIViewController, AlertmoViewControllerDelegate { var alertViewController: Alertmo! override func viewDidLoad() { super.viewDidLoad() let toggleButton = UIButton(frame: CGRect(x: 10, y: 20, width: 200, height: 30)) toggleButton.setTitle("Show Alert", for: .normal) toggleButton.setTitleColor(UIColor.red, for: .normal) toggleButton.addTarget(self, action:#selector(showEmailAlreadyExistAlert), for: .touchUpInside) view.addSubview(toggleButton) // 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. } func showEmailAlreadyExistAlert() { alertViewController = Alertmo() alertViewController.titleText = "Do you want to reset your password?" alertViewController.messageText = "We will guide you through the process" alertViewController.firstButtonText = "Yes, reset" alertViewController.secondButtonText = "Skip for now" alertViewController.minimizeSecondButton = true alertViewController.delegate = self // alertViewController.image = UIImage(named: "lock.png") self.present(alertViewController, animated: true, completion: nil) } func onAlertFirstButton() { self.alertViewController.dismiss(animated: true, completion: nil) } func onAlertSecondButton() { self.alertViewController.dismiss(animated: true, completion: nil) } }
mit
774a8ee68fb09250de78411cd346e714
33.09434
103
0.681793
4.977961
false
false
false
false
terryokay/learnAnimationBySwift
learnAnimation/learnAnimation/AnimationsListViewController.swift
1
5635
// // AnimationsListViewController.swift // learnAnimation // // Created by likai on 2017/4/14. // Copyright © 2017年 terry. All rights reserved. // import UIKit class AnimationsListViewController: CustomNormalContentViewController,DefaultNotificationCenterDelegate,UITableViewDelegate,UITableViewDataSource { fileprivate var tableView: UITableView! fileprivate var notification : DefaultNotificationCenter = DefaultNotificationCenter() fileprivate var adapters :[CellDataAdapter] = [CellDataAdapter]() override func setup() { super.setup() notification.delegate = self //添加通知名字,会添加代码方法 notification.addNotificationName(NotificationEvent.animationsListViewControllerFirstTimeLoadData.Message()) tableView = UITableView(frame: (contentView?.bounds)!) tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = .none tableView.rowHeight = 50 tableView.showsVerticalScrollIndicator = false contentView?.addSubview(tableView) //注册的cell ListItemCell.RegisterTo(tableView) } // MARK: DefaultNotificationCenterDelegate func defaultNotificationCenter(_ notificationName: String, object: AnyObject?) { func add(_ controllerClass : AnyClass! , name : String!){ adapters.append(ListItemCell.Adapter( data: ControllerItem(controllerClass: controllerClass, name: name))) } //添加控制器 add(HeaderViewTapAnimationController.classForCoder(), name: "UITableView展开缩放动画") add(TapCellAnimationController.classForCoder(), name: "Cell点击动画") add(MixedColorProgressViewController.classForCoder(), name: "UILabel混色显示") var indexPaths = [IndexPath]() for i in 0 ..< self.adapters.count { indexPaths.append(IndexPath(row: i, section: 0)) } self.tableView.insertRows(at: indexPaths, with: .fade) } override func buildTitleView() { super.buildTitleView() func createBackgroundStringLabel(){ let string = "Animations" let richText = NSMutableAttributedString(string: string) let length = string.lengthOfBytes(using: .utf8) let allColor = UIColor.Hex(0x545454) let partColor = UIColor.clear richText.addAttributes([NSForegroundColorAttributeName : allColor], range: NSMakeRange(0, length)) richText.addAttributes([NSForegroundColorAttributeName : partColor], range: NSMakeRange(1, 1)) richText.addAttributes([NSFontAttributeName : UIFont.AvenirLight(28)], range: NSMakeRange(0, length)) let label = UILabel() label.attributedText = richText label.sizeToFit() titleView?.addSubview(label) label.center = (titleView?.middlePoint)! } func createForegroundStringLabel(){ let string = "Animations" let richText = NSMutableAttributedString(string: string) let length = string.lengthOfBytes(using: .utf8) let allColor = UIColor.clear let partColor = UIColor.Hex(0x4699D9) richText.addAttributes([NSForegroundColorAttributeName : allColor], range: NSMakeRange(0, length)) richText.addAttributes([NSForegroundColorAttributeName : partColor], range: NSMakeRange(1, 1)) richText.addAttributes([NSFontAttributeName : UIFont.AvenirLight(28)], range: NSMakeRange(0, length)) let label = UILabel() label.attributedText = richText label.sizeToFit() titleView?.addSubview(label) label.center = (titleView?.middlePoint)! label.startGlowWithGlowRadius(2, glowOpacity: 0.8, glowColor: partColor, glowDuration: 1, hideDuration: 3, glowAnimationDuration: 2) } titleView?.addSubview(BackgroundLineView(frame: titleView!.bounds, lineWidth: 4, lineGap: 4, lineColor: UIColor.black.alpha(0.015), rotate: CGFloat(Double.pi / 4))) createBackgroundStringLabel() createBackgroundStringLabel() titleView?.addSubview(UIView.CreateLine(CGRect(x: 0, y: titleView!.height - 0.5, width: Width(), height: 0.5), lineColor: UIColor.gray.alpha(0.2))) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return adapters.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueCellAndLoadContentFromAdapter(adapters[(indexPath as NSIndexPath).row], indexPath: indexPath, controller: self) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.selectedEventWithIndexPath(indexPath) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) enableInteractivPopGestureRecognizer = false } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) enableInteractivPopGestureRecognizer = true } }
mit
3abdd24b646fc88b2e6300c808683883
32.107143
172
0.630888
5.612513
false
false
false
false
EasySwift/EasySwift
Carthage/Checkouts/Bond/BondTests/NSObjectTests.swift
4
4253
// // NSObjectTests.swift // Bond // // Created by Srdan Rasic on 23/10/2016. // Copyright © 2016 Swift Bond. All rights reserved. // @testable import Bond import ReactiveKit import XCTest class NSObjectTests: XCTestCase { class TestObject: NSObject { } var object: TestObject! override func setUp() { super.setUp() object = TestObject() } func testBndDeallocated() { object.bnd_deallocated.expect([.completed], expectation: expectation(description: #function)) object = nil waitForExpectations(timeout: 1) } func testBndBag() { let d1 = SimpleDisposable() let d2 = SimpleDisposable() object.bnd_bag.add(disposable: d1) d2.disposeIn(object.bnd_bag) object = nil XCTAssert(d1.isDisposed) XCTAssert(d2.isDisposed) } } class NSObjectKVOTests: XCTestCase { class TestObject: NSObject { dynamic var property: Any! = "a" } var object: TestObject! override func setUp() { super.setUp() object = TestObject() } func testObservation() { let subject = object.dynamic(keyPath: "property", ofType: String.self) subject.expectNext(["a", "b", "c"]) object.property = "b" object.property = "c" } func testBinding() { let subject = object.dynamic(keyPath: "property", ofType: String.self) subject.expectNext(["a", "b", "c"]) Signal1.just("b").bind(to: subject) XCTAssert((object.property as! String) == "b") Signal1.just("c").bind(to: subject) XCTAssert((object.property as! String) == "c") } func testOptionalObservation() { let subject = object.dynamic(keyPath: "property", ofType: Optional<String>.self) subject.expectNext(["a", "b", nil, "c"]) object.property = "b" object.property = nil object.property = "c" } func testOptionalBinding() { let subject = object.dynamic(keyPath: "property", ofType: Optional<String>.self) subject.expectNext(["a", "b", nil, "c"]) Signal1.just("b").bind(to: subject) XCTAssert((object.property as! String) == "b") Signal1.just(nil).bind(to: subject) XCTAssert(object.property == nil) Signal1.just("c").bind(to: subject) XCTAssert((object.property as! String) == "c") } func testExpectedTypeObservation() { let subject = object.dynamic(keyPath: "property", ofExpectedType: String.self) subject.expectNext(["a", "b", "c"]) object.property = "b" object.property = "c" } func testExpectedTypeBinding() { let subject = object.dynamic(keyPath: "property", ofExpectedType: String.self) subject.expectNext(["a", "b", "c"]) Signal1.just("b").bind(to: subject) XCTAssert((object.property as! String) == "b") Signal1.just("c").bind(to: subject) XCTAssert((object.property as! String) == "c") } func testExpectedTypeFailure() { let subject = object.dynamic(keyPath: "property", ofExpectedType: String.self) subject.expect([.next("a"), .failed(.notConvertible(""))]) object.property = 5 } func testExpectedTypeOptionalObservation() { let subject = object.dynamic(keyPath: "property", ofExpectedType: Optional<String>.self) subject.expectNext(["a", "b", nil, "c"]) object.property = "b" object.property = nil object.property = "c" } func testExpectedTypeOptionalBinding() { let subject = object.dynamic(keyPath: "property", ofExpectedType: Optional<String>.self) subject.expectNext(["a", "b", nil, "c"]) Signal1.just("b").bind(to: subject) XCTAssert((object.property as! String) == "b") Signal1.just(nil).bind(to: subject) XCTAssert(object.property == nil) Signal1.just("c").bind(to: subject) XCTAssert((object.property as! String) == "c") } func testExpectedTypeOptionalFailure() { let subject = object.dynamic(keyPath: "property", ofExpectedType: Optional<String>.self) subject.expect([.next("a"), .failed(.notConvertible(""))]) object.property = 5 } func testDeallocation() { let subject = object.dynamic(keyPath: "property", ofExpectedType: String.self) subject.expect([.next("a"), .completed], expectation: expectation(description: #function)) weak var weakObject = object object = nil XCTAssert(weakObject == nil) waitForExpectations(timeout: 1) } }
apache-2.0
983b838b4d6d565ac58dc0ba85c50bf8
28.324138
97
0.660865
3.796429
false
true
false
false
jotade/onthemap-udacity
onthemap/FindOnTheMapViewController.swift
1
2266
// // FindOnTheMapViewController.swift // onthemap // // Created by IM Development on 7/27/17. // Copyright © 2017 IM Development. All rights reserved. // import UIKit import CoreLocation class FindOnTheMapViewController: UIViewController { @IBOutlet weak var findButton: UIButton! @IBOutlet weak var locationTextField: UITextField! let geocoder = CLGeocoder() var activityIndicator: UIView? func geocodeLocation(city: String){ geocoder.geocodeAddressString(city) { (placemarks, error) in if error != nil{ print(error!.localizedDescription) self.activityIndicator?.removeFromSuperview() Utils.showAlert(with: "Error", message: "couldn't find your location!", viewController: self, isDefault: true, actions: nil) return } if let place = placemarks?.first, let coordinate = place.location?.coordinate, let name = place.name, let country = place.country{ AuthService.instance.currentStudent?.latitude = coordinate.latitude AuthService.instance.currentStudent?.longitude = coordinate.longitude AuthService.instance.currentStudent?.mapString = "\(name), \(country)" NotificationCenter.default.post(name: NSNotification.Name(rawValue: "showLocation"), object: nil) self.dismiss(animated: true) { self.activityIndicator?.removeFromSuperview() } } } } @IBAction func find(_ sender: UIButton) { guard let location = locationTextField.text , locationTextField.text != "" else { Utils.showAlert(with: "Oops", message: "You forgot to put your location!", viewController: self, isDefault: true, actions: nil) return } activityIndicator = Utils.showActivityIndicatory(uiView: self.view) geocodeLocation(city: location) } @IBAction func cancel(_ sender: UIButton) { dismiss(animated: true, completion: nil) } }
gpl-3.0
e7a2ca9dca46fb71c42024dbe16a3da1
33.318182
142
0.58543
5.551471
false
false
false
false
Mahmoud333/FileManager-Swift
FileManager-Swift/Classes/FileManagerVC+Constraints.swift
1
9322
// // FileManagerVC+Constraints.swift // NoorMagazine // // Created by Mahmoud Hamad on 7/13/17. // Copyright © 2017 yassin abdelmaguid. All rights reserved. // import UIKit //Configuer Our views @available(iOS 9.0, *) extension FileManagerVC { func configuerHeaderView() -> FancyView { let view = FancyView() view.backgroundColor = customizations.headerViewColor ?? UIColor.purple view.translatesAutoresizingMaskIntoConstraints = false view.addShadow = true return view } func configuerCollectionView() -> UICollectionView { let flow = UICollectionViewFlowLayout() flow.sectionInset = UIEdgeInsetsMake(14, 20, 14, 20) //let width = UIScreen.main.bounds.size.width //flow?.itemSize = CGSize(width: width/3, height: width/3) flow.itemSize = CGSize(width: 140, height: 140) flow.minimumLineSpacing = 14 flow.minimumInteritemSpacing = 14 flow.scrollDirection = .vertical let cV = UICollectionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: flow) cV.allowsMultipleSelection = true cV.translatesAutoresizingMaskIntoConstraints = false cV.backgroundColor = UIColor.clear return cV } func configuerMarkBtn() -> UIButton { let btn = UIButton(type: .system) btn.setTitle(" Mark", for: .normal) btn.setTitleColor( UIColor.lightGray, for: .normal) btn.frame.size = CGSize(width: 48, height: 38) btn.translatesAutoresizingMaskIntoConstraints = false //btn.titleLabel?.font = UIFont(name: "Avenir", size: 18) btn.titleLabel?.font = UIFont.systemFont(ofSize: 19) btn.setImage( UIImage(named: "messageindicator1.png"), for: .normal) btn.layer.cornerRadius = 5 btn.backgroundColor = UIColor.clear btn.addTarget(self, action: #selector(markTapped), for: .touchUpInside) btn.tintColor = UIColor.gray return btn } func configuerDeleteBtn() -> UIButton { let btn = UIButton(type: .system) btn.setTitle("Delete", for: .normal) btn.setTitleColor( UIColor.lightGray, for: .normal) btn.frame.size = CGSize(width: 48, height: 38) btn.setImage( UIImage(named: "trash"), for: .normal) btn.translatesAutoresizingMaskIntoConstraints = false //btn.titleLabel?.font = UIFont(name: "Avenir", size: 18) btn.titleLabel?.font = UIFont.systemFont(ofSize: 19) btn.layer.cornerRadius = 5 btn.backgroundColor = UIColor.clear btn.addTarget(self, action: #selector(deleteFilesPressed), for: .touchUpInside) btn.tintColor = UIColor.gray return btn } func configuerBackBtn() -> UIButton { let btn = UIButton(type: .system) btn.setTitle(" Back", for: .normal) btn.setTitleColor( UIColor.lightGray, for: .normal) btn.contentVerticalAlignment = .fill btn.contentHorizontalAlignment = .fill //btn.setImage(UIImage.make(name: "send_btn"), for: .normal) btn.setImage(UIImage(named: "send_btn"), for: .normal) //btn.setImage(FileManagerVC._imagess["back"], for: .normal) btn.frame.size = CGSize(width: 48, height: 38) btn.translatesAutoresizingMaskIntoConstraints = false //btn.titleLabel?.font = UIFont(name: "Avenir", size: 18) btn.titleLabel?.font = UIFont.systemFont(ofSize: 19) btn.layer.cornerRadius = 5 btn.backgroundColor = UIColor.clear btn.addTarget(self, action: #selector(backTapped), for: .touchUpInside) btn.tintColor = UIColor.gray return btn } } //Constraints @available(iOS 9.0, *) extension FileManagerVC { //Important func setCollectionViewConstraints() { //handle x , y, width and height collectionView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true collectionView.topAnchor.constraint(equalTo: headerView.bottomAnchor).isActive = true collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true collectionView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true } func setButtonsContrainsts() { //handle x , y, width and height backBtn.bottomAnchor.constraint(equalTo: headerView.bottomAnchor, constant: -8).isActive = true backBtn.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 13).isActive = true deleteBtn.bottomAnchor.constraint(equalTo: headerView.bottomAnchor, constant: -8).isActive = true deleteBtn.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -14).isActive = true markBTN.bottomAnchor.constraint(equalTo: headerView.bottomAnchor, constant: -8).isActive = true markBTN.rightAnchor.constraint(equalTo: deleteBtn.leftAnchor, constant: -17).isActive = true } func setHeaderViewConstraints(){ //handle x , y, width and height headerView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true headerView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true headerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true headerView.heightAnchor.constraint(equalToConstant: 70).isActive = true } } @available(iOS 9.0, *) extension FileManagerVC { ///////////////////////////////////// func AlertDismiss(t: String, msg: String, yesCompletion: @escaping () -> ()) { let ac = UIAlertController(title: t, message: msg, preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) ac.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (alert: UIAlertAction) in //self.dismiss(animated: true, completion: nil) yesCompletion() })) self.present(ac, animated: true, completion: nil) } } @available(iOS 9.0, *) public extension UIImage { static func make(name: String) -> UIImage? { let bundle = Bundle(for: FileManagerVC.self) debugFM("\(contentsOfDirectoryAtPath(path: "\(Bundle(for: FileManagerVC.self).bundlePath)"))") debugFM("\(Bundle(for: FileManagerVC.self).bundlePath)/FileManager_Swift") debugFM("FileManager_Swift/Assets/\(name).xcassets/\(name)") //return UIImage(named: "FileManager-Swift/Assets/\(name).xcassets/\(name).imageset/\(name)", in: bundle, compatibleWith: nil) //return UIImage(named: "/Users/Mahmoud/Library/Developer/CoreSimulator/Devices/57E06727-662D-44F0-8A8D-83DA6B8776A9/data/Containers/Bundle/Application/10B539AB-038D-482B-A6B8-476CD929B841/FileManager-Swift_Example.app/Frameworks/FileManager_Swift.framework/send_btn.png", in: bundle, compatibleWith: nil) let url = URL(fileURLWithPath: "/Users/Mahmoud/Library/Developer/CoreSimulator/Devices/57E06727-662D-44F0-8A8D-83DA6B8776A9/data/Containers/Bundle/Application/10B539AB-038D-482B-A6B8-476CD929B841/FileManager-Swift_Example.app/Frameworks/FileManager_Swift.framework/").appendingPathComponent(name) return UIImage(contentsOfFile: "\(url)") } } /* ["/Users/Mahmoud/Library/Developer/CoreSimulator/Devices/57E06727-662D-44F0-8A8D-83DA6B8776A9/data/Containers/Bundle/Application/976A33C2-21DA-4EAF-94B5-2652C9B23A15/FileManager-Swift_Example.app/Frameworks/FileManager_Swift.framework/_CodeSignature", "/Users/Mahmoud/Library/Developer/CoreSimulator/Devices/57E06727-662D-44F0-8A8D-83DA6B8776A9/data/Containers/Bundle/Application/976A33C2-21DA-4EAF-94B5-2652C9B23A15/FileManager-Swift_Example.app/Frameworks/FileManager_Swift.framework/FileManager_Swift", "/Users/Mahmoud/Library/Developer/CoreSimulator/Devices/57E06727-662D-44F0-8A8D-83DA6B8776A9/data/Containers/Bundle/Application/976A33C2-21DA-4EAF-94B5-2652C9B23A15/FileManager-Swift_Example.app/Frameworks/FileManager_Swift.framework/Info.plist"] */ /* ["/Users/Mahmoud/Library/Developer/CoreSimulator/Devices/57E06727-662D-44F0-8A8D-83DA6B8776A9/data/Containers/Bundle/Application/10B539AB-038D-482B-A6B8-476CD929B841/FileManager-Swift_Example.app/Frameworks/FileManager_Swift.framework/_CodeSignature", "/Users/Mahmoud/Library/Developer/CoreSimulator/Devices/57E06727-662D-44F0-8A8D-83DA6B8776A9/data/Containers/Bundle/Application/10B539AB-038D-482B-A6B8-476CD929B841/FileManager-Swift_Example.app/Frameworks/FileManager_Swift.framework/Assets.car", "/Users/Mahmoud/Library/Developer/CoreSimulator/Devices/57E06727-662D-44F0-8A8D-83DA6B8776A9/data/Containers/Bundle/Application/10B539AB-038D-482B-A6B8-476CD929B841/FileManager-Swift_Example.app/Frameworks/FileManager_Swift.framework/FileManager_Swift", "/Users/Mahmoud/Library/Developer/CoreSimulator/Devices/57E06727-662D-44F0-8A8D-83DA6B8776A9/data/Containers/Bundle/Application/10B539AB-038D-482B-A6B8-476CD929B841/FileManager-Swift_Example.app/Frameworks/FileManager_Swift.framework/Info.plist", "/Users/Mahmoud/Library/Developer/CoreSimulator/Devices/57E06727-662D-44F0-8A8D-83DA6B8776A9/data/Containers/Bundle/Application/10B539AB-038D-482B-A6B8-476CD929B841/FileManager-Swift_Example.app/Frameworks/FileManager_Swift.framework/send_btn.png"]) */
mit
50f3e0f8787dda2a8032c9f29ea74f9d
51.661017
313
0.710653
3.896739
false
false
false
false
OpenStreetMap-Monitoring/OsMoiOs
iOsmo/XML.swift
2
3842
// XML.swift // XML // // Created by Craig Grummitt on 24/08/2016. // Copyright © 2016 interactivecoconut. All rights reserved. // import Foundation //Use XML class for XML document //Parse using Foundation's XMLParser open class XML:XMLNode { var parser:XMLParser init(data: Data) { self.parser = XMLParser(data: data) super.init() parser.delegate = self parser.parse() } init?(contentsOf url: URL) { guard let parser = XMLParser(contentsOf: url) else { return nil} self.parser = parser super.init() parser.delegate = self parser.parse() } } //Each element of the XML hierarchy is represented by an XMLNode //<name attribute="attribute_data">text<child></child></name> open class XMLNode:NSObject { var name:String? var attributes:[String:String] = [:] var text = "" var children:[XMLNode] = [] var parent:XMLNode? override init() { } init(name:String) { self.name = name } init(name:String,value:String) { self.name = name self.text = value } //MARK: Update data func indexIsValid(index: Int) -> Bool { return (index >= 0 && index <= children.count) } subscript(index: Int) -> XMLNode { get { assert(indexIsValid(index: index), "Index out of range") return children[index] } set { assert(indexIsValid(index: index), "Index out of range") children[index] = newValue newValue.parent = self } } subscript(index: String) -> XMLNode? { //if more than one exists, assume the first get { return children.filter({ $0.name == index }).first } set { guard let newNode = newValue, let filteredChild = children.filter({ $0.name == index }).first else {return} filteredChild.attributes = newNode.attributes filteredChild.text = newNode.text filteredChild.children = newNode.children } } func addChild(_ node:XMLNode) { children.append(node) node.parent = self } func addChild(name:String,value:String) { addChild(XMLNode(name: name, value: value)) } func removeChild(at index:Int) { children.remove(at: index) } //MARK: Description properties override open var description:String { if let name = name { return "<\(name)\(attributesDescription)>\(text)\(childrenDescription)</\(name)>" } else if let first = children.first { return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\(first.description)" } else { return "" } } var attributesDescription:String { return attributes.map({" \($0)=\"\($1)\" "}).joined() } var childrenDescription:String { return children.map({ $0.description }).joined() } } extension XMLNode:XMLParserDelegate { public func parser(_ parser: XMLParser, foundCharacters string: String) { text += string.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) } public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { let childNode = XMLNode() childNode.name = elementName childNode.parent = self childNode.attributes = attributeDict parser.delegate = childNode children.append(childNode) } public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if let parent = parent { parser.delegate = parent } } }
gpl-3.0
8a74ee9c300d223a5b74016a2617a63a
31.277311
186
0.596199
4.550948
false
false
false
false
dydyistc/DYWeibo
DYWeibo/AppDelegate.swift
1
1039
// // AppDelegate.swift // DYWeibo // // Created by Yi Deng on 26/03/2017. // Copyright © 2017 TD. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var defaultViewController : UIViewController? { let isLogin = UserAccountViewModel.sharedIntance.isLogin return isLogin ? WelcomeViewController() : UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // 设置全局颜色 UITabBar.appearance().tintColor = UIColor.orange UINavigationBar.appearance().tintColor = UIColor.orange // 创建window window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = defaultViewController window?.makeKeyAndVisible() return true } }
apache-2.0
e3b168cf9bc53966363e61832ec09590
27.388889
144
0.676125
5.465241
false
false
false
false
Egibide-DAM/swift
02_ejemplos/07_ciclo_vida/01_inicializacion/04_etiquetas_argumentos.playground/Contents.swift
1
478
struct Color { let red, green, blue: Double init(red: Double, green: Double, blue: Double) { self.red = red self.green = green self.blue = blue } init(white: Double) { red = white green = white blue = white } } let magenta = Color(red: 1.0, green: 0.0, blue: 1.0) let halfGray = Color(white: 0.5) let veryGreen = Color(0.0, 1.0, 0.0) // this reports a compile-time error - argument labels are required
apache-2.0
84849f120b3549671cb731a8cc5da981
24.157895
67
0.577406
3.208054
false
false
false
false
mwharrison/headphoned
Headphoned/StatusMenuController.swift
1
1407
// // StatusMenuController.swift // Headphoned // // Created by Michael Harrison on 9/17/15. // Copyright (c) 2015 Michael Harrison. All rights reserved. // import Cocoa class StatusMenuController: NSObject { @IBOutlet weak var headphoneMenu: NSMenu! @IBOutlet weak var deviceLabel: NSMenuItem! let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1) @IBAction func quitApp(sender: AnyObject) { NSApplication.sharedApplication().terminate(self) } override func awakeFromNib() { let headphoneIcon = NSImage(named: "headphoneIcon") statusItem.image = headphoneIcon deviceLabel.title = "Initializing..." statusItem.menu = headphoneMenu var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "updateAudio", userInfo: nil, repeats: true) } @objc func updateAudio() { var deviceName = EZAudioDevice.currentOutputDevice().name let redHeadphones = NSImage(named: "redHeadphones") let greenHeadphones = NSImage(named: "greenHeadphones") if deviceName == "Built-in Output" { statusItem.image = greenHeadphones }else{ statusItem.image = redHeadphones } statusItem.menu = headphoneMenu deviceLabel.title = deviceName } }
gpl-3.0
b53dec8f659c0c81c0e79eb62f390f56
28.3125
132
0.641791
4.936842
false
false
false
false
AnRanScheme/magiGlobe
magi/magiGlobe/Pods/SQLite.swift/Sources/SQLite/Typed/CustomFunctions.swift
17
7567
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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. // public extension Connection { /// Creates or redefines a custom SQL function. /// /// - Parameters: /// /// - function: The name of the function to create or redefine. /// /// - deterministic: Whether or not the function is deterministic (_i.e._ /// the function always returns the same result for a given input). /// /// Default: `false` /// /// - block: A block of code to run when the function is called. /// The assigned types must be explicit. /// /// - Returns: A closure returning an SQL expression to call the function. public func createFunction<Z : Value>(_ function: String, deterministic: Bool = false, _ block: @escaping () -> Z) throws -> (() -> Expression<Z>) { let fn = try createFunction(function, 0, deterministic) { _ in block() } return { fn([]) } } public func createFunction<Z : Value>(_ function: String, deterministic: Bool = false, _ block: @escaping () -> Z?) throws -> (() -> Expression<Z?>) { let fn = try createFunction(function, 0, deterministic) { _ in block() } return { fn([]) } } // MARK: - public func createFunction<Z : Value, A : Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A) -> Z) throws -> ((Expression<A>) -> Expression<Z>) { let fn = try createFunction(function, 1, deterministic) { args in block(value(args[0])) } return { arg in fn([arg]) } } public func createFunction<Z : Value, A : Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A?) -> Z) throws -> ((Expression<A?>) -> Expression<Z>) { let fn = try createFunction(function, 1, deterministic) { args in block(args[0].map(value)) } return { arg in fn([arg]) } } public func createFunction<Z : Value, A : Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A) -> Z?) throws -> ((Expression<A>) -> Expression<Z?>) { let fn = try createFunction(function, 1, deterministic) { args in block(value(args[0])) } return { arg in fn([arg]) } } public func createFunction<Z : Value, A : Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A?) -> Z?) throws -> ((Expression<A?>) -> Expression<Z?>) { let fn = try createFunction(function, 1, deterministic) { args in block(args[0].map(value)) } return { arg in fn([arg]) } } // MARK: - public func createFunction<Z : Value, A : Value, B : Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A, B) -> Z) throws -> (Expression<A>, Expression<B>) -> Expression<Z> { let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), value(args[1])) } return { a, b in fn([a, b]) } } public func createFunction<Z : Value, A : Value, B : Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A?, B) -> Z) throws -> (Expression<A?>, Expression<B>) -> Expression<Z> { let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), value(args[1])) } return { a, b in fn([a, b]) } } public func createFunction<Z : Value, A : Value, B : Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A, B?) -> Z) throws -> (Expression<A>, Expression<B?>) -> Expression<Z> { let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), args[1].map(value)) } return { a, b in fn([a, b]) } } public func createFunction<Z : Value, A : Value, B : Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A, B) -> Z?) throws -> (Expression<A>, Expression<B>) -> Expression<Z?> { let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), value(args[1])) } return { a, b in fn([a, b]) } } public func createFunction<Z : Value, A : Value, B : Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A?, B?) -> Z) throws -> (Expression<A?>, Expression<B?>) -> Expression<Z> { let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), args[1].map(value)) } return { a, b in fn([a, b]) } } public func createFunction<Z : Value, A : Value, B : Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A?, B) -> Z?) throws -> (Expression<A?>, Expression<B>) -> Expression<Z?> { let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), value(args[1])) } return { a, b in fn([a, b]) } } public func createFunction<Z : Value, A : Value, B : Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A, B?) -> Z?) throws -> (Expression<A>, Expression<B?>) -> Expression<Z?> { let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), args[1].map(value)) } return { a, b in fn([a, b]) } } public func createFunction<Z : Value, A : Value, B : Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A?, B?) -> Z?) throws -> (Expression<A?>, Expression<B?>) -> Expression<Z?> { let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), args[1].map(value)) } return { a, b in fn([a, b]) } } // MARK: - fileprivate func createFunction<Z : Value>(_ function: String, _ argumentCount: UInt, _ deterministic: Bool, _ block: @escaping ([Binding?]) -> Z) throws -> (([Expressible]) -> Expression<Z>) { createFunction(function, argumentCount: argumentCount, deterministic: deterministic) { arguments in block(arguments).datatypeValue } return { arguments in function.quote().wrap(", ".join(arguments)) } } fileprivate func createFunction<Z : Value>(_ function: String, _ argumentCount: UInt, _ deterministic: Bool, _ block: @escaping ([Binding?]) -> Z?) throws -> (([Expressible]) -> Expression<Z?>) { createFunction(function, argumentCount: argumentCount, deterministic: deterministic) { arguments in block(arguments)?.datatypeValue } return { arguments in function.quote().wrap(", ".join(arguments)) } } }
mit
ffb56d18bf877a9d5740d22f0507d63a
54.632353
210
0.629527
3.961257
false
false
false
false
BalestraPatrick/Tweetometer
Carthage/Checkouts/OAuthSwift/Demo/Common/FormViewController.swift
2
5005
// // FormViewController.swift // OAuthSwift // // Created by phimage on 23/07/16. // Copyright © 2016 Dongri Jin. All rights reserved. // #if os(iOS) import UIKit typealias FormViewControllerType = UITableViewController typealias Button = UISwitch typealias TextField = UITextField #elseif os(OSX) import AppKit typealias FormViewControllerType = NSViewController typealias Button = NSButton typealias TextField = NSTextField extension NSTextField { var text: String? { get { return self.stringValue } set { self.stringValue = newValue ?? "" } } } extension NSButton { var isOn: Bool { get { return self.state == .on } set { self.state = newValue ? .on : .off} } func setOn(_ value: Bool, animated: Bool) { isOn = value } } #endif enum URLHandlerType { case `internal` case external case safari } protocol FormViewControllerProvider { var key: String? {get} var secret: String? {get} } protocol FormViewControllerDelegate: FormViewControllerProvider { func didValidate(key: String?, secret: String?, handlerType: URLHandlerType) func didCancel() } class FormViewController: FormViewControllerType { var delegate: FormViewControllerDelegate? var safariURLHandlerAvailable: Bool { if #available(iOS 9.0, *) { return true } return false } override func viewDidLoad() { self.keyTextField.text = self.delegate?.key self.secretTextField.text = self.delegate?.secret #if os(iOS) safariURLHandlerView.isHidden = !self.safariURLHandlerAvailable #endif self.urlHandlerType = .`internal` } @IBOutlet weak var externalURLHandler: Button! @IBOutlet weak var internalURLHandler: Button! @IBOutlet var keyTextField: TextField! @IBOutlet var secretTextField: TextField! #if os(iOS) @IBOutlet weak var safariURLHandler: UISwitch! @IBOutlet weak var safariURLHandlerView: UITableViewCell! #endif @IBAction func ok(_ sender: AnyObject?) { self.dismiss(sender: sender) let key = keyTextField.text let secret = secretTextField.text let handlerType = urlHandlerType delegate?.didValidate(key: key, secret: secret, handlerType: handlerType) } @IBAction func cancel(_ sender: AnyObject?) { self.dismiss(sender: sender) delegate?.didCancel() } func dismiss(sender: AnyObject?) { #if os(iOS) // let parent #else self.dismiss(sender) #endif } @IBAction func urlHandlerChange(_ sender: Button) { if sender.isOn { if externalURLHandler == sender { urlHandlerType = .external } else if internalURLHandler == sender { urlHandlerType = .`internal` } #if os(iOS) if safariURLHandler == sender { urlHandlerType = .safari } #endif } else { // set another... if externalURLHandler == sender { urlHandlerType = .`internal` } else if internalURLHandler == sender { urlHandlerType = .external } #if os(iOS) if safariURLHandler == sender { urlHandlerType = .`internal` } #endif } } var urlHandlerType: URLHandlerType { get { if externalURLHandler.isOn { return .external } if internalURLHandler.isOn { return .`internal` } #if os(iOS) if safariURLHandler.isOn { return .safari } #endif return .`internal` } set { switch newValue { case .external: externalURLHandler.setOn(true, animated: false) internalURLHandler.setOn(false, animated: true) #if os(iOS) safariURLHandler.setOn(false, animated: true) #endif break case .`internal`: internalURLHandler.setOn(true, animated: false) externalURLHandler.setOn(false, animated: true) #if os(iOS) safariURLHandler.setOn(false, animated: true) #endif break case .safari: #if os(iOS) safariURLHandler.setOn(true, animated: false) #endif externalURLHandler.setOn(false, animated: true) internalURLHandler.setOn(false, animated: true) break } } } }
mit
6ddeb480be3f6d38e088e38852399d42
26.8
81
0.543565
5.351872
false
false
false
false
wangjianquan/wjq-weibo
weibo_wjq/Tool/Transition/PopAnimation.swift
1
3886
// // PopAnimation.swift // weibo_wjq // // Created by landixing on 2017/5/25. // Copyright © 2017年 WJQ. All rights reserved. // import UIKit class PopAnimation: NSObject{ //MARK: -- 属性 // 是否是presendted出来的 fileprivate var isPresented : Bool = false var presentedFrame:CGRect = CGRect.zero //闭包 var presentedCallBack : ((_ isPresented : Bool) -> ())? } extension PopAnimation : UIViewControllerTransitioningDelegate{ //返回一个负责转场动画的对象(UIPresentationController) func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController?{ let wjPresentationCoutroll = WjPresentationCoutro(presentedViewController: presented, presenting: presenting) wjPresentationCoutroll.presentedFrame = presentedFrame return wjPresentationCoutroll } //返回一个负责转场如何出现对象 --> presented func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresented = true if let presentedCallBack = presentedCallBack { presentedCallBack(isPresented) } return self } //返回一个负责转场如何消失对象 --> dismiss func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresented = false if let presentedCallBack = presentedCallBack { presentedCallBack(isPresented) } return self } } extension PopAnimation : UIViewControllerAnimatedTransitioning { //动画时长 func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } //管理modal如何展现和消失方式, 具体的动画实现完全由自己定义 func animateTransition(using transitionContext: UIViewControllerContextTransitioning){ isPresented ? presentedAnimate(transitionContext: transitionContext) : dismissAnimate(transitionContext: transitionContext) } //弹出时(presented)的动画 fileprivate func presentedAnimate(transitionContext: UIViewControllerContextTransitioning) { //toView是toVC对应的view guard let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) else { return } //将view添加到容器视图 transitionContext.containerView.addSubview(toView) /* **执行动画 */ //设置锚点(从上往下) toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0) //设置动画 toView.transform = CGAffineTransform(scaleX: 1.0, y: 0.0) UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { //还原动画 toView.transform = CGAffineTransform.identity }) { (_) in //结束动画 transitionContext.completeTransition(true) } } //消失时(dismiss)的动画 fileprivate func dismissAnimate(transitionContext: UIViewControllerContextTransitioning){ //从哪个视图控制器弹出的view let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from) UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { //还原动画 fromView?.transform = CGAffineTransform(scaleX: 1.0, y: 0.0000001) }) { (_) in //结束动画 transitionContext.completeTransition(true) } } }
apache-2.0
c83df7a93e78790cfad229a649b89d4a
31.627273
170
0.659794
5.705882
false
false
false
false
yoshiki/YKParallaxHeaderView
YKParallaxHeaderViewDemo/ViewController.swift
1
1140
import UIKit class ViewController: UIViewController { @IBOutlet var tableView: UITableView? let headerViewHeight: CGFloat = 200.0 override func viewDidLoad() { super.viewDidLoad() YKParallaxHeaderView(image: UIImage(named: "image.jpg")!, height: headerViewHeight, inView: tableView) tableView?.dataSource = self } } extension ViewController: UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 30 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let CellIdentifier: String = "Cell" var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(CellIdentifier) as? UITableViewCell if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: CellIdentifier) } cell?.textLabel?.text = "Row \(indexPath.row)" return cell! } }
mit
6199fe5303b89497a4ac42e49b5cbd78
32.558824
116
0.67807
5.643564
false
false
false
false
fredrikcollden/LittleMaestro
PuzzlePieceDestination.swift
1
1386
// // PuzzlePieceDestination.swift // MaestroLevel // // Created by Fredrik Colldén on 2015-10-29. // Copyright © 2015 Marie. All rights reserved. // import Foundation import SpriteKit class PuzzlePieceDestination: SKNode{ var depth: Int let note: Int var isActive = true var connectedPuzzlePiece: PuzzlePiece? let size: CGSize let bird: SKSpriteNode init(depth: Int, note: Int, textureName: String){ self.note = note self.depth = depth let texture = SKTexture(imageNamed: textureName) self.size = texture.size() self.bird = SKSpriteNode(texture: texture) self.bird.anchorPoint = CGPoint(x: 0.5, y: 0) super.init() self.addChild(bird) self.userInteractionEnabled = true self.bird.color = SKColor(red: 0, green: 0, blue: 0, alpha: 1) self.bird.colorBlendFactor = 1 self.zPosition = 50 self.physicsBody = SKPhysicsBody(rectangleOfSize: self.size) self.physicsBody?.dynamic = true self.physicsBody?.categoryBitMask = PhysicsCategory.PieceDestination self.physicsBody?.contactTestBitMask = PhysicsCategory.PuzzlePiece self.physicsBody?.collisionBitMask = PhysicsCategory.None } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
lgpl-3.0
3d321651efafd72caf53e0009dee0f58
28.446809
76
0.660405
4.393651
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/NCChargeTableViewCell.swift
2
2987
// // NCChargeTableViewCell.swift // Neocom // // Created by Artem Shimanski on 01.02.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit class NCChargeTableViewCell: NCTableViewCell { @IBOutlet weak var iconView: UIImageView? @IBOutlet weak var titleLabel: UILabel? @IBOutlet weak var emLabel: NCDamageTypeLabel! @IBOutlet weak var thermalLabel: NCDamageTypeLabel! @IBOutlet weak var kineticLabel: NCDamageTypeLabel! @IBOutlet weak var explosiveLabel: NCDamageTypeLabel! } extension Prototype { enum NCChargeTableViewCell { static let `default` = Prototype(nib: UINib(nibName: "NCChargeTableViewCell", bundle: nil), reuseIdentifier: "NCChargeTableViewCell") static let compact = Prototype(nib: UINib(nibName: "NCChargeCompactTableViewCell", bundle: nil), reuseIdentifier: "NCChargeCompactTableViewCell") } } class NCChargeRow: TreeRow { let type: NCDBInvType init(prototype: Prototype = Prototype.NCChargeTableViewCell.default, type: NCDBInvType, route: Route? = nil, accessoryButtonRoute: Route? = nil) { self.type = type let p = type.dgmppItem?.damage == nil ? Prototype.NCDefaultTableViewCell.compact : prototype super.init(prototype: p, route: route, accessoryButtonRoute: accessoryButtonRoute) } override func configure(cell: UITableViewCell) { if let cell = cell as? NCChargeTableViewCell { cell.titleLabel?.text = type.typeName cell.iconView?.image = type.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image cell.object = type if let damage = type.dgmppItem?.damage { var total = damage.emAmount + damage.kineticAmount + damage.thermalAmount + damage.explosiveAmount if total == 0 { total = 1 } cell.emLabel.progress = damage.emAmount / total cell.emLabel.text = NCUnitFormatter.localizedString(from: damage.emAmount, unit: .none, style: .short) cell.kineticLabel.progress = damage.kineticAmount / total cell.kineticLabel.text = NCUnitFormatter.localizedString(from: damage.kineticAmount, unit: .none, style: .short) cell.thermalLabel.progress = damage.thermalAmount / total cell.thermalLabel.text = NCUnitFormatter.localizedString(from: damage.thermalAmount, unit: .none, style: .short) cell.explosiveLabel.progress = damage.explosiveAmount / total cell.explosiveLabel.text = NCUnitFormatter.localizedString(from: damage.explosiveAmount, unit: .none, style: .short) } else { for label in [cell.emLabel, cell.kineticLabel, cell.thermalLabel, cell.explosiveLabel] { label?.progress = 0 label?.text = "0" } } } else if let cell = cell as? NCDefaultTableViewCell { cell.titleLabel?.text = type.typeName cell.iconView?.image = type.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image cell.object = type } } override var hash: Int { return type.hashValue } override func isEqual(_ object: Any?) -> Bool { return (object as? NCChargeRow)?.hashValue == hashValue } }
lgpl-2.1
3d2a2cf7c72c6c0e7e3e0d2b6801beab
35.414634
147
0.735432
3.828205
false
false
false
false
adrfer/swift
test/SILGen/expressions.swift
1
16315
// RUN: rm -rf %t // RUN: mkdir %t // RUN: echo "public var x = Int()" | %target-swift-frontend -module-name FooBar -emit-module -o %t - // RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s -I%t -disable-access-control | FileCheck %s import Swift import FooBar struct SillyString : _BuiltinStringLiteralConvertible, StringLiteralConvertible { init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {} init(unicodeScalarLiteral value: SillyString) { } init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1 ) { } init(extendedGraphemeClusterLiteral value: SillyString) { } init( _builtinStringLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1) { } init(stringLiteral value: SillyString) { } } struct SillyUTF16String : _BuiltinUTF16StringLiteralConvertible, StringLiteralConvertible { init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { } init(unicodeScalarLiteral value: SillyString) { } init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1 ) { } init(extendedGraphemeClusterLiteral value: SillyString) { } init( _builtinStringLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1 ) { } init( _builtinUTF16StringLiteral start: Builtin.RawPointer, numberOfCodeUnits: Builtin.Word ) { } init(stringLiteral value: SillyUTF16String) { } } func literals() { var a = 1 var b = 1.25 var d = "foö" var e:SillyString = "foo" } // CHECK-LABEL: sil hidden @_TF11expressions8literalsFT_T_ // CHECK: integer_literal $Builtin.Int2048, 1 // CHECK: float_literal $Builtin.FPIEEE{{64|80}}, {{0x3FF4000000000000|0x3FFFA000000000000000}} // CHECK: string_literal utf16 "foö" // CHECK: string_literal utf8 "foo" func bar(x: Int) {} func bar(x: Int, _ y: Int) {} func call_one() { bar(42); } // CHECK-LABEL: sil hidden @_TF11expressions8call_oneFT_T_ // CHECK: [[BAR:%[0-9]+]] = function_ref @_TF11expressions3bar{{.*}} : $@convention(thin) (Int) -> () // CHECK: [[FORTYTWO:%[0-9]+]] = integer_literal {{.*}} 42 // CHECK: [[FORTYTWO_CONVERTED:%[0-9]+]] = apply {{.*}}([[FORTYTWO]], {{.*}}) // CHECK: apply [[BAR]]([[FORTYTWO_CONVERTED]]) func call_two() { bar(42, 219) } // CHECK-LABEL: sil hidden @_TF11expressions8call_twoFT_T_ // CHECK: [[BAR:%[0-9]+]] = function_ref @_TF11expressions3bar{{.*}} : $@convention(thin) (Int, Int) -> () // CHECK: [[FORTYTWO:%[0-9]+]] = integer_literal {{.*}} 42 // CHECK: [[FORTYTWO_CONVERTED:%[0-9]+]] = apply {{.*}}([[FORTYTWO]], {{.*}}) // CHECK: [[TWONINETEEN:%[0-9]+]] = integer_literal {{.*}} 219 // CHECK: [[TWONINETEEN_CONVERTED:%[0-9]+]] = apply {{.*}}([[TWONINETEEN]], {{.*}}) // CHECK: apply [[BAR]]([[FORTYTWO_CONVERTED]], [[TWONINETEEN_CONVERTED]]) func tuples() { bar((4, 5).1) var T1 : (a: Int16, b: Int) = (b : 42, a : 777) } // CHECK-LABEL: sil hidden @_TF11expressions6tuplesFT_T_ class C { var chi:Int init() { chi = 219 } init(x:Int) { chi = x } } // CHECK-LABEL: sil hidden @_TF11expressions7classesFT_T_ func classes() { // CHECK: function_ref @_TFC11expressions1CC{{.*}} : $@convention(thin) (@thick C.Type) -> @owned C var a = C() // CHECK: function_ref @_TFC11expressions1CC{{.*}} : $@convention(thin) (Int, @thick C.Type) -> @owned C var b = C(x: 0) } struct S { var x:Int init() { x = 219 } init(x: Int) { self.x = x } } // CHECK-LABEL: sil hidden @_TF11expressions7structsFT_T_ func structs() { // CHECK: function_ref @_TFV11expressions1SC{{.*}} : $@convention(thin) (@thin S.Type) -> S var a = S() // CHECK: function_ref @_TFV11expressions1SC{{.*}} : $@convention(thin) (Int, @thin S.Type) -> S var b = S(x: 0) } func inoutcallee(inout x: Int) {} func address_of_expr() { var x: Int = 4 inoutcallee(&x) } func identity<T>(x: T) -> T {} struct SomeStruct { mutating func a() {} } // CHECK-LABEL: sil hidden @_TF11expressions5callsFT_T_ // CHECK: [[METHOD:%[0-9]+]] = function_ref @_TFV11expressions10SomeStruct1a{{.*}} : $@convention(method) (@inout SomeStruct) -> () // CHECK: apply [[METHOD]]({{.*}}) func calls() { var a : SomeStruct a.a() } // CHECK-LABEL: sil hidden @_TF11expressions11module_path func module_path() -> Int { return FooBar.x // CHECK: [[x_GET:%[0-9]+]] = function_ref @_TF6FooBarau1xSi // CHECK-NEXT: apply [[x_GET]]() } func default_args(x: Int, y: Int = 219, z: Int = 20721) {} // CHECK-LABEL: sil hidden @_TF11expressions19call_default_args_1 func call_default_args_1(x: Int) { default_args(x) // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF11expressions12default_args // CHECK: [[YFUNC:%[0-9]+]] = function_ref @_TIF11expressions12default_args // CHECK: [[Y:%[0-9]+]] = apply [[YFUNC]]() // CHECK: [[ZFUNC:%[0-9]+]] = function_ref @_TIF11expressions12default_args // CHECK: [[Z:%[0-9]+]] = apply [[ZFUNC]]() // CHECK: apply [[FUNC]]({{.*}}, [[Y]], [[Z]]) } // CHECK-LABEL: sil hidden @_TF11expressions19call_default_args_2 func call_default_args_2(x: Int, z: Int) { default_args(x, z:z) // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF11expressions12default_args // CHECK: [[DEFFN:%[0-9]+]] = function_ref @_TIF11expressions12default_args // CHECK-NEXT: [[C219:%[0-9]+]] = apply [[DEFFN]]() // CHECK: apply [[FUNC]]({{.*}}, [[C219]], {{.*}}) } struct Generic<T> { var mono_member:Int var typevar_member:T // CHECK-LABEL: sil hidden @_TFV11expressions7Generic13type_variable mutating func type_variable() -> T.Type { return T.self // CHECK: [[METATYPE:%[0-9]+]] = metatype $@thick T.Type // CHECK: return [[METATYPE]] } // CHECK-LABEL: sil hidden @_TFV11expressions7Generic19copy_typevar_member mutating func copy_typevar_member(x: Generic<T>) { typevar_member = x.typevar_member } // CHECK-LABEL: sil hidden @_TZFV11expressions7Generic12class_method static func class_method() {} } // CHECK-LABEL: sil hidden @_TF11expressions18generic_member_ref func generic_member_ref<T>(x: Generic<T>) -> Int { // CHECK: bb0([[XADDR:%[0-9]+]] : $*Generic<T>): return x.mono_member // CHECK: [[MEMBER_ADDR:%[0-9]+]] = struct_element_addr {{.*}}, #Generic.mono_member // CHECK: load [[MEMBER_ADDR]] } // CHECK-LABEL: sil hidden @_TF11expressions24bound_generic_member_ref func bound_generic_member_ref(x: Generic<UnicodeScalar>) -> Int { var x = x // CHECK: bb0([[XADDR:%[0-9]+]] : $Generic<UnicodeScalar>): return x.mono_member // CHECK: [[MEMBER_ADDR:%[0-9]+]] = struct_element_addr {{.*}}, #Generic.mono_member // CHECK: load [[MEMBER_ADDR]] } // CHECK-LABEL: sil hidden @_TF11expressions6coerce func coerce(x: Int32) -> Int64 { return 0 } class B { } class D : B { } // CHECK-LABEL: sil hidden @_TF11expressions8downcast func downcast(x: B) -> D { return x as! D // CHECK: unconditional_checked_cast %{{[0-9]+}} : {{.*}} to $D } // CHECK-LABEL: sil hidden @_TF11expressions6upcast func upcast(x: D) -> B { return x // CHECK: upcast %{{[0-9]+}} : ${{.*}} to $B } // CHECK-LABEL: sil hidden @_TF11expressions14generic_upcast func generic_upcast<T : B>(x: T) -> B { return x // CHECK: upcast %{{.*}} to $B // CHECK: return } // CHECK-LABEL: sil hidden @_TF11expressions16generic_downcast func generic_downcast<T : B>(x: T, y: B) -> T { return y as! T // CHECK: unconditional_checked_cast %{{[0-9]+}} : {{.*}} to $T // CHECK: return } // TODO: generic_downcast // CHECK-LABEL: sil hidden @_TF11expressions15metatype_upcast func metatype_upcast() -> B.Type { return D.self // CHECK: metatype $@thick D // CHECK-NEXT: upcast } // CHECK-LABEL: sil hidden @_TF11expressions19interpolated_string func interpolated_string(x: Int, y: String) -> String { return "The \(x) Million Dollar \(y)" } protocol Runcible { typealias U var free:Int { get } var associated:U { get } func free_method() -> Int mutating func associated_method() -> U.Type static func static_method() } protocol Mincible { var free:Int { get } func free_method() -> Int static func static_method() } protocol Bendable { } protocol Wibbleable { } // CHECK-LABEL: sil hidden @_TF11expressions20archetype_member_ref func archetype_member_ref<T : Runcible>(x: T) { var x = x x.free_method() // CHECK: witness_method $T, #Runcible.free_method!1 // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $T // CHECK-NEXT: copy_addr [[X:%.*]] to [initialization] [[TEMP]] // CHECK-NEXT: apply // CHECK-NEXT: destroy_addr [[TEMP]] var u = x.associated_method() // CHECK: witness_method $T, #Runcible.associated_method!1 // CHECK-NEXT: apply T.static_method() // CHECK: witness_method $T, #Runcible.static_method!1 // CHECK-NEXT: metatype $@thick T.Type // CHECK-NEXT: apply } // CHECK-LABEL: sil hidden @_TF11expressions22existential_member_ref func existential_member_ref(x: Mincible) { x.free_method() // CHECK: open_existential_addr // CHECK-NEXT: witness_method // CHECK-NEXT: apply } /*TODO archetype and existential properties and subscripts func archetype_property_ref<T : Runcible>(x: T) -> (Int, T.U) { x.free = x.free_method() x.associated = x.associated_method() return (x.free, x.associated) } func existential_property_ref<T : Runcible>(x: T) -> Int { x.free = x.free_method() return x.free } also archetype/existential subscripts */ struct Spoon : Runcible, Mincible { typealias U = Float var free: Int { return 4 } var associated: Float { return 12 } func free_method() -> Int {} func associated_method() -> Float.Type {} static func static_method() {} } struct Hat<T> : Runcible { typealias U = [T] var free: Int { return 1 } var associated: U { get {} } func free_method() -> Int {} // CHECK-LABEL: sil hidden @_TFV11expressions3Hat17associated_method mutating func associated_method() -> U.Type { return U.self // CHECK: [[META:%[0-9]+]] = metatype $@thin Array<T>.Type // CHECK: return [[META]] } static func static_method() {} } // CHECK-LABEL: sil hidden @_TF11expressions7erasure func erasure(x: Spoon) -> Mincible { return x // CHECK: init_existential_addr // CHECK: return } // CHECK-LABEL: sil hidden @_TF11expressions19declref_to_metatypeFT_MVS_5Spoon func declref_to_metatype() -> Spoon.Type { return Spoon.self // CHECK: metatype $@thin Spoon.Type } // CHECK-LABEL: sil hidden @_TF11expressions27declref_to_generic_metatype func declref_to_generic_metatype() -> Generic<UnicodeScalar>.Type { // FIXME parsing of T<U> in expression context typealias GenericChar = Generic<UnicodeScalar> return GenericChar.self // CHECK: metatype $@thin Generic<UnicodeScalar>.Type } func int(x: Int) {} func float(x: Float) {} func tuple() -> (Int, Float) { return (1, 1.0) } // CHECK-LABEL: sil hidden @_TF11expressions13tuple_element func tuple_element(x: (Int, Float)) { var x = x // CHECK: [[XADDR:%.*]] = alloc_box $(Int, Float) // CHECK: [[PB:%.*]] = project_box [[XADDR]] int(x.0) // CHECK: tuple_element_addr [[PB]] : {{.*}}, 0 // CHECK: apply float(x.1) // CHECK: tuple_element_addr [[PB]] : {{.*}}, 1 // CHECK: apply int(tuple().0) // CHECK: [[ZERO:%.*]] = tuple_extract {{%.*}} : {{.*}}, 0 // CHECK: apply {{.*}}([[ZERO]]) float(tuple().1) // CHECK: [[ONE:%.*]] = tuple_extract {{%.*}} : {{.*}}, 1 // CHECK: apply {{.*}}([[ONE]]) } // CHECK-LABEL: sil hidden @_TF11expressions10containers func containers() -> ([Int], Dictionary<String, Int>) { return ([1, 2, 3], ["Ankeny": 1, "Burnside": 2, "Couch": 3]) } // CHECK-LABEL: sil hidden @_TF11expressions7if_expr func if_expr(a: Bool, b: Bool, x: Int, y: Int, z : Int) -> Int { var a = a var b = b var x = x var y = y var z = z // CHECK: bb0({{.*}}): // CHECK: [[AB:%[0-9]+]] = alloc_box $Bool // CHECK: [[PBA:%.*]] = project_box [[AB]] // CHECK: [[BB:%[0-9]+]] = alloc_box $Bool // CHECK: [[PBB:%.*]] = project_box [[BB]] // CHECK: [[XB:%[0-9]+]] = alloc_box $Int // CHECK: [[PBX:%.*]] = project_box [[XB]] // CHECK: [[YB:%[0-9]+]] = alloc_box $Int // CHECK: [[PBY:%.*]] = project_box [[YB]] // CHECK: [[ZB:%[0-9]+]] = alloc_box $Int // CHECK: [[PBZ:%.*]] = project_box [[ZB]] return a ? x : b ? y : z // CHECK: [[A:%[0-9]+]] = load [[PBA]] // CHECK: [[ACOND:%[0-9]+]] = apply {{.*}}([[A]]) // CHECK: cond_br [[ACOND]], [[IF_A:bb[0-9]+]], [[ELSE_A:bb[0-9]+]] // CHECK: [[IF_A]]: // CHECK: [[XVAL:%[0-9]+]] = load [[PBX]] // CHECK: br [[CONT_A:bb[0-9]+]]([[XVAL]] : $Int) // CHECK: [[ELSE_A]]: // CHECK: [[B:%[0-9]+]] = load [[PBB]] // CHECK: [[BCOND:%[0-9]+]] = apply {{.*}}([[B]]) // CHECK: cond_br [[BCOND]], [[IF_B:bb[0-9]+]], [[ELSE_B:bb[0-9]+]] // CHECK: [[IF_B]]: // CHECK: [[YVAL:%[0-9]+]] = load [[PBY]] // CHECK: br [[CONT_B:bb[0-9]+]]([[YVAL]] : $Int) // CHECK: [[ELSE_B]]: // CHECK: [[ZVAL:%[0-9]+]] = load [[PBZ]] // CHECK: br [[CONT_B:bb[0-9]+]]([[ZVAL]] : $Int) // CHECK: [[CONT_B]]([[B_RES:%[0-9]+]] : $Int): // CHECK: br [[CONT_A:bb[0-9]+]]([[B_RES]] : $Int) // CHECK: [[CONT_A]]([[A_RES:%[0-9]+]] : $Int): // CHECK: return [[A_RES]] } // Test that magic identifiers expand properly. We test __COLUMN__ here because // it isn't affected as this testcase slides up and down the file over time. func magic_identifier_expansion(a: Int = __COLUMN__) { // CHECK-LABEL: sil hidden @{{.*}}magic_identifier_expansion // This should expand to the column number of the first _. var tmp = __COLUMN__ // CHECK: integer_literal $Builtin.Int2048, 13 // This should expand to the column number of the (, not to the column number // of __COLUMN__ in the default argument list of this function. // rdar://14315674 magic_identifier_expansion() // CHECK: integer_literal $Builtin.Int2048, 29 } func print_string() { // CHECK-LABEL: print_string var str = "\u{08}\u{09}\thello\r\n\0wörld\u{1e}\u{7f}" // CHECK: string_literal utf16 "\u{08}\t\thello\r\n\0wörld\u{1E}\u{7F}" } // Test that we can silgen superclass calls that go farther than the immediate // superclass. class Super1 { func funge() {} } class Super2 : Super1 {} class Super3 : Super2 { override func funge() { super.funge() } } // <rdar://problem/16880240> SILGen crash assigning to _ func testDiscardLValue() { var a = 42 _ = a } func dynamicTypePlusZero(a : Super1) -> Super1.Type { return a.dynamicType } // CHECK-LABEL: dynamicTypePlusZero // CHECK: bb0(%0 : $Super1): // CHECK-NOT: retain // CHECK: value_metatype $@thick Super1.Type, %0 : $Super1 struct NonTrivialStruct { var c : Super1 } func dontEmitIgnoredLoadExpr(a : NonTrivialStruct) -> NonTrivialStruct.Type { return a.dynamicType } // CHECK-LABEL: dontEmitIgnoredLoadExpr // CHECK: bb0(%0 : $NonTrivialStruct): // CHECK-NEXT: debug_value // CHECK-NEXT: %2 = metatype $@thin NonTrivialStruct.Type // CHECK-NEXT: release_value %0 // CHECK-NEXT: return %2 : $@thin NonTrivialStruct.Type // <rdar://problem/18851497> Swiftc fails to compile nested destructuring tuple binding // CHECK-LABEL: sil hidden @_TF11expressions21implodeRecursiveTupleFGSqTTSiSi_Si__T_ // CHECK: bb0(%0 : $Optional<((Int, Int), Int)>): func implodeRecursiveTuple(expr: ((Int, Int), Int)?) { // CHECK: [[WHOLE:%[0-9]+]] = load {{.*}} : $*((Int, Int), Int) // CHECK-NEXT: [[WHOLE0:%[0-9]+]] = tuple_extract [[WHOLE]] : $((Int, Int), Int), 0 // CHECK-NEXT: [[WHOLE00:%[0-9]+]] = tuple_extract [[WHOLE0]] : $(Int, Int), 0 // CHECK-NEXT: [[WHOLE01:%[0-9]+]] = tuple_extract [[WHOLE0]] : $(Int, Int), 1 // CHECK-NEXT: [[WHOLE1:%[0-9]+]] = tuple_extract [[WHOLE]] : $((Int, Int), Int), 1 // CHECK-NEXT: [[X:%[0-9]+]] = tuple ([[WHOLE00]] : $Int, [[WHOLE01]] : $Int) // CHECK-NEXT: debug_value [[X]] : $(Int, Int), let, name "x" // CHECK-NEXT: debug_value [[WHOLE1]] : $Int, let, name "y" let (x, y) = expr! } func test20087517() { class Color { static func greenColor() -> Color { return Color() } } let x: (Color!, Int) = (.greenColor(), 1) } func test20596042() { enum E { case thing1 case thing2 } func f() -> (E?, Int)? { return (.thing1, 1) } } func test21886435() { () = () }
apache-2.0
41844e64477ee3d4a827da63addc3e8e
27.219723
131
0.618356
3.1678
false
false
false
false
adrfer/swift
test/ClangModules/ctypes_parse_bitfields.swift
14
515
// RUN: %target-parse-verify-swift %clang-importer-sdk import ctypes func useStructWithBitfields(mrm: ModRM) -> ModRM { let rm: CUnsignedInt = mrm.rm let reg: CUnsignedInt = mrm.reg let mod: CUnsignedInt = mrm.mod let opcode: CUnsignedInt = mrm.opcode var new: ModRM = ModRM() new.rm = rm new.reg = reg new.mod = mod new.opcode = opcode return mrm } func constructStructWithBitfields(x: CUnsignedInt) { _ = StructWithBitfields() _ = StructWithBitfields(First: x, Second: x, Third: x) }
apache-2.0
172b70e3a7859c95d15fefd585319ad5
21.391304
56
0.697087
3.433333
false
false
false
false
tuannme/Up
Up+/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallScaleRipple.swift
2
2941
// // NVActivityIndicatorAnimationBallScaleRipple.swift // NVActivityIndicatorViewDemo // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit class NVActivityIndicatorAnimationBallScaleRipple: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let duration: CFTimeInterval = 1 let timingFunction = CAMediaTimingFunction(controlPoints: 0.21, 0.53, 0.56, 0.8) // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.7] scaleAnimation.timingFunction = timingFunction scaleAnimation.values = [0.1, 1] scaleAnimation.duration = duration // Opacity animation let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.keyTimes = [0, 0.7, 1] opacityAnimation.timingFunctions = [timingFunction, timingFunction] opacityAnimation.values = [1, 0.7, 0] opacityAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimation] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circle let circle = NVActivityIndicatorShape.ring.layerWith(size: size, color: color) let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } }
mit
6535e9e52a75277cc387c09e1266f5d8
40.422535
89
0.681741
5.079447
false
false
false
false
artsy/eigen
ios/ArtsyWidget/FullBleed/FullBleed+View.swift
1
2527
import Foundation import SwiftUI import WidgetKit extension FullBleed { struct View: SwiftUI.View { static var supportedFamilies: [WidgetFamily] { if #available(iOSApplicationExtension 15.0, *) { return [.systemLarge, .systemExtraLarge] } else { return [.systemLarge] } } let entry: Entry var artwork: Artwork { return entry.artwork } var body: some SwiftUI.View { let artsyLogo = UIImage(named: "WhiteArtsyLogo")! let artworkImage = artwork.image! let artistName = artwork.artist.name let artworkTitle = artwork.title let artworkUrl = artwork.url GeometryReader { geo in ZStack() { Image(uiImage: artworkImage) .resizable() .scaledToFill() .frame(width: geo.size.width, height: geo.size.height, alignment: .top) VStack() { Spacer() HStack() { VStack() { PrimaryText(name: artistName, color: .white) .lineLimit(1) .frame(maxWidth: .infinity, alignment: .leading) SecondaryText(title: artworkTitle, color: .white) .lineLimit(1) .frame(maxWidth: .infinity, alignment: .leading) } Spacer() Image(uiImage: artsyLogo) .resizable() .frame(width: 20, height: 20) } .padding(16) .background(Color.black) } .widgetURL(artworkUrl) } } } } } struct FullBleed_View_Previews: PreviewProvider { static var previews: some SwiftUI.View { let entry = FullBleed.Entry.fallback() let families = FullBleed.View.supportedFamilies Group { ForEach(families, id: \.self) { family in FullBleed.View(entry: entry) .previewContext(WidgetPreviewContext(family: family)) } } } }
mit
28f9420685f501937bf9906a1e0c2dfe
33.148649
95
0.43332
5.863109
false
false
false
false
tavultesoft/keymanweb
ios/engine/KMEI/KeymanEngine/Classes/Installation/PackageInstallViewController.swift
1
22094
// // PackageInstallViewController.swift // KeymanEngine // // Created by Joshua Horton on 12/18/19. // Copyright © 2019 SIL International. All rights reserved. // import Foundation import WebKit import DeviceKit public class PackageInstallViewController<Resource: LanguageResource>: UIViewController, UITableViewDelegate, UITableViewDataSource, UITabBarControllerDelegate, UIAdaptivePresentationControllerDelegate { private enum NavigationMode: Int { // b/c hashable // left nav case cancel case back // right nav case none case next case install } private enum CellStyle { case none case preinstalled case install } public typealias CompletionHandler = ([Resource.FullID]?) -> Void // Needed to support iOS 9 + 10. @IBOutlet weak var webViewContainer: UIView! // Common fields between both layout formats. @IBOutlet weak var lblVersion: UILabel! @IBOutlet weak var lblCopyright: UILabel! @IBOutlet weak var languageTable: UITableView! // iPad layout only - May be altered programatically. @IBOutlet weak var ipadTagWidthConstraint: NSLayoutConstraint? // iPhone layout only // Do _NOT_ use `weak` here - things break otherwise. @IBOutlet var iphoneTabViewController: UITabBarController! let package: Resource.Package var packagePageController: PackageWebViewController? let pickingCompletionHandler: CompletionHandler let uiCompletionHandler: (() -> Void) let defaultLanguageCode: String let associators: [LanguagePickAssociator] let languages: [Language] let preinstalledLanguageCodes: Set<String> private var leftNavMode: NavigationMode = .cancel private var rightNavMode: NavigationMode = .none private var navMapping: [NavigationMode : UIBarButtonItem] = [:] private var dismissalBlock: (() -> Void)? = nil private weak var welcomeView: UIView? private var mayPick: Bool = true public init(for package: Resource.Package, defaultLanguageCode: String? = nil, languageAssociators: [LanguagePickAssociator] = [], pickingCompletionHandler: @escaping CompletionHandler, uiCompletionHandler: @escaping (() -> Void)) { self.package = package self.pickingCompletionHandler = pickingCompletionHandler self.uiCompletionHandler = uiCompletionHandler self.languages = package.languages self.associators = languageAssociators var xib: String if Device.current.isPad { xib = "PackageInstallView_iPad" } else { xib = "PackageInstallView_iPhone" } self.preinstalledLanguageCodes = PackageInstallViewController<Resource>.checkPreinstalledResources(package: package) self.defaultLanguageCode = PackageInstallViewController<Resource>.chooseDefaultSelectedLanguage(from: package, promptingCode: defaultLanguageCode, preinstalleds: self.preinstalledLanguageCodes) super.init(nibName: xib, bundle: Bundle.init(for: PackageInstallViewController.self)) _ = view } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Must be static if we want the resulting value to be stored via `let` semantics during init. private static func checkPreinstalledResources(package: Resource.Package) -> Set<String> { var preinstalleds: Set<String> = Set() guard let typedPackage = package as? TypedKeymanPackage<Resource> else { log.warning("Cannot check for previously-installed resources of unexpected type") return preinstalleds } if let installedResources: [Resource] = Storage.active.userDefaults.userResources(ofType: Resource.self) { installedResources.forEach { resource in if resource.packageKey == package.key { // The resource is from this package. let langResources = typedPackage.installables(forLanguage: resource.languageID) if langResources.contains(where: { $0.typedFullID == resource.typedFullID }){ preinstalleds.insert(resource.languageID) } } } } return preinstalleds } private static func chooseDefaultSelectedLanguage(from package: Resource.Package, promptingCode defaultLanguageCode: String?, preinstalleds: Set<String>) -> String { // If a default language code was specified, always pre-select it by default. // Even if the corresponding resource was already installed - the user may be 'manually updating' it. if package.languages.contains(where: { $0.id == defaultLanguageCode }) { return defaultLanguageCode! } // Otherwise... find the first not-already-installed language code. For now, at least. let uninstalledSet = package.installableResourceSets.first { set in return set.contains(where: { !preinstalleds.contains($0.languageID) }) } if uninstalledSet != nil { return uninstalledSet!.first{ !preinstalleds.contains($0.languageID) }!.languageID } // Failing that... just return the very first language and be done with it. return package.installableResourceSets[0][0].languageID } override public func viewDidLoad() { // The 'readme' version is guaranteed. // "Embeds" an instance of the more general PackageWebViewController. packagePageController = PackageWebViewController(for: package, page: .readme)! packagePageController!.willMove(toParent: self) let wkWebView = packagePageController!.view wkWebView!.frame = webViewContainer.frame wkWebView!.backgroundColor = .white wkWebView!.translatesAutoresizingMaskIntoConstraints = false webViewContainer.addSubview(wkWebView!) self.addChild(packagePageController!) packagePageController!.didMove(toParent: self) // Ensure the web view fills its available space. Required b/c iOS 9 & 10 cannot load // these correctly from XIBs. wkWebView!.topAnchor.constraint(equalTo: webViewContainer.topAnchor).isActive = true wkWebView!.leadingAnchor.constraint(equalTo: webViewContainer.leadingAnchor).isActive = true wkWebView!.bottomAnchor.constraint(equalTo: webViewContainer.bottomAnchor).isActive = true wkWebView!.trailingAnchor.constraint(equalTo: webViewContainer.trailingAnchor).isActive = true loadNavigationItems() leftNavigationMode = .cancel rightNavigationMode = .install navigationItem.title = package.name // Initialize the package info labels and the language-picker table. let versionFormat = NSLocalizedString("installer-label-version", bundle: engineBundle, comment: "") lblVersion.text = String.localizedStringWithFormat(versionFormat, package.version.description) if let copyright = package.metadata.info?.copyright?.description { lblCopyright.text = copyright } else { lblCopyright.isHidden = true } languageTable.delegate = self languageTable.dataSource = self // Set the default selection. let defaultRow = languages.firstIndex(where: { $0.id == self.defaultLanguageCode })! let defaultIndexPath = IndexPath(row: defaultRow, section: 0) languageTable.selectRow(at: defaultIndexPath, animated: false, scrollPosition: .top) languageTable.cellForRow(at: defaultIndexPath)?.accessoryType = .checkmark associators.forEach { $0.pickerInitialized() $0.selectLanguages(Set([self.defaultLanguageCode])) } // iPhone-only layout setup if let tabVC = iphoneTabViewController { tabVC.delegate = self let tabView = tabVC.view! tabView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(tabVC.view) tabView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true tabView.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor).isActive = true tabView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true tabView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true tabVC.tabBar.items![0].title = NSLocalizedString("installer-label-package-info", bundle: engineBundle, comment: "") tabVC.tabBar.items![1].title = NSLocalizedString("installer-label-select-languages", bundle: engineBundle, comment: "") // Prevents the tab view from being obscured by the navigation bar. // It's weird, yeah. edgesForExtendedLayout = [] rightNavigationMode = .next if #available(*, iOS 13.4) { // No icon issues here. } else { tabVC.tabBar.items![0].titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -16) tabVC.tabBar.items![1].titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -16) } } // If there's only one language in the package, hide the language picker. if languages.count <= 1 { if let sourceTagConstraint = ipadTagWidthConstraint { // Rebuild the width constraint, setting it to zero width. // The 'proper' iOS approach is to disable the old one and replace it with a new one. sourceTagConstraint.isActive = false let hideTagConstraint = NSLayoutConstraint(item: sourceTagConstraint.firstItem as Any, attribute: sourceTagConstraint.firstAttribute, relatedBy: sourceTagConstraint.relation, toItem: sourceTagConstraint.secondItem, attribute: sourceTagConstraint.secondAttribute, multiplier: 0, constant: 0) hideTagConstraint.isActive = true } else if let tabVC = iphoneTabViewController { // Hide the tab bar, making it appear as if only the "info view" portion exists. tabVC.tabBar.isHidden = true // Since we won't be showing the user a language list, allow them to install from the info view. rightNavigationMode = .install } } } private func loadNavigationItems() { navMapping[.cancel] = UIBarButtonItem(title: NSLocalizedString("command-cancel", bundle: engineBundle, comment: ""), style: .plain, target: self, action: #selector(cancelBtnHandler)) navMapping[.back] = UIBarButtonItem(title: NSLocalizedString("command-back", bundle: engineBundle, comment: ""), style: .plain, target: self, action: #selector(backBtnHandler)) navMapping[.none] = UIBarButtonItem(title: NSLocalizedString("command-install", bundle: engineBundle, comment: ""), style: .plain, target: self, action: nil) navMapping[.none]!.isEnabled = false navMapping[.next] = UIBarButtonItem(title: NSLocalizedString("command-next", bundle: engineBundle, comment: ""), style: .plain, target: self, action: #selector(nextBtnHandler)) navMapping[.install] = UIBarButtonItem(title: NSLocalizedString("command-install", bundle: engineBundle, comment: ""), style: .plain, target: self, action: #selector(installBtnHandler)) } private var leftNavigationMode: NavigationMode { get { return leftNavMode } set(mode) { if mayPick { leftNavMode = mode navigationItem.leftBarButtonItem = navMapping[mode] } } } private var rightNavigationMode: NavigationMode { get { return rightNavMode } set(mode) { if mayPick { rightNavMode = mode navigationItem.rightBarButtonItem = navMapping[mode] } } } public func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { if viewController.view.tag == 1, languages.count <= 1 { return false } else { return true } } public func tabBarController(_ tabBarController: UITabBarController, didSelect item: UIViewController) { if item.view.tag == 0 { leftNavigationMode = .cancel rightNavigationMode = .next } else if item.view.tag == 1 { leftNavigationMode = .back if languageTable.indexPathsForSelectedRows?.count ?? 0 == 0 { rightNavigationMode = .none } else { rightNavigationMode = .install } } } @objc func cancelBtnHandler() { // If it is not the root view of a navigationController, just pop it off the stack. if let navVC = self.navigationController, navVC.viewControllers[0] != self { navVC.popViewController(animated: true) } else { // Otherwise, if the root view of a navigation controller, dismiss it outright. (pop not available) dismiss(animated: true) } self.pickingCompletionHandler(nil) self.associators.forEach { $0.pickerDismissed() } } @objc func backBtnHandler() { guard let tabVC = iphoneTabViewController else { return } // Should only occur for iPhone layouts tabVC.selectedIndex -= 1 // Is not automatically called! tabBarController(tabVC, didSelect: tabVC.viewControllers![tabVC.selectedIndex]) } @objc func nextBtnHandler() { guard let tabVC = iphoneTabViewController else { return } // Should only occur for iPhone layouts tabVC.selectedIndex += 1 // Is not automatically called! tabBarController(tabVC, didSelect: tabVC.viewControllers![tabVC.selectedIndex]) } @objc func installBtnHandler() { let selectedItems = self.languageTable.indexPathsForSelectedRows ?? [] let selectedLanguageCodes = selectedItems.map { self.languages[$0.row].id } let selectedResources = self.package.installableResourceSets.flatMap { $0.filter { selectedLanguageCodes.contains($0.languageID) }} as! [Resource] // Always reload after installing or updating resources. Manager.shared.inputViewController.setShouldReload() self.pickingCompletionHandler(selectedResources.map { $0.typedFullID }) // Prevent swipe dismissal. if #available(iOS 13.0, *) { self.isModalInPresentation = true } // No more selection-manipulation allowed. // This matters when there's no welcome page available. languageTable.isUserInteractionEnabled = false // Prevent extra 'install' commands and nav-bar related manipulation. self.navigationItem.leftBarButtonItem?.isEnabled = false self.rightNavigationMode = .none self.mayPick = false let dismissalBlock = { self.associators.forEach { $0.pickerFinalized() } } // First, show the package's welcome - if it exists. if let welcomeVC = PackageWebViewController(for: package, page: .welcome) { // Prevent swipe dismissal. if #available(iOS 13.0, *) { welcomeVC.isModalInPresentation = true } let subNavVC = UINavigationController(rootViewController: welcomeVC) _ = subNavVC.view let doneItem = UIBarButtonItem(title: NSLocalizedString("command-done", bundle: engineBundle, comment: ""), style: .plain, target: self, action: #selector(self.onWelcomeDismissed)) // The view's navigation buttoms need to be set on its controller's navigation item, // not the UINavigationController's navigationItem. welcomeVC.navigationItem.rightBarButtonItem = doneItem // We need to listen to delegated presentation events on the view-controller being presented. // This version handles iOS 13's "page sheet" slide-dismissal. subNavVC.presentationController?.delegate = self self.present(subNavVC, animated: true, completion: nil) self.welcomeView = welcomeVC.view self.dismissalBlock = { // Tells the user that we've received the 'done' command. doneItem.isEnabled = false dismissalBlock() } } else { self.dismissalBlock = dismissalBlock onWelcomeDismissed() } } public func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { onWelcomeDismissed() } @objc private func onWelcomeDismissed() { if let dismissalBlock = self.dismissalBlock { dismissalBlock() self.dismissalBlock = nil // Tell our owner (the AssociatingPackageInstaller) that all UI interactions are done. // Triggers synchronization code, so make sure it only runs once! self.uiCompletionHandler() } // Show a spinner forever. // When installation is complete, this controller's view will be dismissed, // removing said spinner. let activitySpinner = Alerts.constructActivitySpinner() // Determine the top-most view. If we're presenting the welcome page, THAT. // If we aren't, our directly-owned view should be the top-most. let activeView: UIView = self.welcomeView ?? view activitySpinner.center = activeView.center activitySpinner.startAnimating() activeView.addSubview(activitySpinner) activitySpinner.centerXAnchor.constraint(equalTo: activeView.centerXAnchor).isActive = true activitySpinner.centerYAnchor.constraint(equalTo: activeView.centerYAnchor).isActive = true // Note: we do NOT block user interaction; we merely bind them to the active view. // Why prevent them from reading more on the welcome page while they wait? } public func tableView(_ tableView: UITableView, titleForHeaderInSection: Int) -> String? { return NSLocalizedString("installer-section-available-languages", bundle: engineBundle, comment: "") } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return languages.count default: return 0 } } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "any" var cell: UITableViewCell if let reusedCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) { cell = reusedCell } else { let selectionColor = UIView() selectionColor.backgroundColor = Colors.selectionPrimary cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier) cell.selectedBackgroundView = selectionColor } cell.isUserInteractionEnabled = true cell.backgroundColor = .none switch indexPath.section { case 0: let index = indexPath.row cell.detailTextLabel?.text = languages[index].name // Check: is the language ALREADY installed? // The checkmark is not properly managed by default. let shouldCheck = languageTable.indexPathsForSelectedRows?.contains(indexPath) ?? false if self.preinstalledLanguageCodes.contains(languageCodeForCellAt(indexPath)) { setCellStyle(cell, style: shouldCheck ? .install : .preinstalled) } else { setCellStyle(cell, style: shouldCheck ? .install : .none) } return cell default: return cell } } private func languageCodeForCellAt(_ indexPath: IndexPath) -> String { return languages[indexPath.row].id } private func setCellStyle(_ cell: UITableViewCell, style: CellStyle) { var textColor: UIColor if #available(*, iOS 13.0) { textColor = .label } else { textColor = .black } switch style { case .none: cell.detailTextLabel?.textColor = textColor cell.accessoryType = .none case .preinstalled: cell.detailTextLabel?.textColor = .systemGray cell.accessoryType = .checkmark cell.tintColor = .systemGray case .install: cell.detailTextLabel?.textColor = textColor cell.accessoryType = .checkmark cell.tintColor = .systemBlue } } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let cell = tableView.cellForRow(at: indexPath) else { return } guard cell.isUserInteractionEnabled == true else { tableView.deselectRow(at: indexPath, animated: false) return } rightNavigationMode = .install setCellStyle(cell, style: .install) associators.forEach { $0.selectLanguages( Set([languages[indexPath.row].id]) ) } } public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { guard let cell = tableView.cellForRow(at: indexPath) else { return } if languageTable.indexPathsForSelectedRows?.count ?? 0 == 0 && self.preinstalledLanguageCodes.count == 0 { rightNavigationMode = .none } else { rightNavigationMode = .install } let wasPreinstalled = self.preinstalledLanguageCodes.contains(languageCodeForCellAt(indexPath)) setCellStyle(cell, style: wasPreinstalled ? .preinstalled : .none) associators.forEach { $0.deselectLanguages( Set([languages[indexPath.row].id]) ) } } internal func progressUpdate<Package: TypedKeymanPackage<Resource>>(_ status: AssociatingPackageInstaller<Resource, Package>.Progress) where Resource.Package == Package { switch(status) { case .starting, .inProgress: // nothing worth note break // All UI interactions have been completed AND installation is fully complete. case .complete, .cancelled: if let nvc = self.navigationController { self.dismiss(animated: true) nvc.popToRootViewController(animated: false) } else { // Otherwise, if the root view of a navigation controller, dismiss it outright. (pop not available) self.dismiss(animated: true) } } } }
apache-2.0
9678df48a663ef853fadf3a059bbb352
37.355903
203
0.677409
5.178856
false
false
false
false
ObserveSocial/Focus
Sources/DefaultReporter.swift
1
2926
// // DefaultReporter.swift // Focus // // Created by Sam Meech-Ward on 2017-03-20. // // import Foundation enum ANSI { case escapeCode func escape() -> String { return ANSI.escapeCode.caseString()+self.caseString() } func console() { let string = self.escape() print(string, terminator: "") } case clearLine case clearScreen case moveCursorBack(times: Int) case moveCursorUp(times: Int) // MARK: Colors case green case white case red private func caseString() -> String { switch self { case .escapeCode: return "\u{001B}[" case .clearLine: return "0J" case .clearScreen: return "2J" case let .moveCursorBack(times): return "\(times)D" case let .moveCursorUp(times): return "\(times)A" case .green: return "32m" case .white: return "37m" case .red: return "31m" } } } public class DefaultReporter: Reportable { private init() { } public static let sharedReporter = DefaultReporter() public var failBlock: ((_ message: String, _ file: StaticString, _ line: UInt) -> Void)? public var totalTestsPassed = 0 public var totalTestsFailed = 0 public func testPassed(file: StaticString, method: String, line: UInt, message: String, evaluation: String) { totalTestsFailed+=1 var printMessage = " " printMessage += "👍" printPass(printMessage) } public func testFailed(file: StaticString, method: String, line: UInt, message: String, evaluation: String) { totalTestsPassed+=1 var printMessage = " " printMessage += "👎 \(message), \(evaluation). File: \(file), Method: \(method), Line:\(line)" printFail(printMessage) if let failBlock = failBlock { failBlock(message, file, line) } } } // MARK: Print public extension DefaultReporter { func printTest(_ text: String) { ANSI.white.console() print(text) } func printPass(_ text: String) { ANSI.green.console() print(text) ANSI.white.console() } func printFail(_ text: String) { ANSI.red.console() print(text) ANSI.white.console() } func printWithIndentation(file: StaticString, method: String, line: UInt, message: String, blockType: String, indentationLevel: Int) { if indentationLevel == 0 { print("") printTest("\nFile: \(file), Method: \(method)") } var printMessage = "" for _ in 0...indentationLevel { printMessage += "--" } printMessage += "| \(blockType)): " printMessage += message printTest(printMessage) } }
mit
08091e9fe766908545881236f738e662
22.934426
138
0.557534
4.45122
false
true
false
false
WeefJim/JYJDrawerContainerController
JYJDrawerContainerController/JYJDrawerContainerController/JYJDrawerContainerController.swift
2
9171
// // DrawerContainerViewController.swift // E-Share // // 该视图控制器主要作为一个容器(container),来提供leftViewController和centerViewController之间的交互 // // Created by Mr.Jim on 6/8/15. // Copyright (c) 2015 Jim. All rights reserved. // import UIKit /** 开关状态枚举类型,主要用于记录当前leftViewController是否处于打开状态 - Open: leftViewController处于打开状态 - Close: leftViewController处于关闭状态 */ enum ToggleState { case Open case Close } /** * 侧拉控制器,通过手指滑动centerViewController侧拉打开leftViewController */ class JYJDrawerContainerController: UIViewController, UIGestureRecognizerDelegate { var centerViewController: UIViewController? var leftViewController: UIViewController? // centerViewController的待移动位置原点x坐标,起始初始化为0 private var centerViewTempOriginX: CGFloat! = 0 // centerViewController 最大偏移比例 var maximunOffsetRatio: CGFloat = 0.78 // centerViewController 最大偏移量 private var maxinumOffsetX: CGFloat {return maximunOffsetRatio * self.view.bounds.width} // centerViewController 最小缩放比例 var minimumScaleRatio: CGFloat = 0.8 // 触发toggle的最小手指滑动速度 var minVelocityX: CGFloat = 100 // 侧拉动画开始到结束的时间 var animationDuration: Double = 0.2 //左侧视图的开闭状态,初始默认为关闭 var toggleState: ToggleState = .Close init(centerViewController: UIViewController, leftViewController: UIViewController){ self.leftViewController = leftViewController self.centerViewController = centerViewController super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() if leftViewController != nil && centerViewController != nil { self.view.addSubview(leftViewController!.view) self.view.addSubview(centerViewController!.view) self.addChildViewController(leftViewController!) self.addChildViewController(centerViewController!) // 给中间视图添加pan手势 let centerPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: "centerViewDidPan:") centerViewController!.view.addGestureRecognizer(centerPanGestureRecognizer) // 给中间视图添加tap手势 let centerTapGestureRecogizer = UITapGestureRecognizer(target: self, action: "centerViewDidTap:") centerTapGestureRecogizer.delegate = self centerViewController!.view.addGestureRecognizer(centerTapGestureRecogizer) } } // MARK: - Gesture Recoginzer Event /** 中间视图控制器(centerViewController)的拖动手势事件 - parameter recognizer: 拖动手势 */ func centerViewDidPan(recognizer: UIPanGestureRecognizer) { // 手势在container中的x轴移动距离 let panOffsetX = recognizer.translationInView(self.view).x // centerViewController 将要移动到的位置 let centerViewWillToOrginX = centerViewTempOriginX + panOffsetX // 检测侧滑边界,最大不能超过maxium, 最小不能超过0 if centerViewWillToOrginX <= maxinumOffsetX && centerViewWillToOrginX >= 0 { // 改变中间视图位置 transformCenterViewToX(centerViewWillToOrginX) } // 如果手指滑动已经结束 if recognizer.state == .Ended { // 判断手指滑动速度,如果大于触发开关toggle的阈值,则调用toggleLeftViewController let velocityX = recognizer.velocityInView(self.view).x if abs(velocityX) >= minVelocityX { toggleLeftViewController() }else{ // 计算剩余滑动时间 let currentX = centerViewController!.view.frame.origin.x var leftDuration: Double! if panOffsetX > 0 { leftDuration = animationDuration * Double((maxinumOffsetX - currentX)/maxinumOffsetX) }else{ leftDuration = animationDuration * Double(currentX/maxinumOffsetX) } // 如果目前centerViewController的滑动距离超过maximunOffsetX的一半,则打开leftViewController,否则关闭leftViewController if centerViewController!.view.frame.origin.x > maxinumOffsetX/2 { showLeftViewControllerWithDuration(leftDuration) }else if centerViewController!.view.frame.origin.x < maxinumOffsetX/2 { hideLeftViewControllerWithDuration(leftDuration) } } // 更新centerViewStopOriginX centerViewTempOriginX = centerViewWillToOrginX } } /** 中间视图控制器(centerViewController)的触摸手势事件 - parameter recogizer: 中间视图控制器(centerViewController)的触摸手势 */ func centerViewDidTap(recogizer: UITapGestureRecognizer){ // 如果目前左侧视图为打开状态,则关闭。 if toggleState == .Open { hideLeftViewControllerWithDuration(animationDuration) } } /** 如果leftViewController处于关闭状态,那么tap事件应该交给下级响应者来处理 - parameter gestureRecognizer: tap手势 - parameter touch: tap触摸事件 - returns: 如果当前处于关闭状态那么返回false,如果处于开启状态返回true */ func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { if gestureRecognizer is UITapGestureRecognizer && toggleState == .Close { return false } return true } /** 显示左侧视图,并且改变toggleState为Open, 并且更新centerTempOriginX 为 maxinumOffsetX */ func showLeftViewControllerWithDuration(duration: Double){ UIView.animateWithDuration(duration, delay: 0, options: .CurveLinear, animations: { () -> Void in self.transformCenterViewToX(self.maxinumOffsetX) }){[unowned self](finished) -> Void in self.toggleState = .Open self.centerViewTempOriginX = self.maxinumOffsetX } } /** 隐藏左侧视图,并且改变toggleState为Close, 并且更新centerTempOriginX 为 0 */ func hideLeftViewControllerWithDuration(duration: Double){ UIView.animateWithDuration(duration, delay: 0, options: .CurveLinear, animations: { () -> Void in self.transformCenterViewToX(0) }){[unowned self](finished) -> Void in self.toggleState = .Close self.centerViewTempOriginX = 0 } } /** 打开或者关闭leftViewController。根据目前leftViewController的状态自动判断是打开还是关闭 */ func toggleLeftViewController(){ if toggleState == .Open { hideLeftViewControllerWithDuration(animationDuration) }else{ showLeftViewControllerWithDuration(animationDuration) } } /** 通过offsetX, 来改变centerView的位置以及大小 - parameter offsetX: centerView离最左边的横坐标滑动偏移量 */ private func transformCenterViewToX(x: CGFloat){ //centerView 大小缩放比例 let sizeRatio = (minimumScaleRatio - 1)/maxinumOffsetX * x + 1 // 平移变换 let translation = CGAffineTransformMakeTranslation(x, 0) // 缩放变化 let scale = CGAffineTransformScale(CGAffineTransformIdentity, sizeRatio, sizeRatio) // 组合变换 centerViewController!.view.transform = CGAffineTransformConcat(translation, scale) } } /** * 对UIViewController扩展,为了在任何DrawerController的子视图控制器中都能通过self.drawerContainerViewController访问到侧拉控制器 */ extension UIViewController { var drawerContainerViewController: JYJDrawerContainerController? { var parentViewController = self.parentViewController while parentViewController != nil { if parentViewController!.isKindOfClass(JYJDrawerContainerController) { return parentViewController as? JYJDrawerContainerController } parentViewController = parentViewController!.parentViewController } return nil } }
apache-2.0
1d453916600391557c60b92bc2149985
28.8125
112
0.63189
5.434987
false
false
false
false
xwu/swift
test/IDE/complete_member_decls_from_parent_decl_context.swift
3
37214
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLASS_INSTANCE_METHOD_1 | %FileCheck %s -check-prefix=IN_CLASS_INSTANCE_METHOD_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLASS_STATIC_METHOD_1 | %FileCheck %s -check-prefix=IN_CLASS_STATIC_METHOD_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLASS_STATIC_METHOD_1 | %FileCheck %s -check-prefix=IN_CLASS_STATIC_METHOD_1_NEGATIVE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLASS_CONSTRUCTOR_1 | %FileCheck %s -check-prefix=IN_CLASS_CONSTRUCTOR_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLASS_DESTRUCTOR_1 | %FileCheck %s -check-prefix=IN_CLASS_DESTRUCTOR_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_STRUCT_INSTANCE_METHOD_1 | %FileCheck %s -check-prefix=IN_STRUCT_INSTANCE_METHOD_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_STRUCT_STATIC_METHOD_1 | %FileCheck %s -check-prefix=IN_STRUCT_STATIC_METHOD_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_STRUCT_STATIC_METHOD_1 | %FileCheck %s -check-prefix=IN_STRUCT_STATIC_METHOD_1_NEGATIVE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_STRUCT_CONSTRUCTOR_1 | %FileCheck %s -check-prefix=IN_STRUCT_CONSTRUCTOR_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_A_1 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_A_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_A_2 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_A_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_A_3 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_A_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_A_4 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_A_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_A_5 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_A_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_B_1 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_B_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_B_2 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_B_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_B_3 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_B_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_B_4 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_B_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_B_5 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_B_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_C_1 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_C_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_C_2 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_C_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_C_3 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_C_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_C_4 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_C_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_C_5 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_C_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_D_1 | %FileCheck %s -allow-deprecated-dag-overlap -check-prefix=NESTED_NOMINAL_DECL_D_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_E_1 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_E_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SR627_SUBCLASS | %FileCheck %s -check-prefix=SR627_SUBCLASS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SR627_SUB_SUBCLASS | %FileCheck %s -check-prefix=SR627_SUB_SUBCLASS //===--- //===--- Test that we can code complete in methods, and correctly distinguish //===--- static and non-static contexts. //===--- class CodeCompletionInClassMethods1 { /// @{ Members. /// Warning: there are negative tests about code completion of instance /// members of this class. Read the tests below before adding, removing or /// modifying members. var instanceVar: Int func instanceFunc0() {} func instanceFunc1(_ a: Int) {} subscript(i: Int) -> Double { get { return Double(i) } set(v) { instanceVar = i } } struct NestedStruct {} class NestedClass {} enum NestedEnum {} // Cannot declare a nested protocol. // protocol NestedProtocol {} typealias NestedTypealias = Int class var staticVar: Int class func staticFunc0() {} class func staticFunc1(_ a: Int) {} /// @} Members. /// @{ Tests. func instanceTest1() { #^IN_CLASS_INSTANCE_METHOD_1^# // IN_CLASS_INSTANCE_METHOD_1: Begin completions // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[LocalVar]/Local: self[#CodeCompletionInClassMethods1#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#NestedStruct#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[Class]/CurrNominal: NestedClass[#NestedClass#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#NestedEnum#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1: End completions } class func staticTest1() { #^IN_CLASS_STATIC_METHOD_1^# // Negative tests. // IN_CLASS_STATIC_METHOD_1_NEGATIVE-NOT: instanceVar // // Positive tests. // IN_CLASS_STATIC_METHOD_1: Begin completions // IN_CLASS_STATIC_METHOD_1-DAG: Decl[LocalVar]/Local: self[#CodeCompletionInClassMethods1.Type#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc0({#(self): CodeCompletionInClassMethods1#})[#() -> Void#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#(self): CodeCompletionInClassMethods1#})[#(Int) -> Void#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#NestedStruct#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[Class]/CurrNominal: NestedClass[#NestedClass#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#NestedEnum#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[StaticMethod]/CurrNominal: staticFunc0()[#Void#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[StaticMethod]/CurrNominal: staticFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1: End completions } init() { #^IN_CLASS_CONSTRUCTOR_1^# // IN_CLASS_CONSTRUCTOR_1: Begin completions // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[LocalVar]/Local: self[#CodeCompletionInClassMethods1#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#NestedStruct#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[Class]/CurrNominal: NestedClass[#NestedClass#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#NestedEnum#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1: End completions } deinit { #^IN_CLASS_DESTRUCTOR_1^# // IN_CLASS_DESTRUCTOR_1: Begin completions // IN_CLASS_DESTRUCTOR_1-DAG: Decl[LocalVar]/Local: self[#CodeCompletionInClassMethods1#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#NestedStruct#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1-DAG: Decl[Class]/CurrNominal: NestedClass[#NestedClass#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#NestedEnum#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1: End completions } /// @} } struct CodeCompletionInStructMethods1 { /// @{ Members. /// Warning: there are negative tests about code completion of instance /// members of this struct. Read the tests below before adding, removing or /// modifying members. var instanceVar: Int mutating func instanceFunc0() {} mutating func instanceFunc1(_ a: Int) {} subscript(i: Int) -> Double { get { return Double(i) } set(v) { instanceVar = i } } struct NestedStruct {} class NestedClass {} enum NestedEnum {} // Cannot declare a nested protocol. // protocol NestedProtocol {} typealias NestedTypealias = Int static var staticVar: Int static func staticFunc0() {} static func staticFunc1(_ a: Int) {} /// @} Members. func instanceTest1() { #^IN_STRUCT_INSTANCE_METHOD_1^# // IN_STRUCT_INSTANCE_METHOD_1: Begin completions // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[LocalVar]/Local: self[#CodeCompletionInStructMethods1#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#NestedStruct#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[Class]/CurrNominal: NestedClass[#NestedClass#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#NestedEnum#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1: End completions } static func staticTest1() { #^IN_STRUCT_STATIC_METHOD_1^# // Negative tests. // IN_STRUCT_STATIC_METHOD_1_NEGATIVE-NOT: instanceVar // // Positive tests. // IN_STRUCT_STATIC_METHOD_1: Begin completions // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[LocalVar]/Local: self[#CodeCompletionInStructMethods1.Type#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc0({#(self): &CodeCompletionInStructMethods1#})[#() -> Void#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#(self): &CodeCompletionInStructMethods1#})[#(Int) -> Void#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#NestedStruct#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[Class]/CurrNominal: NestedClass[#NestedClass#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#NestedEnum#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[StaticMethod]/CurrNominal: staticFunc0()[#Void#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[StaticMethod]/CurrNominal: staticFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1: End completions } init() { #^IN_STRUCT_CONSTRUCTOR_1^# // IN_STRUCT_CONSTRUCTOR_1: Begin completions // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[LocalVar]/Local: self[#CodeCompletionInStructMethods1#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#NestedStruct#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[Class]/CurrNominal: NestedClass[#NestedClass#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#NestedEnum#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1: End completions } } //===--- //===--- Test that code completion works in non-toplevel nominal type decls. //===--- struct NestedOuter1 { mutating func testInstanceFunc() { struct NestedInnerA { mutating func aTestInstanceFunc() { #^NESTED_NOMINAL_DECL_A_1^# // NESTED_NOMINAL_DECL_A_1: Begin completions // NESTED_NOMINAL_DECL_A_1-DAG: Decl[LocalVar]/Local: self[#NestedInnerA#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[InstanceMethod]/CurrNominal: aTestInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[InstanceVar]/CurrNominal: aInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[InstanceMethod]/CurrNominal: aInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[Struct]/CurrNominal: NestedInnerAStruct[#NestedInnerAStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[Class]/CurrNominal: NestedInnerAClass[#NestedInnerAClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[Enum]/CurrNominal: NestedInnerAEnum[#NestedInnerAEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[TypeAlias]/CurrNominal: NestedInnerATypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_A_1-DAG: Decl[Struct]/Local: NestedInnerA[#NestedInnerA#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // FIXME: the following decls are wrong. // NESTED_NOMINAL_DECL_A_1-DAG: Decl[LocalVar]/Local: self[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[InstanceMethod]/OutNominal: testInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[InstanceVar]/OutNominal: outerInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[InstanceMethod]/OutNominal: outerInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1: End completions } static func aTestStaticFunc() { #^NESTED_NOMINAL_DECL_A_2^# // NESTED_NOMINAL_DECL_A_2: Begin completions // NESTED_NOMINAL_DECL_A_2-DAG: Decl[LocalVar]/Local: self[#NestedInnerA.Type#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[InstanceMethod]/CurrNominal: aTestInstanceFunc({#(self): &NestedInnerA#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[StaticMethod]/CurrNominal: aTestStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[InstanceMethod]/CurrNominal: aInstanceFunc({#(self): &NestedInnerA#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[StaticVar]/CurrNominal: aStaticVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[StaticMethod]/CurrNominal: aStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[Struct]/CurrNominal: NestedInnerAStruct[#NestedInnerAStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[Class]/CurrNominal: NestedInnerAClass[#NestedInnerAClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[Enum]/CurrNominal: NestedInnerAEnum[#NestedInnerAEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[TypeAlias]/CurrNominal: NestedInnerATypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_A_2-DAG: Decl[Struct]/Local: NestedInnerA[#NestedInnerA#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // FIXME: the following decls are wrong. // NESTED_NOMINAL_DECL_A_2-DAG: Decl[LocalVar]/Local: self[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[InstanceMethod]/OutNominal: testInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[InstanceVar]/OutNominal: outerInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[InstanceMethod]/OutNominal: outerInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2: End completions } typealias ATestTypealias = #^NESTED_NOMINAL_DECL_A_3^# // NESTED_NOMINAL_DECL_A_3: Begin completions // NESTED_NOMINAL_DECL_A_3-DAG: Decl[Struct]/OutNominal: NestedInnerAStruct[#NestedInnerAStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_3-DAG: Decl[Class]/OutNominal: NestedInnerAClass[#NestedInnerAClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_3-DAG: Decl[Enum]/OutNominal: NestedInnerAEnum[#NestedInnerAEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_3-DAG: Decl[TypeAlias]/OutNominal: NestedInnerATypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_A_3-DAG: Decl[Struct]/Local: NestedInnerA[#NestedInnerA#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_3-DAG: Decl[TypeAlias]/OutNominal: OuterTypealias[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_3-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_3: End completions // Put these decls after code completion points to ensure that delayed // parsing works. var aInstanceVar: Int mutating func aInstanceFunc() {} static var aStaticVar: Int = 42 static func aStaticFunc() {} subscript(i: Int) -> Double { get { return Double(i) } set(v) { instanceVar = i } } struct NestedInnerAStruct {} class NestedInnerAClass {} enum NestedInnerAEnum {} typealias NestedInnerATypealias = Int } // end NestedInnerA #^NESTED_NOMINAL_DECL_A_4^# // NESTED_NOMINAL_DECL_A_4: Begin completions // NESTED_NOMINAL_DECL_A_4-DAG: Decl[Struct]/Local: NestedInnerA[#NestedInnerA#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_4-DAG: Decl[LocalVar]/Local: self[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_4-DAG: Decl[InstanceMethod]/CurrNominal: testInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_4-DAG: Decl[InstanceVar]/CurrNominal: outerInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_4-DAG: Decl[InstanceMethod]/CurrNominal: outerInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_4-DAG: Decl[TypeAlias]/CurrNominal: OuterTypealias[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_4-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_4: End completions NestedInnerA(aInstanceVar: 42)#^NESTED_NOMINAL_DECL_A_5^# // NESTED_NOMINAL_DECL_A_5: Begin completions, 5 items // NESTED_NOMINAL_DECL_A_5-NEXT: Decl[InstanceMethod]/CurrNominal: .aTestInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_5-NEXT: Decl[InstanceVar]/CurrNominal: .aInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_5-NEXT: Decl[InstanceMethod]/CurrNominal: .aInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_5-NEXT: Decl[Subscript]/CurrNominal: [{#(i): Int#}][#Double#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_5-NEXT: Keyword[self]/CurrNominal: .self[#NestedInnerA#]; name=self // NESTED_NOMINAL_DECL_A_5-NEXT: End completions } static func testStaticFunc() { struct NestedInnerB { mutating func bTestInstanceFunc() { #^NESTED_NOMINAL_DECL_B_1^# // NESTED_NOMINAL_DECL_B_1: Begin completions // NESTED_NOMINAL_DECL_B_1-DAG: Decl[LocalVar]/Local: self[#NestedInnerB#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[InstanceMethod]/CurrNominal: bTestInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[InstanceVar]/CurrNominal: bInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[InstanceMethod]/CurrNominal: bInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[Struct]/CurrNominal: NestedInnerBStruct[#NestedInnerBStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[Class]/CurrNominal: NestedInnerBClass[#NestedInnerBClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[Enum]/CurrNominal: NestedInnerBEnum[#NestedInnerBEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[TypeAlias]/CurrNominal: NestedInnerBTypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_B_1-DAG: Decl[Struct]/Local: NestedInnerB[#NestedInnerB#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // FIXME: the following decls are wrong. // NESTED_NOMINAL_DECL_B_1-DAG: Decl[LocalVar]/Local: self[#NestedOuter1.Type#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[InstanceMethod]/OutNominal: testInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[StaticMethod]/OutNominal: testStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[InstanceMethod]/OutNominal: outerInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[StaticVar]/OutNominal: outerStaticVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[StaticMethod]/OutNominal: outerStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[TypeAlias]/OutNominal: OuterTypealias[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1: End completions } static func bTestStaticFunc() { #^NESTED_NOMINAL_DECL_B_2^# // NESTED_NOMINAL_DECL_B_2: Begin completions // NESTED_NOMINAL_DECL_B_2-DAG: Decl[LocalVar]/Local: self[#NestedInnerB.Type#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[InstanceMethod]/CurrNominal: bTestInstanceFunc({#(self): &NestedInnerB#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[StaticMethod]/CurrNominal: bTestStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[InstanceMethod]/CurrNominal: bInstanceFunc({#(self): &NestedInnerB#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[StaticVar]/CurrNominal: bStaticVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[StaticMethod]/CurrNominal: bStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[Struct]/CurrNominal: NestedInnerBStruct[#NestedInnerBStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[Class]/CurrNominal: NestedInnerBClass[#NestedInnerBClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[Enum]/CurrNominal: NestedInnerBEnum[#NestedInnerBEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[TypeAlias]/CurrNominal: NestedInnerBTypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_B_2-DAG: Decl[Struct]/Local: NestedInnerB[#NestedInnerB#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // FIXME: the following decls are wrong. // NESTED_NOMINAL_DECL_B_2-DAG: Decl[LocalVar]/Local: self[#NestedOuter1.Type#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[InstanceMethod]/OutNominal: testInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[StaticMethod]/OutNominal: testStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[InstanceMethod]/OutNominal: outerInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[StaticVar]/OutNominal: outerStaticVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[StaticMethod]/OutNominal: outerStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[TypeAlias]/OutNominal: OuterTypealias[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2: End completions } typealias BTestTypealias = #^NESTED_NOMINAL_DECL_B_3^# // NESTED_NOMINAL_DECL_B_3: Begin completions // NESTED_NOMINAL_DECL_B_3-DAG: Decl[Struct]/OutNominal: NestedInnerBStruct[#NestedInnerBStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_3-DAG: Decl[Class]/OutNominal: NestedInnerBClass[#NestedInnerBClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_3-DAG: Decl[Enum]/OutNominal: NestedInnerBEnum[#NestedInnerBEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_3-DAG: Decl[TypeAlias]/OutNominal: NestedInnerBTypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_B_3-DAG: Decl[Struct]/Local: NestedInnerB[#NestedInnerB#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_3-DAG: Decl[TypeAlias]/OutNominal: OuterTypealias[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_3-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_3: End completions // Put these decls after code completion points to ensure that delayed // parsing works. var bInstanceVar: Int mutating func bInstanceFunc() {} static var bStaticVar: Int = 17 static func bStaticFunc() {} subscript(i: Int) -> Double { get { return Double(i) } set(v) { instanceVar = i } } struct NestedInnerBStruct {} class NestedInnerBClass {} enum NestedInnerBEnum {} typealias NestedInnerBTypealias = Int } // end NestedInnerB #^NESTED_NOMINAL_DECL_B_4^# // NESTED_NOMINAL_DECL_B_4: Begin completions // NESTED_NOMINAL_DECL_B_4-DAG: Decl[Struct]/Local: NestedInnerB[#NestedInnerB#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[LocalVar]/Local: self[#NestedOuter1.Type#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[InstanceMethod]/CurrNominal: testInstanceFunc({#(self): &NestedOuter1#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[StaticMethod]/CurrNominal: testStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[InstanceMethod]/CurrNominal: outerInstanceFunc({#(self): &NestedOuter1#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[StaticVar]/CurrNominal: outerStaticVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[StaticMethod]/CurrNominal: outerStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[TypeAlias]/CurrNominal: OuterTypealias[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4: End completions NestedInnerB(bInstanceVar: 42)#^NESTED_NOMINAL_DECL_B_5^# // NESTED_NOMINAL_DECL_B_5: Begin completions, 5 items // NESTED_NOMINAL_DECL_B_5-DAG: Decl[InstanceMethod]/CurrNominal: .bTestInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_5-DAG: Decl[InstanceVar]/CurrNominal: .bInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_5-DAG: Decl[InstanceMethod]/CurrNominal: .bInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_5-DAG: Decl[Subscript]/CurrNominal: [{#(i): Int#}][#Double#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_5-DAG: Keyword[self]/CurrNominal: .self[#NestedInnerB#]; name=self // NESTED_NOMINAL_DECL_B_5: End completions } var outerInstanceVar: Int mutating func outerInstanceFunc() {} static var outerStaticVar: Int = 1 static func outerStaticFunc() {} typealias OuterTypealias = Int } func testOuterC() { struct NestedInnerC { mutating func cTestInstanceFunc() { #^NESTED_NOMINAL_DECL_C_1^# // NESTED_NOMINAL_DECL_C_1: Begin completions // NESTED_NOMINAL_DECL_C_1-DAG: Decl[LocalVar]/Local: self[#NestedInnerC#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[InstanceMethod]/CurrNominal: cTestInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[InstanceVar]/CurrNominal: cInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[InstanceMethod]/CurrNominal: cInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[Struct]/CurrNominal: NestedInnerCStruct[#NestedInnerCStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[Class]/CurrNominal: NestedInnerCClass[#NestedInnerCClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[Enum]/CurrNominal: NestedInnerCEnum[#NestedInnerCEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[TypeAlias]/CurrNominal: NestedInnerCTypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_C_1-DAG: Decl[Struct]/Local: NestedInnerC[#NestedInnerC#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1: End completions } static func cTestStaticFunc() { #^NESTED_NOMINAL_DECL_C_2^# // NESTED_NOMINAL_DECL_C_2: Begin completions // NESTED_NOMINAL_DECL_C_2-DAG: Decl[LocalVar]/Local: self[#NestedInnerC.Type#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[InstanceMethod]/CurrNominal: cTestInstanceFunc({#(self): &NestedInnerC#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[StaticMethod]/CurrNominal: cTestStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[InstanceMethod]/CurrNominal: cInstanceFunc({#(self): &NestedInnerC#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[StaticVar]/CurrNominal: cStaticVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[StaticMethod]/CurrNominal: cStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[Struct]/CurrNominal: NestedInnerCStruct[#NestedInnerCStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[Class]/CurrNominal: NestedInnerCClass[#NestedInnerCClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[Enum]/CurrNominal: NestedInnerCEnum[#NestedInnerCEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[TypeAlias]/CurrNominal: NestedInnerCTypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_C_2-DAG: Decl[Struct]/Local: NestedInnerC[#NestedInnerC#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2: End completions } typealias CTestTypealias = #^NESTED_NOMINAL_DECL_C_3^# // NESTED_NOMINAL_DECL_C_3: Begin completions // NESTED_NOMINAL_DECL_C_3-DAG: Decl[Struct]/OutNominal: NestedInnerCStruct[#NestedInnerCStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_3-DAG: Decl[Class]/OutNominal: NestedInnerCClass[#NestedInnerCClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_3-DAG: Decl[Enum]/OutNominal: NestedInnerCEnum[#NestedInnerCEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_3-DAG: Decl[TypeAlias]/OutNominal: NestedInnerCTypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_C_3-DAG: Decl[Struct]/Local: NestedInnerC[#NestedInnerC#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_3: End completions // Put these decls after code completion points to ensure that delayed // parsing works. var cInstanceVar: Int mutating func cInstanceFunc() {} static var cStaticVar: Int = 1 static func cStaticFunc() {} subscript(i: Int) -> Double { get { return Double(i) } set(v) { instanceVar = i } } struct NestedInnerCStruct {} class NestedInnerCClass {} enum NestedInnerCEnum {} typealias NestedInnerCTypealias = Int } // end NestedInnerC #^NESTED_NOMINAL_DECL_C_4^# // NESTED_NOMINAL_DECL_C_4: Begin completions // NESTED_NOMINAL_DECL_C_4-DAG: Decl[Struct]/Local: NestedInnerC[#NestedInnerC#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_4: End completions NestedInnerC(cInstanceVar: 42)#^NESTED_NOMINAL_DECL_C_5^# // NESTED_NOMINAL_DECL_C_5: Begin completions, 5 items // NESTED_NOMINAL_DECL_C_5-NEXT: Decl[InstanceMethod]/CurrNominal: .cTestInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_5-NEXT: Decl[InstanceVar]/CurrNominal: .cInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_5-NEXT: Decl[InstanceMethod]/CurrNominal: .cInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_5-NEXT: Decl[Subscript]/CurrNominal: [{#(i): Int#}][#Double#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_5-NEXT: Keyword[self]/CurrNominal: .self[#NestedInnerC#]; name=self // NESTED_NOMINAL_DECL_C_5-NEXT: End completions } func testOuterD() { func dFunc1() {} func foo() { func dFunc2() {} struct Nested1 { struct Nested2 { func bar() { func dFunc4() {} #^NESTED_NOMINAL_DECL_D_1^# } func dFunc3() {} } func dFunc2() {} } } } // NESTED_NOMINAL_DECL_D_1: Begin completions // NESTED_NOMINAL_DECL_D_1-DAG: Decl[LocalVar]/Local: self[#Nested1.Nested2#]{{; name=.+$}} // NESTED_NOMINAL_DECL_D_1-DAG: Decl[FreeFunction]/Local: dFunc4()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_D_1-DAG: Decl[InstanceMethod]/CurrNominal: dFunc3()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_D_1-DAG: Decl[FreeFunction]/Local: dFunc2()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_D_1-DAG: Decl[FreeFunction]/Local: dFunc2()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_D_1-DAG: Decl[FreeFunction]/Local: dFunc1()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_D_1: End completions func testOuterE() { var c1 = { func dFunc1() {} var c2 = { func dFunc2() {} struct Nested1 { struct Nested2 { func bar() { func dFunc4() {} var c3 = { func dFunc5() {} #^NESTED_NOMINAL_DECL_E_1^# } } func dFunc3() {} } func dFunc2() {} } } // end c2 } // end c1 } // NESTED_NOMINAL_DECL_E_1: Begin completions // NESTED_NOMINAL_DECL_E_1-DAG: Decl[LocalVar]/Local: self[#Nested1.Nested2#]{{; name=.+$}} // NESTED_NOMINAL_DECL_E_1-DAG: Decl[FreeFunction]/Local: dFunc5()[#Void#]; name=dFunc5() // NESTED_NOMINAL_DECL_E_1-DAG: Decl[FreeFunction]/Local: dFunc4()[#Void#]; name=dFunc4() // NESTED_NOMINAL_DECL_E_1-DAG: Decl[InstanceMethod]/OutNominal: dFunc3()[#Void#]; name=dFunc3() // NESTED_NOMINAL_DECL_E_1-DAG: Decl[InstanceMethod]/OutNominal: dFunc2()[#Void#]; name=dFunc2() // NESTED_NOMINAL_DECL_E_1-DAG: Decl[FreeFunction]/Local: dFunc2()[#Void#]; name=dFunc2() // NESTED_NOMINAL_DECL_E_1-DAG: Decl[FreeFunction]/Local: dFunc1()[#Void#]; name=dFunc1() // NESTED_NOMINAL_DECL_E_1: End completions class SR627_BaseClass<T> { func myFunction(_ x: T) -> T? { return nil } } class SR627_Subclass: SR627_BaseClass<String> { #^SR627_SUBCLASS^# // SR627_SUBCLASS: Begin completions // SR627_SUBCLASS-DAG: Decl[InstanceMethod]/Super: override func myFunction(_ x: String) -> String? {|}; name=myFunction(_:) // SR627_SUBCLASS: End completions } class SR627_SubSubclass: SR627_Subclass { #^SR627_SUB_SUBCLASS^# // SR627_SUB_SUBCLASS: Begin completions // SR627_SUB_SUBCLASS-DAG: Decl[InstanceMethod]/Super: override func myFunction(_ x: String) -> String? {|}; name=myFunction(_:) // SR627_SUB_SUBCLASS: End completions }
apache-2.0
65707935b35aa955a4f23a55e8ec15bc
59.80719
198
0.668592
3.725871
false
true
false
false
lancy98/CircularCompetion
CircularCompetion/RepresentationView.swift
1
2227
// // RepresentationView.Swift // CircularCompetion // // Created by Lancy on 22/05/15. // Copyright (c) 2015 Coder. All rights reserved. // import UIKit class RepresentationView: UIView { /** Width of the circle as a float value. */ var circleWidth: CGFloat = 10 /** This is the distance from the cornor of the rectangle. */ private let safePadding = CGFloat(10.0) /** Radius of the donut bar. */ private var radius: CGFloat { return min(frame.size.width/2.0, frame.size.height/2.0) - safePadding } /** Background color representation. */ private var bgColor: UIColor { return UIColor.grayColor() } /** Progress color representation. */ private var competionCircleColor: UIColor { return UIColor.greenColor() } /** Progress that needs to be represented in the Donut bar. */ var progress: Double = 0.0 { didSet { setNeedsDisplay() } } /** Draws the progress to the view in the form of donut. Progress can be between 0.0 and 1.0. - parameter progress: The progress value to be shown in the view. - parameter rect: The rectangle in which the progress needs to be drawn. - parameter color: The color that depicts the progress. */ private func drawProgress(progress: Double, rect: CGRect, color: UIColor) { let startAngle = CGFloat(0) let endAngle = CGFloat(M_PI*2.0*progress) let context = UIGraphicsGetCurrentContext() CGContextAddArc(context, rect.size.width/2.0, rect.size.height/2.0, radius, startAngle, endAngle, 0) color.setStroke() CGContextSetLineWidth(context, circleWidth) CGContextSetLineCap(context, CGLineCap.Butt) CGContextDrawPath(context, CGPathDrawingMode.Stroke) } override func drawRect(rect: CGRect) { super.drawRect(rect) //background circle. drawProgress(1.0, rect: rect, color: bgColor) // Competion circle. drawProgress(progress, rect: rect, color: competionCircleColor) } }
mit
35aac5edc442c36d269cf49c66a531c4
24.597701
108
0.60934
4.489919
false
false
false
false
gorozco58/Apps-List
Apps List/Application/Controllers/Apps Controllers/App Details Controller/AppDetailsViewController.swift
1
3831
// // AppDetailsViewController.swift // Apps List // // Created by iOS on 3/25/16. // Copyright © 2016 Giovanny Orozco. All rights reserved. // import UIKit import SafariServices class AppDetailsViewController: UIViewController { @IBOutlet private weak var backgroundImageView: UIImageView! @IBOutlet private weak var appImageView: UIImageView! @IBOutlet private weak var appNameLabel: UILabel! @IBOutlet private weak var descriptionLabel: UILabel! @IBOutlet private weak var rightsLabel: UILabel! @IBOutlet private weak var artistLabel: UILabel! @IBOutlet private weak var contentTypeLabel: UILabel! @IBOutlet private weak var releaseDateLabel: UILabel! @IBOutlet private weak var priceLabel: UILabel! @IBOutlet private weak var linkButton: UIButton! private var app: App //MARK: Initializers init(app: App) { self.app = app super.init(nibName: nil, bundle: nil) self.transitioningDelegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() setupAppInformation() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) view.layoutIfNeeded() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - Utils func setupAppInformation() { let blurEffect = UIBlurEffect(style: .Light) let visualEffectView = UIVisualEffectView(effect: blurEffect) visualEffectView.translatesAutoresizingMaskIntoConstraints = false backgroundImageView.addSubview(visualEffectView) let views = ["effectView" : visualEffectView] backgroundImageView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[effectView]|", options: .AlignAllLeading, metrics: nil, views: views)) backgroundImageView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[effectView]|", options: .AlignAllLeading, metrics: nil, views: views)) backgroundImageView.af_setImageWithURL(app.image.link) appImageView.af_setImageWithURL(app.image.link) appNameLabel.text = app.name descriptionLabel.text = app.summary rightsLabel.text = app.rights artistLabel.text = app.artist contentTypeLabel.text = app.contentType releaseDateLabel.text = app.releaseDate priceLabel.text = app.price.priceString linkButton.setTitle(app.link.absoluteString, forState: .Normal) } //MARK: - Actions @IBAction func linkButtonPressed(sender: UIButton) { if #available(iOS 9.0, *) { let vc = SFSafariViewController(URL: app.link, entersReaderIfAvailable: true) presentViewController(vc, animated: true, completion: nil) } else { UIApplication.sharedApplication().openURL(app.link) } } @IBAction func gobackButtonPressed(sender: UIButton) { dismissViewControllerAnimated(true, completion: nil) } } extension AppDetailsViewController: UIViewControllerTransitioningDelegate { func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return ViewControllerPresentAnimator() } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return ViewControllerDismissAnimator() } }
mit
27a2916ea14e9e8ab905d84265c2ae7b
34.794393
217
0.697389
5.615836
false
false
false
false
xeo-it/zipbooks-invoices-swift
zipbooks-ios/ViewControllers/InsertViewController.swift
1
4881
// // InsertViewController.swift // zipbooks-ios // // Created by Francesco Pretelli on 27/01/16. // Copyright © 2016 Francesco Pretelli. All rights reserved. // import Foundation import UIKit enum InsertType{ case customer case project case task } class InsertViewController: UIViewController { @IBOutlet weak var addCustomerContainer: UIView! @IBOutlet weak var addProjectContainer: UIView! var insertType:InsertType? override func viewDidLoad() { super.viewDidLoad() customizeNavBar() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if insertType == InsertType.customer{ addCustomerContainer.isHidden = false addProjectContainer.isHidden = true title = "New Customer" } if insertType == InsertType.project{ addCustomerContainer.isHidden = true addProjectContainer.isHidden = false title = "New Project" } if Utility.getScreenWidth() < IPHONE_6_SCREEN_WIDTH { NotificationCenter.default.addObserver(self, selector: #selector(InsertViewController.OnKeyboardAppear(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(InsertViewController.OnKeyboardDisappear(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) title = "" if Utility.getScreenWidth() < IPHONE_6_SCREEN_WIDTH { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) } } func customizeNavBar(){ navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName : UIFont(name: "HelveticaNeue", size: 18)!, NSForegroundColorAttributeName : UIColor.white] navigationController?.navigationBar.barTintColor = Utility.getMainColor() navigationController?.navigationBar.isTranslucent = false } override var preferredStatusBarStyle : UIStatusBarStyle { return .lightContent } func OnKeyboardAppear(_ notify:Notification) { if let dicUserInfo = notify.userInfo { let recKeyboardFrame:CGRect = ((dicUserInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue)! adjustKeyboard(true, frame:recKeyboardFrame) } } func OnKeyboardDisappear(_ notify:Notification) { adjustKeyboard(false) } func adjustKeyboard(_ show:Bool, frame:CGRect?=nil){ if insertType == InsertType.customer{ let vc = childViewControllers[0] as! InsertNewCustomer show == true ? vc.adjustInsetForKeyboard(frame!) : vc.restoreInsetForKeyboard() } } @IBAction func OnCancelBtnTouchUpInside(_ sender: AnyObject) { navigationController?.dismiss(animated: true, completion:nil) } @IBAction func onSaveButtonTouchUpInside(_ sender: AnyObject) { if insertType == InsertType.customer{ let addCustomerVC = childViewControllers[0] as! InsertNewCustomer let data = addCustomerVC.generateApiData() saveNewCustomer(data) } else if insertType == InsertType.project{ let addProjectVC = childViewControllers[1] as! InsertNewProjectVC let data = addProjectVC.generateApiData() saveNewProject(data) } } func saveNewCustomer(_ data:CustomerPost){ APIservice.sharedInstance.saveNewCustomer(data){ (data:Customer?) in if data == nil { //self.errorLbl.text = "Error saving customer, please check your internet" //self.errorLbl.hidden = false } else { self.dismiss(animated: true, completion: nil) } //self.saveBtn.enabled = true //self.activityIndicator.hidden = true //self.activityIndicator.stopAnimating() } } func saveNewProject(_ data:ProjectPost){ APIservice.sharedInstance.saveNewProject(data){ (data:Project?) in if data == nil { //self.errorLbl.text = "Error saving customer, please check your internet" //self.errorLbl.hidden = false } else { self.dismiss(animated: true, completion: nil) } //self.saveBtn.enabled = true //self.activityIndicator.hidden = true //self.activityIndicator.stopAnimating() } } }
mit
ef69bcf4c4180c10452d8f8697f72d44
35.41791
182
0.639549
5.287107
false
false
false
false
ResearchSuite/ResearchSuiteExtensions-iOS
source/Core/Classes/RSEnhancedDayOfWeekChoiceStep.swift
1
2477
// // RSEnhancedDayOfWeekChoiceStep.swift // ResearchSuiteExtensions // // Created by James Kizer on 10/20/18. // import UIKit import ResearchKit extension String { var localized: String { return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "") } } open class RSEnhancedDayOfWeekChoiceStep: RSEnhancedMultipleChoiceStep { static public var choices: [ORKTextChoice] { let pairs = [ ("Sunday".localized, NSNumber(integerLiteral: 1)), ("Monday".localized, NSNumber(integerLiteral: 2)), ("Tuesday".localized, NSNumber(integerLiteral: 3)), ("Wednesday".localized, NSNumber(integerLiteral: 4)), ("Thursday".localized, NSNumber(integerLiteral: 5)), ("Friday".localized, NSNumber(integerLiteral: 6)), ("Saturday".localized, NSNumber(integerLiteral: 7)), ] return pairs.map { pair in RSTextChoiceWithAuxiliaryAnswer( identifier: pair.0, text: pair.0, detailText: nil, value: pair.1, exclusive: false, auxiliaryItem: nil ) } } public let minimumDays: Int public let maximumDays: Int public let consecutiveDaysAllowed: Bool public init( identifier: String, title: String?, text: String?, minimumDays: Int = 0, maximumDays: Int = 7, consecutiveDaysAllowed: Bool = true, cellControllerGenerators: [RSEnhancedMultipleChoiceCellControllerGenerator.Type] ) { self.minimumDays = minimumDays self.maximumDays = maximumDays self.consecutiveDaysAllowed = consecutiveDaysAllowed let answerFormat = ORKTextChoiceAnswerFormat(style: (maximumDays > 1) ? .multipleChoice : .singleChoice , textChoices: RSEnhancedDayOfWeekChoiceStep.choices) super.init( identifier: identifier, title: title, text: text, answer: answerFormat, cellControllerGenerators: cellControllerGenerators ) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func stepViewControllerClass() -> AnyClass { return RSEnhancedDayOfWeekChoiceStepViewController.self } }
apache-2.0
22f4f5875cdb3bff66085db27d7999f9
29.580247
165
0.608397
5.247881
false
false
false
false
jathu/sweetercolor
SweetercolorTests/LAB_Test.swift
1
1362
// // LAB_Test.swift // Sweetercolor // // Created by Jathu Satkunarajah - August 2015 - Toronto // Copyright (c) 2015 Jathu Satkunarajah. All rights reserved. // import UIKit import XCTest class LAB_Test: XCTestCase { // Test source: http://colormine.org/convert/rgb-to-lab func testBlack() { let color = UIColor.black().LAB let expect:[CGFloat] = [0, 0, 0] XCTAssertTrue(color[0].residualCompare(with: expect[0])) XCTAssertTrue(color[1].residualCompare(with: expect[1])) XCTAssertTrue(color[2].residualCompare(with: expect[2])) } func testWhite() { let color = UIColor.white().LAB let expect:[CGFloat] = [100, 0.00526049995830391, -0.010408184525267927] XCTAssertTrue(color[0].residualCompare(with: expect[0])) XCTAssertTrue(color[1].residualCompare(with: expect[1])) XCTAssertTrue(color[2].residualCompare(with: expect[2])) } func testRandomColor() { let color = UIColor(r: 2, g: 8, b: 94, a: 1).LAB let expect:[CGFloat] = [8.947414060170729, 33.48449601168331, -49.19236878079187] XCTAssertTrue(color[0].residualCompare(with: expect[0])) XCTAssertTrue(color[1].residualCompare(with: expect[1])) XCTAssertTrue(color[2].residualCompare(with: expect[2])) } }
mit
2a2c87f6b128b71ac146e2f21f79939d
30.674419
89
0.633627
3.711172
false
true
false
false
gongruike/RKRequest3
Demo/Demo/RequestModel.swift
2
3247
// // RequestModel.swift // Demo // // Created by gongruike on 2017/3/1. // Copyright © 2017年 gongruike. All rights reserved. // import Alamofire import SwiftyJSON class User { let uid: String let username: String init(attributes: JSON) { // uid = attributes["uid"].stringValue username = attributes["username"].stringValue } } struct MyError: Error { // 与服务器协商的错误信息 enum ErrorType { case stringInfo(String) case numberInfo(Int) case arrayInfo(Array<String>) } let type: ErrorType // 可以添加别的信息 func getErrorInfo() -> String { switch self.type { case .stringInfo(let str): return str case .numberInfo(let number): return "\(number)" default: return "unknown error" } } } extension Error { func getErrorInfo() -> String { if let err = self as? MyError { return err.getErrorInfo() } else { return localizedDescription } } } class BaseRequest<Value>: RKSwiftyJSONRequest<Value> { override func parse(_ dataResponse: DataResponse<JSON>) -> Result<Value> { switch dataResponse.result { case .success(let data): return checkResponseError(dataResponse) ?? getExpectedResult(data) case .failure(let error): return Result.failure(error) } } /* 我一直犹豫是否要把checkResponseError和getExpectedResult放到Request中 现在流行的restful api接口有两种类型, 1、以http status code为准,只有200系列是成功的,其他401,400,500类型的都是错误 2、只要服务器有返回都是200,具体的错误code和信息都在返回的响应里 */ // 根据与服务器协定的错误处理方式进行检查 func checkResponseError(_ dataResponse: DataResponse<JSON>) -> Result<Value>? { let statusCode = dataResponse.response?.statusCode if statusCode == 400 { return Result.failure(MyError(type: .stringInfo("error"))) } else if statusCode == 401 { return Result.failure(MyError(type: .numberInfo(12345))) } else { return nil } } // 获取期望的数据 func getExpectedResult(_ data: JSON) -> Result<Value> { return Result.failure(RKError.invalidRequestType) } } class UserInfoRequest: BaseRequest<User> { init(userID: String, completionHandler: CompletionHandler?) { super.init(url: "user/\(userID)", completionHandler: completionHandler) } override func getExpectedResult(_ data: JSON) -> Result<User> { return Result.success(User(attributes: data)) } } class UserListRequest: BaseRequest<[User]> { init(completionHandler: CompletionHandler?) { super.init(url: "user", completionHandler: completionHandler) } override func getExpectedResult(_ data: JSON) -> Result<Array<User>> { return Result.success(data.map { User(attributes: $1) }) } }
mit
7aba959f589467810fb8573c2ea5d45f
22.777778
83
0.597797
4.273894
false
false
false
false
lenssss/whereAmI
Whereami/Controller/Contact/ContactMainViewController.swift
1
14593
// // ContactMainViewController.swift // Whereami // // Created by WuQifei on 16/2/16. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit import PureLayout import ReactiveCocoa import SWTableViewCell import SocketIOClientSwift //import SDWebImage class ContactMainViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchControllerDelegate,UISearchBarDelegate,SWTableViewCellDelegate,UINavigationControllerDelegate { var tableView:UITableView? = nil // private var currentConversations:[ConversationModel]? = nil var searchResultVC:AnyObject? = nil var searchController:UISearchController? = nil var currentFriends:[FriendsModel]? = nil var newConversationHasDone:NewConversation? = nil override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = NSLocalizedString("Contact",tableName:"Localizable", comment: "") self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName:UIFont.customFontWithStyle("Bold", size:18.0)!,NSForegroundColorAttributeName:UIColor.whiteColor()] self.setConfig() self.setupUI() self.registerNotification() self.navigationController!.delegate = self } func setupUI() { self.tableView = UITableView() self.view.addSubview(self.tableView!) self.tableView?.separatorStyle = .None self.tableView?.delegate = self self.tableView?.dataSource = self self.tableView?.tableFooterView = UIView() self.tableView?.registerClass(ContactMainViewCell.self, forCellReuseIdentifier: "ContactMainViewCell") searchResultVC = ContactMainViewSearchResultViewController() searchController = UISearchController(searchResultsController: searchResultVC as! ContactMainViewSearchResultViewController) searchController?.searchResultsUpdater = searchResultVC as! ContactMainViewSearchResultViewController searchController?.delegate = self searchController?.searchBar.sizeToFit() searchController?.active = true searchController?.searchBar.delegate = self self.tableView?.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)) self.tableView?.tableHeaderView = searchController?.searchBar } func registerNotification(){ LNotificationCenter().rac_addObserverForName(UIKeyboardWillHideNotification, object: nil).subscribeNext { (notification) -> Void in self.searchController?.active = false } LNotificationCenter().rac_addObserverForName(KNotificationDismissSearchView, object: nil).subscribeNext { (notification) -> Void in let id = notification.object! as! String self.runInMainQueue({ let personalVC = TourRecordsViewController() personalVC.userId = id personalVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(personalVC, animated: true) }) } LNotificationCenter().rac_addObserverForName("addFriended", object: nil).subscribeNext { (notification) -> Void in // let friend = notification.object! as! FriendsModel self.currentFriends = CoreDataManager.sharedInstance.fetchAllFriends() self.tableView?.reloadData() } } // func addFriend(){ // let friendVC = ContactIncreaseFriendViewController() // friendVC.hidesBottomBarWhenPushed = true // self.navigationController?.pushViewController(friendVC, animated: true) // } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.currentFriends = CoreDataManager.sharedInstance.fetchAllFriends() self.tableView?.reloadData() } func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool){ if viewController.isKindOfClass(ContactMainViewController.self) || viewController.isKindOfClass(ConversationViewController.self) { self.navigationController?.navigationBar.backgroundColor = UIColor.getNavigationBarColor() self.navigationController?.navigationBar.barTintColor = UIColor.getNavigationBarColor() }else { self.navigationController?.navigationBar.backgroundColor = UIColor.getGameColor() self.navigationController?.navigationBar.barTintColor = UIColor.getGameColor() } } func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool){ if viewController.isKindOfClass(ContactMainViewController.self) || viewController.isKindOfClass(ConversationViewController.self) { self.navigationController?.navigationBar.backgroundColor = UIColor.getNavigationBarColor() self.navigationController?.navigationBar.barTintColor = UIColor.getNavigationBarColor() }else { self.navigationController?.navigationBar.backgroundColor = UIColor.getGameColor() self.navigationController?.navigationBar.barTintColor = UIColor.getGameColor() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if currentFriends != nil { return currentFriends!.count } return 0 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 70.0; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:ContactMainViewCell = tableView.dequeueReusableCellWithIdentifier("ContactMainViewCell", forIndexPath: indexPath) as! ContactMainViewCell cell.selectionStyle = .None let friendModel = currentFriends![indexPath.row] let avatarUrl = friendModel.headPortrait != nil ? friendModel.headPortrait : "" // cell.avatar?.setImageWithString(avatarUrl!, placeholderImage: UIImage(named: "avator.png")!) cell.avatar?.kf_setImageWithURL(NSURL(string:avatarUrl!)!, placeholderImage: UIImage(named: "avator.png"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) cell.chatName?.text = friendModel.nickname! cell.chatAction = {(button) -> Void in let status = SocketManager.sharedInstance.socket?.status if status == SocketIOClientStatus.Connected { self.createConversation(indexPath) } else{ let alertController = UIAlertController(title: NSLocalizedString("warning",tableName:"Localizable", comment: ""), message: "网络异常", preferredStyle: .Alert) let confirmAction = UIAlertAction(title: NSLocalizedString("ok",tableName:"Localizable", comment: ""), style: .Default, handler: { (confirmAction) in SocketManager.sharedInstance.connection({ (ifConnection) in }) }) alertController.addAction(confirmAction) self.presentViewController(alertController, animated: true, completion: nil) } } cell.playAction = {(button) -> Void in let newGameVC = ContactPresentNewGameViewController() newGameVC.friend = friendModel newGameVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(newGameVC, animated: true) } let deleteBtn = UIButton() deleteBtn.backgroundColor = UIColor.redColor() deleteBtn.setTitle("删除", forState: .Normal) cell.rightUtilityButtons = [deleteBtn] cell.delegate = self let userModel = CoreDataManager.sharedInstance.fetchUserById(friendModel.friendId!) cell.location?.text = userModel?.countryName return cell } func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerRightUtilityButtonWithIndex index: Int) { let indexPath = self.tableView?.indexPathForCell(cell) var dict = [String: AnyObject]() dict["accountId"] = self.currentFriends![indexPath!.row].accountId dict["friendId"] = self.currentFriends![indexPath!.row].friendId SocketManager.sharedInstance.sendMsg("delFreind", data: dict, onProto: "delFreinded", callBack: { (code, objs) in if code == statusCode.Normal.rawValue { CoreDataManager.sharedInstance.deleteFriends(self.currentFriends![indexPath!.row].accountId!,friendId: self.currentFriends![indexPath!.row].friendId!) self.currentFriends = CoreDataManager.sharedInstance.fetchAllFriends() self.runInMainQueue({ self.tableView!.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Middle) }) } }) } /* func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return .Delete } func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let delAction = UITableViewRowAction(style: UITableViewRowActionStyle.Destructive, title: "删除") { (_, _) -> Void in var dict = [String: AnyObject]() dict["accountId"] = self.currentFriends![indexPath.row].accountId dict["friendId"] = self.currentFriends![indexPath.row].friendId SocketManager.sharedInstance.sendMsg("delFreind", data: dict, onProto: "delFreinded", callBack: { (code, objs) in if code == statusCode.Normal.rawValue { CoreDataManager.sharedInstance.deleteFriends(self.currentFriends![indexPath.row].accountId!,friendId: self.currentFriends![indexPath.row].friendId!) self.currentFriends = CoreDataManager.sharedInstance.fetchAllFriends() self.runInMainQueue({ tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Middle) }) } }) } delAction.backgroundColor = UIColor.grayColor() return [delAction] } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { //是删除,就删除 if editingStyle == .Delete { var dict = [String: AnyObject]() dict["accountId"] = currentFriends![indexPath.row].accountId dict["friendId"] = currentFriends![indexPath.row].friendId SocketManager.sharedInstance.sendMsg("delFreind", data: dict, onProto: "delFreinded", callBack: { (code, objs) in if code == statusCode.Normal.rawValue { CoreDataManager.sharedInstance.deleteFriends(self.currentFriends![indexPath.row].accountId!,friendId: self.currentFriends![indexPath.row].friendId!) self.currentFriends = CoreDataManager.sharedInstance.fetchAllFriends() self.runInMainQueue({ tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Middle) }) } }) } } */ func searchBarSearchButtonClicked(searchBar: UISearchBar) { print("=====================\(searchBar.text)") } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let friendModel:FriendsModel = currentFriends![indexPath.row] let personalVC = TourRecordsViewController() personalVC.userId = friendModel.friendId personalVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(personalVC, animated: true) } func createConversation(indexPath:NSIndexPath){ let friendModel:FriendsModel = currentFriends![indexPath.row] let currentUser = UserModel.getCurrentUser() let guestUser = ChattingUserModel() let hostUser = ChattingUserModel() guestUser.accountId = friendModel.friendId guestUser.headPortrait = friendModel.headPortrait guestUser.nickname = friendModel.nickname hostUser.accountId = currentUser?.id hostUser.headPortrait = currentUser?.headPortraitUrl hostUser.nickname = currentUser?.nickname LeanCloudManager.sharedInstance.createConversitionWithClientIds(guestUser.accountId!, clientIds: [guestUser.accountId!]) { (succed, conversion) in if(succed) { CoreDataConversationManager.sharedInstance.increaseOrCreateUnreadCountByConversation( conversion!, lastMsg: "", msgType: kAVIMMessageMediaTypeText) self.push2ConversationVC(conversion!, hostUser: hostUser, guestUser: guestUser) } } } func push2ConversationVC(conversion:AVIMConversation,hostUser:ChattingUserModel,guestUser:ChattingUserModel) { let conversationVC = ConversationViewController() conversationVC.conversation = conversion conversationVC.hostModel = hostUser conversationVC.guestModel = guestUser conversationVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(conversationVC, animated: true) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.searchController?.active = false } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
c850ade5891a07f4bf85950a701d296e
47.211921
195
0.678091
5.979466
false
false
false
false
ptsochantaris/trailer-cli
Sources/trailer/Actions/Actions-Show.swift
1
2754
// // Actions-Show.swift // trailer // // Created by Paul Tsochantaris on 26/08/2017. // Copyright © 2017 Paul Tsochantaris. All rights reserved. // import Foundation extension Actions { static func failShow(_ message: String?) { printErrorMesage(message) printOptionHeader("Please provide one of the following options for 'show'") printOption(name: "item <number>", description: "Show any item with the specified number") printOption(name: "pr <number>", description: "Show a PR with the specified number") printOption(name: "issue <number>", description: "Show an issue with the specified number") log() printOptionHeader("Options (can combine)") printOption(name: "-body", description: "Show the body of the item") printOption(name: "-comments", description: "Show the comments on the item") printOption(name: "-refresh", description: "Update item (& comments, if requested) from remote") log() printFilterOptions() } static func processShowDirective(_ list: [String]) async throws { if list.first == "help" { log() failShow(nil) } guard list.count > 2 else { failShow("Missing argument") return } guard let number = Int(list[2]) else { failShow("Invalid number: \(list[2])") return } let command = list[1] switch command { case "item": await DB.load() if !(try await showItem(number, includePrs: true, includeIssues: true)) { log("[R*Item #\(number) not found*]") } case "pr": await DB.load() if !(try await showItem(number, includePrs: true, includeIssues: false)) { log("[R*PR #\(number) not found*]") } case "issue": await DB.load() if !(try await showItem(number, includePrs: false, includeIssues: true)) { log("[R*Issue #\(number) not found*]") } default: failShow("Unknown argmument: \(command)") } } private static func showItem(_ number: Int, includePrs: Bool, includeIssues: Bool) async throws -> Bool { if let items = findItems(number: number, includePrs: includePrs, includeIssues: includeIssues, warnIfMultiple: true) { if items.count == 1, var item = items.first { if CommandLine.argument(exists: "-refresh") { item = try await Actions.singleItemUpdate(for: item) } item.printDetails() } return items.count > 0 } return false } }
mit
8ba5f33f6d1907c136f984c53f107796
33.4125
126
0.565202
4.63468
false
false
false
false
eBardX/XestiMonitors
Sources/Core/Extensions/CMAcceleration+DeviceOrientation.swift
1
1388
// // CMAccelerometerData+DeviceOrientation.swift // XestiMonitors // // Created by J. G. Pusey on 2016-12-16. // // © 2016 J. G. Pusey (see LICENSE.md) // #if os(iOS) import CoreMotion import UIKit public extension CMAcceleration { /// /// Returns the device orientation as calculated from the 3-axis /// acceleration data. /// /// This property allows you to determine the physical orientation of /// the device from an acceleration measurement provided by an /// `AccelerometerMonitor` instance. There is one important case where /// you might choose to use this technique rather than directly monitor /// device orientation changes with an `OrientationMonitor` /// instance—when rotation is locked on the device. /// var deviceOrientation: UIDeviceOrientation { if z > 0.8 { return .faceDown } if z < -0.8 { return .faceUp } let angle = atan2(y, -x) if (angle >= -2.0) && (angle <= -1.0) { return .portrait } if (angle >= -0.5) && (angle <= 0.5) { return .landscapeLeft } if (angle >= 1.0) && (angle <= 2.0) { return .portraitUpsideDown } if (angle <= -2.5) || (angle >= 2.5) { return .landscapeRight } return .unknown } } #endif
mit
b1d326c4f7bf14630e88d824b1c3d602
22.87931
75
0.568953
4.18429
false
false
false
false
Yvent/QQMusic
QQMusic/QQMusic/ZGlobal.swift
1
5043
// // ZGlobal.swift // wave // // Created by 周逸文 on 16/9/7. // Copyright © 2016年 com.paohaile.zyw. All rights reserved. //全局配置文件 import Foundation import UIKit let NAVBC: UIColor = RGB(58, G: 193, B: 126) let CURRENTVERSION = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String //MARK: UI let ScreenWidth = UIScreen.main.bounds.width let ScreenHeight = UIScreen.main.bounds.height func AdaptationHeight(_ height: CGFloat) -> CGFloat { return CGFloat(ScreenHeight/667) * height } func AdaptationWidth(_ width: CGFloat) -> CGFloat { return CGFloat(ScreenWidth/375) * width } func AdaptationFontSize(_ size: CGFloat) -> CGFloat { return CGFloat(ScreenHeight/667) * size } func getStr(str: String? = nil) -> String { if str != nil { return str! }else{ return "小组" } } func RGBSingle(_ s: CGFloat) -> UIColor { return RGB(s, G: s, B: s) } func RGB(_ R: CGFloat, G: CGFloat, B: CGFloat) -> UIColor { return UIColor(red: R/255.0, green: G/255.0, blue: B/255.0, alpha: 1.0) } func RGBA(_ R: CGFloat, G: CGFloat, B: CGFloat, A: CGFloat) -> UIColor { return UIColor(red: R/255.0, green: G/255.0, blue: B/255.0, alpha: A) } //func GetRandomColor() -> UIColor { // // let aa = GetRandomColor() // // let color = CGFloat() // // let color = CGFloat(CGFloat(random())/CGFloat(RAND_MAX)) // let color1 = CGFloat(CGFloat(random())/CGFloat(RAND_MAX)) // let color2 = CGFloat(CGFloat(random())/CGFloat(RAND_MAX)) // // return UIColor(red: color, green: color1, blue: color2, alpha: 1); //} //创建渐变背景色 func GetGradientLayer(_ top: UIColor, bottom: UIColor) -> CAGradientLayer{ let gradientColors: [CGColor] = [top.cgColor, bottom.cgColor] let gradientLocations: [CGFloat] = [0.0, 1.0] let gradientLayer: CAGradientLayer = CAGradientLayer() gradientLayer.colors = gradientColors gradientLayer.locations = gradientLocations as [NSNumber]? return gradientLayer } //func GetImageView(imageName: String? = nil, BackC: UIColor? = nil) -> UIImageView{ // let imageV = UIImageView() // if imageName != nil { // imageV.image = UIImage(named: imageName!) // } // imageV.backgroundColor = BackC // return imageV //} /// 是否登录 let USER_IS_LOGINED = "USER_IS_LOGINED" /// 用户token let USER_TOKEN = "USER_TOKEN" /// 用户手机号 let USER_PNONENUM = "USER_PNONENUM" /// 用户收藏的歌曲数 let USER_LIKECOUNT = "USER_LIKECOUNT" let FreeUserCount = 10 let UserDefaults = Foundation.UserDefaults.standard /// 获取用户token func getUserToken() -> String { var newtoken: String! = "" if let token = UserDefaults.object(forKey: USER_TOKEN) as? String { newtoken = token } return newtoken } func getHeaders() -> [String : String] { var accessToken: String! = "" if let token = UserDefaults.object(forKey: USER_TOKEN) as? String { accessToken = token } return ["Authorization": "Bearer \(accessToken!)"] } func getiPhoneNumber() -> String { var newtoken: String! = "" if let token = UserDefaults.object(forKey: USER_PNONENUM) as? String { newtoken = token } return newtoken } func getLikeCount() -> Int { var newzcount: Int! = 0 if let zcount = UserDefaults.object(forKey: USER_LIKECOUNT) as? Int { newzcount = zcount } return newzcount } func addLikeCount() { let likecount = getLikeCount() + 1 UserDefaults.set(likecount, forKey: USER_LIKECOUNT) } func deleLikeCount() { let likecount = getLikeCount() - 1 UserDefaults.set(likecount, forKey: USER_LIKECOUNT) } //MARK: OTHER //debug func DebugPrint<T>(_ message: T) { print(message) } //成功回调的返回码 let SuccessStatusCode = 200 // 下载完成的歌曲在本地的文件夹 let DownloadedFolderName = "WAVE_Downloaded" //歌手cell的宽 let SingerCW = (ScreenWidth)/4 //歌手cell的高 let SingerCH = AdaptationHeight(40) //进度圈的宽高 let ProgressWH = AdaptationWidth(267) // 进度条的粗 let ProgressBW = CGFloat(10) ///MARK: 数据库大小 let SongsCount = 10 ///过滤数据 func GETSID(_ sid: String) -> String { let fullName = sid var fullNameArr = fullName.characters.split{$0 == "-"}.map(String.init) return fullNameArr[0] // var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil } func getR(_ maxX: Float,minX: Float,maxR: Float,minR: Float,currentX: Float) -> Float { return minR + ((currentX - (maxX - minX)) * ((maxR - minR)/(maxX - minX))) } func getLeft(_ maxX: Float,minX: Float,maxR: Float,minR: Float,currentX: Float) -> Float { return minR + (((maxX - minX) - currentX) * ((maxR - minR)/(maxX - minX))) } func getX(_ maxX: Float,minX: Float,maxBGX: Float,minBGX: Float,currentX: Float) -> Float { return minBGX + ((currentX - (maxX - minX)) * ((maxBGX - minBGX)/(maxX - minX))) } //=============================================
mit
15e16eb6f978158e7a2c5428e7d30ff3
23.29
91
0.644298
3.383008
false
false
false
false
eleneakhvlediani/GalleryLS
GalleryLS/Classes/INSPhoto.swift
1
6712
// // INSPhoto.swift // INSPhotoViewer // // Created by Michal Zaborowski on 28.02.2016. // Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this library 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 UIKit import AVFoundation import AVKit /* * This is marked as @objc because of Swift bug http://stackoverflow.com/questions/30100787/fatal-error-array-cannot-be-bridged-from-objective-c-why-are-you-even-trying when passing for example [INSPhoto] array * to INSPhotosViewController */ @objc public protocol INSPhotoViewable: class { var image: UIImage? { get } var thumbnailImage: UIImage? { get } var video: AVPlayer? { get } var isVideo: NSNumber? { get } var playerLayer:AVPlayerLayer? { get } // var playerViewController: AVPlayerViewController? { get } func loadImageWithCompletionHandler(_ completion: @escaping (_ image: UIImage?, _ error: Error?) -> ()) func loadThumbnailImageWithCompletionHandler(_ completion: @escaping (_ image: UIImage?, _ error: Error?) -> ()) func loadVideoWithCompletionHandler(_ completion: @escaping (_ video: AVPlayer?, _ error: Error?) -> ()) var attributedTitle: NSAttributedString? { get } } open class INSPhoto: INSPhotoViewable, Equatable { @objc open var video: AVPlayer? @objc open var image: UIImage? @objc open var thumbnailImage: UIImage? var url: URL? var thumbnailImageURL: URL? public var playerLayer:AVPlayerLayer? // public var playerViewController:AVPlayerViewController? public var isVideo: NSNumber? @objc open var attributedTitle: NSAttributedString? public init(image: UIImage?, thumbnailImage: UIImage?) { self.image = image self.thumbnailImage = thumbnailImage self.isVideo = 0 } public init(image:UIImage?, video: AVPlayer?, thumbnailImage: UIImage?) { self.video = video self.image = image self.thumbnailImage = thumbnailImage self.isVideo = 1 } public init(video: AVPlayer?, thumbnailImageURL: URL?) { self.video = video self.thumbnailImageURL = thumbnailImageURL self.isVideo = 1 } public init(videoURL: URL?, thumbnailImageURL: URL?) { self.url = videoURL self.thumbnailImageURL = thumbnailImageURL self.isVideo = 1 } public init(videoURL: URL?, thumbnailImage: UIImage?) { self.url = videoURL self.thumbnailImage = thumbnailImage self.isVideo = 1 } public init(imageURL: URL?, thumbnailImageURL: URL?) { self.url = imageURL self.thumbnailImageURL = thumbnailImageURL self.isVideo = 0 } public init (imageURL: URL?, thumbnailImage: UIImage) { self.url = imageURL self.thumbnailImage = thumbnailImage self.isVideo = 0 } @objc open func loadImageWithCompletionHandler(_ completion: @escaping (_ image: UIImage?, _ error: Error?) -> ()) { if let image = image { completion(image, nil) return } loadImageWithURL(url, completion: completion) } @objc open func loadVideoWithCompletionHandler(_ completion: @escaping (_ video: AVPlayer?, _ error: Error?) -> ()) { if let video = video { completion(video, nil) return } loadVideoWithURL(url, completion: completion) } @objc open func loadThumbnailImageWithCompletionHandler(_ completion: @escaping (_ image: UIImage?, _ error: Error?) -> ()) { if let thumbnailImage = thumbnailImage { completion(thumbnailImage, nil) return } loadImageWithURL(thumbnailImageURL, completion: completion) } open func loadImageWithURL(_ url: URL?, completion: @escaping (_ image: UIImage?, _ error: Error?) -> ()) { let session = URLSession(configuration: URLSessionConfiguration.default) if let imageURL = url { session.dataTask(with: imageURL, completionHandler: { (response, data, error) in DispatchQueue.main.async(execute: { () -> Void in if error != nil { completion(nil, error) } else if let response = response, let image = UIImage(data: response) { completion(image, nil) } else { completion(nil, NSError(domain: "INSPhotoDomain", code: -1, userInfo: [ NSLocalizedDescriptionKey: "Couldn't load image"])) } session.finishTasksAndInvalidate() }) }).resume() } else { completion(nil, NSError(domain: "INSPhotoDomain", code: -2, userInfo: [ NSLocalizedDescriptionKey: "Image URL not found."])) } } open func loadVideoWithURL(_ url: URL?, completion: @escaping (_ video: AVPlayer?, _ error: Error?) -> ()) { let session = URLSession(configuration: URLSessionConfiguration.default) if let url = url { session.dataTask(with: url, completionHandler: { (response, data, error) in DispatchQueue.main.async(execute: { () -> Void in if error != nil { completion(nil, error) } else if response != nil { let video = AVPlayer(url: url) completion(video, nil) } else { completion(nil, NSError(domain: "INSPhotoDomain", code: -1, userInfo: [ NSLocalizedDescriptionKey: "Couldn't load image"])) } session.finishTasksAndInvalidate() }) }).resume() } else { completion(nil, NSError(domain: "INSPhotoDomain", code: -2, userInfo: [ NSLocalizedDescriptionKey: "Image URL not found."])) } } } public func ==<T: INSPhoto>(lhs: T, rhs: T) -> Bool { return lhs === rhs }
mit
8e714644624f68aa04ffb0830cb50ad4
34.497354
210
0.600686
4.980698
false
false
false
false
iOSTestApps/PhoneBattery
PhoneBattery WatchKit Extension/BatteryInformation.swift
1
766
// // BatteryInformation.swift // PhoneBattery // // Created by Marcel Voß on 29.07.15. // Copyright (c) 2015 Marcel Voss. All rights reserved. // import UIKit class BatteryInformation: NSObject { class func stringForBatteryState(batteryState: UIDeviceBatteryState) -> String { if batteryState == UIDeviceBatteryState.Full { return NSLocalizedString("FULL", comment: "") } else if batteryState == UIDeviceBatteryState.Charging { return NSLocalizedString("CHARGING", comment: "") } else if batteryState == UIDeviceBatteryState.Unplugged { return NSLocalizedString("REMAINING", comment: "") } else { return NSLocalizedString("UNKNOWN", comment: "") } } }
mit
7b06125d221eb18f1717709c9c7c7cd8
28.423077
84
0.647059
4.935484
false
false
false
false
ajrosario08/Calculator
MyCalculator/CalculatorBrain.swift
1
2807
// // CalculatorBrain.swift // MyCalculator // // Created by Anthony Rosario on 10/21/15. // Copyright © 2015 Anthony Rosario. All rights reserved. // import Foundation class CalculatorBrain { private enum Op: CustomStringConvertible { case Operand(Double) case UnaryOperation(String, Double -> Double) case BinaryOperation(String, (Double, Double) -> Double) var description: String { get { switch self { case .Operand(let operand): return "\(operand)" case .UnaryOperation(let symbol, _): return symbol case .BinaryOperation(let symbol, _): return symbol } } } } private var opStack = [Op]() private var knownOps = [String:Op]() init() { knownOps["×"] = Op.BinaryOperation("×") { $0 * $1 } knownOps["÷"] = Op.BinaryOperation("÷") { $1 / $0 } knownOps["+"] = Op.BinaryOperation("+") { $0 + $1 } knownOps["−"] = Op.BinaryOperation("−") { $1 - $0 } knownOps["√"] = Op.UnaryOperation("√") { sqrt($0) } } private func evaluate(ops: [Op]) -> (result: Double?, remainingOps: [Op]) { if !ops.isEmpty { var remainingOps = ops let op = remainingOps.removeLast() switch op { case .Operand(let operand): return (operand, remainingOps) case .UnaryOperation(_, let operation): let operandEvaluation = evaluate(remainingOps) if let operand = operandEvaluation.result { return (operation(operand), operandEvaluation.remainingOps) } case .BinaryOperation(_, let operation): let op1Evaluation = evaluate(remainingOps) if let operand1 = op1Evaluation.result { let op2Evaluation = evaluate(op1Evaluation.remainingOps) if let operand2 = op2Evaluation.result { return (operation(operand1, operand2), op2Evaluation.remainingOps) } } } } return (nil, ops) } func evaluate() -> Double? { let (result, remainder) = evaluate(opStack) print("\(opStack) = \(result) with \(remainder) left over") return result } func pushOperand(operand: Double) -> Double? { opStack.append(Op.Operand(operand)) return evaluate() } func performOperation(symbol: String) -> Double? { if let operation = knownOps[symbol] { opStack.append(operation) } return evaluate() } }
gpl-2.0
69abe8c93cea798bfa3a0180ee554cf7
31.126437
90
0.520043
4.792453
false
false
false
false
xedin/swift
test/decl/func/dynamic_self.swift
1
10882
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-objc-interop // ---------------------------------------------------------------------------- // DynamicSelf is only allowed on the return type of class and // protocol methods. func global() -> Self { } // expected-error{{global function cannot return 'Self'}} func inFunction() { func local() -> Self { } // expected-error{{local function cannot return 'Self'}} } struct S0 { func f() -> Self { } func g(_ ds: Self) { } } enum E0 { func f() -> Self { } func g(_ ds: Self) { } } class C0 { func f() -> Self { } // okay func g(_ ds: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C0'?}}{{16-20=C0}} func h(_ ds: Self) -> Self { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C0'?}}{{16-20=C0}} } protocol P0 { func f() -> Self // okay func g(_ ds: Self) // okay } extension P0 { func h() -> Self { // okay func g(_ t : Self) -> Self { // okay return t } return g(self) } } protocol P1: class { func f() -> Self // okay func g(_ ds: Self) // okay } extension P1 { func h() -> Self { // okay func g(_ t : Self) -> Self { // okay return t } return g(self) } } // ---------------------------------------------------------------------------- // The 'self' type of a Self method is based on Self class C1 { required init(int i: Int) {} // Instance methods have a self of type Self. func f(_ b: Bool) -> Self { // FIXME: below diagnostic should complain about C1 -> Self conversion if b { return C1(int: 5) } // expected-error{{cannot convert return expression of type 'C1' to return type 'Self'}} // One can use `type(of:)` to attempt to construct an object of type Self. if !b { return type(of: self).init(int: 5) } // Can't utter Self within the body of a method. var _: Self = self // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C1'?}} {{12-16=C1}} // Okay to return 'self', because it has the appropriate type. return self // okay } // Type methods have a self of type Self.Type. class func factory(_ b: Bool) -> Self { // Check directly. var x: Int = self // expected-error{{cannot convert value of type 'Self.Type' to specified type 'Int'}} // Can't utter Self within the body of a method. var c1 = C1(int: 5) as Self // expected-error{{'C1' is not convertible to 'Self'; did you mean to use 'as!' to force downcast?}} if b { return self.init(int: 5) } return Self() // expected-error{{non-nominal type 'Self' does not support explicit initialization}} } // This used to crash because metatype construction went down a // different code path that didn't handle DynamicSelfType. class func badFactory() -> Self { return self(int: 0) // expected-error@-1 {{initializing from a metatype value must reference 'init' explicitly}} } } // ---------------------------------------------------------------------------- // Using a method with a Self result carries the receiver type. class X { func instance() -> Self { } class func factory() -> Self { } func produceX() -> X { } } class Y : X { func produceY() -> Y { } } func testInvokeInstanceMethodSelf() { // Trivial case: invoking on the declaring class. var x = X() var x2 = x.instance() x = x2 // at least an X x2 = x // no more than an X // Invoking on a subclass. var y = Y() var y2 = y.instance(); y = y2 // at least a Y y2 = y // no more than a Y } func testInvokeTypeMethodSelf() { // Trivial case: invoking on the declaring class. var x = X() var x2 = X.factory() x = x2 // at least an X x2 = x // no more than an X // Invoking on a subclass. var y = Y() var y2 = Y.factory() y = y2 // at least a Y y2 = y // no more than a Y } func testCurryInstanceMethodSelf() { // Trivial case: currying on the declaring class. var produceX = X.produceX var produceX2 = X.instance produceX = produceX2 produceX2 = produceX // Currying on a subclass. var produceY = Y.produceY var produceY2 = Y.instance produceY = produceY2 produceY2 = produceY } class GX<T> { func instance() -> Self { } class func factory() -> Self { } func produceGX() -> GX { } } class GY<T> : GX<[T]> { func produceGY() -> GY { } } func testInvokeInstanceMethodSelfGeneric() { // Trivial case: invoking on the declaring class. var x = GX<Int>() var x2 = x.instance() x = x2 // at least an GX<Int> x2 = x // no more than an GX<Int> // Invoking on a subclass. var y = GY<Int>() var y2 = y.instance(); y = y2 // at least a GY<Int> y2 = y // no more than a GY<Int> } func testInvokeTypeMethodSelfGeneric() { // Trivial case: invoking on the declaring class. var x = GX<Int>() var x2 = GX<Int>.factory() x = x2 // at least an GX<Int> x2 = x // no more than an GX<Int> // Invoking on a subclass. var y = GY<Int>() var y2 = GY<Int>.factory(); y = y2 // at least a GY<Int> y2 = y // no more than a GY<Int> } func testCurryInstanceMethodSelfGeneric() { // Trivial case: currying on the declaring class. var produceGX = GX<Int>.produceGX var produceGX2 = GX<Int>.instance produceGX = produceGX2 produceGX2 = produceGX // Currying on a subclass. var produceGY = GY<Int>.produceGY var produceGY2 = GY<Int>.instance produceGY = produceGY2 produceGY2 = produceGY } // ---------------------------------------------------------------------------- // Overriding a method with a Self class Z : Y { override func instance() -> Self { } override class func factory() -> Self { } } func testOverriddenMethodSelfGeneric() { var z = Z() var z2 = z.instance(); z = z2 z2 = z var z3 = Z.factory() z = z3 z3 = z } // ---------------------------------------------------------------------------- // Generic uses of Self methods. protocol P { func f() -> Self } func testGenericCall<T: P>(_ t: T) { var t = t var t2 = t.f() t2 = t t = t2 } // ---------------------------------------------------------------------------- // Existential uses of Self methods. func testExistentialCall(_ p: P) { _ = p.f() } // ---------------------------------------------------------------------------- // Dynamic lookup of Self methods. @objc class SomeClass { @objc func method() -> Self { return self } } func testAnyObject(_ ao: AnyObject) { var ao = ao var result : AnyObject = ao.method!() result = ao ao = result } // ---------------------------------------------------------------------------- // Name lookup on Self values extension Y { func testInstance() -> Self { if false { return self.instance() } return instance() } class func testFactory() -> Self { if false { return self.factory() } return factory() } } // ---------------------------------------------------------------------------- // Optional Self returns extension X { func tryToClone() -> Self? { return nil } func tryHarderToClone() -> Self! { return nil } func cloneOrFail() -> Self { return self } func cloneAsObjectSlice() -> X? { return self } } extension Y { func operationThatOnlyExistsOnY() {} } func testOptionalSelf(_ y : Y) { if let clone = y.tryToClone() { clone.operationThatOnlyExistsOnY() } // Sanity-checking to make sure that the above succeeding // isn't coincidental. if let clone = y.cloneOrFail() { // expected-error {{initializer for conditional binding must have Optional type, not 'Y'}} clone.operationThatOnlyExistsOnY() } // Sanity-checking to make sure that the above succeeding // isn't coincidental. if let clone = y.cloneAsObjectSlice() { clone.operationThatOnlyExistsOnY() // expected-error {{value of type 'X' has no member 'operationThatOnlyExistsOnY'}} } if let clone = y.tryHarderToClone().tryToClone() { clone.operationThatOnlyExistsOnY(); } } // ---------------------------------------------------------------------------- // Conformance lookup on Self protocol Runcible { associatedtype Runcer } extension Runcible { func runce() {} func runced(_: Runcer) {} } func wantsRuncible<T : Runcible>(_: T) {} class Runce : Runcible { typealias Runcer = Int func getRunced() -> Self { runce() wantsRuncible(self) runced(3) return self } } // ---------------------------------------------------------------------------- // Forming a type with 'Self' in invariant position struct Generic<T> { init(_: T) {} } // expected-note {{arguments to generic parameter 'T' ('Self' and 'InvariantSelf') are expected to be equal}} // expected-note@-1 {{arguments to generic parameter 'T' ('Self' and 'FinalInvariantSelf') are expected to be equal}} class InvariantSelf { func me() -> Self { let a = Generic(self) let _: Generic<InvariantSelf> = a // expected-error@-1 {{cannot assign value of type 'Generic<Self>' to type 'Generic<InvariantSelf>'}} return self } } // FIXME: This should be allowed final class FinalInvariantSelf { func me() -> Self { let a = Generic(self) let _: Generic<FinalInvariantSelf> = a // expected-error@-1 {{cannot assign value of type 'Generic<Self>' to type 'Generic<FinalInvariantSelf>'}} return self } } // ---------------------------------------------------------------------------- // Semi-bogus factory init pattern protocol FactoryPattern { init(factory: @autoclosure () -> Self) } extension FactoryPattern { init(factory: @autoclosure () -> Self) { self = factory() } } class Factory : FactoryPattern { init(_string: String) {} convenience init(string: String) { self.init(factory: Factory(_string: string)) // expected-error@-1 {{incorrect argument label in call (have 'factory:', expected '_string:')}} // FIXME: Bogus diagnostic } } // Final classes are OK final class FinalFactory : FactoryPattern { init(_string: String) {} convenience init(string: String) { self.init(factory: FinalFactory(_string: string)) } } // Operators returning Self class SelfOperator { required init() {} static func +(lhs: SelfOperator, rhs: SelfOperator) -> Self { return self.init() } func double() -> Self { // FIXME: Should this work? return self + self // expected-error {{cannot convert return expression of type 'SelfOperator' to return type 'Self'}} } } func useSelfOperator() { let s = SelfOperator() _ = s + s } // for ... in loops struct DummyIterator : IteratorProtocol { func next() -> Int? { return nil } } class Iterable : Sequence { func returnsSelf() -> Self { for _ in self {} return self } func makeIterator() -> DummyIterator { return DummyIterator() } }
apache-2.0
238f9b81375af48e04dbe4c1c8bd3b13
23.788155
164
0.582062
3.857497
false
false
false
false
segmentio/analytics-swift
Examples/apps/SegmentExtensionsExample/SegmentExtensionsExample/ResultViewController.swift
1
1079
// // ResultViewController.swift // SegmentExtensionsExample // // Created by Alan Charles on 8/10/21. // import UIKit import AuthenticationServices class ResultViewController: UIViewController { var analytics = UIApplication.shared.delegate?.analytics @IBOutlet weak var userIdentifierLabel: UILabel! @IBOutlet weak var givenNameLabel: UILabel! @IBOutlet weak var familyNameLabel: UILabel! @IBOutlet weak var emailLabel: UILabel! @IBOutlet weak var signOutButton: UIButton! override func viewDidLoad() { super.viewDidLoad() userIdentifierLabel.text = KeychainItem.currentUserIdentifier } @IBAction func signOutButtonPressed(_ sender: UIButton!) { KeychainItem.deleteUserIdentifierFromKeychain() userIdentifierLabel.text = "" givenNameLabel.text = "" familyNameLabel.text = "" emailLabel.text = "" DispatchQueue.main.async { self.showLoginViewController() } analytics?.track(name: "Logged Out") } }
mit
c696aa41c3a57d1aa90f509ad5213876
25.975
69
0.668211
5.263415
false
false
false
false
asurinsaka/swift_examples_2.1
LocationTraker/LocationTraker/APPStatus.swift
1
563
// // APPStatus.swift // LocationTraker // // Created by larryhou on 29/7/2015. // Copyright © 2015 larryhou. All rights reserved. // import Foundation import CoreData @objc(APPStatus) class APPStatus: NSManagedObject { // Insert code here to add functionality to your managed object subclass } enum APPStatusType:String { case Launch = "Launch" case EnterBackground = "EnterBackground" case EnterForeground = "EnterForeground" case BecomeActive = "BecomeActive" case ResignActive = "ResignActive" case Terminate = "Terminate" }
mit
14670f5250a5016205041250e64b3604
19.814815
72
0.725979
4.014286
false
false
false
false
wordpress-mobile/AztecEditor-iOS
Aztec/Classes/Libxml2/DOM/Data/ElementNode.swift
2
13140
import Foundation import UIKit /// Element node. Everything but text basically. /// public class ElementNode: Node { public var attributes = [Attribute]() public var children: [Node] { didSet { updateParentForChildren() } } private static let headerLevels: [Element] = [.h1, .h2, .h3, .h4, .h5, .h6] class func elementTypeForHeaderLevel(_ headerLevel: Int) -> Element? { if headerLevel < 1 || headerLevel > headerLevels.count { return nil } return headerLevels[headerLevel - 1] } public var type: Element { get { return Element(name) } } // MARK: - CustomReflectable override public var customMirror: Mirror { get { return Mirror(self, children: ["type": "element", "name": name, "parent": parent.debugDescription, "attributes": attributes, "children": children], ancestorRepresentation: .suppressed) } } // MARK: - Hashable override public func hash(into hasher: inout Hasher) { hasher.combine(name) hasher.combine(attributes) hasher.combine(children) } // MARK: - ElementNode Equatable override public func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? ElementNode else { return false } return name == rhs.name && attributes == rhs.attributes && children == rhs.children } // MARK: - Initializers public init(name: String, attributes: [Attribute], children: [Node]) { self.attributes.append(contentsOf: attributes) self.children = children super.init(name: name) updateParentForChildren() } public convenience init(type: Element, attributes: [Attribute] = [], children: [Node] = []) { self.init(name: type.rawValue, attributes: attributes, children: children) } // MARK: - CSS Attributes public func containsCSSAttribute(matching matcher: CSSAttributeMatcher) -> Bool { for attribute in attributes { return attribute.containsCSSAttribute(matching: matcher) } return false } public func containsCSSAttribute(where check: (CSSAttribute) -> Bool) -> Bool { for attribute in attributes { return attribute.containsCSSAttribute(where: check) } return false } /// Removes the CSS attributes matching a specified condition. /// /// - Parameters: /// - check: the condition that defines what CSS attributes will be removed. /// public func removeCSSAttributes(matching check: (CSSAttribute) -> Bool) { for attribute in attributes { attribute.removeCSSAttributes(matching: check) } } /// Removes the CSS attributes matching a specified condition. /// /// - Parameters: /// - check: the condition that defines what CSS attributes will be removed. /// public func removeCSSAttributes(matching matcher: CSSAttributeMatcher) { for attribute in attributes { attribute.removeCSSAttributes(matching: matcher) } } // MARK: - Children Logic private func updateParentForChildren() { for child in children where child.parent !== self { if let oldParent = child.parent, let childIndex = oldParent.children.firstIndex(where: { child === $0 }) { oldParent.children.remove(at: childIndex) } child.parent = self } } // MARK: - Node Overrides override func needsClosingParagraphSeparator() -> Bool { return (!hasChildren()) && (canBeLastInTree() || !isLastInTree()) && (isBlockLevel() || hasRightBlockLevelSibling() || isLastInAncestorEndingInBlockLevelSeparation()) } /// Checks if the specified node requires a closing paragraph separator in itself, or in the any of its descendants. /// /// - Returns: true if the element needs an explicit representation (to avoid losing attributes), /// and if it either has a block level element to the right or is the last element in a block level separation. /// func needsClosingParagraphSeparatorIncludingDescendants() -> Bool { return (hasAttributes() || !isLastInTree()) && (hasRightBlockLevelSibling() || isLastInAncestorEndingInBlockLevelSeparation()) } // MARK: - Node Queries public func attribute(named name: String) -> Attribute? { return attributes.first { (attribute) -> Bool in return attribute.name.lowercased() == name.lowercased() } } public func attribute(ofType type: AttributeType) -> Attribute? { return attributes.first { (attribute) -> Bool in return attribute.type == type } } public func hasAttributes() -> Bool { return attributes.count > 0 } func stringValueForAttribute(named attributeName: String) -> String? { for attribute in attributes { if attribute.name == attributeName { return attribute.value.toString() } } return nil } /// Updates or adds an attribute with the specificed name with the corresponding value /// /// - Parameters: /// - attributeName: the name of the attribute /// - value: the value for the attribute /// func updateAttribute(named targetAttributeName: String, value: Attribute.Value) { for attribute in attributes { if attribute.name == targetAttributeName { attribute.value = value return } } let attribute = Attribute(name: targetAttributeName, value: value) attributes.append(attribute) } func updateAttribute(ofType type: AttributeType, value: Attribute.Value) { updateAttribute(named: type.rawValue, value: value) } /// Check if the node is the first child in its parent node. /// /// - Returns: `true` if the node is the first child in it's parent. `false` otherwise. /// func isFirstChildInParent() -> Bool { guard let parent = parent else { assertionFailure("This scenario should not be possible. Review the logic.") return false } guard let first = parent.children.first else { return false } return first === self } /// Check if the node is the last child in its parent node. /// /// - Returns: `true` if the node is the last child in it's parent. `false` otherwise. /// func isLastChildInParent() -> Bool { guard let parent = parent else { assertionFailure("This scenario should not be possible. Review the logic.") return false } guard let last = parent.children.last else { return false } return last === self } /// Check if the last of this children element is a block level element /// /// - Returns: true if the last child of this element is a block level element, false otherwise /// func isLastChildBlockLevelElement() -> Bool { let childrenIgnoringEmptyTextNodes = children.filter { (node) -> Bool in if let textNode = node as? TextNode { return !textNode.text().isEmpty } return true } if let lastChild = childrenIgnoringEmptyTextNodes.last as? ElementNode { return lastChild.isBlockLevel() } return false } /// Check if the node can be the last one in a tree /// /// - Returns: Returns `true` if it can be the last one, false otherwise. /// func canBeLastInTree() -> Bool { return hasAttributes() || isBlockLevel() } /// Find out if this is a block-level element. /// /// - Returns: `true` if this is a block-level element. `false` otherwise. /// public func isBlockLevel() -> Bool { return type.isBlockLevel() } public func isVoid() -> Bool { return type.isVoid() } public func requiresClosingTag() -> Bool { return !isVoid() } public func isNodeType(_ type: Element) -> Bool { return type.equivalentNames.contains(Element(name)) } func hasChildren() -> Bool { return children.count > 0 } /// Retrieves the last child matching a specific filtering closure. /// /// - Parameters: /// - filter: the filtering closure. /// /// - Returns: the requested node, or `nil` if there are no nodes matching the request. /// func lastChild(matching filter: (Node) -> Bool) -> Node? { return children.filter(filter).last } /// If there's exactly just one child node, this method will return it's instance. Otherwise, nil will be returned /// func onlyChild() -> ElementNode? { guard children.count == 1 else { return nil } return children.first as? ElementNode } /// Returns the child ElementNode of the specified nodeType -whenever there's a *single* child-, or nil otherwise. /// /// - Parameter type: Type of the 'single child' node to be retrieved. /// /// - Returns: the requested child (if it's the only children in the collection, and if the type matches), or nil otherwise. /// func onlyChild(ofType type: Element) -> ElementNode? { guard let child = onlyChild(), child.isNodeType(type) else { return nil } return child } /// Returns the first child ElementNode that matches the specified nodeType, or nil if there were no matches. /// /// - Parameter type: Type of the 'first child' node to be retrieved. /// /// - Returns: the first child in the children collection, that matches the specified type. /// public func firstChild(ofType type: Element) -> ElementNode? { let elements = children.compactMap { node in return node as? ElementNode } return elements.first { element in return element.isNodeType(type) } } // MARK: - DOM Queries /// Returns the index of the specified child node. This method should only be called when /// there's 100% certainty that this node should contain the specified child node, as it /// fails otherwise. /// /// Call `children.indexOf()` if you need to test the parent-child relationship instead. /// /// - Parameters: /// - childNode: the child node to find the index of. /// /// - Returns: the index of the specified child node. /// func indexOf(childNode: Node) -> Int { guard let index = children.firstIndex(where: { childNode === $0 } ) else { fatalError("Broken parent-child relationship found.") } return index } typealias NodeMatchTest = (_ node: Node) -> Bool typealias NodeIntersectionReport = (_ node: Node, _ intersection: NSRange) -> Void typealias RangeReport = (_ range: NSRange) -> Void /// Retrieves the right-side sibling of the child at the specified index. /// /// - Parameters: /// - index: the index of the child to get the sibling of. /// /// - Returns: the requested sibling, or `nil` if there's none. /// func sibling<T: Node>(rightOf childIndex: Int) -> T? { guard childIndex >= 0 && childIndex < children.count else { fatalError("Out of bounds!") } guard childIndex < children.count - 1 else { return nil } let siblingNode = children[childIndex + 1] // Ignore empty text nodes. // if let textSibling = siblingNode as? TextNode, textSibling.length() == 0 { return sibling(rightOf: childIndex + 1) } return siblingNode as? T } override public func rawText() -> String { let rawText: String switch type { case .br: rawText = "\n" default: rawText = "" } return children.reduce(rawText, { (previous, node) -> String in return previous + node.rawText() }) } } // MARK: - RootNode public class RootNode: ElementNode { static let name = "aztec.htmltag.rootnode" public override weak var parent: ElementNode? { get { return nil } set { } } // MARK: - CustomReflectable override public var customMirror: Mirror { get { return Mirror(self, children: ["name": name, "children": children]) } } // MARK: - Initializers public init(children: [Node]) { super.init(name: Swift.type(of: self).name, attributes: [], children: children) } }
mpl-2.0
0ef308e7a13505b110a14a51519a8f57
29.137615
196
0.588889
4.843347
false
false
false
false
longsirhero/DinDinShop
DinDinShopDemo/DinDinShopDemo/个人中心/ViewControllers/WCPersonalCenterVC.swift
1
7042
// // WCPersonalCenterVC.swift // DinDinShopDemo // // Created by longsirHERO on 2017/8/18. // Copyright © 2017年 WingChingYip(https://longsirhero.github.io) All rights reserved. // import UIKit import SwiftyJSON class WCPersonalCenterVC: WCBaseController { let portrailCellID = "portrailCellID" let normalCellID = "normalCellID" let functionCellID = "functionCellID" var model:WCPersonalInfoModel? lazy var tableView:UITableView = { let tableView:UITableView = UITableView.init(frame: CGRect.init(x: 0, y: 64, width: kScreenW, height: kScreenH - 113), style: .grouped) tableView.delegate = self tableView.dataSource = self tableView.tableFooterView = UIView.init() return tableView }() override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.black] self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "设置", style: .done, target: self, action: #selector(WCPersonalCenterVC.rightClick)) self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.black], for: .normal) self.automaticallyAdjustsScrollViewInsets = false tableView.register(UINib.init(nibName: "WCCenterPortraiCell", bundle: Bundle.main), forCellReuseIdentifier: portrailCellID) tableView.register(UITableViewCell.self, forCellReuseIdentifier: normalCellID) tableView.register(WCFunctionsCell.self, forCellReuseIdentifier: functionCellID) self.view.addSubview(tableView) loadPersonalDatas() } func rightClick() -> Void { let setVC = WCSettingVC() self.navigationController?.pushViewController(setVC, animated: true) } private func loadPersonalDatas() -> Void { let para = ["userNumber":UserDefaults.standard.value(forKey: usrNumberKey)] WCRequest.shareInstance.requestDatas(methodType: .POST, urlString: personalDatas_Url, parameters: para as [String : AnyObject]) { (result, error) in if (error != nil) { self.view.showWarning(words: "网络错误,请稍后连接") return } let json:JSON = JSON.init(data: result as! Data) let value = json["result"] if value == "0" { let dict:NSDictionary = json["content"].rawValue as! NSDictionary print(dict) self.model = WCPersonalInfoModel.initModelWithDictionary(dic:dict as! [String : Any]) self.tableView.reloadData() } else { self.view.showWarning(words: "网络错误,请稍后连接") } } } } extension WCPersonalCenterVC:WCFunctionsCellDelegate { func functionsCellDidSelectItemAtIndex(functionCell: WCFunctionsCell, index: NSInteger) { print(index) } } extension WCPersonalCenterVC:UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch indexPath.section { case 0: let manager:WCAccountManagerVC = WCAccountManagerVC() self.navigationController?.pushViewController(manager, animated: true) case 1: if indexPath.row == 0 { let orderVC:WCMyOrdersVC = WCMyOrdersVC() self.navigationController?.pushViewController(orderVC, animated: true) } default: if indexPath.row == 0 { let service:WCServiceVC = WCServiceVC() self.navigationController?.pushViewController(service, animated: true) } else if indexPath.row == 1 { let collect:WCCollectVC = WCCollectVC() self.navigationController?.pushViewController(collect, animated: true) } else if indexPath.row == 2 { let address:WCAddressVC = WCAddressVC() self.navigationController?.pushViewController(address, animated: true) } } } func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return 2 default: return 3 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: let cell:WCCenterPortraiCell = tableView.dequeueReusableCell(withIdentifier: portrailCellID, for: indexPath) as! WCCenterPortraiCell cell.accessoryType = .disclosureIndicator guard let model = model else { return cell } cell.model = model return cell case 1: if indexPath.row == 0 { let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: normalCellID, for: indexPath) cell.accessoryType = .disclosureIndicator cell.textLabel?.text = "我的订单" return cell } else { let cell:WCFunctionsCell = tableView.dequeueReusableCell(withIdentifier: functionCellID, for: indexPath) as! WCFunctionsCell cell.delegate = self cell.selectionStyle = .none return cell } default: let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: normalCellID, for: indexPath) cell.accessoryType = .disclosureIndicator if indexPath.row == 0 { cell.textLabel?.text = "客服中心" } else if indexPath.row == 1 { cell.textLabel?.text = "我的收藏" } else { cell.textLabel?.text = "收货地址管理" } return cell } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.section { case 0: return 100 case 1: if indexPath.row == 0 { return 45 } else { return 75 } default: return 45 } } }
mit
91416ce1a3ec23bba4cc60322581fbc1
32.157143
160
0.569869
5.461176
false
false
false
false
modocache/swift
test/ClangModules/autolinking.swift
17
2011
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-swift-frontend %s -sdk %S/Inputs -I %S/Inputs/custom-modules -emit-ir -o %t/without-adapter.ll // RUN: %FileCheck %s < %t/without-adapter.ll // RUN: %target-swift-frontend -emit-module %S/Inputs/adapter.swift -sdk %S/Inputs -module-link-name SwiftAdapter -module-name ClangModuleWithAdapter -I %S/Inputs/custom-modules -o %t // RUN: %target-swift-frontend %s -sdk %S/Inputs -I %S/Inputs/custom-modules -I %t -emit-ir -o %t/with-adapter.ll // RUN: %FileCheck %s < %t/with-adapter.ll // RUN: %FileCheck --check-prefix=CHECK-WITH-SWIFT %s < %t/with-adapter.ll // RUN: %target-swift-frontend %s -sdk %S/Inputs -I %S/Inputs/custom-modules -emit-ir -disable-autolink-framework LinkFramework -o %t/with-disabled.ll // RUN: %FileCheck --check-prefix=CHECK-WITH-DISABLED %s < %t/with-disabled.ll // Linux uses a different autolinking mechanism, based on // swift-autolink-extract. This file tests the Darwin mechanism. // UNSUPPORTED: OS=linux-gnu // UNSUPPORTED: OS=linux-gnueabihf // UNSUPPORTED: OS=freebsd // UNSUPPORTED: OS=linux-androideabi import LinkMusket import LinkFramework import ClangModuleUser import IndirectFrameworkImporter import UsesSubmodule _ = LinkFramework.IComeFromLinkFramework UsesSubmodule.useSomethingFromSubmodule() // CHECK: !{{[0-9]+}} = !{i32 6, !"Linker Options", ![[LINK_LIST:[0-9]+]]} // CHECK: ![[LINK_LIST]] = !{ // CHECK-DAG: !{{[0-9]+}} = !{!"-lLock"} // CHECK-DAG: !{{[0-9]+}} = !{!"-lStock"} // CHECK-DAG: !{{[0-9]+}} = !{!"-framework", !"Barrel"} // CHECK-DAG: !{{[0-9]+}} = !{!"-framework", !"LinkFramework"} // CHECK-DAG: !{{[0-9]+}} = !{!"-lUnderlyingClangLibrary"} // CHECK-DAG: !{{[0-9]+}} = !{!"-framework", !"Indirect"} // CHECK-DAG: !{{[0-9]+}} = !{!"-framework", !"HasSubmodule"} // CHECK-WITH-SWIFT: !{{[0-9]+}} = !{!"-lSwiftAdapter"} // CHECK-WITH-DISABLED: !{!"-framework", !"Barrel"} // CHECK-WITH-DISABLED-NOT: !{!"-framework", !"LinkFramework"} // CHECK-WITH-DISABLED: !{!"-framework", !"Indirect"}
apache-2.0
7895eeffc1805382faafcd353bb7ebf9
43.688889
183
0.660865
3.127527
false
false
false
false
gerbot150/SwiftyFire
swift/SwiftyFire/StringUtils.swift
1
941
// // StringUtils.swift // SwiftyJSONModelMaker // // Created by Gregory Bateman on 2017-03-04. // Copyright © 2017 Gregory Bateman. All rights reserved. // import Foundation extension String { var camelCased: String { let delimiters = CharacterSet(charactersIn: " _") var words = self.components(separatedBy: delimiters) guard let firstWord = words.first else { return "" } words.removeFirst() var camelCasedSelf = firstWord for word in words { camelCasedSelf += word.capitalized } return camelCasedSelf } var capitalCased: String { let delimiters = CharacterSet(charactersIn: " _") let words = self.components(separatedBy: delimiters) var capitalCasedSelf = "" for word in words { capitalCasedSelf += word.capitalized } return capitalCasedSelf } }
mit
188d74ee7b7b4a62e96446ef22e5b872
25.111111
60
0.608511
5
false
false
false
false
TwilioDevEd/twiliochat-swift
twiliochat/MessagingManager.swift
1
6746
import UIKit class MessagingManager: NSObject { static let _sharedManager = MessagingManager() var client:TwilioChatClient? var delegate:ChannelManager? var connected = false var userIdentity:String { return SessionManager.getUsername() } var hasIdentity: Bool { return SessionManager.isLoggedIn() } override init() { super.init() delegate = ChannelManager.sharedManager } class func sharedManager() -> MessagingManager { return _sharedManager } func presentRootViewController() { if (!hasIdentity) { presentViewControllerByName(viewController: "LoginViewController") return } if (!connected) { connectClientWithCompletion { success, error in print("Delegate method will load views when sync is complete") if (!success || error != nil) { DispatchQueue.main.async { self.presentViewControllerByName(viewController: "LoginViewController") } } } return } presentViewControllerByName(viewController: "RevealViewController") } func presentViewControllerByName(viewController: String) { presentViewController(controller: storyBoardWithName(name: "Main").instantiateViewController(withIdentifier: viewController)) } func presentLaunchScreen() { presentViewController(controller: storyBoardWithName(name: "LaunchScreen").instantiateInitialViewController()!) } func presentViewController(controller: UIViewController) { let window = UIApplication.shared.delegate!.window!! window.rootViewController = controller } func storyBoardWithName(name:String) -> UIStoryboard { return UIStoryboard(name:name, bundle: Bundle.main) } // MARK: User and session management func loginWithUsername(username: String, completion: @escaping (Bool, NSError?) -> Void) { SessionManager.loginWithUsername(username: username) connectClientWithCompletion(completion: completion) } func logout() { SessionManager.logout() DispatchQueue.global(qos: .userInitiated).async { self.client?.shutdown() self.client = nil } self.connected = false } // MARK: Twilio Client func loadGeneralChatRoomWithCompletion(completion:@escaping (Bool, NSError?) -> Void) { ChannelManager.sharedManager.joinGeneralChatRoomWithCompletion { succeeded in if succeeded { completion(succeeded, nil) } else { let error = self.errorWithDescription(description: "Could not join General channel", code: 300) completion(succeeded, error) } } } func connectClientWithCompletion(completion: @escaping (Bool, NSError?) -> Void) { if (client != nil) { logout() } requestTokenWithCompletion { succeeded, token in if let token = token, succeeded { self.initializeClientWithToken(token: token) completion(succeeded, nil) } else { let error = self.errorWithDescription(description: "Could not get access token", code:301) completion(succeeded, error) } } } func initializeClientWithToken(token: String) { DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = true } TwilioChatClient.chatClient(withToken: token, properties: nil, delegate: self) { [weak self] result, chatClient in guard (result.isSuccessful()) else { return } UIApplication.shared.isNetworkActivityIndicatorVisible = true self?.connected = true self?.client = chatClient } } func requestTokenWithCompletion(completion:@escaping (Bool, String?) -> Void) { if let device = UIDevice.current.identifierForVendor?.uuidString { TokenRequestHandler.fetchToken(params: ["device": device, "identity":SessionManager.getUsername()]) {response,error in var token: String? token = response["token"] as? String completion(token != nil, token) } } } func errorWithDescription(description: String, code: Int) -> NSError { let userInfo = [NSLocalizedDescriptionKey : description] return NSError(domain: "app", code: code, userInfo: userInfo) } } // MARK: - TwilioChatClientDelegate extension MessagingManager : TwilioChatClientDelegate { func chatClient(_ client: TwilioChatClient, channelAdded channel: TCHChannel) { self.delegate?.chatClient(client, channelAdded: channel) } func chatClient(_ client: TwilioChatClient, channel: TCHChannel, updated: TCHChannelUpdate) { self.delegate?.chatClient(client, channel: channel, updated: updated) } func chatClient(_ client: TwilioChatClient, channelDeleted channel: TCHChannel) { self.delegate?.chatClient(client, channelDeleted: channel) } func chatClient(_ client: TwilioChatClient, synchronizationStatusUpdated status: TCHClientSynchronizationStatus) { if status == TCHClientSynchronizationStatus.completed { UIApplication.shared.isNetworkActivityIndicatorVisible = false ChannelManager.sharedManager.channelsList = client.channelsList() ChannelManager.sharedManager.populateChannelDescriptors() loadGeneralChatRoomWithCompletion { success, error in if success { self.presentRootViewController() } } } self.delegate?.chatClient(client, synchronizationStatusUpdated: status) } func chatClientTokenWillExpire(_ client: TwilioChatClient) { requestTokenWithCompletion { succeeded, token in if (succeeded) { client.updateToken(token!) } else { print("Error while trying to get new access token") } } } func chatClientTokenExpired(_ client: TwilioChatClient) { requestTokenWithCompletion { succeeded, token in if (succeeded) { client.updateToken(token!) } else { print("Error while trying to get new access token") } } } }
mit
598aba39a87665998eeeccf705ea0de2
34.135417
133
0.613104
5.790558
false
false
false
false
luzefeng/MLSwiftBasic
Demo/MLSwiftBasic/Demo/Demo3ViewController.swift
1
2478
// github: https://github.com/MakeZL/MLSwiftBasic // author: @email <[email protected]> // // Demo3ViewController.swift // MLSwiftBasic // // Created by 张磊 on 15/7/6. // Copyright (c) 2015年 MakeZL. All rights reserved. // import UIKit class Demo3ViewController: MBBaseViewController,UITableViewDataSource,UITableViewDelegate { lazy var lists = { return ["提示成功","提示成功延时2秒","提示失败","提示失败延时2秒","提示进度条","提示进度条延时2秒","等待"] }() override func viewDidLoad() { super.viewDidLoad() self.setupTableView() } func setupTableView(){ var tableView = UITableView(frame: self.view.frame, style: .Plain) tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") tableView.dataSource = self tableView.delegate = self self.view.insertSubview(tableView, atIndex: 0) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return lists.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = "cell" var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! UITableViewCell cell.textLabel?.text = lists[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if (indexPath.row == 0){ MLProgressHUD.showSuccessMessage("请求成功..") }else if (indexPath.row == 1){ MLProgressHUD.showSuccessMessage("请求成功..", durationAfterDismiss: 2.0) }else if (indexPath.row == 2){ MLProgressHUD.showErrorMessage("请求失败..") }else if (indexPath.row == 3){ MLProgressHUD.showErrorMessage("请求失败..", durationAfterDismiss: 2.0) }else if (indexPath.row == 4){ MLProgressHUD.showProgress(0.5, message: "已经缓冲到\(0.5 * 100)%") }else if (indexPath.row == 5){ MLProgressHUD.showProgress(0.9, message: "已经缓冲到\(0.9 * 100)%", durationAfterDismiss: 2.0) }else if (indexPath.row == 6){ MLProgressHUD.showWaiting("等待中...",duration:2.0) } } override func titleStr() -> String { return "Demo3 HUD" } }
mit
31fd67ccc3aeffc7954c1915fee6c7d0
35
135
0.640598
4.448669
false
false
false
false
jaanussiim/weather-scrape
Sources/Scraper.swift
1
1228
/* * Copyright 2016 JaanusSiim * * 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 class Scraper { private let config: CloudConfig init(config: CloudConfig) { self.config = config } func scrape() { Log.debug("Scrape") let ilm = Ilmateenistus() ilm.fetch() { table in let places = Places.load() let data = table.tableByAppending(other: places) Log.debug(data) let points = WeatherPoint.from(table: data) let cloud = TheCloud(config: self.config, measuredAt: table.measuredAt!, data: points) cloud.upload() } } }
apache-2.0
e49223ab297475c5353de6e3c2b97985
27.55814
98
0.62785
4.249135
false
true
false
false
Norod/Filterpedia
Filterpedia/customFilters/Bokeh.swift
1
11773
// // Bokeh.swift // Filterpedia // // Created by Simon Gladman on 30/04/2016. // Copyright © 2016 Simon Gladman. All rights reserved. // // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> import CoreImage // MARK: Core Image Kernel Languag based bokeh class MaskedVariableHexagonalBokeh: MaskedVariableCircularBokeh { override func displayName() -> String { return "Masked Variable Hexagonal Bokeh" } // MaskedVariableHexagonalBokeh override func withinProbe() -> String { return "float withinProbe = ((xx > h || yy > v * 2.0) ? 1.0 : ((2.0 * v * h - v * xx - h * yy) >= 0.0) ? 0.0 : 1.0);" } } class MaskedVariableCircularBokeh: CIFilter { var inputImage: CIImage? var inputBokehMask: CIImage? var inputMaxBokehRadius: CGFloat = 20 var inputBlurRadius: CGFloat = 2 override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: displayName(), "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputBokehMask": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputMaxBokehRadius": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 20, kCIAttributeDisplayName: "Bokeh Radius", kCIAttributeMin: 1, kCIAttributeSliderMin: 1, kCIAttributeSliderMax: 50, kCIAttributeType: kCIAttributeTypeScalar], "inputBlurRadius": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 2, kCIAttributeDisplayName: "Blur Radius", kCIAttributeMin: 1, kCIAttributeSliderMin: 1, kCIAttributeSliderMax: 5, kCIAttributeType: kCIAttributeTypeScalar] ] } lazy var maskedVariableBokeh: CIKernel = { return CIKernel(string: "kernel vec4 lumaVariableBlur(sampler image, sampler bokehMask, float maxBokehRadius) " + "{ " + " vec2 d = destCoord(); " + " vec3 bokehMaskPixel = sample(bokehMask, samplerCoord(bokehMask)).rgb; " + " float bokehMaskPixelLuma = dot(bokehMaskPixel, vec3(0.2126, 0.7152, 0.0722)); " + " int radius = int(bokehMaskPixelLuma * maxBokehRadius); " + " vec3 brightestPixel = sample(image, samplerCoord(image)).rgb; " + " float brightestLuma = 0.0;" + " float v = float(radius) / 2.0;" + " float h = v * sqrt(3.0);" + " for (int x = -radius; x <= radius; x++)" + " { " + " for (int y = -radius; y <= radius; y++)" + " { " + " float xx = abs(float(x));" + " float yy = abs(float(y));" + self.withinProbe() + " vec2 workingSpaceCoordinate = d + vec2(x,y);" + " vec2 imageSpaceCoordinate = samplerTransform(image, workingSpaceCoordinate); " + " vec3 color = sample(image, imageSpaceCoordinate).rgb; " + " float luma = dot(color, vec3(0.2126, 0.7152, 0.0722)); " + " if (withinProbe == 0.0 && luma > brightestLuma) {brightestLuma = luma; brightestPixel = color; } " + " } " + " } " + " return vec4(brightestPixel, 1.0); " + "} ")! }() func displayName() -> String { return "Masked Variable Circular Bokeh" } // MaskedVariableCircularBokeh func withinProbe() -> String { return "float withinProbe = length(vec2(xx, yy)) < float(radius) ? 0.0 : 1.0; " } override var outputImage: CIImage! { guard let inputImage = inputImage, let inputBlurMask = inputBokehMask else { return nil } let extent = inputImage.extent let blur = maskedVariableBokeh.apply( withExtent: inputImage.extent, roiCallback: { (index, rect) in return rect }, arguments: [inputImage, inputBlurMask, inputMaxBokehRadius]) return blur! .applyingFilter("CIMaskedVariableBlur", withInputParameters: ["inputMask": inputBlurMask, "inputRadius": inputBlurRadius]) .cropping(to: extent) } } // MARK: Metal Performance Shaders based bokeh #if !arch(i386) && !arch(x86_64) import MetalPerformanceShaders class HexagonalBokehFilter: CIFilter, MetalRenderable { override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Hexagonal Bokeh", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputBokehRadius": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 20, kCIAttributeDisplayName: "Bokeh Radius", kCIAttributeMin: 1, kCIAttributeSliderMin: 1, kCIAttributeSliderMax: 50, kCIAttributeType: kCIAttributeTypeScalar], "inputBlurSigma": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 2, kCIAttributeDisplayName: "Blur Sigma", kCIAttributeMin: 1, kCIAttributeSliderMin: 1, kCIAttributeSliderMax: 5, kCIAttributeType: kCIAttributeTypeScalar] ] } var inputImage: CIImage? { didSet { if let inputImage = inputImage { let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor( pixelFormat: .rgba8Unorm, width: Int(inputImage.extent.width), height: Int(inputImage.extent.height), mipmapped: false) sourceTexture = device.makeTexture(descriptor: textureDescriptor) destinationTexture = device.makeTexture(descriptor: textureDescriptor) intermediateTexture = device.makeTexture(descriptor: textureDescriptor) } } } var inputBokehRadius: CGFloat = 15 { didSet { if oldValue != inputBokehRadius { dilate = nil } } } var inputBlurSigma: CGFloat = 2 { didSet { if oldValue != inputBlurSigma { blur = nil } } } lazy var device: MTLDevice = { return MTLCreateSystemDefaultDevice()! }() lazy var ciContext: CIContext = { [unowned self] in return CIContext(mtlDevice: self.device) }() let colorSpace = CGColorSpaceCreateDeviceRGB() private var probe = [Float]() private var dilate: MPSImageDilate? private var blur: MPSImageGaussianBlur? private var sourceTexture: MTLTexture? private var destinationTexture: MTLTexture? private var intermediateTexture: MTLTexture? override var outputImage: CIImage? { guard let inputImage = inputImage, let inputTexture = sourceTexture, let outputTexture = destinationTexture, let intermediateTexture = intermediateTexture else { return nil } if dilate == nil { createDilate() } if blur == nil { createBlur() } let commandQueue = device.makeCommandQueue() let commandBuffer = commandQueue.makeCommandBuffer() ciContext.render( inputImage, to: inputTexture, commandBuffer: commandBuffer, bounds: inputImage.extent, colorSpace: colorSpace) dilate!.encode( commandBuffer: commandBuffer, sourceTexture: inputTexture, destinationTexture: intermediateTexture) blur!.encode( commandBuffer: commandBuffer, sourceTexture: intermediateTexture, destinationTexture: outputTexture) commandBuffer.commit() return CIImage( mtlTexture: outputTexture, options: [kCIImageColorSpace: colorSpace]) } func createDilate() { var probe = [Float]() let size = Int(inputBokehRadius) * 2 + 1 let v = Float(size / 4) let h = v * sqrt(3.0) let mid = Float(size) / 2 for i in 0 ..< size { for j in 0 ..< size { let x = abs(Float(i) - mid) let y = abs(Float(j) - mid) let element = Float((x > h || y > v * 2.0) ? 1.0 : ((2.0 * v * h - v * x - h * y) >= 0.0) ? 0.0 : 1.0) probe.append(element) } } let dilate = MPSImageDilate( device: device, kernelWidth: size, kernelHeight: size, values: probe) dilate.edgeMode = .clamp self.dilate = dilate } func createBlur() { blur = MPSImageGaussianBlur(device: device, sigma: Float(inputBlurSigma)) } } #else class HexagonalBokehFilter: CIFilter { } #endif
gpl-3.0
48db178d89411a3cb2eac308a9ce7eae
32.634286
134
0.494903
5.624462
false
false
false
false
SteveBarnegren/TweenKit
TweenKit/TweenKitTests/CoreGraphicsTweenableTests.swift
1
2353
// // CoreGraphicsTweenableTests.swift // TweenKit // // Created by Steven Barnegren on 06/04/2017. // Copyright © 2017 Steve Barnegren. All rights reserved. // import XCTest @testable import TweenKit class CoreGraphicsTweenableTests: XCTestCase { // MARK: - CGFloat func testCGFloatLerpResultsInCorrectValue() { let start = CGFloat(2) let end = CGFloat(4) XCTAssertEqual(start.lerp(t: 0.5, end: end), CGFloat(3), accuracy: 0.001) } // MARK: - CGPoint func testCGPointLerpResultsInCorrectValue() { let start = CGPoint(x: 2, y: 2) let end = CGPoint(x: 4, y: 4) AssertCGPointsAreEqualWithAccuracy(start.lerp(t: 0.5, end: end), CGPoint(x: 3, y: 3), accuracy: 0.001) } func testCGPointCanBeConstructedAsTweenable2DCoordinate() { let x = CGFloat(2) let y = CGFloat(3) let normal = CGPoint(x: x, y: y) let tweenable = CGPoint(tweenableX: Double(x), y: Double(y)) AssertCGPointsAreEqualWithAccuracy(normal, tweenable, accuracy: 0.001) } func testCGPointReturnsCorrectXAndYAsTweenableCoordinate() { let x = CGFloat(2) let y = CGFloat(5) let point = CGPoint(x: x, y: y) XCTAssertEqual(point.tweenableX, Double(x), accuracy: 0.001) XCTAssertEqual(point.tweenableY, Double(y), accuracy: 0.001) } // MARK: - CGSize func testCGSizeLerpResultsInCorrectValue() { let start = CGSize(width: 2, height: 10) let end = CGSize(width: 4, height: 20) let result = start.lerp(t: 0.5, end: end) let expected = CGSize(width: 3, height: 15) AssertCGSizesAreEqualWithAccuracy(result, expected, accuracy: 0.001) } // MARK: - CGRect func testCGRectLerpResultsInCorrectValue() { let start = CGRect(x: 10, y: 20, width: 30, height: 40) let end = CGRect(x: 20, y: 30, width: 40, height: 50) let result = start.lerp(t: 0.5, end: end) let expected = CGRect(x: 15, y: 25, width: 35, height: 45) AssertCGRectsAreEqualWithAccuracy(result, expected, accuracy: 0.001) } }
mit
e63be03dc6a4b235d93c80563b643399
27.682927
81
0.571854
3.979695
false
true
false
false
cdmx/MiniMancera
miniMancera/Model/Main/Abstract/MPerkFactory.swift
1
649
import Foundation class MPerkFactory { class func factoryPerks() -> [MPerkProtocol] { let perkReformaCrossing:MPerkReformaCrossing = MPerkReformaCrossing() let perkPollutedGarden:MPerkPollutedGarden = MPerkPollutedGarden() let perkWhistlesVsZombies:MPerkWhistlesVsZombies = MPerkWhistlesVsZombies() // let perkTamalesOaxaquenos:MPerkTamalesOaxaquenos = MPerkTamalesOaxaquenos() let perks:[MPerkProtocol] = [ perkReformaCrossing, perkPollutedGarden, perkWhistlesVsZombies, // perkTamalesOaxaquenos ] return perks } }
mit
1177baebfd93f7bb9287f03cfc71a76c
29.904762
85
0.670262
6.065421
false
false
false
false
wireapp/wire-ios-data-model
Tests/Source/Model/Messages/GenericMessageTests+External.swift
1
3061
// // Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation @testable import WireDataModel class GenericMessageTests_External: XCTestCase { var sut: GenericMessage! override func setUp() { super.setUp() let text = Text.with { $0.content = "She sells sea shells" } sut = GenericMessage.with { $0.text = text $0.messageID = NSUUID.create()!.transportString() } } override func tearDown() { super.tearDown() sut = nil } func testThatItEncryptsTheMessageAndReturnsTheCorrectKeyAndDigest() { // given / when let dataWithKeys = GenericMessage.encryptedDataWithKeys(from: sut) XCTAssertNotNil(dataWithKeys) let keysWithDigest = dataWithKeys!.keys let data = dataWithKeys!.data // then XCTAssertEqual(data?.zmSHA256Digest(), keysWithDigest?.sha256) XCTAssertEqual(data?.zmDecryptPrefixedPlainTextIV(key: keysWithDigest!.aesKey), try? sut.serializedData()) } func testThatItUsesADifferentKeyForEachCall() { // given / when let firstDataWithKeys = GenericMessage.encryptedDataWithKeys(from: sut) let secondDataWithKeys = GenericMessage.encryptedDataWithKeys(from: sut) XCTAssertNotNil(firstDataWithKeys) XCTAssertNotNil(secondDataWithKeys) let firstEncrypted = firstDataWithKeys?.data.zmDecryptPrefixedPlainTextIV(key: firstDataWithKeys!.keys.aesKey) let secondEncrypted = secondDataWithKeys?.data.zmDecryptPrefixedPlainTextIV(key: secondDataWithKeys!.keys.aesKey) // then XCTAssertNotEqual(firstDataWithKeys?.keys.aesKey, secondDataWithKeys?.keys.aesKey) XCTAssertNotEqual(firstDataWithKeys, secondDataWithKeys) XCTAssertEqual(firstEncrypted, try? sut.serializedData()) XCTAssertEqual(secondEncrypted, try? sut.serializedData()) } func testThatDifferentKeysAreNotConsideredEqual() { // given / when let firstKeys = GenericMessage.encryptedDataWithKeys(from: sut)?.keys let secondKeys = GenericMessage.encryptedDataWithKeys(from: sut)?.keys // then XCTAssertFalse(firstKeys?.aesKey == secondKeys?.aesKey) XCTAssertFalse(firstKeys?.sha256 == secondKeys?.sha256) XCTAssertEqual(firstKeys, firstKeys) XCTAssertNotEqual(firstKeys, secondKeys) } }
gpl-3.0
5cdc574fc1bd6b00e84f16d8650db605
35.879518
121
0.701731
4.85873
false
true
false
false
stephentyrone/swift
test/Constraints/requirement_failures_in_contextual_type.swift
6
943
// RUN: %target-typecheck-verify-swift struct A<T> {} extension A where T == Int32 { // expected-note 3{{requirement specified as 'T' == 'Int32' [with T = Int]}} struct B : ExpressibleByIntegerLiteral { typealias E = Int typealias IntegerLiteralType = Int init(integerLiteral: IntegerLiteralType) {} } typealias C = Int } let _: A<Int>.B = 0 // expected-error@-1 {{'A<Int>.B' requires the types 'Int' and 'Int32' be equivalent}} let _: A<Int>.C = 0 // expected-error@-1 {{'A<Int>.C' (aka 'Int') requires the types 'Int' and 'Int32' be equivalent}} let _: A<Int>.B.E = 0 // expected-error@-1 {{'A<Int>.B' requires the types 'Int' and 'Int32' be equivalent}} protocol P {} @propertyWrapper struct Wrapper<T: P> { // expected-note {{where 'T' = 'Int'}} var wrappedValue: T } class C { static let i = 1 @Wrapper // expected-error{{generic struct 'Wrapper' requires that 'Int' conform to 'P'}} var value = C.i }
apache-2.0
ca4cc16b95ac6c987028fa47eb8ef7c5
25.194444
107
0.645811
3.262976
false
false
false
false
Kyoooooo/DouYuZhiBo
DYZB/DYZB/Classes/Home/View/RecommendGameView.swift
1
1917
// // RecommendGameView.swift // DYZB // // Created by 张起哲 on 2017/9/7. // Copyright © 2017年 张起哲. All rights reserved. // import UIKit private let kGameCellID = "kGameCellID" private let kEdgeInsetMargin : CGFloat = 10 class RecommendGameView: UIView { // 定义数据的属性 var groups : [BaseGameModel]? { didSet { // 刷新表格 collectionView.reloadData() } } //控件属性 @IBOutlet weak var collectionView: UICollectionView! //系统回调 override func awakeFromNib() { super.awakeFromNib() //设置该控件不随着父控件拉伸而拉伸 autoresizingMask = UIViewAutoresizing() //注册cell collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) // 给collectionView添加内边距 collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin) } } //提供快速创建的类方法 extension RecommendGameView { class func recommendGameView() -> RecommendGameView { return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView } } //遵守UICollectionView数据源协议 extension RecommendGameView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell cell.baseGame = groups![indexPath.item] return cell } }
mit
4359a8c83808bbb1a2907f22a95c2f89
26
126
0.66835
5.225806
false
false
false
false
acumen1005/iSwfit
ACWaterfallLayout/ACWaterfallLayout/ViewController.swift
1
4329
// // ViewController.swift // ACWaterfallLayout // // Created by acumen on 17/3/3. // Copyright © 2017年 acumen. All rights reserved. // import UIKit struct Layout { static let SCREEN_WIDTH = UIApplication.shared.windows.first?.bounds.size.width static let SCREEN_HEIGHT = UIApplication.shared.windows.first?.bounds.size.height static let SPACING_5: CGFloat = 5.0 } class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, ACCollectionViewLayoutDelegate { @IBOutlet weak var collectionView: UICollectionView! var indexPaths: [UIImage] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. collectionView.delegate = self collectionView.dataSource = self ACImageCollectionViewCell.registerNib(collectionView) collectionView.register(ACHeaderCollectionReusableView.nib(), forSupplementaryViewOfKind: ACCollectionViewLayout.ACCollectionViewSectionHeader, withReuseIdentifier: ACHeaderCollectionReusableView.className) collectionView.register(ACFooterrCollectionReusableView.nib(), forSupplementaryViewOfKind: ACCollectionViewLayout.ACCollectionViewSectionFooter, withReuseIdentifier: ACFooterrCollectionReusableView.className) let layout = ACCollectionViewLayout() layout.delegate = self layout.numberOfRow = 2 layout.sectionHeaderHeight = 100 layout.sectionFooterHeight = 200 collectionView.collectionViewLayout = layout var images: [UIImage] = [] for _ in 0 ..< 20 { let index = arc4random_uniform(4) images.append(UIImage(named: "op\(index).jpg")!) } indexPaths = images } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return indexPaths.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ACImageCollectionViewCell", for: indexPath) as! ACImageCollectionViewCell cell.acImageView.image = indexPaths[indexPath.row] return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == ACCollectionViewLayout.ACCollectionViewSectionHeader { let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ACHeaderCollectionReusableView.className, for: indexPath) as! ACHeaderCollectionReusableView headerView.headerImageView.image = UIImage(named: "op1.jpg") return headerView } else if kind == ACCollectionViewLayout.ACCollectionViewSectionFooter { let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ACFooterrCollectionReusableView.className, for: indexPath) as! ACFooterrCollectionReusableView footerView.footerImageView.image = UIImage(named: "op0.jpg") return footerView } return UICollectionReusableView() } func sizeForItem(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, indexPath: IndexPath) -> CGSize { return indexPaths[indexPath.row].size } } extension UIView { class func nib() -> UINib { return UINib(nibName: "\(self.classForCoder())", bundle: nil) } class func registerNib(_ collectionView: UICollectionView) { collectionView.register(self.nib(), forCellWithReuseIdentifier: "\(self.classForCoder())") } class var className: String { return "\(self.classForCoder())" } } extension UICollectionViewDelegate { } extension UICollectionViewDataSource { } extension ACCollectionViewLayoutDelegate { }
mit
7373350b59689b671de93e80f33250f6
38.327273
216
0.716135
5.877717
false
false
false
false
carabina/Lantern
LanternModel/UniqueURLArray.swift
1
1843
// // UniqueURLArray.swift // Hoverlytics // // Created by Patrick Smith on 28/04/2015. // Copyright (c) 2015 Burnt Caramel. All rights reserved. // import Foundation func conformURL(URL: NSURL, requireHost: Bool = true) -> NSURL? { if let URLComponents = NSURLComponents(URL: URL, resolvingAgainstBaseURL: true) { if requireHost && URLComponents.host == nil { return nil } // Remove #fragments URLComponents.fragment = nil // Home page should always have trailing slash if URLComponents.path == "" { URLComponents.path = "/" } // Return adjusted URL return URLComponents.URL } else { return nil } } class UniqueURLArray: SequenceType { private var uniqueURLs = Set<NSURL>() var orderedURLs = [NSURL]() typealias Generator = Array<NSURL>.Generator func generate() -> Generator { return orderedURLs.generate() } typealias Index = Array<NSURL>.Index subscript(position: Index) -> Generator.Element { return orderedURLs[position] } var count: Int { return uniqueURLs.count } func contains(URL: NSURL) -> Bool { if let URL = conformURL(URL) { return uniqueURLs.contains(URL) } return false } func insertReturningConformedURLIfNew(var URL: NSURL) -> NSURL? { if let URL = conformURL(URL) { if !uniqueURLs.contains(URL) { uniqueURLs.insert(URL) orderedURLs.append(URL) return URL } } return nil } func remove(URL: NSURL) { if let URL = conformURL(URL) { if let setIndex = uniqueURLs.indexOf(URL) { uniqueURLs.removeAtIndex(setIndex) if let arrayIndex = find(orderedURLs, URL) { orderedURLs.removeAtIndex(arrayIndex) } } } } func removeAll() { uniqueURLs.removeAll() orderedURLs.removeAll() } } extension UniqueURLArray: Printable { var description: String { return uniqueURLs.description } }
apache-2.0
2b1a86e0ba91e36fc466217d34706263
19.032609
82
0.683668
3.419295
false
false
false
false
Trxy/TRX
TRXTests/specs/scheduler/SchedulerSpec.swift
1
2486
@testable import TRX import Quick import Nimble class SchedulerSpec: QuickSpec { override func spec() { var subject: Scheduler! var displayLink: CADisplayLink! beforeEach { subject = Scheduler() displayLink = subject.displayLink } describe("subscirptions") { var mockSubscriber: MockSubscriber! beforeEach() { mockSubscriber = MockSubscriber() } afterEach() { displayLink.isPaused = true } describe("when subscribtion added") { beforeEach() { subject.subscribe(mockSubscriber) } it("starts the display link") { expect(displayLink.isPaused) == false } } describe("when no subscriptions") { beforeEach() { subject.subscribe(mockSubscriber) subject.unsubscribe(mockSubscriber) } it("pauses the display link") { expect(displayLink.isPaused) == true } } } describe("overwrite") { var mockSubscriberA: MockTweenable! var mockSubscriberB: MockTweenable! var mockSubscriberC: MockTweenable! beforeEach() { mockSubscriberA = MockTweenable() mockSubscriberB = MockTweenable() mockSubscriberC = MockTweenable() mockSubscriberA.keys = ["A", "A2"] mockSubscriberB.keys = ["A", "B"] mockSubscriberC.keys = ["C"] } describe("when previous subscriber with same key is running") { beforeEach() { mockSubscriberA.paused = false mockSubscriberB.paused = false subject.subscribe(mockSubscriberA) subject.subscribe(mockSubscriberB) } it("pauses previous subscriber") { expect(mockSubscriberA.paused) == true expect(mockSubscriberB.paused) == false } } describe("when only subscribers with different keys") { beforeEach() { mockSubscriberA.paused = false mockSubscriberB.paused = false subject.subscribe(mockSubscriberA) subject.subscribe(mockSubscriberC) } it("doesn't pause previous subscriber") { expect(mockSubscriberA.paused) == false expect(mockSubscriberB.paused) == false } } } } }
mit
6ad43d573fb59d8dd96e1226266b3a41
22.67619
69
0.551086
5.611738
false
false
false
false
klundberg/swift-corelibs-foundation
Foundation/NSSwiftRuntime.swift
1
16516
// 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 // import CoreFoundation // Re-export Darwin and Glibc by importing Foundation // This mimics the behavior of the swift sdk overlay on Darwin #if os(OSX) || os(iOS) @_exported import Darwin #elseif os(Linux) @_exported import Glibc #endif public typealias ObjCBool = Bool internal class __NSCFType : NSObject { private var _cfinfo : Int32 override init() { // This is not actually called; _CFRuntimeCreateInstance will initialize _cfinfo _cfinfo = 0 } override var hash: Int { return Int(bitPattern: CFHash(self)) } override func isEqual(_ object: AnyObject?) -> Bool { if let obj = object { return CFEqual(self, obj) } else { return false } } override var description: String { return CFCopyDescription(unsafeBitCast(self, to: CFTypeRef.self))._swiftObject } deinit { _CFDeinit(self) } } internal func _CFSwiftGetTypeID(_ cf: AnyObject) -> CFTypeID { return (cf as! NSObject)._cfTypeID } internal func _CFSwiftGetHash(_ cf: AnyObject) -> CFHashCode { return CFHashCode(bitPattern: (cf as! NSObject).hash) } internal func _CFSwiftIsEqual(_ cf1: AnyObject, cf2: AnyObject) -> Bool { return (cf1 as! NSObject).isEqual(cf2) } // Ivars in _NSCF* types must be zeroed via an unsafe accessor to avoid deinit of potentially unsafe memory to accces as an object/struct etc since it is stored via a foreign object graph internal func _CFZeroUnsafeIvars<T>(_ arg: inout T) { withUnsafeMutablePointer(&arg) { (ptr: UnsafeMutablePointer<T>) -> Void in bzero(unsafeBitCast(ptr, to: UnsafeMutablePointer<Void>.self), sizeof(T.self)) } } internal func __CFSwiftGetBaseClass() -> AnyObject.Type { return __NSCFType.self } internal func __CFInitializeSwift() { _CFRuntimeBridgeTypeToClass(CFStringGetTypeID(), unsafeBitCast(_NSCFString.self, to: UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFArrayGetTypeID(), unsafeBitCast(_NSCFArray.self, to: UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFDictionaryGetTypeID(), unsafeBitCast(_NSCFDictionary.self, to: UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFSetGetTypeID(), unsafeBitCast(_NSCFSet.self, to: UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFNumberGetTypeID(), unsafeBitCast(NSNumber.self, to: UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFDataGetTypeID(), unsafeBitCast(NSData.self, to: UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFDateGetTypeID(), unsafeBitCast(NSDate.self, to: UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFURLGetTypeID(), unsafeBitCast(NSURL.self, to: UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFCalendarGetTypeID(), unsafeBitCast(Calendar.self, to: UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFLocaleGetTypeID(), unsafeBitCast(Locale.self, to: UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFTimeZoneGetTypeID(), unsafeBitCast(TimeZone.self, to: UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFCharacterSetGetTypeID(), unsafeBitCast(_NSCFCharacterSet.self, to: UnsafePointer<Void>.self)) // _CFRuntimeBridgeTypeToClass(CFErrorGetTypeID(), unsafeBitCast(NSError.self, UnsafePointer<Void>.self)) // _CFRuntimeBridgeTypeToClass(CFAttributedStringGetTypeID(), unsafeBitCast(NSMutableAttributedString.self, UnsafePointer<Void>.self)) // _CFRuntimeBridgeTypeToClass(CFReadStreamGetTypeID(), unsafeBitCast(NSInputStream.self, UnsafePointer<Void>.self)) // _CFRuntimeBridgeTypeToClass(CFWriteStreamGetTypeID(), unsafeBitCast(NSOutputStream.self, UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFRunLoopTimerGetTypeID(), unsafeBitCast(Timer.self, to: UnsafePointer<Void>.self)) __CFSwiftBridge.NSObject.isEqual = _CFSwiftIsEqual __CFSwiftBridge.NSObject.hash = _CFSwiftGetHash __CFSwiftBridge.NSObject._cfTypeID = _CFSwiftGetTypeID __CFSwiftBridge.NSArray.count = _CFSwiftArrayGetCount __CFSwiftBridge.NSArray.objectAtIndex = _CFSwiftArrayGetValueAtIndex __CFSwiftBridge.NSArray.getObjects = _CFSwiftArrayGetValues __CFSwiftBridge.NSMutableArray.addObject = _CFSwiftArrayAppendValue __CFSwiftBridge.NSMutableArray.setObject = _CFSwiftArraySetValueAtIndex __CFSwiftBridge.NSMutableArray.replaceObjectAtIndex = _CFSwiftArrayReplaceValueAtIndex __CFSwiftBridge.NSMutableArray.insertObject = _CFSwiftArrayInsertValueAtIndex __CFSwiftBridge.NSMutableArray.exchangeObjectAtIndex = _CFSwiftArrayExchangeValuesAtIndices __CFSwiftBridge.NSMutableArray.removeObjectAtIndex = _CFSwiftArrayRemoveValueAtIndex __CFSwiftBridge.NSMutableArray.removeAllObjects = _CFSwiftArrayRemoveAllValues __CFSwiftBridge.NSMutableArray.replaceObjectsInRange = _CFSwiftArrayReplaceValues __CFSwiftBridge.NSDictionary.count = _CFSwiftDictionaryGetCount __CFSwiftBridge.NSDictionary.countForKey = _CFSwiftDictionaryGetCountOfKey __CFSwiftBridge.NSDictionary.containsKey = _CFSwiftDictionaryContainsKey __CFSwiftBridge.NSDictionary.objectForKey = _CFSwiftDictionaryGetValue __CFSwiftBridge.NSDictionary._getValueIfPresent = _CFSwiftDictionaryGetValueIfPresent __CFSwiftBridge.NSDictionary.containsObject = _CFSwiftDictionaryContainsValue __CFSwiftBridge.NSDictionary.countForObject = _CFSwiftDictionaryGetCountOfValue __CFSwiftBridge.NSDictionary.getObjects = _CFSwiftDictionaryGetValuesAndKeys __CFSwiftBridge.NSDictionary.__apply = _CFSwiftDictionaryApplyFunction __CFSwiftBridge.NSMutableDictionary.__addObject = _CFSwiftDictionaryAddValue __CFSwiftBridge.NSMutableDictionary.replaceObject = _CFSwiftDictionaryReplaceValue __CFSwiftBridge.NSMutableDictionary.__setObject = _CFSwiftDictionarySetValue __CFSwiftBridge.NSMutableDictionary.removeObjectForKey = _CFSwiftDictionaryRemoveValue __CFSwiftBridge.NSMutableDictionary.removeAllObjects = _CFSwiftDictionaryRemoveAllValues __CFSwiftBridge.NSString._createSubstringWithRange = _CFSwiftStringCreateWithSubstring __CFSwiftBridge.NSString.copy = _CFSwiftStringCreateCopy __CFSwiftBridge.NSString.mutableCopy = _CFSwiftStringCreateMutableCopy __CFSwiftBridge.NSString.length = _CFSwiftStringGetLength __CFSwiftBridge.NSString.characterAtIndex = _CFSwiftStringGetCharacterAtIndex __CFSwiftBridge.NSString.getCharacters = _CFSwiftStringGetCharacters __CFSwiftBridge.NSString.__getBytes = _CFSwiftStringGetBytes __CFSwiftBridge.NSString._fastCStringContents = _CFSwiftStringFastCStringContents __CFSwiftBridge.NSString._fastCharacterContents = _CFSwiftStringFastContents __CFSwiftBridge.NSString._getCString = _CFSwiftStringGetCString __CFSwiftBridge.NSString._encodingCantBeStoredInEightBitCFString = _CFSwiftStringIsUnicode __CFSwiftBridge.NSMutableString.insertString = _CFSwiftStringInsert __CFSwiftBridge.NSMutableString.deleteCharactersInRange = _CFSwiftStringDelete __CFSwiftBridge.NSMutableString.replaceCharactersInRange = _CFSwiftStringReplace __CFSwiftBridge.NSMutableString.setString = _CFSwiftStringReplaceAll __CFSwiftBridge.NSMutableString.appendString = _CFSwiftStringAppend __CFSwiftBridge.NSMutableString.appendCharacters = _CFSwiftStringAppendCharacters __CFSwiftBridge.NSMutableString._cfAppendCString = _CFSwiftStringAppendCString __CFSwiftBridge.NSXMLParser.currentParser = _NSXMLParserCurrentParser __CFSwiftBridge.NSXMLParser._xmlExternalEntityWithURL = _NSXMLParserExternalEntityWithURL __CFSwiftBridge.NSXMLParser.getContext = _NSXMLParserGetContext __CFSwiftBridge.NSXMLParser.internalSubset = _NSXMLParserInternalSubset __CFSwiftBridge.NSXMLParser.isStandalone = _NSXMLParserIsStandalone __CFSwiftBridge.NSXMLParser.hasInternalSubset = _NSXMLParserHasInternalSubset __CFSwiftBridge.NSXMLParser.hasExternalSubset = _NSXMLParserHasExternalSubset __CFSwiftBridge.NSXMLParser.getEntity = _NSXMLParserGetEntity __CFSwiftBridge.NSXMLParser.notationDecl = _NSXMLParserNotationDecl __CFSwiftBridge.NSXMLParser.attributeDecl = _NSXMLParserAttributeDecl __CFSwiftBridge.NSXMLParser.elementDecl = _NSXMLParserElementDecl __CFSwiftBridge.NSXMLParser.unparsedEntityDecl = _NSXMLParserUnparsedEntityDecl __CFSwiftBridge.NSXMLParser.startDocument = _NSXMLParserStartDocument __CFSwiftBridge.NSXMLParser.endDocument = _NSXMLParserEndDocument __CFSwiftBridge.NSXMLParser.startElementNs = _NSXMLParserStartElementNs __CFSwiftBridge.NSXMLParser.endElementNs = _NSXMLParserEndElementNs __CFSwiftBridge.NSXMLParser.characters = _NSXMLParserCharacters __CFSwiftBridge.NSXMLParser.processingInstruction = _NSXMLParserProcessingInstruction __CFSwiftBridge.NSXMLParser.cdataBlock = _NSXMLParserCdataBlock __CFSwiftBridge.NSXMLParser.comment = _NSXMLParserComment __CFSwiftBridge.NSXMLParser.externalSubset = _NSXMLParserExternalSubset __CFSwiftBridge.NSRunLoop._new = _NSRunLoopNew __CFSwiftBridge.NSCharacterSet._expandedCFCharacterSet = _CFSwiftCharacterSetExpandedCFCharacterSet __CFSwiftBridge.NSCharacterSet._retainedBitmapRepresentation = _CFSwiftCharacterSetRetainedBitmapRepresentation __CFSwiftBridge.NSCharacterSet.characterIsMember = _CFSwiftCharacterSetCharacterIsMember __CFSwiftBridge.NSCharacterSet.mutableCopy = _CFSwiftCharacterSetMutableCopy __CFSwiftBridge.NSCharacterSet.longCharacterIsMember = _CFSwiftCharacterSetLongCharacterIsMember __CFSwiftBridge.NSCharacterSet.hasMemberInPlane = _CFSwiftCharacterSetHasMemberInPlane __CFSwiftBridge.NSCharacterSet.invertedSet = _CFSwiftCharacterSetInverted __CFDefaultEightBitStringEncoding = UInt32(kCFStringEncodingUTF8) } public protocol _ObjectTypeBridgeable { associatedtype _ObjectType : AnyObject /// Convert `self` to an Object type func _bridgeToObject() -> _ObjectType /// Bridge from an object of the bridged class type to a value of /// the Self type. /// /// This bridging operation is used for forced downcasting (e.g., /// via as), and may defer complete checking until later. For /// example, when bridging from `NSArray` to `Array<Element>`, we can defer /// the checking for the individual elements of the array. /// /// - parameter result: The location where the result is written. The optional /// will always contain a value. static func _forceBridgeFromObject( _ source: _ObjectType, result: inout Self? ) /// Try to bridge from an object of the bridged class type to a value of /// the Self type. /// /// This conditional bridging operation is used for conditional /// downcasting (e.g., via as?) and therefore must perform a /// complete conversion to the value type; it cannot defer checking /// to a later time. /// /// - parameter result: The location where the result is written. /// /// - Returns: `true` if bridging succeeded, `false` otherwise. This redundant /// information is provided for the convenience of the runtime's `dynamic_cast` /// implementation, so that it need not look into the optional representation /// to determine success. static func _conditionallyBridgeFromObject( _ source: _ObjectType, result: inout Self? ) -> Bool } protocol _NSObjectRepresentable { func _nsObjectRepresentation() -> NSObject } internal func _NSObjectRepresentableBridge(_ value: Any) -> NSObject { if let obj = value as? _NSObjectRepresentable { return obj._nsObjectRepresentation() } else if let str = value as? String { return str._nsObjectRepresentation() } else if let obj = value as? NSObject { return obj } else if let obj = value as? Int { return obj._bridgeToObject() } else if let obj = value as? UInt { return obj._bridgeToObject() } else if let obj = value as? Float { return obj._bridgeToObject() } else if let obj = value as? Double { return obj._bridgeToObject() } else if let obj = value as? Bool { return obj._bridgeToObject() } fatalError("Unable to convert value of type \(value.dynamicType)") } extension Array : _NSObjectRepresentable { func _nsObjectRepresentation() -> NSObject { return _bridgeToObject() } } extension Dictionary : _NSObjectRepresentable { func _nsObjectRepresentation() -> NSObject { return _bridgeToObject() } } extension String : _NSObjectRepresentable { func _nsObjectRepresentation() -> NSObject { return _bridgeToObject() } } extension Set : _NSObjectRepresentable { func _nsObjectRepresentation() -> NSObject { return _bridgeToObject() } } extension Int : _NSObjectRepresentable { func _nsObjectRepresentation() -> NSObject { return _bridgeToObject() } } extension UInt : _NSObjectRepresentable { func _nsObjectRepresentation() -> NSObject { return _bridgeToObject() } } extension Float : _NSObjectRepresentable { func _nsObjectRepresentation() -> NSObject { return _bridgeToObject() } } extension Double : _NSObjectRepresentable { func _nsObjectRepresentation() -> NSObject { return _bridgeToObject() } } extension Bool : _NSObjectRepresentable { func _nsObjectRepresentation() -> NSObject { return _bridgeToObject() } } public func === (lhs: AnyClass, rhs: AnyClass) -> Bool { return unsafeBitCast(lhs, to: UnsafePointer<Void>.self) == unsafeBitCast(rhs, to: UnsafePointer<Void>.self) } /// Swift extensions for common operations in Foundation that use unsafe things... extension NSObject { static func unretainedReference<T, R: NSObject>(_ value: UnsafePointer<T>) -> R { return unsafeBitCast(value, to: R.self) } static func unretainedReference<T, R: NSObject>(_ value: UnsafeMutablePointer<T>) -> R { return unretainedReference(UnsafePointer<T>(value)) } static func releaseReference<T>(_ value: UnsafePointer<T>) { _CFSwiftRelease(UnsafeMutablePointer<Void>(value)) } static func releaseReference<T>(_ value: UnsafeMutablePointer<T>) { _CFSwiftRelease(value) } func withRetainedReference<T, R>(_ work: @noescape (UnsafePointer<T>) -> R) -> R { return work(UnsafePointer<T>(_CFSwiftRetain(unsafeBitCast(self, to: UnsafeMutablePointer<Void>.self))!)) } func withRetainedReference<T, R>(_ work: @noescape (UnsafeMutablePointer<T>) -> R) -> R { return work(UnsafeMutablePointer<T>(_CFSwiftRetain(unsafeBitCast(self, to: UnsafeMutablePointer<Void>.self))!)) } func withUnretainedReference<T, R>(_ work: @noescape (UnsafePointer<T>) -> R) -> R { return work(unsafeBitCast(self, to: UnsafePointer<T>.self)) } func withUnretainedReference<T, R>(_ work: @noescape (UnsafeMutablePointer<T>) -> R) -> R { return work(unsafeBitCast(self, to: UnsafeMutablePointer<T>.self)) } } extension Array { internal mutating func withUnsafeMutablePointerOrAllocation<R>(_ count: Int, fastpath: UnsafeMutablePointer<Element>? = nil, body: @noescape (UnsafeMutablePointer<Element>) -> R) -> R { if let fastpath = fastpath { return body(fastpath) } else if self.count > count { let buffer = UnsafeMutablePointer<Element>(allocatingCapacity: count) let res = body(buffer) buffer.deinitialize(count: count) buffer.deallocateCapacity(count) return res } else { return withUnsafeMutableBufferPointer() { (bufferPtr: inout UnsafeMutableBufferPointer<Element>) -> R in return body(bufferPtr.baseAddress!) } } } } public protocol Bridgeable { associatedtype BridgeType func bridge() -> BridgeType } #if os(OSX) || os(iOS) internal typealias _DarwinCompatibleBoolean = DarwinBoolean #else internal typealias _DarwinCompatibleBoolean = Bool #endif
apache-2.0
5444289e8c934d549960cac25f863e51
42.809019
189
0.737588
5.280051
false
false
false
false
jkiley129/Artfull
Artfull/VCMapView.swift
1
2044
// // VCMapView.swift // Artfull // // Created by Joseph Kiley on 12/2/15. // Copyright © 2015 Joseph Kiley. All rights reserved. // import Foundation import Parse import MapKit extension ViewController: MKMapViewDelegate { // 1 func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { if let annotation = annotation as? GalleryAnnotation { let identifier = "pin" var view: MKPinAnnotationView if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? MKPinAnnotationView { // 2 dequeuedView.annotation = annotation view = dequeuedView } else { // 3 view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) view.canShowCallout = true view.calloutOffset = CGPoint(x: -5, y: 5) view.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure) } return view } return nil } func openInMapsTransit(location:CLLocationCoordinate2D) { let placemark = MKPlacemark(coordinate: location, addressDictionary: nil) let mapItem = MKMapItem(placemark: placemark) let launchOptions = [MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeTransit] mapItem.openInMapsWithLaunchOptions(launchOptions) } func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, leftCalloutAccessoryControlTapped control: UIControl) { let location = view.annotation as! GalleryAnnotation let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeTransit] if let mapItem = location.mapItem(){ mapItem.openInMapsWithLaunchOptions(launchOptions) } else { // handle the fact that mapItem is nil... } } }
mit
94be4b6a06c7a93b16e74217e7f2e799
36.145455
104
0.640235
5.887608
false
false
false
false
Zewo/System
Sources/POSIX/SystemError.swift
7
13529
#if os(Linux) import Glibc #else import Darwin.C #endif public enum SystemError : Error { case operationNotPermitted case noSuchFileOrDirectory case noSuchProcess case interruptedSystemCall case inputOutputError case deviceNotConfigured case argumentListTooLong case executableFormatError case badFileDescriptor case noChildProcesses case resourceDeadlockAvoided case cannotAllocateMemory case permissionDenied case badAddress case blockDeviceRequired case deviceOrResourceBusy case fileExists case crossDeviceLink case operationNotSupportedByDevice case notADirectory case isADirectory case invalidArgument case tooManyOpenFilesInSystem case tooManyOpenFiles case inappropriateInputOutputControlForDevice case textFileBusy case fileTooLarge case noSpaceLeftOnDevice case illegalSeek case readOnlyFileSystem case tooManyLinks case brokenPipe /* math software */ case numericalArgumentOutOfDomain case resultTooLarge /* non-blocking and interrupt i/o */ case resourceTemporarilyUnavailable case operationWouldBlock case operationNowInProgress case operationAlreadyInProgress /* ipc/network software -- argument errors */ case socketOperationOnNonSocket case destinationAddressRequired case messageTooLong case protocolWrongTypeForSocket case protocolNotAvailable case protocolNotSupported case socketTypeNotSupported case operationNotSupported case protocolFamilyNotSupported case addressFamilyNotSupportedByProtocolFamily case addressAlreadyInUse case cannotAssignRequestedAddress /* ipc/network software -- operational errors */ case networkIsDown case networkIsUnreachable case networkDroppedConnectionOnReset case softwareCausedConnectionAbort case connectionResetByPeer case noBufferSpaceAvailable case socketIsAlreadyConnected case socketIsNotConnected case cannotSendAfterSocketShutdown case tooManyReferences case operationTimedOut case connectionRefused case tooManyLevelsOfSymbolicLinks case fileNameTooLong case hostIsDown case noRouteToHost case directoryNotEmpty /* quotas & mush */ case tooManyUsers case diskQuotaExceeded /* Network File System */ case staleFileHandle case objectIsRemote case noLocksAvailable case functionNotImplemented case valueTooLargeForDefinedDataType case operationCanceled case identifierRemoved case noMessageOfDesiredType case illegalByteSequence case badMessage case multihopAttempted case noDataAvailable case linkHasBeenSevered case outOfStreamsResources case deviceNotAStream case protocolError case timerExpired case stateNotRecoverable case previousOwnerDied case other(errorNumber: Int32) } extension SystemError { public init?(errorNumber: Int32) { switch errorNumber { case 0: return nil case EPERM: self = .operationNotPermitted case ENOENT: self = .noSuchFileOrDirectory case ESRCH: self = .noSuchProcess case EINTR: self = .interruptedSystemCall case EIO: self = .inputOutputError case ENXIO: self = .deviceNotConfigured case E2BIG: self = .argumentListTooLong case ENOEXEC: self = .executableFormatError case EBADF: self = .badFileDescriptor case ECHILD: self = .noChildProcesses case EDEADLK: self = .resourceDeadlockAvoided case ENOMEM: self = .cannotAllocateMemory case EACCES: self = .permissionDenied case EFAULT: self = .badAddress case ENOTBLK: self = .blockDeviceRequired case EBUSY: self = .deviceOrResourceBusy case EEXIST: self = .fileExists case EXDEV: self = .crossDeviceLink case ENODEV: self = .operationNotSupportedByDevice case ENOTDIR: self = .notADirectory case EISDIR: self = .isADirectory case EINVAL: self = .invalidArgument case ENFILE: self = .tooManyOpenFilesInSystem case EMFILE: self = .tooManyOpenFiles case ENOTTY: self = .inappropriateInputOutputControlForDevice case ETXTBSY: self = .textFileBusy case EFBIG: self = .fileTooLarge case ENOSPC: self = .noSpaceLeftOnDevice case ESPIPE: self = .illegalSeek case EROFS: self = .readOnlyFileSystem case EMLINK: self = .tooManyLinks case EPIPE: self = .brokenPipe /* math software */ case EDOM: self = .numericalArgumentOutOfDomain case ERANGE: self = .resultTooLarge /* non-blocking and interrupt i/o */ case EAGAIN: self = .resourceTemporarilyUnavailable case EWOULDBLOCK: self = .operationWouldBlock case EINPROGRESS: self = .operationNowInProgress case EALREADY: self = .operationAlreadyInProgress /* ipc/network software -- argument errors */ case ENOTSOCK: self = .socketOperationOnNonSocket case EDESTADDRREQ: self = .destinationAddressRequired case EMSGSIZE: self = .messageTooLong case EPROTOTYPE: self = .protocolWrongTypeForSocket case ENOPROTOOPT: self = .protocolNotAvailable case EPROTONOSUPPORT: self = .protocolNotSupported case ESOCKTNOSUPPORT: self = .socketTypeNotSupported case ENOTSUP: self = .operationNotSupported case EPFNOSUPPORT: self = .protocolFamilyNotSupported case EAFNOSUPPORT: self = .addressFamilyNotSupportedByProtocolFamily case EADDRINUSE: self = .addressAlreadyInUse case EADDRNOTAVAIL: self = .cannotAssignRequestedAddress /* ipc/network software -- operational errors */ case ENETDOWN: self = .networkIsDown case ENETUNREACH: self = .networkIsUnreachable case ENETRESET: self = .networkDroppedConnectionOnReset case ECONNABORTED: self = .softwareCausedConnectionAbort case ECONNRESET: self = .connectionResetByPeer case ENOBUFS: self = .noBufferSpaceAvailable case EISCONN: self = .socketIsAlreadyConnected case ENOTCONN: self = .socketIsNotConnected case ESHUTDOWN: self = .cannotSendAfterSocketShutdown case ETOOMANYREFS: self = .tooManyReferences case ETIMEDOUT: self = .operationTimedOut case ECONNREFUSED: self = .connectionRefused case ELOOP: self = .tooManyLevelsOfSymbolicLinks case ENAMETOOLONG: self = .fileNameTooLong case EHOSTDOWN: self = .hostIsDown case EHOSTUNREACH: self = .noRouteToHost case ENOTEMPTY: self = .directoryNotEmpty /* quotas & mush */ case EUSERS: self = .tooManyUsers case EDQUOT: self = .diskQuotaExceeded /* Network File System */ case ESTALE: self = .staleFileHandle case EREMOTE: self = .objectIsRemote case ENOLCK: self = .noLocksAvailable case ENOSYS: self = .functionNotImplemented case EOVERFLOW: self = .valueTooLargeForDefinedDataType case ECANCELED: self = .operationCanceled case EIDRM: self = .identifierRemoved case ENOMSG: self = .noMessageOfDesiredType case EILSEQ: self = .illegalByteSequence case EBADMSG: self = .badMessage case EMULTIHOP: self = .multihopAttempted case ENODATA: self = .noDataAvailable case ENOLINK: self = .linkHasBeenSevered case ENOSR: self = .outOfStreamsResources case ENOSTR: self = .deviceNotAStream case EPROTO: self = .protocolError case ETIME: self = .timerExpired case ENOTRECOVERABLE: self = .stateNotRecoverable case EOWNERDEAD: self = .previousOwnerDied default: self = .other(errorNumber: errorNumber) } } } extension SystemError { public var errorNumber: Int32 { switch self { case .operationNotPermitted: return EPERM case .noSuchFileOrDirectory: return ENOENT case .noSuchProcess: return ESRCH case .interruptedSystemCall: return EINTR case .inputOutputError: return EIO case .deviceNotConfigured: return ENXIO case .argumentListTooLong: return E2BIG case .executableFormatError: return ENOEXEC case .badFileDescriptor: return EBADF case .noChildProcesses: return ECHILD case .resourceDeadlockAvoided: return EDEADLK case .cannotAllocateMemory: return ENOMEM case .permissionDenied: return EACCES case .badAddress: return EFAULT case .blockDeviceRequired: return ENOTBLK case .deviceOrResourceBusy: return EBUSY case .fileExists: return EEXIST case .crossDeviceLink: return EXDEV case .operationNotSupportedByDevice: return ENODEV case .notADirectory: return ENOTDIR case .isADirectory: return EISDIR case .invalidArgument: return EINVAL case .tooManyOpenFilesInSystem: return ENFILE case .tooManyOpenFiles: return EMFILE case .inappropriateInputOutputControlForDevice: return ENOTTY case .textFileBusy: return ETXTBSY case .fileTooLarge: return EFBIG case .noSpaceLeftOnDevice: return ENOSPC case .illegalSeek: return ESPIPE case .readOnlyFileSystem: return EROFS case .tooManyLinks: return EMLINK case .brokenPipe: return EPIPE /* math software */ case .numericalArgumentOutOfDomain: return EDOM case .resultTooLarge: return ERANGE /* non-blocking and interrupt i/o */ case .resourceTemporarilyUnavailable: return EAGAIN case .operationWouldBlock: return EWOULDBLOCK case .operationNowInProgress: return EINPROGRESS case .operationAlreadyInProgress: return EALREADY /* ipc/network software -- argument errors */ case .socketOperationOnNonSocket: return ENOTSOCK case .destinationAddressRequired: return EDESTADDRREQ case .messageTooLong: return EMSGSIZE case .protocolWrongTypeForSocket: return EPROTOTYPE case .protocolNotAvailable: return ENOPROTOOPT case .protocolNotSupported: return EPROTONOSUPPORT case .socketTypeNotSupported: return ESOCKTNOSUPPORT case .operationNotSupported: return ENOTSUP case .protocolFamilyNotSupported: return EPFNOSUPPORT case .addressFamilyNotSupportedByProtocolFamily: return EAFNOSUPPORT case .addressAlreadyInUse: return EADDRINUSE case .cannotAssignRequestedAddress: return EADDRNOTAVAIL /* ipc/network software -- operational errors */ case .networkIsDown: return ENETDOWN case .networkIsUnreachable: return ENETUNREACH case .networkDroppedConnectionOnReset: return ENETRESET case .softwareCausedConnectionAbort: return ECONNABORTED case .connectionResetByPeer: return ECONNRESET case .noBufferSpaceAvailable: return ENOBUFS case .socketIsAlreadyConnected: return EISCONN case .socketIsNotConnected: return ENOTCONN case .cannotSendAfterSocketShutdown: return ESHUTDOWN case .tooManyReferences: return ETOOMANYREFS case .operationTimedOut: return ETIMEDOUT case .connectionRefused: return ECONNREFUSED case .tooManyLevelsOfSymbolicLinks: return ELOOP case .fileNameTooLong: return ENAMETOOLONG case .hostIsDown: return EHOSTDOWN case .noRouteToHost: return EHOSTUNREACH case .directoryNotEmpty: return ENOTEMPTY /* quotas & mush */ case .tooManyUsers: return EUSERS case .diskQuotaExceeded: return EDQUOT /* Network File System */ case .staleFileHandle: return ESTALE case .objectIsRemote: return EREMOTE case .noLocksAvailable: return ENOLCK case .functionNotImplemented: return ENOSYS case .valueTooLargeForDefinedDataType: return EOVERFLOW case .operationCanceled: return ECANCELED case .identifierRemoved: return EIDRM case .noMessageOfDesiredType: return ENOMSG case .illegalByteSequence: return EILSEQ case .badMessage: return EBADMSG case .multihopAttempted: return EMULTIHOP case .noDataAvailable: return ENODATA case .linkHasBeenSevered: return ENOLINK case .outOfStreamsResources: return ENOSR case .deviceNotAStream: return ENOSTR case .protocolError: return EPROTO case .timerExpired: return ETIME case .stateNotRecoverable: return ENOTRECOVERABLE case .previousOwnerDied: return EOWNERDEAD case .other(let errorNumber): return errorNumber } } } extension SystemError : Equatable {} public func == (lhs: SystemError, rhs: SystemError) -> Bool { return lhs.errorNumber == rhs.errorNumber } extension SystemError { public static func description(for errorNumber: Int32) -> String { return String(cString: strerror(errorNumber)) } } extension SystemError : CustomStringConvertible { public var description: String { return SystemError.description(for: errorNumber) } } extension SystemError { public static var lastOperationError: SystemError? { return SystemError(errorNumber: errno) } } public func ensureLastOperationSucceeded() throws { if let error = SystemError.lastOperationError { throw error } }
mit
6006bb8880ba727f5b03cce94ab0e685
31.757869
76
0.707
5.553777
false
false
false
false
karavakis/simply_counted
simply_counted/Activity.swift
1
1036
// // Activity.swift // simply_counted // // Created by Jennifer Karavakis on 8/26/16. // Copyright © 2017 Jennifer Karavakis. All rights reserved. // import UIKit import CloudKit open class Activity: CloudKitRecord { var clientReference: CKRecord.Reference? var date: Date init(className: String, clientId: CKRecord.ID, date: Date) { self.clientReference = CKRecord.Reference(recordID: clientId, action: .deleteSelf) self.date = date super.init() self.record = CKRecord(recordType: className) } init(activityRecord: CKRecord!) { self.clientReference = activityRecord.object(forKey: "client") as? CKRecord.Reference self.date = activityRecord.object(forKey: "date") as! Date super.init() self.record = activityRecord } open func save() { record!.setObject(self.clientReference, forKey: "client") record!.setObject(self.date as CKRecordValue?, forKey: "date") self.saveRecord(nil, errorHandler: nil) } }
apache-2.0
0a3a9096afb0f7df9cbe317207064a4f
26.236842
93
0.666667
4.058824
false
false
false
false
crashoverride777/Swift-iAds-and-AdMob-Helper
Example/SwiftyAdExample/GameViewController.swift
1
2521
// // GameViewController.swift // SwiftyAds // // Created by Dominik on 04/09/2015. import UIKit import SpriteKit class GameViewController: UIViewController { private let swiftyAd: SwiftyAd = .shared override func viewDidLoad() { super.viewDidLoad() // Setup swifty ad swiftyAd.setup(with: self, delegate: self) { hasConsent in guard hasConsent else { return } DispatchQueue.main.async { self.swiftyAd.showBanner(from: self) } } // Load game scene if let scene = GameScene(fileNamed: "GameScene") { // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .aspectFill skView.presentScene(scene) } } override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .all } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override var prefersStatusBarHidden: Bool { return true } } // MARK: - SwiftyAdDelegate extension GameViewController: SwiftyAdDelegate { func swiftyAdDidOpen(_ swiftyAd: SwiftyAd) { print("SwiftyAd did open") } func swiftyAdDidClose(_ swiftyAd: SwiftyAd) { print("SwiftyAd did close") } func swiftyAd(_ swiftyAd: SwiftyAd, didChange consentStatus: SwiftyAd.ConsentStatus) { print("SwiftyAd did change consent status to \(consentStatus)") // e.g update mediation networks } func swiftyAd(_ swiftyAd: SwiftyAd, didRewardUserWithAmount rewardAmount: Int) { print("SwiftyAd did reward user with \(rewardAmount)") if let scene = (view as? SKView)?.scene as? GameScene { scene.coins += rewardAmount } // Will actually not work with this sample project, adMob just shows a black ad in test mode // It only works with 3rd party mediation partners you set up through your adMob account } }
mit
e7d262ca941279d6ff2f5d6c7bcdd0ce
27.647727
100
0.612455
5.318565
false
false
false
false