repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
BoxJeon/funjcam-ios | refs/heads/feature/bookmakr-swiftui | Application/Application/Bookmark/BookmarkController.swift | mit | 1 | import Combine
import Usecase
public protocol BookmarkDependency {
var bookmarkImageUsecase: BookmarkImageUsecase { get }
func alertBuilder() -> AlertBuildable
}
public protocol BookmarkListener: AnyObject {
}
protocol BookmarkViewControllable: ViewControllable {
}
final class BookmarkController: BookmarkControllable {
private let dependency: BookmarkDependency
private let stateSubject: CurrentValueSubject<BookmarkState, Never>
private let eventSubject: PassthroughSubject<BookmarkEvent, Never>
private var state: BookmarkState {
get { self.stateSubject.value }
set { self.stateSubject.send(newValue) }
}
private weak var listener: BookmarkListener?
private weak var viewController: BookmarkViewControllable?
private var cancellables: Set<AnyCancellable>
init(dependency: BookmarkDependency, listener: BookmarkListener?) {
self.dependency = dependency
let initialState = BookmarkState(images: [])
self.stateSubject = CurrentValueSubject(initialState)
self.eventSubject = PassthroughSubject()
self.listener = listener
self.cancellables = Set()
}
// MARK: - BookmarkControllable
lazy var observableState: ObservableState<BookmarkState> = {
return ObservableState(subject: self.stateSubject)
}()
lazy var observableEvent: ObservableEvent<BookmarkEvent> = {
return ObservableEvent(subject: self.eventSubject)
}()
func activate(with viewController: BookmarkViewControllable) {
self.viewController = viewController
self.requestBookmarks()
}
private func requestBookmarks() {
let usecase = self.dependency.bookmarkImageUsecase
usecase.query()
.sink { [weak self] completion in
if case let .failure(error) = completion {
let title = String(describing: error)
let message = error.localizedDescription
self?.routeToAlert(title: title, message: message)
}
} receiveValue: { [weak self] images in
self?.state.images = images
}
.store(in: &(self.cancellables))
}
private func routeToAlert(title: String, message: String) {
let builder = self.dependency.alertBuilder()
let viewController = builder.build(title: title, message: message)
self.viewController?.present(viewControllable: viewController, animated: true)
}
}
| 79229f5f669df0ce80e5b2e3dcf44bdf | 30.173333 | 82 | 0.729256 | false | false | false | false |
jacobwhite/firefox-ios | refs/heads/master | StorageTests/TestSQLiteHistoryRecommendations.swift | mpl-2.0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
@testable import Storage
import Deferred
import SDWebImage
import XCTest
private let microsecondsPerMinute: UInt64 = 60_000_000 // 1000 * 1000 * 60
private let oneHourInMicroseconds: UInt64 = 60 * microsecondsPerMinute
private let oneDayInMicroseconds: UInt64 = 24 * oneHourInMicroseconds
class TestSQLiteHistoryRecommendations: XCTestCase {
let files = MockFiles()
var db: BrowserDB!
var prefs: MockProfilePrefs!
var history: SQLiteHistory!
var bookmarks: MergedSQLiteBookmarks!
var metadata: SQLiteMetadata!
override func setUp() {
super.setUp()
db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
metadata = SQLiteMetadata(db: db)
prefs = MockProfilePrefs()
history = SQLiteHistory(db: db, prefs: prefs)
bookmarks = MergedSQLiteBookmarks(db: db)
}
override func tearDown() {
// Clear out anything we might have changed on disk
history.clearHistory().succeeded()
db.run("DELETE FROM page_metadata").succeeded()
db.run("DELETE FROM highlights").succeeded()
db.run("DELETE FROM activity_stream_blocklist").succeeded()
SDWebImageManager.shared().imageCache?.clearDisk()
SDWebImageManager.shared().imageCache?.clearMemory()
super.tearDown()
}
/*
* Verify that we return a non-recent history highlight if:
*
* 1. We haven't visited the site in the last 30 minutes
* 2. We've only visited the site less than or equal to 3 times
* 3. The site we visited has a non-empty title
*
*/
func testHistoryHighlights() {
let startTime = Date.nowMicroseconds()
let oneHourAgo = startTime - oneHourInMicroseconds
let fifteenMinutesAgo = startTime - 15 * microsecondsPerMinute
/*
* Site A: 1 visit, 1 hour ago = highlight
* Site B: 1 visits, 15 minutes ago = non-highlight
* Site C: 3 visits, 1 hour ago = highlight
* Site D: 4 visits, 1 hour ago = non-highlight
*/
let siteA = Site(url: "http://siteA/", title: "A")
let siteB = Site(url: "http://siteB/", title: "B")
let siteC = Site(url: "http://siteC/", title: "C")
let siteD = Site(url: "http://siteD/", title: "D")
let siteVisitA1 = SiteVisit(site: siteA, date: oneHourAgo, type: .link)
let siteVisitB1 = SiteVisit(site: siteB, date: fifteenMinutesAgo, type: .link)
let siteVisitC1 = SiteVisit(site: siteC, date: oneHourAgo + 1, type: .link)
let siteVisitC2 = SiteVisit(site: siteC, date: oneHourAgo + 1000, type: .link)
let siteVisitC3 = SiteVisit(site: siteC, date: oneHourAgo + 2000, type: .link)
let siteVisitD1 = SiteVisit(site: siteD, date: oneHourAgo, type: .link)
let siteVisitD2 = SiteVisit(site: siteD, date: oneHourAgo + 1000, type: .link)
let siteVisitD3 = SiteVisit(site: siteD, date: oneHourAgo + 2000, type: .link)
let siteVisitD4 = SiteVisit(site: siteD, date: oneHourAgo + 3000, type: .link)
history.clearHistory().succeeded()
history.addLocalVisit(siteVisitA1).succeeded()
history.addLocalVisit(siteVisitB1).succeeded()
history.addLocalVisit(siteVisitC1).succeeded()
history.addLocalVisit(siteVisitC2).succeeded()
history.addLocalVisit(siteVisitC3).succeeded()
history.addLocalVisit(siteVisitD1).succeeded()
history.addLocalVisit(siteVisitD2).succeeded()
history.addLocalVisit(siteVisitD3).succeeded()
history.addLocalVisit(siteVisitD4).succeeded()
history.repopulate(invalidateTopSites: true, invalidateHighlights: true).succeeded()
let highlights = history.getHighlights().value.successValue!
XCTAssertEqual(highlights.count, 2)
XCTAssertEqual(highlights[0]!.title, "A")
XCTAssertEqual(highlights[1]!.title, "C")
}
/*
* Verify that we do not return a highlight if
* its domain is in the blacklist
*
*/
func testBlacklistHighlights() {
let startTime = Date.nowMicroseconds()
let oneHourAgo = startTime - oneHourInMicroseconds
let fifteenMinutesAgo = startTime - 15 * microsecondsPerMinute
/*
* Site A: 1 visit, 1 hour ago = highlight that is on the blacklist
* Site B: 1 visits, 15 minutes ago = non-highlight
* Site C: 3 visits, 1 hour ago = highlight that is on the blacklist
* Site D: 4 visits, 1 hour ago = non-highlight
*/
let siteA = Site(url: "http://www.google.com", title: "A")
let siteB = Site(url: "http://siteB/", title: "B")
let siteC = Site(url: "http://www.search.yahoo.com/", title: "C")
let siteD = Site(url: "http://siteD/", title: "D")
let siteVisitA1 = SiteVisit(site: siteA, date: oneHourAgo, type: .link)
let siteVisitB1 = SiteVisit(site: siteB, date: fifteenMinutesAgo, type: .link)
let siteVisitC1 = SiteVisit(site: siteC, date: oneHourAgo, type: .link)
let siteVisitC2 = SiteVisit(site: siteC, date: oneHourAgo + 1000, type: .link)
let siteVisitC3 = SiteVisit(site: siteC, date: oneHourAgo + 2000, type: .link)
let siteVisitD1 = SiteVisit(site: siteD, date: oneHourAgo, type: .link)
let siteVisitD2 = SiteVisit(site: siteD, date: oneHourAgo + 1000, type: .link)
let siteVisitD3 = SiteVisit(site: siteD, date: oneHourAgo + 2000, type: .link)
let siteVisitD4 = SiteVisit(site: siteD, date: oneHourAgo + 3000, type: .link)
history.clearHistory().succeeded()
history.addLocalVisit(siteVisitA1).succeeded()
history.addLocalVisit(siteVisitB1).succeeded()
history.addLocalVisit(siteVisitC1).succeeded()
history.addLocalVisit(siteVisitC2).succeeded()
history.addLocalVisit(siteVisitC3).succeeded()
history.addLocalVisit(siteVisitD1).succeeded()
history.addLocalVisit(siteVisitD2).succeeded()
history.addLocalVisit(siteVisitD3).succeeded()
history.addLocalVisit(siteVisitD4).succeeded()
history.repopulate(invalidateTopSites: true, invalidateHighlights: true).succeeded()
let highlights = history.getHighlights().value.successValue!
XCTAssertEqual(highlights.count, 0)
}
/*
* Verify that we return the most recent highlight per domain
*/
func testMostRecentUniqueDomainReturnedInHighlights() {
let startTime = Date.nowMicroseconds()
let oneHourAgo = startTime - oneHourInMicroseconds
let twoHoursAgo = startTime - 2 * oneHourInMicroseconds
/*
* Site A: 1 visit, 1 hour ago = highlight
* Site C: 2 visits, 2 hours ago = highlight with the same domain
*/
let siteA = Site(url: "http://www.foo.com/", title: "A")
let siteC = Site(url: "http://m.foo.com/", title: "C")
let siteVisitA1 = SiteVisit(site: siteA, date: oneHourAgo, type: .link)
let siteVisitC1 = SiteVisit(site: siteC, date: twoHoursAgo, type: .link)
let siteVisitC2 = SiteVisit(site: siteC, date: twoHoursAgo + 1000, type: .link)
history.clearHistory().succeeded()
history.addLocalVisit(siteVisitA1).succeeded()
history.addLocalVisit(siteVisitC1).succeeded()
history.addLocalVisit(siteVisitC2).succeeded()
history.repopulate(invalidateTopSites: true, invalidateHighlights: true).succeeded()
let highlights = history.getHighlights().value.successValue!
XCTAssertEqual(highlights.count, 1)
XCTAssertEqual(highlights[0]!.title, "A")
}
func testBookmarkHighlights() {
history.clearHistory().succeeded()
populateForRecommendationCalculations(history, bookmarks: bookmarks, metadata: metadata, historyCount: 10, bookmarkCount: 10)
let sites = history.getRecentBookmarks(5).value.successValue?.asArray()
XCTAssertEqual(sites!.count, 5, "5 bookmarks should have been fetched")
sites!.forEach { XCTAssertEqual($0.guid, "bookmark-\(sites!.index(of: $0)!)"); XCTAssertEqual($0.metadata?.description, "Test Description") }
}
func testMetadataReturnedInHighlights() {
let startTime = Date.nowMicroseconds()
let oneHourAgo = startTime - oneHourInMicroseconds
let siteA = Site(url: "http://siteA.com", title: "Site A")
let siteB = Site(url: "http://siteB.com/", title: "Site B")
let siteC = Site(url: "http://siteC.com/", title: "Site C")
let siteVisitA1 = SiteVisit(site: siteA, date: oneHourAgo, type: .link)
let siteVisitB1 = SiteVisit(site: siteB, date: oneHourAgo + 1000, type: .link)
let siteVisitC1 = SiteVisit(site: siteC, date: oneHourAgo, type: .link)
let siteVisitC2 = SiteVisit(site: siteC, date: oneHourAgo + 1000, type: .link)
let siteVisitC3 = SiteVisit(site: siteC, date: oneHourAgo + 2000, type: .link)
history.clearHistory().succeeded()
history.addLocalVisit(siteVisitA1).succeeded()
history.addLocalVisit(siteVisitB1).succeeded()
history.addLocalVisit(siteVisitC1).succeeded()
history.addLocalVisit(siteVisitC2).succeeded()
history.addLocalVisit(siteVisitC3).succeeded()
// add metadata for 2 of the sites
let metadata = SQLiteMetadata(db: db)
let pageA = PageMetadata(id: nil, siteURL: siteA.url, mediaURL: "http://image.com",
title: siteA.title, description: "Test Description", type: nil, providerName: nil)
metadata.storeMetadata(pageA, forPageURL: siteA.url.asURL!, expireAt: Date.now() + 3000).succeeded()
let pageB = PageMetadata(id: nil, siteURL: siteB.url, mediaURL: "http://image.com",
title: siteB.title, description: "Test Description", type: nil, providerName: nil)
metadata.storeMetadata(pageB, forPageURL: siteB.url.asURL!, expireAt: Date.now() + 3000).succeeded()
let pageC = PageMetadata(id: nil, siteURL: siteC.url, mediaURL: "http://image.com",
title: siteC.title, description: "Test Description", type: nil, providerName: nil)
metadata.storeMetadata(pageC, forPageURL: siteC.url.asURL!, expireAt: Date.now() + 3000).succeeded()
history.repopulate(invalidateTopSites: true, invalidateHighlights: true).succeeded()
let highlights = history.getHighlights().value.successValue!
XCTAssertEqual(highlights.count, 3)
for highlight in highlights {
XCTAssertNotNil(highlight?.metadata)
XCTAssertNotNil(highlight?.metadata?.mediaURL)
}
}
func testRemoveHighlightForURL() {
let startTime = Date.nowMicroseconds()
let oneHourAgo = startTime - oneHourInMicroseconds
let siteA = Site(url: "http://siteA/", title: "A")
let siteVisitA1 = SiteVisit(site: siteA, date: oneHourAgo, type: .link)
history.clearHistory().succeeded()
history.addLocalVisit(siteVisitA1).succeeded()
history.repopulate(invalidateTopSites: true, invalidateHighlights: true).succeeded()
var highlights = history.getHighlights().value.successValue!
XCTAssertEqual(highlights.count, 1)
XCTAssertEqual(highlights[0]!.title, "A")
history.removeHighlightForURL(siteA.url).succeeded()
history.repopulate(invalidateTopSites: true, invalidateHighlights: true).succeeded()
highlights = history.getHighlights().value.successValue!
XCTAssertEqual(highlights.count, 0)
}
func testClearHighlightsCache() {
let startTime = Date.nowMicroseconds()
let oneHourAgo = startTime - oneHourInMicroseconds
let siteA = Site(url: "http://siteA/", title: "A")
let siteVisitA1 = SiteVisit(site: siteA, date: oneHourAgo, type: .link)
history.clearHistory().succeeded()
history.addLocalVisit(siteVisitA1).succeeded()
history.repopulate(invalidateTopSites: true, invalidateHighlights: true).succeeded()
let highlights = history.getHighlights().value.successValue!
XCTAssertEqual(highlights.count, 1)
XCTAssertEqual(highlights[0]!.title, "A")
}
}
class TestSQLiteHistoryRecommendationsPerf: XCTestCase {
func testRecommendationPref() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let metadata = SQLiteMetadata(db: db)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let bookmarks = MergedSQLiteBookmarks(db: db)
let count = 500
history.clearHistory().succeeded()
populateForRecommendationCalculations(history, bookmarks: bookmarks, metadata: metadata, historyCount: count, bookmarkCount: count)
self.measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: true) {
for _ in 0...5 {
history.repopulate(invalidateTopSites: true, invalidateHighlights: true).succeeded()
}
self.stopMeasuring()
}
}
}
private func populateForRecommendationCalculations(_ history: SQLiteHistory, bookmarks: MergedSQLiteBookmarks, metadata: SQLiteMetadata, historyCount: Int, bookmarkCount: Int) {
let baseMillis: UInt64 = baseInstantInMillis - 20000
for i in 0..<historyCount {
let site = Site(url: "http://s\(i)ite\(i)/foo", title: "A \(i)")
site.guid = "abc\(i)def"
history.insertOrUpdatePlace(site.asPlace(), modified: baseMillis).succeeded()
for j in 0...20 {
let visitTime = advanceMicrosecondTimestamp(baseInstantInMicros, by: (1000000 * i) + (1000 * j))
addVisitForSite(site, intoHistory: history, from: .local, atTime: visitTime)
addVisitForSite(site, intoHistory: history, from: .remote, atTime: visitTime)
}
}
(0..<bookmarkCount).forEach { i in
let modifiedTime = advanceMicrosecondTimestamp(baseInstantInMicros, by: (1000000 * i))
let bookmarkSite = Site(url: "http://bookmark-\(i)/", title: "\(i) Bookmark")
bookmarkSite.guid = "bookmark-\(i)"
addVisitForSite(bookmarkSite, intoHistory: history, from: .local, atTime: modifiedTime)
addVisitForSite(bookmarkSite, intoHistory: history, from: .remote, atTime: modifiedTime)
addVisitForSite(bookmarkSite, intoHistory: history, from: .local, atTime: modifiedTime)
addVisitForSite(bookmarkSite, intoHistory: history, from: .remote, atTime: modifiedTime)
let pageA = PageMetadata(id: nil, siteURL: bookmarkSite.url, mediaURL: "http://image.com",
title: bookmarkSite.title, description: "Test Description", type: nil, providerName: nil)
metadata.storeMetadata(pageA, forPageURL: bookmarkSite.url.asURL!, expireAt: Date.now() + 3000).succeeded()
bookmarks.local.addToMobileBookmarks(URL(string:"http://bookmark-\(i)/")!, title: "\(i) Bookmark", favicon: nil).succeeded()
}
}
| a9bcccb1bd4a0308d7461d3611b29bd9 | 45.03003 | 177 | 0.664927 | false | true | false | false |
lllyyy/LY | refs/heads/master | U17-master/U17/U17/Component/SnapKitExtension/ConstraintArray+Extensions.swift | mit | 1 | //
// ConstraintArray+Extensions.swift
// U17
//
// Created by charles on 2017/8/27.
// Copyright © 2017年 None. All rights reserved.
//
import SnapKit
public extension Array {
@available(*, deprecated:3.0, message:"Use newer snp.* syntax.")
public func snp_prepareConstraints(_ closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] {
return self.snp.prepareConstraints(closure)
}
@available(*, deprecated:3.0, message:"Use newer snp.* syntax.")
public func snp_makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) {
self.snp.makeConstraints(closure)
}
@available(*, deprecated:3.0, message:"Use newer snp.* syntax.")
public func snp_remakeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) {
self.snp.remakeConstraints(closure)
}
@available(*, deprecated:3.0, message:"Use newer snp.* syntax.")
public func snp_updateConstraints(_ closure: (_ make: ConstraintMaker) -> Void) {
self.snp.updateConstraints(closure)
}
@available(*, deprecated:3.0, message:"Use newer snp.* syntax.")
public func snp_removeConstraints() {
self.snp.removeConstraints()
}
@available(*, deprecated:3.0, message:"Use newer snp.* syntax.")
public func snp_distributeViewsAlong(axisType: UILayoutConstraintAxis,
fixedSpacing: CGFloat,
leadSpacing: CGFloat = 0,
tailSpacing: CGFloat = 0) {
self.snp.distributeViewsAlong(axisType: axisType,
fixedSpacing: fixedSpacing,
leadSpacing: leadSpacing,
tailSpacing: tailSpacing)
}
@available(*, deprecated:3.0, message:"Use newer snp.* syntax.")
public func snp_distributeViewsAlong(axisType: UILayoutConstraintAxis,
fixedItemLength: CGFloat,
leadSpacing: CGFloat = 0,
tailSpacing: CGFloat = 0) {
self.snp.distributeViewsAlong(axisType: axisType,
fixedItemLength: fixedItemLength,
leadSpacing: leadSpacing,
tailSpacing: tailSpacing)
}
@available(*, deprecated:3.0, message:"Use newer snp.* syntax.")
public func snp_distributeSudokuViews(fixedItemWidth: CGFloat,
fixedItemHeight: CGFloat,
warpCount: Int,
edgeInset: UIEdgeInsets = UIEdgeInsets.zero) {
self.snp.distributeSudokuViews(fixedItemWidth: fixedItemWidth,
fixedItemHeight: fixedItemHeight,
warpCount: warpCount,
edgeInset: edgeInset)
}
@available(*, deprecated:3.0, message:"Use newer snp.* syntax.")
public func snp_distributeSudokuViews(fixedLineSpacing: CGFloat,
fixedInteritemSpacing: CGFloat,
warpCount: Int,
edgeInset: UIEdgeInsets = UIEdgeInsets.zero) {
self.snp.distributeSudokuViews(fixedLineSpacing: fixedLineSpacing,
fixedInteritemSpacing: fixedInteritemSpacing,
warpCount: warpCount,
edgeInset: edgeInset)
}
public var snp: ConstraintArrayDSL {
return ConstraintArrayDSL(array: self as? Array<ConstraintView> ?? [])
}
}
| aaf7a69284033f6904394fdcfb4ea91e | 40.351064 | 102 | 0.524312 | false | false | false | false |
therealbnut/swift | refs/heads/master | stdlib/public/core/ArrayBuffer.swift | apache-2.0 | 1 | //===--- ArrayBuffer.swift - Dynamic storage for Swift Array --------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This is the class that implements the storage and object management for
// Swift Array.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
internal typealias _ArrayBridgeStorage
= _BridgeStorage<_ContiguousArrayStorageBase, _NSArrayCore>
@_versioned
@_fixed_layout
internal struct _ArrayBuffer<Element> : _ArrayBufferProtocol {
/// Create an empty buffer.
internal init() {
_storage = _ArrayBridgeStorage(native: _emptyArrayStorage)
}
@_versioned // FIXME(abi): Used from tests
internal init(nsArray: _NSArrayCore) {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_storage = _ArrayBridgeStorage(objC: nsArray)
}
/// Returns an `_ArrayBuffer<U>` containing the same elements.
///
/// - Precondition: The elements actually have dynamic type `U`, and `U`
/// is a class or `@objc` existential.
internal func cast<U>(toBufferOf _: U.Type) -> _ArrayBuffer<U> {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_sanityCheck(_isClassOrObjCExistential(U.self))
return _ArrayBuffer<U>(storage: _storage)
}
/// The spare bits that are set when a native array needs deferred
/// element type checking.
internal var deferredTypeCheckMask: Int { return 1 }
/// Returns an `_ArrayBuffer<U>` containing the same elements,
/// deferring checking each element's `U`-ness until it is accessed.
///
/// - Precondition: `U` is a class or `@objc` existential derived from
/// `Element`.
internal func downcast<U>(
toBufferWithDeferredTypeCheckOf _: U.Type
) -> _ArrayBuffer<U> {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_sanityCheck(_isClassOrObjCExistential(U.self))
// FIXME: can't check that U is derived from Element pending
// <rdar://problem/20028320> generic metatype casting doesn't work
// _sanityCheck(U.self is Element.Type)
return _ArrayBuffer<U>(
storage: _ArrayBridgeStorage(
native: _native._storage, bits: deferredTypeCheckMask))
}
internal var needsElementTypeCheck: Bool {
// NSArray's need an element typecheck when the element type isn't AnyObject
return !_isNativeTypeChecked && !(AnyObject.self is Element.Type)
}
//===--- private --------------------------------------------------------===//
internal init(storage: _ArrayBridgeStorage) {
_storage = storage
}
internal var _storage: _ArrayBridgeStorage
}
extension _ArrayBuffer {
/// Adopt the storage of `source`.
internal init(_buffer source: NativeBuffer, shiftedToStartIndex: Int) {
_sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0")
_storage = _ArrayBridgeStorage(native: source._storage)
}
/// `true`, if the array is native and does not need a deferred type check.
internal var arrayPropertyIsNativeTypeChecked: Bool {
return _isNativeTypeChecked
}
/// Returns `true` iff this buffer's storage is uniquely-referenced.
internal mutating func isUniquelyReferenced() -> Bool {
if !_isClassOrObjCExistential(Element.self) {
return _storage.isUniquelyReferenced_native_noSpareBits()
}
return _storage.isUniquelyReferencedNative() && _isNative
}
/// Returns `true` iff this buffer's storage is either
/// uniquely-referenced or pinned.
internal mutating func isUniquelyReferencedOrPinned() -> Bool {
if !_isClassOrObjCExistential(Element.self) {
return _storage.isUniquelyReferencedOrPinned_native_noSpareBits()
}
return _storage.isUniquelyReferencedOrPinnedNative() && _isNative
}
/// Convert to an NSArray.
///
/// O(1) if the element type is bridged verbatim, O(*n*) otherwise.
@_versioned // FIXME(abi): Used from tests
internal func _asCocoaArray() -> _NSArrayCore {
return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative
}
/// If this buffer is backed by a uniquely-referenced mutable
/// `_ContiguousArrayBuffer` that can be grown in-place to allow the self
/// buffer store minimumCapacity elements, returns that buffer.
/// Otherwise, returns `nil`.
internal mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int)
-> NativeBuffer? {
if _fastPath(isUniquelyReferenced()) {
let b = _native
if _fastPath(b.capacity >= minimumCapacity) {
return b
}
}
return nil
}
internal mutating func isMutableAndUniquelyReferenced() -> Bool {
return isUniquelyReferenced()
}
internal mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool {
return isUniquelyReferencedOrPinned()
}
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
internal func requestNativeBuffer() -> NativeBuffer? {
if !_isClassOrObjCExistential(Element.self) {
return _native
}
return _fastPath(_storage.isNative) ? _native : nil
}
// We have two versions of type check: one that takes a range and the other
// checks one element. The reason for this is that the ARC optimizer does not
// handle loops atm. and so can get blocked by the presence of a loop (over
// the range). This loop is not necessary for a single element access.
@inline(never)
internal func _typeCheckSlowPath(_ index: Int) {
if _fastPath(_isNative) {
let element: AnyObject = cast(toBufferOf: AnyObject.self)._native[index]
_precondition(
element is Element,
"Down-casted Array element failed to match the target type")
}
else {
let ns = _nonNative
_precondition(
ns.objectAt(index) is Element,
"NSArray element failed to match the Swift Array Element type")
}
}
internal func _typeCheck(_ subRange: Range<Int>) {
if !_isClassOrObjCExistential(Element.self) {
return
}
if _slowPath(needsElementTypeCheck) {
// Could be sped up, e.g. by using
// enumerateObjectsAtIndexes:options:usingBlock: in the
// non-native case.
for i in CountableRange(subRange) {
_typeCheckSlowPath(i)
}
}
}
/// Copy the elements in `bounds` from this buffer into uninitialized
/// memory starting at `target`. Return a pointer "past the end" of the
/// just-initialized memory.
@discardableResult
internal func _copyContents(
subRange bounds: Range<Int>,
initializing target: UnsafeMutablePointer<Element>
) -> UnsafeMutablePointer<Element> {
_typeCheck(bounds)
if _fastPath(_isNative) {
return _native._copyContents(subRange: bounds, initializing: target)
}
let nonNative = _nonNative
let nsSubRange = SwiftShims._SwiftNSRange(
location: bounds.lowerBound,
length: bounds.upperBound - bounds.lowerBound)
let buffer = UnsafeMutableRawPointer(target).assumingMemoryBound(
to: AnyObject.self)
// Copies the references out of the NSArray without retaining them
nonNative.getObjects(buffer, range: nsSubRange)
// Make another pass to retain the copied objects
var result = target
for _ in CountableRange(bounds) {
result.initialize(to: result.pointee)
result += 1
}
return result
}
/// Returns a `_SliceBuffer` containing the given sub-range of elements in
/// `bounds` from this buffer.
internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> {
get {
_typeCheck(bounds)
if _fastPath(_isNative) {
return _native[bounds]
}
let boundsCount = bounds.count
if boundsCount == 0 {
return _SliceBuffer(
_buffer: _ContiguousArrayBuffer<Element>(),
shiftedToStartIndex: bounds.lowerBound)
}
// Look for contiguous storage in the NSArray
let nonNative = self._nonNative
let cocoa = _CocoaArrayWrapper(nonNative)
let cocoaStorageBaseAddress =
cocoa.contiguousStorage(Range(self.indices))
if let cocoaStorageBaseAddress = cocoaStorageBaseAddress {
let basePtr = UnsafeMutableRawPointer(cocoaStorageBaseAddress)
.assumingMemoryBound(to: Element.self)
return _SliceBuffer(
owner: nonNative,
subscriptBaseAddress: basePtr,
indices: bounds,
hasNativeBuffer: false)
}
// No contiguous storage found; we must allocate
let result = _ContiguousArrayBuffer<Element>(
_uninitializedCount: boundsCount, minimumCapacity: 0)
// Tell Cocoa to copy the objects into our storage
cocoa.buffer.getObjects(
UnsafeMutableRawPointer(result.firstElementAddress)
.assumingMemoryBound(to: AnyObject.self),
range: _SwiftNSRange(location: bounds.lowerBound, length: boundsCount))
return _SliceBuffer(
_buffer: result, shiftedToStartIndex: bounds.lowerBound)
}
set {
fatalError("not implemented")
}
}
/// A pointer to the first element.
///
/// - Precondition: The elements are known to be stored contiguously.
@_versioned
internal var firstElementAddress: UnsafeMutablePointer<Element> {
_sanityCheck(_isNative, "must be a native buffer")
return _native.firstElementAddress
}
internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? {
return _fastPath(_isNative) ? firstElementAddress : nil
}
/// The number of elements the buffer stores.
internal var count: Int {
@inline(__always)
get {
return _fastPath(_isNative) ? _native.count : _nonNative.count
}
set {
_sanityCheck(_isNative, "attempting to update count of Cocoa array")
_native.count = newValue
}
}
/// Traps if an inout violation is detected or if the buffer is
/// native and the subscript is out of range.
///
/// wasNative == _isNative in the absence of inout violations.
/// Because the optimizer can hoist the original check it might have
/// been invalidated by illegal user code.
internal func _checkInoutAndNativeBounds(_ index: Int, wasNative: Bool) {
_precondition(
_isNative == wasNative,
"inout rules were violated: the array was overwritten")
if _fastPath(wasNative) {
_native._checkValidSubscript(index)
}
}
// TODO: gyb this
/// Traps if an inout violation is detected or if the buffer is
/// native and typechecked and the subscript is out of range.
///
/// wasNativeTypeChecked == _isNativeTypeChecked in the absence of
/// inout violations. Because the optimizer can hoist the original
/// check it might have been invalidated by illegal user code.
internal func _checkInoutAndNativeTypeCheckedBounds(
_ index: Int, wasNativeTypeChecked: Bool
) {
_precondition(
_isNativeTypeChecked == wasNativeTypeChecked,
"inout rules were violated: the array was overwritten")
if _fastPath(wasNativeTypeChecked) {
_native._checkValidSubscript(index)
}
}
/// The number of elements the buffer can store without reallocation.
internal var capacity: Int {
return _fastPath(_isNative) ? _native.capacity : _nonNative.count
}
@_versioned
@inline(__always)
internal func getElement(_ i: Int, wasNativeTypeChecked: Bool) -> Element {
if _fastPath(wasNativeTypeChecked) {
return _nativeTypeChecked[i]
}
return unsafeBitCast(_getElementSlowPath(i), to: Element.self)
}
@_versioned
@inline(never)
internal func _getElementSlowPath(_ i: Int) -> AnyObject {
_sanityCheck(
_isClassOrObjCExistential(Element.self),
"Only single reference elements can be indexed here.")
let element: AnyObject
if _isNative {
// _checkInoutAndNativeTypeCheckedBounds does no subscript
// checking for the native un-typechecked case. Therefore we
// have to do it here.
_native._checkValidSubscript(i)
element = cast(toBufferOf: AnyObject.self)._native[i]
_precondition(
element is Element,
"Down-casted Array element failed to match the target type")
} else {
// ObjC arrays do their own subscript checking.
element = _nonNative.objectAt(i)
_precondition(
element is Element,
"NSArray element failed to match the Swift Array Element type")
}
return element
}
/// Get or set the value of the ith element.
internal subscript(i: Int) -> Element {
get {
return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked)
}
nonmutating set {
if _fastPath(_isNative) {
_native[i] = newValue
}
else {
var refCopy = self
refCopy.replaceSubrange(
i..<(i + 1),
with: 1,
elementsOf: CollectionOfOne(newValue))
}
}
}
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage. If no such storage exists, it is
/// created on-demand.
internal func withUnsafeBufferPointer<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
if _fastPath(_isNative) {
defer { _fixLifetime(self) }
return try body(
UnsafeBufferPointer(start: firstElementAddress, count: count))
}
return try ContiguousArray(self).withUnsafeBufferPointer(body)
}
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
///
/// - Precondition: Such contiguous storage exists or the buffer is empty.
internal mutating func withUnsafeMutableBufferPointer<R>(
_ body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R {
_sanityCheck(
_isNative || count == 0,
"Array is bridging an opaque NSArray; can't get a pointer to the elements"
)
defer { _fixLifetime(self) }
return try body(UnsafeMutableBufferPointer(
start: firstElementAddressIfContiguous, count: count))
}
/// An object that keeps the elements stored in this buffer alive.
internal var owner: AnyObject {
return _fastPath(_isNative) ? _native._storage : _nonNative
}
/// An object that keeps the elements stored in this buffer alive.
///
/// - Precondition: This buffer is backed by a `_ContiguousArrayBuffer`.
internal var nativeOwner: AnyObject {
_sanityCheck(_isNative, "Expect a native array")
return _native._storage
}
/// A value that identifies the storage used by the buffer. Two
/// buffers address the same elements when they have the same
/// identity and count.
internal var identity: UnsafeRawPointer {
if _isNative {
return _native.identity
}
else {
return UnsafeRawPointer(Unmanaged.passUnretained(_nonNative).toOpaque())
}
}
//===--- Collection conformance -------------------------------------===//
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
internal var startIndex: Int {
return 0
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `index(after:)`.
internal var endIndex: Int {
return count
}
internal typealias Indices = CountableRange<Int>
//===--- private --------------------------------------------------------===//
internal typealias Storage = _ContiguousArrayStorage<Element>
internal typealias NativeBuffer = _ContiguousArrayBuffer<Element>
@_versioned
internal var _isNative: Bool {
if !_isClassOrObjCExistential(Element.self) {
return true
} else {
return _storage.isNative
}
}
/// `true`, if the array is native and does not need a deferred type check.
internal var _isNativeTypeChecked: Bool {
if !_isClassOrObjCExistential(Element.self) {
return true
} else {
return _storage.isNativeWithClearedSpareBits(deferredTypeCheckMask)
}
}
/// Our native representation.
///
/// - Precondition: `_isNative`.
@_versioned
internal var _native: NativeBuffer {
return NativeBuffer(
_isClassOrObjCExistential(Element.self)
? _storage.nativeInstance : _storage.nativeInstance_noSpareBits)
}
/// Fast access to the native representation.
///
/// - Precondition: `_isNativeTypeChecked`.
@_versioned
internal var _nativeTypeChecked: NativeBuffer {
return NativeBuffer(_storage.nativeInstance_noSpareBits)
}
@_versioned
internal var _nonNative: _NSArrayCore {
@inline(__always)
get {
_sanityCheck(_isClassOrObjCExistential(Element.self))
return _storage.objCInstance
}
}
}
#endif
| e7a2e5eed4d2de5041edf38220fafd0c | 31.971209 | 80 | 0.669228 | false | false | false | false |
SereivoanYong/Charts | refs/heads/master | Source/Charts/Highlight/RadarHighlighter.swift | apache-2.0 | 1 | //
// RadarHighlighter.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class RadarHighlighter: PieRadarHighlighter
{
open override func closestHighlight(index: Int, x: CGFloat, y: CGFloat) -> Highlight?
{
guard let chart = self.chart as? RadarChartView
else { return nil }
let highlights = getHighlights(forIndex: index)
let distanceToCenter = chart.distanceToCenter(x: x, y: y) / chart.factor
var closest: Highlight? = nil
var distance = CGFloat.greatestFiniteMagnitude
for high in highlights
{
let cdistance = abs(high.y - distanceToCenter)
if cdistance < distance
{
closest = high
distance = cdistance
}
}
return closest
}
/// - returns: An array of Highlight objects for the given index.
/// The Highlight objects give information about the value at the selected index and DataSet it belongs to.
///
/// - parameter index:
internal func getHighlights(forIndex index: Int) -> [Highlight]
{
var vals = [Highlight]()
guard let chart = self.chart as? RadarChartView
else { return vals }
let phaseX = chart.animator.phaseX
let phaseY = chart.animator.phaseY
let sliceangle = chart.sliceAngle
let factor = chart.factor
for i in 0..<(chart.data?.dataSets.count ?? 0)
{
guard let dataSet = chart.data?.getDataSetByIndex(i)
else { continue }
let entry = dataSet.entries[index]
let y = (entry.y - chart.chartYMin)
let p = ChartUtils.getPosition(
center: chart.centerOffsets,
dist: y * factor * phaseY,
angle: sliceangle * CGFloat(index) * phaseX + chart.rotationAngle)
vals.append(Highlight(x: CGFloat(index), y: entry.y, xPx: p.x, yPx: p.y, dataSetIndex: i, axis: dataSet.axisDependency))
}
return vals
}
}
| 0df5a25e70775e9933b12b5170806a8a | 29.597403 | 132 | 0.568761 | false | false | false | false |
ExTEnS10N/The-Month | refs/heads/master | 月历/NSDateExtension.swift | gpl-2.0 | 1 | //
// NSDateExtension.swift
// The Month
//
// Created by macsjh on 15/10/19.
// Copyright © 2015年 TurboExtension. All rights reserved.
//
import Foundation
extension NSDate
{
var year:Int?
{
get
{
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy"
let yearString = formatter.stringFromDate(self)
return NSNumberFormatter().numberFromString(yearString)?.integerValue
}
}
var month:Int?
{
get
{
let formatter = NSDateFormatter()
formatter.dateFormat = "MM"
let monthString = formatter.stringFromDate(self)
return NSNumberFormatter().numberFromString(monthString)?.integerValue
}
}
var dayOfMonth:Int?
{
get
{
let formatter = NSDateFormatter()
formatter.dateFormat = "dd"
let dayString = formatter.stringFromDate(self)
return NSNumberFormatter().numberFromString(dayString)?.integerValue
}
}
var dayOfWeek:Int?
{
get
{
let formatter = NSDateFormatter()
formatter.dateFormat = "e"
let dayString = formatter.stringFromDate(self)
return NSNumberFormatter().numberFromString(dayString)?.integerValue
}
}
var hour:Int?
{
get
{
let formatter = NSDateFormatter()
formatter.dateFormat = "HH"
let hourString = formatter.stringFromDate(self)
return NSNumberFormatter().numberFromString(hourString)?.integerValue
}
}
var minute:Int?
{
get
{
let formatter = NSDateFormatter()
formatter.dateFormat = "mm"
let minuteString = formatter.stringFromDate(self)
return NSNumberFormatter().numberFromString(minuteString)?.integerValue
}
}
var second:Int?
{
get
{
let formatter = NSDateFormatter()
formatter.dateFormat = "mm"
let secondString = formatter.stringFromDate(self)
return NSNumberFormatter().numberFromString(secondString)?.integerValue
}
}
func dateStringByFormat(format:String)->String?
{
let formatter = NSDateFormatter()
formatter.dateFormat = format
return formatter.stringFromDate(self)
}
var firstDayOfMonth:NSDate?
{
get
{
var exceptDayFormat = ""
if(self.year != nil)
{
exceptDayFormat += "yyyy/"
}
if (self.month != nil)
{
exceptDayFormat += "MM/"
}
if (self.hour != nil)
{
exceptDayFormat += "HH/"
}
if (self.minute != nil)
{
exceptDayFormat += "mm/"
}
if (self.second != nil)
{
exceptDayFormat += "ss/"
}
let exceptDay = dateStringByFormat(exceptDayFormat)
let formatter = NSDateFormatter()
formatter.dateFormat = exceptDayFormat + "dd"
if(exceptDay != nil)
{
return formatter.dateFromString(exceptDay! + "01")
}
return nil
}
}
var lastDayOfMonth:NSDate?
{
get
{
if(self.month != nil)
{
var exceptMonthFormat = ""
if(self.year != nil)
{
exceptMonthFormat += "yyyy/"
}
if (self.dayOfMonth != nil)
{
exceptMonthFormat += "dd/"
}
if (self.hour != nil)
{
exceptMonthFormat += "HH/"
}
if (self.minute != nil)
{
exceptMonthFormat += "mm/"
}
if (self.second != nil)
{
exceptMonthFormat += "ss/"
}
let exceptDay = dateStringByFormat(exceptMonthFormat)
let formatter = NSDateFormatter()
formatter.dateFormat = exceptMonthFormat + "MM"
if(exceptDay != nil)
{
let nextMonth = formatter.dateFromString(exceptDay! + "\(self.month!)")
if(nextMonth != nil)
{
return NSDate(timeInterval: -24*60*60, sinceDate: nextMonth!.firstDayOfMonth!)
}
}
}
return nil
}
}
}
| c2be2340e8ee85b1ef8dcda9e68e1945 | 18.786517 | 84 | 0.647076 | false | false | false | false |
VladiMihaylenko/omim | refs/heads/master | iphone/Maps/Bookmarks/Catalog/DownloadedBookmarksViewController.swift | apache-2.0 | 1 | class DownloadedBookmarksViewController: MWMViewController {
@IBOutlet var bottomView: UIView!
@IBOutlet weak var noDataView: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var bottomViewTitleLabel: UILabel! {
didSet {
bottomViewTitleLabel.text = L("guides_catalogue_title").uppercased()
}
}
@IBOutlet weak var bottomViewDownloadButton: UIButton! {
didSet {
bottomViewDownloadButton.setTitle(L("download_guides").uppercased(), for: .normal)
}
}
@IBOutlet weak var noDataViewDownloadButton: UIButton! {
didSet {
noDataViewDownloadButton.setTitle(L("download_guides").uppercased(), for: .normal)
}
}
let dataSource = DownloadedBookmarksDataSource()
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = UIColor.pressBackground()
tableView.separatorColor = UIColor.blackDividers()
tableView.tableHeaderView = bottomView
tableView.registerNib(cell: CatalogCategoryCell.self)
tableView.registerNibForHeaderFooterView(BMCCategoriesHeader.self)
if #available(iOS 11, *) { return } // workaround for https://jira.mail.ru/browse/MAPSME-8101
reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
reloadData()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
var f = bottomView.frame
let s = bottomView.systemLayoutSizeFitting(CGSize(width: tableView.width, height: 1),
withHorizontalFittingPriority: .required,
verticalFittingPriority: .defaultLow)
f.size = s
bottomView.frame = f
tableView.refresh()
}
@IBAction func onDownloadBookmarks(_ sender: Any) {
if MWMPlatform.networkConnectionType() == .none {
MWMAlertViewController.activeAlert().presentNoConnectionAlert();
Statistics.logEvent("Bookmarks_Downloaded_Catalogue_error",
withParameters: [kStatError : "no_internet"])
return
}
Statistics.logEvent(kStatCatalogOpen, withParameters: [kStatFrom: kStatDownloaded])
let webViewController = CatalogWebViewController.catalogFromAbsoluteUrl(nil, utm: .bookmarksPageCatalogButton)
MapViewController.topViewController().navigationController?.pushViewController(webViewController,
animated: true)
}
private func reloadData() {
dataSource.reloadData()
noDataView.isHidden = dataSource.categoriesCount > 0
tableView.reloadData()
}
private func setCategoryVisible(_ visible: Bool, at index: Int) {
dataSource.setCategory(visible: visible, at: index)
if let categoriesHeader = tableView.headerView(forSection: 0) as? BMCCategoriesHeader {
categoriesHeader.isShowAll = dataSource.allCategoriesHidden
}
}
private func deleteCategory(at index: Int) {
guard index >= 0 && index < dataSource.categoriesCount else {
assertionFailure()
return
}
dataSource.deleteCategory(at: index)
if dataSource.categoriesCount > 0 {
tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
} else {
noDataView.isHidden = false
tableView.reloadData()
}
}
}
extension DownloadedBookmarksViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.categoriesCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(cell: CatalogCategoryCell.self, indexPath: indexPath)
cell.update(with: dataSource.category(at: indexPath.row), delegate: self)
return cell
}
}
extension DownloadedBookmarksViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 48
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterView(BMCCategoriesHeader.self)
headerView.isShowAll = dataSource.allCategoriesHidden
headerView.title = L("guides_groups_cached")
headerView.delegate = self
return headerView
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let category = dataSource.category(at: indexPath.row)
if let bmViewController = BookmarksVC(category: category.categoryId) {
MapViewController.topViewController().navigationController?.pushViewController(bmViewController,
animated: true)
}
}
}
extension DownloadedBookmarksViewController: CatalogCategoryCellDelegate {
func cell(_ cell: CatalogCategoryCell, didCheck visible: Bool) {
if let indexPath = tableView.indexPath(for: cell) {
setCategoryVisible(visible, at: indexPath.row)
}
}
func cell(_ cell: CatalogCategoryCell, didPress moreButton: UIButton) {
if let indexPath = tableView.indexPath(for: cell) {
let category = dataSource.category(at: indexPath.row)
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
if let ppc = actionSheet.popoverPresentationController {
ppc.sourceView = moreButton
ppc.sourceRect = moreButton.bounds
}
let showHide = L(category.isVisible ? "hide" : "show").capitalized
actionSheet.addAction(UIAlertAction(title: showHide, style: .default, handler: { _ in
self.setCategoryVisible(!category.isVisible, at: indexPath.row)
self.tableView.reloadRows(at: [indexPath], with: .none)
}))
let delete = L("delete").capitalized
let deleteAction = UIAlertAction(title: delete, style: .destructive, handler: { _ in
self.deleteCategory(at: indexPath.row)
})
actionSheet.addAction(deleteAction)
let cancel = L("cancel").capitalized
actionSheet.addAction(UIAlertAction(title: cancel, style: .cancel, handler: nil))
present(actionSheet, animated: true, completion: nil)
}
}
}
extension DownloadedBookmarksViewController: BMCCategoriesHeaderDelegate {
func visibilityAction(_ categoriesHeader: BMCCategoriesHeader) {
dataSource.allCategoriesHidden = !dataSource.allCategoriesHidden
tableView.reloadData()
}
}
| 09d45bebb2badb06d0353cecd0a3c672 | 37.523529 | 114 | 0.703924 | false | false | false | false |
ken0nek/swift | refs/heads/master | stdlib/public/core/String.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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 SwiftShims
// FIXME: complexity documentation for most of methods on String is ought to be
// qualified with "amortized" at least, as Characters are variable-length.
/// A Unicode string value.
///
/// A string is a series of characters, such as `"Swift"`. Strings in Swift are
/// Unicode correct, locale insensitive, and designed to be efficient. The
/// `String` type bridges with the Objective-C class `NSString` and offers
/// interoperability with C functions that works with strings.
///
/// You can create new strings using string literals or string interpolations.
/// A string literal is a series of characters enclosed in quotes.
///
/// let greeting = "Welcome!"
///
/// String interpolations are string literals that evaluate any included
/// expressions and convert the results to string form. String interpolations
/// are an easy way to build a string from multiple pieces. Wrap each
/// expression in a string interpolation in parentheses, prefixed by a
/// backslash.
///
/// let name = "Rosa"
/// let personalizedGreeting = "Welcome, \(name)!"
///
/// let price = 2
/// let number = 3
/// let cookiePrice = "\(number) cookies: $\(price * number)."
///
/// Combine strings using the concatenation operator (`+`).
///
/// let longerGreeting = greeting + " We're glad you're here!"
/// print(longerGreeting)
/// // Prints "Welcome! We're glad you're here!"
///
/// Modifying and Comparing Strings
/// ===============================
///
/// Strings always have value semantics. Modifying a copy of a string leaves
/// the original unaffected.
///
/// var otherGreeting = greeting
/// otherGreeting += " Have a nice time!"
/// print(otherGreeting)
/// // Prints "Welcome! Have a nice time!"
///
/// print(greeting)
/// // Prints "Welcome!"
///
/// Comparing strings for equality using the is-equal-to operator (`==`) or a
/// relational operator (like `<` and `>=`) is always performed using the
/// Unicode canonical representation. This means that different
/// representations of a string compare as being equal.
///
/// let cafe1 = "Cafe\u{301}"
/// let cafe2 = "Café"
/// print(cafe1 == cafe2)
/// // Prints "true"
///
/// The Unicode code point `"\u{301}"` modifies the preceding character to
/// include an accent, so `"e\u{301}"` has the same canonical representation
/// as the single Unicode code point `"é"`.
///
/// Basic string operations are not sensitive to locale settings. This ensures
/// that string comparisons and other operations always have a single, stable
/// result, allowing strings to be used as keys in `Dictionary` instances and
/// for other purposes.
///
/// Representing Strings: Views
/// ===========================
///
/// A string is not itself a collection. Instead, it has properties that
/// present its contents as meaningful collections. Each of these collections
/// is a particular type of *view* of the string's visible and data
/// representation.
///
/// To demonstrate the different views available for every string, the
/// following examples use this `String` instance:
///
/// let cafe = "Cafe\u{301} du 🌍"
/// print(cafe)
/// // Prints "Café du 🌍"
///
/// Character View
/// --------------
///
/// A string's `characters` property is a collection of *extended grapheme
/// clusters*, which approximate human-readable characters. Many individual
/// characters, such as "é", "김", and "🇮🇳", can be made up of multiple Unicode
/// code points. These code points are combined by Unicode's boundary
/// algorithms into extended grapheme clusters, represented by Swift's
/// `Character` type. Each element of the `characters` view is represented by
/// a `Character` instance.
///
/// print(cafe.characters.count)
/// // Prints "9"
/// print(Array(cafe.characters))
/// // Prints "["C", "a", "f", "é", " ", "d", "u", " ", "🌍"]"
///
/// Each visible character in the `cafe` string is a separate element of the
/// `characters` view.
///
/// Unicode Scalar View
/// -------------------
///
/// A string's `unicodeScalars` property is a collection of Unicode scalar
/// values, the 21-bit codes that are the basic unit of Unicode. Each scalar
/// value is represented by a `UnicodeScalar` instance and is equivalent to a
/// UTF-32 code unit.
///
/// print(cafe.unicodeScalars.count)
/// // Prints "10"
/// print(Array(cafe.unicodeScalars))
/// // Prints "["C", "a", "f", "e", "\u{0301}", " ", "d", "u", " ", "\u{0001F30D}"]"
/// print(cafe.unicodeScalars.map { $0.value })
/// // Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 127757]"
///
/// The `unicodeScalars` view's elements comprise each Unicode scalar value in
/// the `cafe` string. In particular, because `cafe` was declared using the
/// decomposed form of the `"é"` character, `unicodeScalars` contains the code
/// points for both the letter `"e"` (101) and the accent character `"´"`
/// (769).
///
/// UTF-16 View
/// -----------
///
/// A string's `utf16` property is a collection of UTF-16 code units, the
/// 16-bit encoding form of the string's Unicode scalar values. Each code unit
/// is stored as a `UInt16` instance.
///
/// print(cafe.utf16.count)
/// // Prints "11"
/// print(Array(cafe.utf16))
/// // Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 55356, 57101]"
///
/// The elements of the `utf16` view are the code units for the string when
/// encoded in UTF-16.
///
/// The elements of this collection match those accessed through indexed
/// `NSString` APIs.
///
/// let nscafe = cafe as NSString
/// print(nscafe.length)
/// // Prints "11"
/// print(nscafe.character(at: 3))
/// // Prints "101"
///
/// UTF-8 View
/// ----------
///
/// A string's `utf8` property is a collection of UTF-8 code units, the 8-bit
/// encoding form of the string's Unicode scalar values. Each code unit is
/// stored as a `UInt8` instance.
///
/// print(cafe.utf8.count)
/// // Prints "14"
/// print(Array(cafe.utf8))
/// // Prints "[67, 97, 102, 101, 204, 129, 32, 100, 117, 32, 240, 159, 140, 141]"
///
/// The elements of the `utf8` view are the code units for the string when
/// encoded in UTF-8. This representation matches the one used when `String`
/// instances are passed to C APIs.
///
/// let cLength = strlen(cafe)
/// print(cLength)
/// // Prints "14"
///
/// Counting the Length of a String
/// ===============================
///
/// When you need to know the length of a string, you must first consider what
/// you'll use the length for. Are you measuring the number of characters that
/// will be displayed on the screen, or are you measuring the amount of
/// storage needed for the string in a particular encoding? A single string
/// can have greatly differing lengths when measured by its different views.
///
/// For example, an ASCII character like the capital letter *A* is represented
/// by a single element in each of its four views. The Unicode scalar value of
/// *A* is `65`, which is small enough to fit in a single code unit in both
/// UTF-16 and UTF-8.
///
/// let capitalA = "A"
/// print(capitalA.characters.count)
/// // Prints "1"
/// print(capitalA.unicodeScalars.count)
/// // Prints "1"
/// print(capitalA.utf16.count)
/// // Prints "1"
/// print(capitalA.utf8.count)
/// // Prints "1"
///
///
/// On the other hand, an emoji flag character is constructed from a pair of
/// Unicode scalars values, like `"\u{1F1F5}"` and `"\u{1F1F7}"`. Each of
/// these scalar values, in turn, is too large to fit into a single UTF-16 or
/// UTF-8 code unit. As a result, each view of the string `"🇵🇷"` reports a
/// different length.
///
/// let flag = "🇵🇷"
/// print(flag.characters.count)
/// // Prints "1"
/// print(flag.unicodeScalars.count)
/// // Prints "2"
/// print(flag.utf16.count)
/// // Prints "4"
/// print(flag.utf8.count)
/// // Prints "8"
///
/// Accessing String View Elements
/// ==============================
///
/// To find individual elements of a string, use the appropriate view for your
/// task. For example, to retrieve the first word of a longer string, you can
/// search the `characters` view for a space and then create a new string from
/// a prefix of the `characters` view up to that point.
///
/// let name = "Marie Curie"
/// let firstSpace = name.characters.index(of: " ")!
/// let firstName = String(name.characters.prefix(upTo: firstSpace))
/// print(firstName)
/// // Prints "Marie"
///
/// You can convert an index into one of a string's views to an index into
/// another view.
///
/// let firstSpaceUTF8 = firstSpace.samePosition(in: name.utf8)
/// print(Array(name.utf8.prefix(upTo: firstSpaceUTF8)))
/// // Prints "[77, 97, 114, 105, 101]"
///
/// Performance Optimizations
/// =========================
///
/// Although strings in Swift have value semantics, strings use a copy-on-write
/// strategy to store their data in a buffer. This buffer can then be shared
/// by different copies of a string. A string's data is only copied lazily,
/// upon mutation, when more than one string instance is using the same
/// buffer. Therefore, the first in any sequence of mutating operations may
/// cost O(*n*) time and space.
///
/// When a string's contiguous storage fills up, a new buffer must be allocated
/// and data must be moved to the new storage. String buffers use an
/// exponential growth strategy that makes appending to a string a constant
/// time operation when averaged over many append operations.
///
/// Bridging between String and NSString
/// ====================================
///
/// Any `String` instance can be bridged to `NSString` using the type-cast
/// operator (`as`), and any `String` instance that originates in Objective-C
/// may use an `NSString` instance as its storage. Because any arbitrary
/// subclass of `NSString` can become a `String` instance, there are no
/// guarantees about representation or efficiency when a `String` instance is
/// backed by `NSString` storage. Because `NSString` is immutable, it is just
/// as though the storage was shared by a copy: The first in any sequence of
/// mutating operations causes elements to be copied into unique, contiguous
/// storage which may cost O(*n*) time and space, where *n* is the length of
/// the string's encoded representation (or more, if the underlying `NSString`
/// has unusual performance characteristics).
///
/// For more information about the Unicode terms used in this discussion, see
/// the [Unicode.org glossary][glossary]. In particular, this discussion
/// mentions [extended grapheme clusters][clusters],
/// [Unicode scalar values][scalars], and [canonical equivalence][equivalence].
///
/// [glossary]: http://www.unicode.org/glossary/
/// [clusters]: http://www.unicode.org/glossary/#extended_grapheme_cluster
/// [scalars]: http://www.unicode.org/glossary/#unicode_scalar_value
/// [equivalence]: http://www.unicode.org/glossary/#canonical_equivalent
///
/// - SeeAlso: `String.CharacterView`, `String.UnicodeScalarView`,
/// `String.UTF16View`, `String.UTF8View`
@_fixed_layout
public struct String {
/// Creates an empty string.
public init() {
_core = _StringCore()
}
public // @testable
init(_ _core: _StringCore) {
self._core = _core
}
public // @testable
var _core: _StringCore
}
extension String {
public // @testable
static func _fromWellFormedCodeUnitSequence<
Encoding: UnicodeCodec, Input: Collection
where Input.Iterator.Element == Encoding.CodeUnit
>(
_ encoding: Encoding.Type, input: Input
) -> String {
return String._fromCodeUnitSequence(encoding, input: input)!
}
public // @testable
static func _fromCodeUnitSequence<
Encoding: UnicodeCodec, Input: Collection
where Input.Iterator.Element == Encoding.CodeUnit
>(
_ encoding: Encoding.Type, input: Input
) -> String? {
let (stringBufferOptional, _) =
_StringBuffer.fromCodeUnits(input, encoding: encoding,
repairIllFormedSequences: false)
if let stringBuffer = stringBufferOptional {
return String(_storage: stringBuffer)
} else {
return nil
}
}
public // @testable
static func _fromCodeUnitSequenceWithRepair<
Encoding: UnicodeCodec, Input: Collection
where Input.Iterator.Element == Encoding.CodeUnit
>(
_ encoding: Encoding.Type, input: Input
) -> (String, hadError: Bool) {
let (stringBuffer, hadError) =
_StringBuffer.fromCodeUnits(input, encoding: encoding,
repairIllFormedSequences: true)
return (String(_storage: stringBuffer!), hadError)
}
}
extension String : _BuiltinUnicodeScalarLiteralConvertible {
@effects(readonly)
public // @testable
init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {
self = String._fromWellFormedCodeUnitSequence(
UTF32.self, input: CollectionOfOne(UInt32(value)))
}
}
extension String : UnicodeScalarLiteralConvertible {
/// Creates an instance initialized to the given Unicode scalar value.
///
/// Don't call this initializer directly. It may be used by the compiler when
/// you initialize a string using a string literal that contains a single
/// Unicode scalar value.
public init(unicodeScalarLiteral value: String) {
self = value
}
}
extension String : _BuiltinExtendedGraphemeClusterLiteralConvertible {
@effects(readonly)
@_semantics("string.makeUTF8")
public init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1) {
self = String._fromWellFormedCodeUnitSequence(
UTF8.self,
input: UnsafeBufferPointer(
start: UnsafeMutablePointer<UTF8.CodeUnit>(start),
count: Int(utf8CodeUnitCount)))
}
}
extension String : ExtendedGraphemeClusterLiteralConvertible {
/// Creates an instance initialized to the given extended grapheme cluster
/// literal.
///
/// Don't call this initializer directly. It may be used by the compiler when
/// you initialize a string using a string literal containing a single
/// extended grapheme cluster.
public init(extendedGraphemeClusterLiteral value: String) {
self = value
}
}
extension String : _BuiltinUTF16StringLiteralConvertible {
@effects(readonly)
@_semantics("string.makeUTF16")
public init(
_builtinUTF16StringLiteral start: Builtin.RawPointer,
utf16CodeUnitCount: Builtin.Word
) {
self = String(
_StringCore(
baseAddress: OpaquePointer(start),
count: Int(utf16CodeUnitCount),
elementShift: 1,
hasCocoaBuffer: false,
owner: nil))
}
}
extension String : _BuiltinStringLiteralConvertible {
@effects(readonly)
@_semantics("string.makeUTF8")
public init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1) {
if Bool(isASCII) {
self = String(
_StringCore(
baseAddress: OpaquePointer(start),
count: Int(utf8CodeUnitCount),
elementShift: 0,
hasCocoaBuffer: false,
owner: nil))
}
else {
self = String._fromWellFormedCodeUnitSequence(
UTF8.self,
input: UnsafeBufferPointer(
start: UnsafeMutablePointer<UTF8.CodeUnit>(start),
count: Int(utf8CodeUnitCount)))
}
}
}
extension String : StringLiteralConvertible {
/// Creates an instance initialized to the given string value.
///
/// Don't call this initializer directly. It is used by the compiler when you
/// initialize a string using a string literal. For example:
///
/// let nextStop = "Clark & Lake"
///
/// This assignment to the `nextStop` constant calls this string literal
/// initializer behind the scenes.
public init(stringLiteral value: String) {
self = value
}
}
extension String : CustomDebugStringConvertible {
/// A representation of the string that is suitable for debugging.
public var debugDescription: String {
var result = "\""
for us in self.unicodeScalars {
result += us.escaped(asASCII: false)
}
result += "\""
return result
}
}
extension String {
/// Returns the number of code units occupied by this string
/// in the given encoding.
func _encodedLength<
Encoding: UnicodeCodec
>(_ encoding: Encoding.Type) -> Int {
var codeUnitCount = 0
let output: (Encoding.CodeUnit) -> Void = { _ in codeUnitCount += 1 }
self._encode(encoding, output: output)
return codeUnitCount
}
// FIXME: this function does not handle the case when a wrapped NSString
// contains unpaired surrogates. Fix this before exposing this function as a
// public API. But it is unclear if it is valid to have such an NSString in
// the first place. If it is not, we should not be crashing in an obscure
// way -- add a test for that.
// Related: <rdar://problem/17340917> Please document how NSString interacts
// with unpaired surrogates
func _encode<
Encoding: UnicodeCodec
>(_ encoding: Encoding.Type, output: @noescape (Encoding.CodeUnit) -> Void)
{
return _core.encode(encoding, output: output)
}
}
#if _runtime(_ObjC)
/// Compare two strings using the Unicode collation algorithm in the
/// deterministic comparison mode. (The strings which are equivalent according
/// to their NFD form are considered equal. Strings which are equivalent
/// according to the plain Unicode collation algorithm are additionally ordered
/// based on their NFD.)
///
/// See Unicode Technical Standard #10.
///
/// The behavior is equivalent to `NSString.compare()` with default options.
///
/// - returns:
/// * an unspecified value less than zero if `lhs < rhs`,
/// * zero if `lhs == rhs`,
/// * an unspecified value greater than zero if `lhs > rhs`.
@_silgen_name("swift_stdlib_compareNSStringDeterministicUnicodeCollation")
public func _stdlib_compareNSStringDeterministicUnicodeCollation(
_ lhs: AnyObject, _ rhs: AnyObject
) -> Int32
@_silgen_name("swift_stdlib_compareNSStringDeterministicUnicodeCollationPtr")
public func _stdlib_compareNSStringDeterministicUnicodeCollationPointer(
_ lhs: OpaquePointer, _ rhs: OpaquePointer
) -> Int32
#endif
extension String : Equatable {
}
public func ==(lhs: String, rhs: String) -> Bool {
if lhs._core.isASCII && rhs._core.isASCII {
if lhs._core.count != rhs._core.count {
return false
}
return _swift_stdlib_memcmp(
lhs._core.startASCII, rhs._core.startASCII,
rhs._core.count) == 0
}
return lhs._compareString(rhs) == 0
}
extension String : Comparable {
}
extension String {
#if _runtime(_ObjC)
/// This is consistent with Foundation, but incorrect as defined by Unicode.
/// Unicode weights some ASCII punctuation in a different order than ASCII
/// value. Such as:
///
/// 0022 ; [*02FF.0020.0002] # QUOTATION MARK
/// 0023 ; [*038B.0020.0002] # NUMBER SIGN
/// 0025 ; [*038C.0020.0002] # PERCENT SIGN
/// 0026 ; [*0389.0020.0002] # AMPERSAND
/// 0027 ; [*02F8.0020.0002] # APOSTROPHE
///
/// - Precondition: Both `self` and `rhs` are ASCII strings.
public // @testable
func _compareASCII(_ rhs: String) -> Int {
var compare = Int(_swift_stdlib_memcmp(
self._core.startASCII, rhs._core.startASCII,
min(self._core.count, rhs._core.count)))
if compare == 0 {
compare = self._core.count - rhs._core.count
}
// This efficiently normalizes the result to -1, 0, or 1 to match the
// behavior of NSString's compare function.
return (compare > 0 ? 1 : 0) - (compare < 0 ? 1 : 0)
}
#endif
/// Compares two strings with the Unicode Collation Algorithm.
@inline(never)
@_semantics("stdlib_binary_only") // Hide the CF/ICU dependency
public // @testable
func _compareDeterministicUnicodeCollation(_ rhs: String) -> Int {
// Note: this operation should be consistent with equality comparison of
// Character.
#if _runtime(_ObjC)
if self._core.hasContiguousStorage && rhs._core.hasContiguousStorage {
let lhsStr = _NSContiguousString(self._core)
let rhsStr = _NSContiguousString(rhs._core)
let res = lhsStr._unsafeWithNotEscapedSelfPointerPair(rhsStr) {
return Int(
_stdlib_compareNSStringDeterministicUnicodeCollationPointer($0, $1))
}
return res
}
return Int(_stdlib_compareNSStringDeterministicUnicodeCollation(
_bridgeToObjectiveCImpl(), rhs._bridgeToObjectiveCImpl()))
#else
switch (_core.isASCII, rhs._core.isASCII) {
case (true, false):
let lhsPtr = UnsafePointer<Int8>(_core.startASCII)
let rhsPtr = UnsafePointer<UTF16.CodeUnit>(rhs._core.startUTF16)
return Int(_swift_stdlib_unicode_compare_utf8_utf16(
lhsPtr, Int32(_core.count), rhsPtr, Int32(rhs._core.count)))
case (false, true):
// Just invert it and recurse for this case.
return -rhs._compareDeterministicUnicodeCollation(self)
case (false, false):
let lhsPtr = UnsafePointer<UTF16.CodeUnit>(_core.startUTF16)
let rhsPtr = UnsafePointer<UTF16.CodeUnit>(rhs._core.startUTF16)
return Int(_swift_stdlib_unicode_compare_utf16_utf16(
lhsPtr, Int32(_core.count),
rhsPtr, Int32(rhs._core.count)))
case (true, true):
let lhsPtr = UnsafePointer<Int8>(_core.startASCII)
let rhsPtr = UnsafePointer<Int8>(rhs._core.startASCII)
return Int(_swift_stdlib_unicode_compare_utf8_utf8(
lhsPtr, Int32(_core.count),
rhsPtr, Int32(rhs._core.count)))
}
#endif
}
public // @testable
func _compareString(_ rhs: String) -> Int {
#if _runtime(_ObjC)
// We only want to perform this optimization on objc runtimes. Elsewhere,
// we will make it follow the unicode collation algorithm even for ASCII.
if (_core.isASCII && rhs._core.isASCII) {
return _compareASCII(rhs)
}
#endif
return _compareDeterministicUnicodeCollation(rhs)
}
}
public func <(lhs: String, rhs: String) -> Bool {
return lhs._compareString(rhs) < 0
}
// Support for copy-on-write
extension String {
/// Appends the given string to this string.
///
/// The following example builds a customized greeting by using the
/// `append(_:)` method:
///
/// var greeting = "Hello, "
/// if let name = getUserName() {
/// greeting.append(name)
/// } else {
/// greeting.append("friend")
/// }
/// print(greeting)
/// // Prints "Hello, friend"
///
/// - Parameter other: Another string.
public mutating func append(_ other: String) {
_core.append(other._core)
}
/// Appends the given Unicode scalar to the string.
///
/// - Parameter x: A Unicode scalar value.
///
/// - Complexity: Appending a Unicode scalar to a string averages to O(1)
/// over many additions.
public mutating func append(_ x: UnicodeScalar) {
_core.append(x)
}
public // SPI(Foundation)
init(_storage: _StringBuffer) {
_core = _StringCore(_storage)
}
}
#if _runtime(_ObjC)
@_silgen_name("swift_stdlib_NSStringHashValue")
func _stdlib_NSStringHashValue(_ str: AnyObject, _ isASCII: Bool) -> Int
@_silgen_name("swift_stdlib_NSStringHashValuePointer")
func _stdlib_NSStringHashValuePointer(_ str: OpaquePointer, _ isASCII: Bool) -> Int
#endif
extension String : Hashable {
/// The string's hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
public var hashValue: Int {
#if _runtime(_ObjC)
// Mix random bits into NSString's hash so that clients don't rely on
// Swift.String.hashValue and NSString.hash being the same.
#if arch(i386) || arch(arm)
let hashOffset = Int(bitPattern: 0x88dd_cc21)
#else
let hashOffset = Int(bitPattern: 0x429b_1266_88dd_cc21)
#endif
// If we have a contiguous string then we can use the stack optimization.
let core = self._core
let isASCII = core.isASCII
if core.hasContiguousStorage {
let stackAllocated = _NSContiguousString(core)
return hashOffset ^ stackAllocated._unsafeWithNotEscapedSelfPointer {
return _stdlib_NSStringHashValuePointer($0, isASCII)
}
} else {
let cocoaString = unsafeBitCast(
self._bridgeToObjectiveCImpl(), to: _NSStringCore.self)
return hashOffset ^ _stdlib_NSStringHashValue(cocoaString, isASCII)
}
#else
if self._core.isASCII {
return _swift_stdlib_unicode_hash_ascii(
UnsafeMutablePointer<Int8>(_core.startASCII),
Int32(_core.count))
} else {
return _swift_stdlib_unicode_hash(
UnsafeMutablePointer<UInt16>(_core.startUTF16),
Int32(_core.count))
}
#endif
}
}
@effects(readonly)
@_semantics("string.concat")
public func + (lhs: String, rhs: String) -> String {
var lhs = lhs
if (lhs.isEmpty) {
return rhs
}
lhs._core.append(rhs._core)
return lhs
}
// String append
public func += (lhs: inout String, rhs: String) {
if lhs.isEmpty {
lhs = rhs
}
else {
lhs._core.append(rhs._core)
}
}
extension String {
/// Constructs a `String` in `resultStorage` containing the given UTF-8.
///
/// Low-level construction interface used by introspection
/// implementation in the runtime library.
@_silgen_name("swift_stringFromUTF8InRawMemory")
public // COMPILER_INTRINSIC
static func _fromUTF8InRawMemory(
_ resultStorage: UnsafeMutablePointer<String>,
start: UnsafeMutablePointer<UTF8.CodeUnit>,
utf8CodeUnitCount: Int
) {
resultStorage.initialize(with:
String._fromWellFormedCodeUnitSequence(
UTF8.self,
input: UnsafeBufferPointer(start: start, count: utf8CodeUnitCount)))
}
}
extension Sequence where Iterator.Element == String {
/// Returns a new string by concatenating the elements of the sequence,
/// adding the given separator between each element.
///
/// The following example shows how an array of strings can be joined to a
/// single, comma-separated string:
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let list = cast.joined(separator: ", ")
/// print(list)
/// // Prints "Vivien, Marlon, Kim, Karl"
///
/// - Parameter separator: A string to insert between each of the elements
/// in this sequence.
/// - Returns: A single, concatenated string.
public func joined(separator: String) -> String {
var result = ""
// FIXME(performance): this code assumes UTF-16 in-memory representation.
// It should be switched to low-level APIs.
let separatorSize = separator.utf16.count
let reservation = self._preprocessingPass {
() -> Int in
var r = 0
for chunk in self {
// FIXME(performance): this code assumes UTF-16 in-memory representation.
// It should be switched to low-level APIs.
r += separatorSize + chunk.utf16.count
}
return r - separatorSize
}
if let n = reservation {
result.reserveCapacity(n)
}
if separatorSize == 0 {
for x in self {
result.append(x)
}
return result
}
var iter = makeIterator()
if let first = iter.next() {
result.append(first)
while let next = iter.next() {
result.append(separator)
result.append(next)
}
}
return result
}
}
#if _runtime(_ObjC)
@_silgen_name("swift_stdlib_NSStringLowercaseString")
func _stdlib_NSStringLowercaseString(_ str: AnyObject) -> _CocoaString
@_silgen_name("swift_stdlib_NSStringUppercaseString")
func _stdlib_NSStringUppercaseString(_ str: AnyObject) -> _CocoaString
#else
internal func _nativeUnicodeLowercaseString(_ str: String) -> String {
var buffer = _StringBuffer(
capacity: str._core.count, initialSize: str._core.count, elementWidth: 2)
// Try to write it out to the same length.
let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start)
let z = _swift_stdlib_unicode_strToLower(
dest, Int32(str._core.count),
str._core.startUTF16, Int32(str._core.count))
let correctSize = Int(z)
// If more space is needed, do it again with the correct buffer size.
if correctSize != str._core.count {
buffer = _StringBuffer(
capacity: correctSize, initialSize: correctSize, elementWidth: 2)
let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start)
_swift_stdlib_unicode_strToLower(
dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count))
}
return String(_storage: buffer)
}
internal func _nativeUnicodeUppercaseString(_ str: String) -> String {
var buffer = _StringBuffer(
capacity: str._core.count, initialSize: str._core.count, elementWidth: 2)
// Try to write it out to the same length.
let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start)
let z = _swift_stdlib_unicode_strToUpper(
dest, Int32(str._core.count),
str._core.startUTF16, Int32(str._core.count))
let correctSize = Int(z)
// If more space is needed, do it again with the correct buffer size.
if correctSize != str._core.count {
buffer = _StringBuffer(
capacity: correctSize, initialSize: correctSize, elementWidth: 2)
let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start)
_swift_stdlib_unicode_strToUpper(
dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count))
}
return String(_storage: buffer)
}
#endif
// Unicode algorithms
extension String {
// FIXME: implement case folding without relying on Foundation.
// <rdar://problem/17550602> [unicode] Implement case folding
/// A "table" for which ASCII characters need to be upper cased.
/// To determine which bit corresponds to which ASCII character, subtract 1
/// from the ASCII value of that character and divide by 2. The bit is set iff
/// that character is a lower case character.
internal var _asciiLowerCaseTable: UInt64 {
@inline(__always)
get {
return 0b0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000
}
}
/// The same table for upper case characters.
internal var _asciiUpperCaseTable: UInt64 {
@inline(__always)
get {
return 0b0000_0000_0000_0000_0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000
}
}
/// Returns a lowercase version of the string.
///
/// Here's an example of transforming a string to all lowercase letters.
///
/// let cafe = "Café 🍵"
/// print(cafe.lowercased())
/// // Prints "café 🍵"
///
/// - Returns: A lowercase copy of the string.
///
/// - Complexity: O(n)
public func lowercased() -> String {
if self._core.isASCII {
let count = self._core.count
let source = self._core.startASCII
let buffer = _StringBuffer(
capacity: count, initialSize: count, elementWidth: 1)
let dest = UnsafeMutablePointer<UInt8>(buffer.start)
for i in 0..<count {
// For each character in the string, we lookup if it should be shifted
// in our ascii table, then we return 0x20 if it should, 0x0 if not.
// This code is equivalent to:
// switch source[i] {
// case let x where (x >= 0x41 && x <= 0x5a):
// dest[i] = x &+ 0x20
// case let x:
// dest[i] = x
// }
let value = source[i]
let isUpper =
_asciiUpperCaseTable >>
UInt64(((value &- 1) & 0b0111_1111) >> 1)
let add = (isUpper & 0x1) << 5
// Since we are left with either 0x0 or 0x20, we can safely truncate to
// a UInt8 and add to our ASCII value (this will not overflow numbers in
// the ASCII range).
dest[i] = value &+ UInt8(truncatingBitPattern: add)
}
return String(_storage: buffer)
}
#if _runtime(_ObjC)
return _cocoaStringToSwiftString_NonASCII(
_stdlib_NSStringLowercaseString(self._bridgeToObjectiveCImpl()))
#else
return _nativeUnicodeLowercaseString(self)
#endif
}
/// Returns an uppercase version of the string.
///
/// The following example transforms a string to uppercase letters:
///
/// let cafe = "Café 🍵"
/// print(cafe.uppercased())
/// // Prints "CAFÉ 🍵"
///
/// - Returns: An uppercase copy of the string.
///
/// - Complexity: O(n)
public func uppercased() -> String {
if self._core.isASCII {
let count = self._core.count
let source = self._core.startASCII
let buffer = _StringBuffer(
capacity: count, initialSize: count, elementWidth: 1)
let dest = UnsafeMutablePointer<UInt8>(buffer.start)
for i in 0..<count {
// See the comment above in lowercaseString.
let value = source[i]
let isLower =
_asciiLowerCaseTable >>
UInt64(((value &- 1) & 0b0111_1111) >> 1)
let add = (isLower & 0x1) << 5
dest[i] = value &- UInt8(truncatingBitPattern: add)
}
return String(_storage: buffer)
}
#if _runtime(_ObjC)
return _cocoaStringToSwiftString_NonASCII(
_stdlib_NSStringUppercaseString(self._bridgeToObjectiveCImpl()))
#else
return _nativeUnicodeUppercaseString(self)
#endif
}
}
extension String {
@available(*, unavailable, renamed: "append")
public mutating func appendContentsOf(_ other: String) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "append(contentsOf:)")
public mutating func appendContentsOf<
S : Sequence where S.Iterator.Element == Character
>(_ newElements: S) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "insert(contentsOf:at:)")
public mutating func insertContentsOf<
S : Collection where S.Iterator.Element == Character
>(_ newElements: S, at i: Index) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "replaceSubrange")
public mutating func replaceRange<
C : Collection where C.Iterator.Element == Character
>(
_ subRange: Range<Index>, with newElements: C
) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "replaceSubrange")
public mutating func replaceRange(
_ subRange: Range<Index>, with newElements: String
) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "removeAt")
public mutating func removeAtIndex(_ i: Index) -> Character {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "removeSubrange")
public mutating func removeRange(_ subRange: Range<Index>) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "lowercased()")
public var lowercaseString: String {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "uppercased()")
public var uppercaseString: String {
Builtin.unreachable()
}
}
extension Sequence where Iterator.Element == String {
@available(*, unavailable, renamed: "joined")
public func joinWithSeparator(_ separator: String) -> String {
Builtin.unreachable()
}
}
| 29d58a5036c3048dfb4146a37a9962b7 | 33.337838 | 94 | 0.662 | false | false | false | false |
katallaxie/cordova-plugin-ios-document-preview | refs/heads/master | src/ios/iOSDocumentPreview.swift | mit | 1 | import Foundation
@objc(CDViOSDocumentPreview) class iOSDocumentPreview : CDVPlugin, UIDocumentInteractionControllerDelegate {
func open(command: CDVInvokedUrlCommand) {
// run on the background thread
// force type casting of AnyObject
var file = command.arguments[0] as! String
var type = command.arguments[1] as! String
var result: CDVPluginResult?
dispatch_async(dispatch_get_main_queue()) {
// using print; faster then NSLog
print("Looking for \(file) in ")
let documentPath = NSBundle.mainBundle().pathForResource("friedman53", ofType: "pdf")
let documentURL = NSURL(fileURLWithPath: documentPath!, isDirectory: false)
let documentController = UIDocumentInteractionController(URL: documentURL)
documentController.delegate = self
let wasOpen = documentController.presentPreviewAnimated(true)
if (wasOpen) {
result = CDVPluginResult(status: CDVCommandStatus_OK, messageAsBool: true)
} else {
result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsBool: false)
}
self.commandDelegate?.sendPluginResult(result, callbackId: command.callbackId)
}
// dispatch_async(dispatch_get_main_queue(), ^{
// // TODO: test if this is a URI or a path
// NSURL *fileURL = [NSURL URLWithString:path];
//
// localFile = fileURL.path;
//
// NSLog(@"looking for file at %@", fileURL);
// NSFileManager *fm = [NSFileManager defaultManager];
// if(![fm fileExistsAtPath:localFile]) {
// NSDictionary *jsonObj = @{@"status" : @"9",
// @"message" : @"File does not exist"};
// CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR
// messageAsDictionary:jsonObj];
// [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
// return;
// }
}
func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
return self.viewController!
}
}
| fb9fb2f4e09441375b9619421c72ca60 | 41.526316 | 129 | 0.593234 | false | false | false | false |
carsonmcdonald/PlaygroundExplorer | refs/heads/master | PlaygroundExplorer/PlaygroundEntryData.swift | mit | 1 | import Foundation
struct PlaygroundEntryRepoData {
var commitDateTime: NSDate?
var commitHash: String?
var commitMessage: String?
}
class PlaygroundEntryData {
var ident: String!
var name: String!
var playgroundDir: String!
var author: String!
var longDescription: String!
var location: String!
var locationType: String!
var minXcodeVersion: XcodeVersion!
var moreInfoLink: String?
var tags: [String]?
var repoDataList: [PlaygroundEntryRepoData]?
init?(jsonData:NSDictionary) {
if jsonData["description"] == nil {
return nil
}
if jsonData["playground_dir"] == nil {
return nil
}
if jsonData["location"] == nil {
return nil
}
if jsonData["location_type"] == nil {
return nil
}
if jsonData["min_xcode_version"] == nil {
return nil
}
if jsonData["name"] == nil {
return nil
}
if jsonData["author"] == nil {
return nil
}
if jsonData["location"] == nil {
return nil
}
if let name = jsonData["name"] as! String! {
self.name = name
} else {
return nil
}
if let dir = jsonData["playground_dir"] as! String! {
self.playgroundDir = dir
} else {
return nil
}
if let author = jsonData["author"] as! String! {
self.author = author
} else {
return nil
}
if let longDescription = jsonData["description"] as! String! {
self.longDescription = longDescription
} else {
return nil
}
if let location = jsonData["location"] as! String! {
self.location = location
} else {
return nil
}
if let locationType = jsonData["location_type"] as! String! {
self.locationType = locationType
} else {
return nil
}
if let minXcodeVersion = jsonData["min_xcode_version"] as! String! {
self.minXcodeVersion = XcodeVersion(fromFullVersionString:minXcodeVersion)
} else {
return nil
}
self.moreInfoLink = jsonData["more_info_link"] as! String?
self.tags = jsonData["tags"] as! [String]?
self.ident = self.generateMD5Hash(self.location)
}
func tagsAsString() -> String {
if self.tags == nil {
return ""
} else {
return ", ".join(self.tags!)
}
}
func lastUpdatedTime() -> NSDate? {
if self.repoDataList != nil && self.repoDataList!.count > 0 {
return self.repoDataList![0].commitDateTime
}
return nil
}
private func generateMD5Hash(input:String) -> String {
let str = input.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CC_LONG(input.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!, strLen, result)
var hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.dealloc(digestLen)
return String(format: hash as String)
}
}
| 0fa2b302973bd73eec3966880e1041ed | 24.878571 | 86 | 0.518355 | false | false | false | false |
XSega/Words | refs/heads/master | Words/Scenes/Trainings/Old/ListeningTrainingPresenter.swift | mit | 1 | //
// EngRuTrainingPresenter.swift
// Words
//
// Created by Sergey Ilyushin on 24/07/2017.
// Copyright © 2017 Sergey Ilyushin. All rights reserved.
//
import Foundation
protocol IListeningTraining: class {
var mistakes: Int { get set }
var words: Int { get set }
func start()
func finish()
func checkTranslation(text: String)
func selectSkipAction()
}
class ListeningTrainingPresenter: IListeningTraining {
// MARK:- Public Vars
public var attemps: Int = 3
public var mistakes: Int = 0
public var words: Int = 0
public var meanings: [Meaning]!
weak var view: IListeningView!
// MARK:- Private vars
fileprivate var currentMeaningIndex: Int = 0
fileprivate var currentTranlsation: String = ""
// MARK:- Public func
func start() {
currentMeaningIndex = 0
attemps = 3
mistakes = 0
words = 1
displayPair()
}
func finish() {
currentMeaningIndex = 0
attemps = 3
view.finish()
}
func checkTranslation(text: String) {
let meaning = meanings[currentMeaningIndex]
if meaning.translation == currentTranlsation {
didCorrectSelection()
} else {
didWrongSelection()
}
}
func selectSkipAction() {
didWrongSelection()
}
// MARK: Private func
fileprivate func didCorrectSelection() {
attemps = min(attemps + 1, 3)
view?.displayCorrectAlert(attemps: attemps)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [unowned self] in
self.nextPair()
}
}
fileprivate func didWrongSelection() {
attemps -= 1
mistakes += 1
view?.displayWrongAlert(attemps: attemps)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [unowned self] in
guard self.attemps > 0 else {
self.finish()
return
}
self.nextPair()
}
}
fileprivate func nextPair() {
currentMeaningIndex += 1
words += 1
guard currentMeaningIndex < meanings.count else {
finish()
return
}
displayPair()
}
fileprivate func displayPair() {
let meaning = meanings[currentMeaningIndex]
currentTranlsation = meaning.randomTranslation()
view?.display(meaning: meaning.text, imageData: meaning.imageData, soundData: meaning.soundData)
}
}
| 0763686b37283656db389fc839ade138 | 22.816514 | 104 | 0.571263 | false | false | false | false |
zjjzmw1/SwiftCodeFragments | refs/heads/master | Pods/ImageViewer/ImageViewer/Source/ItemBaseController.swift | mit | 1 | //
// ItemBaseController.swift
// ImageViewer
//
// Created by Kristian Angyal on 01/08/2016.
// Copyright © 2016 MailOnline. All rights reserved.
//
import UIKit
public protocol ItemView {
var image: UIImage? { get set }
}
class ItemBaseController<T: UIView>: UIViewController, ItemController, UIGestureRecognizerDelegate, UIScrollViewDelegate where T: ItemView {
//UI
var itemView = T()
let scrollView = UIScrollView()
//DELEGATE / DATASOURCE
weak var delegate: ItemControllerDelegate?
weak var displacedViewsDatasource: GalleryDisplacedViewsDatasource?
//STATE
let index: Int
var isInitialController = false
let itemCount: Int
var swipingToDismiss: SwipeToDismiss?
fileprivate var isAnimating = false
fileprivate var fetchImageBlock: FetchImageBlock
//CONFIGURATION
fileprivate var presentationStyle = GalleryPresentationStyle.displacement
fileprivate var doubleTapToZoomDuration = 0.15
fileprivate var displacementDuration: TimeInterval = 0.55
fileprivate var reverseDisplacementDuration: TimeInterval = 0.25
fileprivate var itemFadeDuration: TimeInterval = 0.3
fileprivate var displacementTimingCurve: UIViewAnimationCurve = .linear
fileprivate var displacementSpringBounce: CGFloat = 0.7
fileprivate let minimumZoomScale: CGFloat = 1
fileprivate var maximumZoomScale: CGFloat = 8
fileprivate var pagingMode: GalleryPagingMode = .standard
fileprivate var thresholdVelocity: CGFloat = 500 // The speed of swipe needs to be at least this amount of pixels per second for the swipe to finish dismissal.
fileprivate var displacementKeepOriginalInPlace = false
fileprivate var displacementInsetMargin: CGFloat = 50
/// INTERACTIONS
fileprivate let singleTapRecognizer = UITapGestureRecognizer()
fileprivate let doubleTapRecognizer = UITapGestureRecognizer()
fileprivate let swipeToDismissRecognizer = UIPanGestureRecognizer()
// TRANSITIONS
fileprivate var swipeToDismissTransition: GallerySwipeToDismissTransition?
// MARK: - Initializers
init(index: Int, itemCount: Int, fetchImageBlock: @escaping FetchImageBlock, configuration: GalleryConfiguration, isInitialController: Bool = false) {
self.index = index
self.itemCount = itemCount
self.isInitialController = isInitialController
self.fetchImageBlock = fetchImageBlock
for item in configuration {
switch item {
case .swipeToDismissThresholdVelocity(let velocity): thresholdVelocity = velocity
case .doubleTapToZoomDuration(let duration): doubleTapToZoomDuration = duration
case .presentationStyle(let style): presentationStyle = style
case .pagingMode(let mode): pagingMode = mode
case .displacementDuration(let duration): displacementDuration = duration
case .reverseDisplacementDuration(let duration): reverseDisplacementDuration = duration
case .displacementTimingCurve(let curve): displacementTimingCurve = curve
case .maximumZoolScale(let scale): maximumZoomScale = scale
case .itemFadeDuration(let duration): itemFadeDuration = duration
case .displacementKeepOriginalInPlace(let keep): displacementKeepOriginalInPlace = keep
case .displacementInsetMargin(let margin): displacementInsetMargin = margin
case .displacementTransitionStyle(let style):
switch style {
case .springBounce(let bounce): displacementSpringBounce = bounce
case .normal: displacementSpringBounce = 1
}
default: break
}
}
super.init(nibName: nil, bundle: nil)
self.modalPresentationStyle = .custom
self.itemView.isHidden = isInitialController
configureScrollView()
configureGestureRecognizers()
}
@available (*, unavailable)
required init?(coder aDecoder: NSCoder) { fatalError() }
deinit {
self.scrollView.removeObserver(self, forKeyPath: "contentOffset")
}
// MARK: - Configuration
fileprivate func configureScrollView() {
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.decelerationRate = UIScrollViewDecelerationRateFast
scrollView.contentInset = UIEdgeInsets.zero
scrollView.contentOffset = CGPoint.zero
scrollView.minimumZoomScale = minimumZoomScale
scrollView.maximumZoomScale = max(maximumZoomScale, aspectFillZoomScale(forBoundingSize: self.view.bounds.size, contentSize: itemView.bounds.size))
scrollView.delegate = self
scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil)
}
func configureGestureRecognizers() {
singleTapRecognizer.addTarget(self, action: #selector(scrollViewDidSingleTap))
singleTapRecognizer.numberOfTapsRequired = 1
scrollView.addGestureRecognizer(singleTapRecognizer)
doubleTapRecognizer.addTarget(self, action: #selector(scrollViewDidDoubleTap(_:)))
doubleTapRecognizer.numberOfTapsRequired = 2
scrollView.addGestureRecognizer(doubleTapRecognizer)
singleTapRecognizer.require(toFail: doubleTapRecognizer)
swipeToDismissRecognizer.addTarget(self, action: #selector(scrollViewDidSwipeToDismiss))
swipeToDismissRecognizer.delegate = self
view.addGestureRecognizer(swipeToDismissRecognizer)
}
fileprivate func createViewHierarchy() {
self.view.addSubview(scrollView)
scrollView.addSubview(itemView)
}
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
createViewHierarchy()
fetchImageBlock { [weak self] image in //DON'T Forget offloading the main thread
if let image = image {
self?.itemView.image = image
self?.view.setNeedsLayout()
self?.view.layoutIfNeeded()
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.delegate?.itemControllerWillAppear(self)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.delegate?.itemControllerDidAppear(self)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.delegate?.itemControllerWillDisappear(self)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.frame = self.view.bounds
if let size = itemView.image?.size , size != CGSize.zero {
let aspectFitItemSize = aspectFitSize(forContentOfSize: size, inBounds: self.scrollView.bounds.size)
itemView.bounds.size = aspectFitItemSize
scrollView.contentSize = itemView.bounds.size
itemView.center = scrollView.boundsCenter
}
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return itemView
}
// MARK: - Scroll View delegate methods
func scrollViewDidZoom(_ scrollView: UIScrollView) {
itemView.center = contentCenter(forBoundingSize: scrollView.bounds.size, contentSize: scrollView.contentSize)
}
func scrollViewDidSingleTap() {
self.delegate?.itemControllerDidSingleTap(self)
}
func scrollViewDidDoubleTap(_ recognizer: UITapGestureRecognizer) {
let touchPoint = recognizer.location(ofTouch: 0, in: itemView)
let aspectFillScale = aspectFillZoomScale(forBoundingSize: scrollView.bounds.size, contentSize: itemView.bounds.size)
if (scrollView.zoomScale == 1.0 || scrollView.zoomScale > aspectFillScale) {
let zoomRectangle = zoomRect(ForScrollView: scrollView, scale: aspectFillScale, center: touchPoint)
UIView.animate(withDuration: doubleTapToZoomDuration, animations: { [weak self] in
self?.scrollView.zoom(to: zoomRectangle, animated: false)
})
}
else {
UIView.animate(withDuration: doubleTapToZoomDuration, animations: { [weak self] in
self?.scrollView.setZoomScale(1.0, animated: false)
})
}
}
func scrollViewDidSwipeToDismiss(_ recognizer: UIPanGestureRecognizer) {
/// a swipe gesture on image view that has no image (it was not yet loaded,so we see a spinner) doesn't make sense
guard itemView.image != nil else { return }
/// A deliberate UX decision...you have to zoom back in to scale 1 to be able to swipe to dismiss. It is difficult for the user to swipe to dismiss from images larger then screen bounds because almost all the time it's not swiping to dismiss but instead panning a zoomed in picture on the canvas.
guard scrollView.zoomScale == scrollView.minimumZoomScale else { return }
let currentVelocity = recognizer.velocity(in: self.view)
let currentTouchPoint = recognizer.translation(in: view)
if swipingToDismiss == nil { swipingToDismiss = (fabs(currentVelocity.x) > fabs(currentVelocity.y)) ? .horizontal : .vertical }
guard let swipingToDismissInProgress = swipingToDismiss else { return }
switch recognizer.state {
case .began:
swipeToDismissTransition = GallerySwipeToDismissTransition(scrollView: self.scrollView)
case .changed:
self.handleSwipeToDismissInProgress(swipingToDismissInProgress, forTouchPoint: currentTouchPoint)
case .ended:
self.handleSwipeToDismissEnded(swipingToDismissInProgress, finalVelocity: currentVelocity, finalTouchPoint: currentTouchPoint)
default:
break
}
}
// MARK: - Swipe To Dismiss
func handleSwipeToDismissInProgress(_ swipeOrientation: SwipeToDismiss, forTouchPoint touchPoint: CGPoint) {
switch (swipeOrientation, index) {
case (.horizontal, 0) where self.itemCount != 1:
/// edge case horizontal first index - limits the swipe to dismiss to HORIZONTAL RIGHT direction.
swipeToDismissTransition?.updateInteractiveTransition(horizontalOffset: min(0, -touchPoint.x))
case (.horizontal, self.itemCount - 1) where self.itemCount != 1:
/// edge case horizontal last index - limits the swipe to dismiss to HORIZONTAL LEFT direction.
swipeToDismissTransition?.updateInteractiveTransition(horizontalOffset: max(0, -touchPoint.x))
case (.horizontal, _):
swipeToDismissTransition?.updateInteractiveTransition(horizontalOffset: -touchPoint.x) // all the rest
case (.vertical, _):
swipeToDismissTransition?.updateInteractiveTransition(verticalOffset: -touchPoint.y) // all the rest
}
}
func handleSwipeToDismissEnded(_ swipeOrientation: SwipeToDismiss, finalVelocity velocity: CGPoint, finalTouchPoint touchPoint: CGPoint) {
let maxIndex = self.itemCount - 1
let swipeToDismissCompletionBlock = { [weak self] in
UIApplication.applicationWindow.windowLevel = UIWindowLevelNormal
self?.swipingToDismiss = nil
self?.delegate?.itemControllerDidFinishSwipeToDismissSuccesfully()
}
switch (swipeOrientation, index) {
/// Any item VERTICAL UP direction
case (.vertical, _) where velocity.y < -thresholdVelocity:
swipeToDismissTransition?.finishInteractiveTransition(swipeOrientation,
touchPoint: touchPoint.y,
targetOffset: (view.bounds.height / 2) + (itemView.bounds.height / 2),
escapeVelocity: velocity.y,
completion: swipeToDismissCompletionBlock)
/// Any item VERTICAL DOWN direction
case (.vertical, _) where thresholdVelocity < velocity.y:
swipeToDismissTransition?.finishInteractiveTransition(swipeOrientation,
touchPoint: touchPoint.y,
targetOffset: -(view.bounds.height / 2) - (itemView.bounds.height / 2),
escapeVelocity: velocity.y,
completion: swipeToDismissCompletionBlock)
/// First item HORIZONTAL RIGHT direction
case (.horizontal, 0) where thresholdVelocity < velocity.x:
swipeToDismissTransition?.finishInteractiveTransition(swipeOrientation,
touchPoint: touchPoint.x,
targetOffset: -(view.bounds.width / 2) - (itemView.bounds.width / 2),
escapeVelocity: velocity.x,
completion: swipeToDismissCompletionBlock)
/// Last item HORIZONTAL LEFT direction
case (.horizontal, maxIndex) where velocity.x < -thresholdVelocity:
swipeToDismissTransition?.finishInteractiveTransition(swipeOrientation,
touchPoint: touchPoint.x,
targetOffset: (view.bounds.width / 2) + (itemView.bounds.width / 2),
escapeVelocity: velocity.x,
completion: swipeToDismissCompletionBlock)
///If nonoe of the above select cases, we cancel.
default:
swipeToDismissTransition?.cancelTransition() { [weak self] in
self?.swipingToDismiss = nil
}
}
}
func animateDisplacedImageToOriginalPosition(_ duration: TimeInterval, completion: ((Bool) -> Void)?) {
guard (self.isAnimating == false) else { return }
isAnimating = true
UIView.animate(withDuration: duration, animations: { [weak self] in
self?.scrollView.zoomScale = self!.scrollView.minimumZoomScale
if UIApplication.isPortraitOnly {
self?.itemView.transform = windowRotationTransform().inverted()
}
}, completion: { [weak self] finished in
completion?(finished)
if finished {
UIApplication.applicationWindow.windowLevel = UIWindowLevelNormal
self?.isAnimating = false
}
})
}
// MARK: - Present/Dismiss transitions
func presentItem(alongsideAnimation: () -> Void, completion: @escaping () -> Void) {
guard isAnimating == false else { return }
isAnimating = true
alongsideAnimation()
if var displacedView = displacedViewsDatasource?.provideDisplacementItem(atIndex: index),
let image = displacedView.image {
if presentationStyle == .displacement {
//Prepare the animated imageview
let animatedImageView = displacedView.imageView()
//rotate the imageview to starting angle
if UIApplication.isPortraitOnly == true {
animatedImageView.transform = deviceRotationTransform()
}
//position the image view to starting center
animatedImageView.center = displacedView.convertPoint(displacedView.boundsCenter, toView: self.view)
animatedImageView.clipsToBounds = true
self.view.addSubview(animatedImageView)
if displacementKeepOriginalInPlace == false {
displacedView.hidden = true
}
UIView.animate(withDuration: displacementDuration, delay: 0, usingSpringWithDamping: displacementSpringBounce, initialSpringVelocity: 1, options: .curveEaseIn, animations: { [weak self] in
if UIApplication.isPortraitOnly == true {
animatedImageView.transform = CGAffineTransform.identity
}
/// Animate it into the center (with optionaly rotating) - that basically includes changing the size and position
animatedImageView.bounds.size = self?.displacementTargetSize(forSize: image.size) ?? image.size
animatedImageView.center = self?.view.boundsCenter ?? CGPoint.zero
}, completion: { [weak self] _ in
self?.itemView.isHidden = false
displacedView.hidden = false
animatedImageView.removeFromSuperview()
self?.isAnimating = false
completion()
})
}
}
else {
itemView.alpha = 0
itemView.isHidden = false
UIView.animate(withDuration: itemFadeDuration, animations: { [weak self] in
self?.itemView.alpha = 1
}, completion: { [weak self] _ in
completion()
self?.isAnimating = false
})
}
}
func displacementTargetSize(forSize size: CGSize) -> CGSize {
let boundingSize = rotationAdjustedBounds().size
return aspectFitSize(forContentOfSize: size, inBounds: boundingSize)
}
func findVisibleDisplacedView() -> DisplaceableView? {
guard let displacedView = displacedViewsDatasource?.provideDisplacementItem(atIndex: index) else { return nil }
let displacedViewFrame = displacedView.frameInCoordinatesOfScreen()
let validAreaFrame = self.view.frame.insetBy(dx: displacementInsetMargin, dy: displacementInsetMargin)
let isVisibleEnough = displacedViewFrame.intersects(validAreaFrame)
return isVisibleEnough ? displacedView : nil
}
func dismissItem(alongsideAnimation: () -> Void, completion: @escaping () -> Void) {
guard isAnimating == false else { return }
isAnimating = true
alongsideAnimation()
switch presentationStyle {
case .displacement:
if var displacedView = self.findVisibleDisplacedView() {
if displacementKeepOriginalInPlace == false {
displacedView.hidden = true
}
UIView.animate(withDuration: reverseDisplacementDuration, animations: { [weak self] in
self?.scrollView.zoomScale = 1
//rotate the image view
self?.itemView.transform = deviceRotationTransform()
//position the image view to starting center
self?.itemView.bounds = displacedView.bounds
self?.itemView.center = displacedView.convertPoint(displacedView.boundsCenter, toView: self!.view)
self?.itemView.clipsToBounds = true
self?.itemView.contentMode = displacedView.contentMode
}, completion: { [weak self] _ in
self?.isAnimating = false
displacedView.hidden = false
completion()
})
}
else { fallthrough }
case .fade:
UIView.animate(withDuration: itemFadeDuration, animations: { [weak self] in
self?.itemView.alpha = 0
}, completion: { [weak self] _ in
self?.isAnimating = false
completion()
})
}
}
// MARK: - Arkane stuff
///This resolves which of the two pan gesture recognizers should kick in. There is one built in the GalleryViewController (as it is a UIPageViewController subclass), and another one is added as part of item controller. When we pan, we need to decide whether it constitutes a horizontal paging gesture, or a horizontal swipe-to-dismiss gesture.
/// All the logic is from the perspective of SwipeToDismissRecognizer - should it kick in (or let the paging recognizer page)?
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
/// We only care about the swipe to dismiss gesture recognizer, not the built-in pan recogizner that handles paging.
guard gestureRecognizer == swipeToDismissRecognizer else { return false }
/// The velocity vector will help us make the right decision
let velocity = swipeToDismissRecognizer.velocity(in: swipeToDismissRecognizer.view)
///A bit of paranoia
guard velocity.orientation != .none else { return false }
/// We continue if the swipe is horizontal, otherwise it's Vertical and it is swipe to dismiss.
guard velocity.orientation == .horizontal else { return true }
/// A special case for horizontal "swipe to dismiss" is when the gallery has carousel mode OFF, then it is possible to reach the beginning or the end of image set while paging. PAging will stop at index = 0 or at index.max. In this case we allow to jump out from the gallery also via horizontal swipe to dismiss.
if (self.index == 0 && velocity.direction == .right) || (self.index == self.itemCount - 1 && velocity.direction == .left) {
return (pagingMode == .standard)
}
return false
}
//Reports the continuous progress of Swipe To Dismiss to the Gallery View Controller
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let swipingToDissmissInProgress = swipingToDismiss else { return }
guard keyPath == "contentOffset" else { return }
let distanceToEdge: CGFloat
let percentDistance: CGFloat
switch swipingToDissmissInProgress {
case .horizontal:
distanceToEdge = (scrollView.bounds.width / 2) + (itemView.bounds.width / 2)
percentDistance = fabs(scrollView.contentOffset.x / distanceToEdge)
case .vertical:
distanceToEdge = (scrollView.bounds.height / 2) + (itemView.bounds.height / 2)
percentDistance = fabs(scrollView.contentOffset.y / distanceToEdge)
}
if let delegate = self.delegate {
delegate.itemController(self, didSwipeToDismissWithDistanceToEdge: percentDistance)
}
}
}
| 9f864c8e7d57fb6b68a722c37ae94222 | 39.157168 | 347 | 0.629306 | false | false | false | false |
waltflanagan/AdventOfCode | refs/heads/master | 2017/AdventOfCode.playground/Pages/Day 17.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous)
import Foundation
go2()
var buffer = [0]
let steps = 3
var currentPosition = 0
for i in 1...9 {
currentPosition = (currentPosition + steps) % (i)
let insert = currentPosition + 1
print(buffer)
buffer.insert(i, at: insert )
currentPosition = insert
}
print("\(buffer[(currentPosition + 1)])")
buffer
//: [Next](@next)
| 7ca07933a25a70776fe6accf2c18ac24 | 12.821429 | 53 | 0.609819 | false | false | false | false |
ben-ng/swift | refs/heads/master | stdlib/public/core/VarArgs.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Instances of conforming types can be encoded, and appropriately
/// passed, as elements of a C `va_list`.
///
/// This protocol is useful in presenting C "varargs" APIs natively in
/// Swift. It only works for APIs that have a `va_list` variant, so
/// for example, it isn't much use if all you have is:
///
/// ~~~ c
/// int c_api(int n, ...)
/// ~~~
///
/// Given a version like this, though,
///
/// ~~~ c
/// int c_api(int, va_list arguments)
/// ~~~
///
/// you can write:
///
/// func swiftAPI(_ x: Int, arguments: CVarArg...) -> Int {
/// return withVaList(arguments) { c_api(x, $0) }
/// }
public protocol CVarArg {
// Note: the protocol is public, but its requirement is stdlib-private.
// That's because there are APIs operating on CVarArg instances, but
// defining conformances to CVarArg outside of the standard library is
// not supported.
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
var _cVarArgEncoding: [Int] { get }
}
/// Floating point types need to be passed differently on x86_64
/// systems. CoreGraphics uses this to make CGFloat work properly.
public // SPI(CoreGraphics)
protocol _CVarArgPassedAsDouble : CVarArg {}
/// Some types require alignment greater than Int on some architectures.
public // SPI(CoreGraphics)
protocol _CVarArgAligned : CVarArg {
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
var _cVarArgAlignment: Int { get }
}
#if arch(x86_64)
let _x86_64CountGPRegisters = 6
let _x86_64CountSSERegisters = 8
let _x86_64SSERegisterWords = 2
let _x86_64RegisterSaveWords = _x86_64CountGPRegisters + _x86_64CountSSERegisters * _x86_64SSERegisterWords
#endif
/// Invokes the given closure with a C `va_list` argument derived from the
/// given array of arguments.
///
/// The pointer passed as an argument to `body` is valid only for the lifetime
/// of the closure. Do not escape it from the closure for later use.
///
/// - Parameters:
/// - args: An array of arguments to convert to a C `va_list` pointer.
/// - body: A closure with a `CVaListPointer` parameter that references the
/// arguments passed as `args`. If `body` has a return value, it is used
/// as the return value for the `withVaList(_:)` function. The pointer
/// argument is valid only for the duration of the closure's execution.
/// - Returns: The return value of the `body` closure parameter, if any.
///
/// - SeeAlso: `getVaList(_:)`
public func withVaList<R>(_ args: [CVarArg],
_ body: (CVaListPointer) -> R) -> R {
let builder = _VaListBuilder()
for a in args {
builder.append(a)
}
return _withVaList(builder, body)
}
/// Invoke `body` with a C `va_list` argument derived from `builder`.
internal func _withVaList<R>(
_ builder: _VaListBuilder,
_ body: (CVaListPointer) -> R
) -> R {
let result = body(builder.va_list())
_fixLifetime(builder)
return result
}
#if _runtime(_ObjC)
// Excluded due to use of dynamic casting and Builtin.autorelease, neither
// of which correctly work without the ObjC Runtime right now.
// See rdar://problem/18801510
/// Returns a `CVaListPointer` that is backed by autoreleased storage, built
/// from the given array of arguments.
///
/// You should prefer `withVaList(_:_:)` instead of this function. In some
/// uses, such as in a `class` initializer, you may find that the
/// language rules do not allow you to use `withVaList(_:_:)` as intended.
///
/// - Parameters args: An array of arguments to convert to a C `va_list`
/// pointer.
/// - Returns: The return value of the `body` closure parameter, if any.
///
/// - SeeAlso: `withVaList(_:_:)`
public func getVaList(_ args: [CVarArg]) -> CVaListPointer {
let builder = _VaListBuilder()
for a in args {
builder.append(a)
}
// FIXME: Use some Swift equivalent of NS_RETURNS_INNER_POINTER if we get one.
Builtin.retain(builder)
Builtin.autorelease(builder)
return builder.va_list()
}
#endif
public func _encodeBitsAsWords<T>(_ x: T) -> [Int] {
let result = [Int](
repeating: 0,
count: (MemoryLayout<T>.size + MemoryLayout<Int>.size - 1) / MemoryLayout<Int>.size)
_sanityCheck(result.count > 0)
var tmp = x
// FIXME: use UnsafeMutablePointer.assign(from:) instead of memcpy.
_memcpy(dest: UnsafeMutablePointer(result._baseAddressIfContiguous!),
src: UnsafeMutablePointer(Builtin.addressof(&tmp)),
size: UInt(MemoryLayout<T>.size))
return result
}
// CVarArg conformances for the integer types. Everything smaller
// than an Int32 must be promoted to Int32 or CUnsignedInt before
// encoding.
// Signed types
extension Int : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension Int64 : CVarArg, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
extension Int32 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension Int16 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(Int32(self))
}
}
extension Int8 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(Int32(self))
}
}
// Unsigned types
extension UInt : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UInt64 : CVarArg, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
extension UInt32 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UInt16 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(CUnsignedInt(self))
}
}
extension UInt8 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(CUnsignedInt(self))
}
}
extension OpaquePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UnsafePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UnsafeMutablePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
#if _runtime(_ObjC)
extension AutoreleasingUnsafeMutablePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
#endif
extension Float : _CVarArgPassedAsDouble, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(Double(self))
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: Double(self))
}
}
extension Double : _CVarArgPassedAsDouble, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
#if !arch(x86_64)
/// An object that can manage the lifetime of storage backing a
/// `CVaListPointer`.
final internal class _VaListBuilder {
func append(_ arg: CVarArg) {
// Write alignment padding if necessary.
// This is needed on architectures where the ABI alignment of some
// supported vararg type is greater than the alignment of Int, such
// as non-iOS ARM. Note that we can't use alignof because it
// differs from ABI alignment on some architectures.
#if arch(arm) && !os(iOS)
if let arg = arg as? _CVarArgAligned {
let alignmentInWords = arg._cVarArgAlignment / MemoryLayout<Int>.size
let misalignmentInWords = count % alignmentInWords
if misalignmentInWords != 0 {
let paddingInWords = alignmentInWords - misalignmentInWords
appendWords([Int](repeating: -1, count: paddingInWords))
}
}
#endif
// Write the argument's value itself.
appendWords(arg._cVarArgEncoding)
}
func va_list() -> CVaListPointer {
// Use Builtin.addressof to emphasize that we are deliberately escaping this
// pointer and assuming it is safe to do so.
let emptyAddr = UnsafeMutablePointer<Int>(
Builtin.addressof(&_VaListBuilder.alignedStorageForEmptyVaLists))
return CVaListPointer(_fromUnsafeMutablePointer: storage ?? emptyAddr)
}
// Manage storage that is accessed as Words
// but possibly more aligned than that.
// FIXME: this should be packaged into a better storage type
func appendWords(_ words: [Int]) {
let newCount = count + words.count
if newCount > allocated {
let oldAllocated = allocated
let oldStorage = storage
let oldCount = count
allocated = max(newCount, allocated * 2)
let newStorage = allocStorage(wordCount: allocated)
storage = newStorage
// count is updated below
if let allocatedOldStorage = oldStorage {
newStorage.moveInitialize(from: allocatedOldStorage, count: oldCount)
deallocStorage(wordCount: oldAllocated, storage: allocatedOldStorage)
}
}
let allocatedStorage = storage!
for word in words {
allocatedStorage[count] = word
count += 1
}
}
func rawSizeAndAlignment(_ wordCount: Int) -> (Builtin.Word, Builtin.Word) {
return ((wordCount * MemoryLayout<Int>.stride)._builtinWordValue,
requiredAlignmentInBytes._builtinWordValue)
}
func allocStorage(wordCount: Int) -> UnsafeMutablePointer<Int> {
let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount)
let rawStorage = Builtin.allocRaw(rawSize, rawAlignment)
return UnsafeMutablePointer<Int>(rawStorage)
}
func deallocStorage(
wordCount: Int,
storage: UnsafeMutablePointer<Int>
) {
let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount)
Builtin.deallocRaw(storage._rawValue, rawSize, rawAlignment)
}
deinit {
if let allocatedStorage = storage {
deallocStorage(wordCount: allocated, storage: allocatedStorage)
}
}
// FIXME: alignof differs from the ABI alignment on some architectures
let requiredAlignmentInBytes = MemoryLayout<Double>.alignment
var count = 0
var allocated = 0
var storage: UnsafeMutablePointer<Int>?
static var alignedStorageForEmptyVaLists: Double = 0
}
#else
/// An object that can manage the lifetime of storage backing a
/// `CVaListPointer`.
final internal class _VaListBuilder {
struct Header {
var gp_offset = CUnsignedInt(0)
var fp_offset = CUnsignedInt(_x86_64CountGPRegisters * MemoryLayout<Int>.stride)
var overflow_arg_area: UnsafeMutablePointer<Int>?
var reg_save_area: UnsafeMutablePointer<Int>?
}
init() {
// prepare the register save area
storage = ContiguousArray(repeating: 0, count: _x86_64RegisterSaveWords)
}
func append(_ arg: CVarArg) {
var encoded = arg._cVarArgEncoding
if arg is _CVarArgPassedAsDouble
&& sseRegistersUsed < _x86_64CountSSERegisters {
var startIndex = _x86_64CountGPRegisters
+ (sseRegistersUsed * _x86_64SSERegisterWords)
for w in encoded {
storage[startIndex] = w
startIndex += 1
}
sseRegistersUsed += 1
}
else if encoded.count == 1 && gpRegistersUsed < _x86_64CountGPRegisters {
storage[gpRegistersUsed] = encoded[0]
gpRegistersUsed += 1
}
else {
for w in encoded {
storage.append(w)
}
}
}
func va_list() -> CVaListPointer {
header.reg_save_area = storage._baseAddress
header.overflow_arg_area
= storage._baseAddress + _x86_64RegisterSaveWords
return CVaListPointer(
_fromUnsafeMutablePointer: UnsafeMutableRawPointer(
Builtin.addressof(&self.header)))
}
var gpRegistersUsed = 0
var sseRegistersUsed = 0
final // Property must be final since it is used by Builtin.addressof.
var header = Header()
var storage: ContiguousArray<Int>
}
#endif
@available(*, unavailable, renamed: "CVarArg")
public typealias CVarArgType = CVarArg
@available(*, unavailable)
final public class VaListBuilder {}
| f5bb7dfb8703dbbdcd77c1fd7de89b36 | 31.260128 | 107 | 0.693126 | false | false | false | false |
aschwaighofer/swift | refs/heads/master | test/SILGen/switch_var.swift | apache-2.0 | 2 | // RUN: %target-swift-emit-silgen -module-name switch_var %s | %FileCheck %s
// TODO: Implement tuple equality in the library.
// BLOCKED: <rdar://problem/13822406>
func ~= (x: (Int, Int), y: (Int, Int)) -> Bool {
return x.0 == y.0 && x.1 == y.1
}
// Some fake predicates for pattern guards.
func runced() -> Bool { return true }
func funged() -> Bool { return true }
func ansed() -> Bool { return true }
func runced(x x: Int) -> Bool { return true }
func funged(x x: Int) -> Bool { return true }
func ansed(x x: Int) -> Bool { return true }
func foo() -> Int { return 0 }
func bar() -> Int { return 0 }
func foobar() -> (Int, Int) { return (0, 0) }
func foos() -> String { return "" }
func bars() -> String { return "" }
func a() {}
func b() {}
func c() {}
func d() {}
func e() {}
func f() {}
func g() {}
func a(x x: Int) {}
func b(x x: Int) {}
func c(x x: Int) {}
func d(x x: Int) {}
func a(x x: String) {}
func b(x x: String) {}
func aa(x x: (Int, Int)) {}
func bb(x x: (Int, Int)) {}
func cc(x x: (Int, Int)) {}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B2_1yyF
func test_var_1() {
// CHECK: function_ref @$s10switch_var3fooSiyF
switch foo() {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK-NOT: br bb
case var x:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1a1xySi_tF
// CHECK: destroy_value [[XADDR]]
a(x: x)
}
// CHECK: function_ref @$s10switch_var1byyF
b()
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B2_2yyF
func test_var_2() {
// CHECK: function_ref @$s10switch_var3fooSiyF
switch foo() {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var6runced1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
// -- TODO: Clean up these empty waypoint bbs.
case var x where runced(x: x):
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1a1xySi_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var6funged1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case var y where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1b1xySi_tF
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
b(x: y)
case var z:
// CHECK: [[NO_CASE2]]:
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1c1xySi_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK: br [[CONT]]
c(x: z)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s10switch_var1dyyF
d()
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B2_3yyF
func test_var_3() {
// CHECK: function_ref @$s10switch_var3fooSiyF
// CHECK: function_ref @$s10switch_var3barSiyF
switch (foo(), bar()) {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 0
// CHECK: function_ref @$s10switch_var6runced1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case var x where runced(x: x.0):
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var2aa1xySi_Sit_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
aa(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var6funged1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (var y, var z) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1a1xySi_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1b1xySi_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
a(x: y)
b(x: z)
// CHECK: [[NO_CASE2]]:
// CHECK: [[WADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[W:%.*]] = project_box [[WADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 0
// CHECK: function_ref @$s10switch_var5ansed1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
case var w where ansed(x: w.0):
// CHECK: [[CASE3]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var2bb1xySi_Sit_tF
// CHECK: br [[CONT]]
bb(x: w)
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[WADDR]]
case var v:
// CHECK: [[VADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[V:%.*]] = project_box [[VADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[V]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var2cc1xySi_Sit_tF
// CHECK: destroy_value [[VADDR]]
// CHECK: br [[CONT]]
cc(x: v)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s10switch_var1dyyF
d()
}
protocol P { func p() }
struct X : P { func p() {} }
struct Y : P { func p() {} }
struct Z : P { func p() {} }
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B2_41pyAA1P_p_tF : $@convention(thin) (@in_guaranteed P) -> () {
func test_var_4(p p: P) {
// CHECK: function_ref @$s10switch_var3fooSiyF
switch (p, foo()) {
// CHECK: [[PAIR:%.*]] = alloc_stack $(P, Int)
// CHECK: store
// CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0
// CHECK: [[T0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 1
// CHECK: [[PAIR_1:%.*]] = load [trivial] [[T0]] : $*Int
// CHECK: [[TMP:%.*]] = alloc_stack $X
// CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to X in [[TMP]] : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]]
// CHECK: [[IS_X]]:
// CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*X
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: store [[PAIR_1]] to [trivial] [[X]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var6runced1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case (is X, var x) where runced(x: x):
// CHECK: [[CASE1]]:
// CHECK: function_ref @$s10switch_var1a1xySi_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[XADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT:bb[0-9]+]]
// CHECK: [[IS_NOT_X]]:
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT]]
// CHECK: [[NEXT]]:
// CHECK: [[TMP:%.*]] = alloc_stack $Y
// CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to Y in [[TMP]] : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]]
// CHECK: [[IS_Y]]:
// CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*Y
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: store [[PAIR_1]] to [trivial] [[Y]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var6funged1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (is Y, var y) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1b1xySi_tF
// CHECK: destroy_value [[YADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[YADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT:bb[0-9]+]]
// CHECK: [[IS_NOT_Y]]:
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT]]
// CHECK: [[NEXT]]:
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var (P, Int) }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 1
// CHECK: function_ref @$s10switch_var5ansed1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[DFLT_NO_CASE3:bb[0-9]+]]
case var z where ansed(x: z.1):
// CHECK: [[CASE3]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 1
// CHECK: function_ref @$s10switch_var1c1xySi_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK-NEXT: destroy_addr [[PAIR]]
// CHECK-NEXT: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
c(x: z.1)
// CHECK: [[DFLT_NO_CASE3]]:
// CHECK-NEXT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_addr
case (_, var w):
// CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0
// CHECK: [[WADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[W:%.*]] = project_box [[WADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1d1xySi_tF
// CHECK: destroy_value [[WADDR]]
// CHECK-NEXT: destroy_addr [[PAIR_0]] : $*P
// CHECK-NEXT: dealloc_stack [[PAIR]]
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: br [[CONT]]
d(x: w)
}
e()
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B2_5yyF : $@convention(thin) () -> () {
func test_var_5() {
// CHECK: function_ref @$s10switch_var3fooSiyF
// CHECK: function_ref @$s10switch_var3barSiyF
switch (foo(), bar()) {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case var x where runced(x: x.0):
// CHECK: [[CASE1]]:
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]]
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (var y, var z) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
b()
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
case (_, _) where runced():
// CHECK: [[CASE3]]:
// CHECK: br [[CONT]]
c()
// CHECK: [[NO_CASE3]]:
// CHECK: br [[CASE4:bb[0-9]+]]
case _:
// CHECK: [[CASE4]]:
d()
}
e()
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B7_returnyyF : $@convention(thin) () -> () {
func test_var_return() {
switch (foo(), bar()) {
case var x where runced():
// CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%[0-9]+]] = project_box [[XADDR]]
// CHECK: function_ref @$s10switch_var1ayyF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[EPILOG:bb[0-9]+]]
a()
return
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]]
case (var y, var z) where funged():
// CHECK: function_ref @$s10switch_var1byyF
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[EPILOG]]
b()
return
case var w where ansed():
// CHECK: [[WADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[W:%[0-9]+]] = project_box [[WADDR]]
// CHECK: function_ref @$s10switch_var1cyyF
// CHECK-NOT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_value [[YADDR]]
// CHECK: destroy_value [[WADDR]]
// CHECK: br [[EPILOG]]
c()
return
case var v:
// CHECK: [[VADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[V:%[0-9]+]] = project_box [[VADDR]]
// CHECK: function_ref @$s10switch_var1dyyF
// CHECK-NOT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_value [[YADDR]]
// CHECK: destroy_value [[VADDR]]
// CHECK: br [[EPILOG]]
d()
return
}
}
// When all of the bindings in a column are immutable, don't emit a mutable
// box. <rdar://problem/15873365>
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var8test_letyyF : $@convention(thin) () -> () {
func test_let() {
// CHECK: [[FOOS:%.*]] = function_ref @$s10switch_var4foosSSyF
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: function_ref @$s10switch_var6runcedSbyF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
switch foos() {
case let x where runced():
// CHECK: [[CASE1]]:
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[A:%.*]] = function_ref @$s10switch_var1a1xySS_tF
// CHECK: apply [[A]]([[BORROWED_VAL_COPY]])
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: [[BORROWED_VAL_2:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY_2:%.*]] = copy_value [[BORROWED_VAL_2]]
// CHECK: function_ref @$s10switch_var6fungedSbyF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case let y where funged():
// CHECK: [[CASE2]]:
// CHECK: [[BORROWED_VAL_COPY_2:%.*]] = begin_borrow [[VAL_COPY_2]]
// CHECK: [[B:%.*]] = function_ref @$s10switch_var1b1xySS_tF
// CHECK: apply [[B]]([[BORROWED_VAL_COPY_2]])
// CHECK: destroy_value [[VAL_COPY_2]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[VAL_COPY_2]]
// CHECK: [[BORROWED_VAL_3:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY_3:%.*]] = copy_value [[BORROWED_VAL_3]]
// CHECK: function_ref @$s10switch_var4barsSSyF
// CHECK: [[BORROWED_VAL_COPY_3:%.*]] = begin_borrow [[VAL_COPY_3]]
// CHECK: store_borrow [[BORROWED_VAL_COPY_3]] to [[IN_ARG:%.*]] :
// CHECK: apply {{%.*}}<String>({{.*}}, [[IN_ARG]])
// CHECK: cond_br {{%.*}}, [[YES_CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
// ExprPatterns implicitly contain a 'let' binding.
case bars():
// CHECK: [[YES_CASE3]]:
// CHECK: destroy_value [[VAL_COPY_3]]
// CHECK: [[FUNC:%.*]] = function_ref @$s10switch_var1cyyF
// CHECK-NEXT: apply [[FUNC]](
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
c()
case _:
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[VAL_COPY_3]]
// CHECK: function_ref @$s10switch_var1dyyF
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: return
}
// CHECK: } // end sil function '$s10switch_var8test_letyyF'
// If one of the bindings is a "var", allocate a box for the column.
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var015test_mixed_let_B0yyF : $@convention(thin) () -> () {
func test_mixed_let_var() {
// CHECK: bb0:
// CHECK: [[FOOS:%.*]] = function_ref @$s10switch_var4foosSSyF
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
switch foos() {
// First pattern.
// CHECK: [[BOX:%.*]] = alloc_box ${ var String }, var, name "x"
// CHECK: [[PBOX:%.*]] = project_box [[BOX]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: store [[VAL_COPY]] to [init] [[PBOX]]
// CHECK: cond_br {{.*}}, [[CASE1:bb[0-9]+]], [[NOCASE1:bb[0-9]+]]
case var x where runced():
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOX]]
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[A:%.*]] = function_ref @$s10switch_var1a1xySS_tF
// CHECK: apply [[A]]([[X]])
// CHECK: destroy_value [[BOX]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NOCASE1]]:
// CHECK: destroy_value [[BOX]]
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: cond_br {{.*}}, [[CASE2:bb[0-9]+]], [[NOCASE2:bb[0-9]+]]
case let y where funged():
// CHECK: [[CASE2]]:
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[B:%.*]] = function_ref @$s10switch_var1b1xySS_tF
// CHECK: apply [[B]]([[BORROWED_VAL_COPY]])
// CHECK: end_borrow [[BORROWED_VAL_COPY]]
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NOCASE2]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: store_borrow [[BORROWED_VAL_COPY]] to [[TMP_VAL_COPY_ADDR:%.*]] :
// CHECK: apply {{.*}}<String>({{.*}}, [[TMP_VAL_COPY_ADDR]])
// CHECK: cond_br {{.*}}, [[CASE3:bb[0-9]+]], [[NOCASE3:bb[0-9]+]]
case bars():
// CHECK: [[CASE3]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: [[FUNC:%.*]] = function_ref @$s10switch_var1cyyF : $@convention(thin) () -> ()
// CHECK: apply [[FUNC]]()
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
c()
// CHECK: [[NOCASE3]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: [[D_FUNC:%.*]] = function_ref @$s10switch_var1dyyF : $@convention(thin) () -> ()
// CHECK: apply [[D_FUNC]]()
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
case _:
d()
}
// CHECK: [[CONT]]:
// CHECK: return
}
// CHECK: } // end sil function '$s10switch_var015test_mixed_let_B0yyF'
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var23test_multiple_patterns1yyF : $@convention(thin) () -> () {
func test_multiple_patterns1() {
// CHECK: function_ref @$s10switch_var6foobarSi_SityF
switch foobar() {
// CHECK-NOT: br bb
case (0, let x), (let x, 0):
// CHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]]
// CHECK: [[FIRST_MATCH_CASE]]:
// CHECK: debug_value [[FIRST_X:%.*]] :
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[FIRST_X]] : $Int)
// CHECK: [[FIRST_FAIL]]:
// CHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]]
// CHECK: [[SECOND_MATCH_CASE]]:
// CHECK: debug_value [[SECOND_X:%.*]] :
// CHECK: br [[CASE_BODY]]([[SECOND_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int):
// CHECK: [[A:%.*]] = function_ref @$s10switch_var1a1xySi_tF
// CHECK: apply [[A]]([[BODY_VAR]])
a(x: x)
default:
// CHECK: [[SECOND_FAIL]]:
// CHECK: function_ref @$s10switch_var1byyF
b()
}
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var23test_multiple_patterns2yyF : $@convention(thin) () -> () {
func test_multiple_patterns2() {
let t1 = 2
let t2 = 4
// CHECK: debug_value [[T1:%.+]] :
// CHECK: debug_value [[T2:%.+]] :
switch (0,0) {
// CHECK-NOT: br bb
case (_, let x) where x > t1, (let x, _) where x > t2:
// CHECK: ([[FIRST:%[0-9]+]], [[SECOND:%[0-9]+]]) = destructure_tuple {{%.+}} : $(Int, Int)
// CHECK: apply {{%.+}}([[SECOND]], [[T1]], {{%.+}})
// CHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]]
// CHECK: [[FIRST_MATCH_CASE]]:
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[SECOND]] : $Int)
// CHECK: [[FIRST_FAIL]]:
// CHECK: apply {{%.*}}([[FIRST]], [[T2]], {{%.+}})
// CHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]]
// CHECK: [[SECOND_MATCH_CASE]]:
// CHECK: br [[CASE_BODY]]([[FIRST]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int):
// CHECK: [[A:%.*]] = function_ref @$s10switch_var1a1xySi_tF
// CHECK: apply [[A]]([[BODY_VAR]])
a(x: x)
default:
// CHECK: [[SECOND_FAIL]]:
// CHECK: function_ref @$s10switch_var1byyF
b()
}
}
enum Foo {
case A(Int, Double)
case B(Double, Int)
case C(Int, Int, Double)
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var23test_multiple_patterns3yyF : $@convention(thin) () -> () {
func test_multiple_patterns3() {
let f = Foo.C(0, 1, 2.0)
switch f {
// CHECK: switch_enum {{%.*}} : $Foo, case #Foo.A!enumelt: [[A:bb[0-9]+]], case #Foo.B!enumelt: [[B:bb[0-9]+]], case #Foo.C!enumelt: [[C:bb[0-9]+]]
case .A(let x, let n), .B(let n, let x), .C(_, let x, let n):
// CHECK: [[A]]([[A_TUP:%.*]] : $(Int, Double)):
// CHECK: ([[A_X:%.*]], [[A_N:%.*]]) = destructure_tuple [[A_TUP]]
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int, [[A_N]] : $Double)
// CHECK: [[B]]([[B_TUP:%.*]] : $(Double, Int)):
// CHECK: ([[B_N:%.*]], [[B_X:%.*]]) = destructure_tuple [[B_TUP]]
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int, [[B_N]] : $Double)
// CHECK: [[C]]([[C_TUP:%.*]] : $(Int, Int, Double)):
// CHECK: ([[C__:%.*]], [[C_X:%.*]], [[C_N:%.*]]) = destructure_tuple [[C_TUP]]
// CHECK: br [[CASE_BODY]]([[C_X]] : $Int, [[C_N]] : $Double)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int, [[BODY_N:%.*]] : $Double):
// CHECK: [[FUNC_A:%.*]] = function_ref @$s10switch_var1a1xySi_tF
// CHECK: apply [[FUNC_A]]([[BODY_X]])
a(x: x)
}
}
enum Bar {
case Y(Foo, Int)
case Z(Int, Foo)
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var23test_multiple_patterns4yyF : $@convention(thin) () -> () {
func test_multiple_patterns4() {
let b = Bar.Y(.C(0, 1, 2.0), 3)
switch b {
// CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt: [[Y:bb[0-9]+]], case #Bar.Z!enumelt: [[Z:bb[0-9]+]]
case .Y(.A(let x, _), _), .Y(.B(_, let x), _), .Y(.C, let x), .Z(let x, _):
// CHECK: [[Y]]([[Y_TUP:%.*]] : $(Foo, Int)):
// CHECK: ([[Y_F:%.*]], [[Y_X:%.*]]) = destructure_tuple [[Y_TUP]]
// CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt: [[A:bb[0-9]+]], case #Foo.B!enumelt: [[B:bb[0-9]+]], case #Foo.C!enumelt: [[C:bb[0-9]+]]
// CHECK: [[A]]([[A_TUP:%.*]] : $(Int, Double)):
// CHECK: ([[A_X:%.*]], [[A_N:%.*]]) = destructure_tuple [[A_TUP]]
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int)
// CHECK: [[B]]([[B_TUP:%.*]] : $(Double, Int)):
// CHECK: ([[B_N:%.*]], [[B_X:%.*]]) = destructure_tuple [[B_TUP]]
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: br [[CASE_BODY]]([[Y_X]] : $Int)
// CHECK: [[Z]]([[Z_TUP:%.*]] : $(Int, Foo)):
// CHECK: ([[Z_X:%.*]], [[Z_F:%.*]]) = destructure_tuple [[Z_TUP]]
// CHECK: br [[CASE_BODY]]([[Z_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
// CHECK: [[FUNC_A:%.*]] = function_ref @$s10switch_var1a1xySi_tF
// CHECK: apply [[FUNC_A]]([[BODY_X]])
a(x: x)
}
}
func aaa(x x: inout Int) {}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var23test_multiple_patterns5yyF : $@convention(thin) () -> () {
func test_multiple_patterns5() {
let b = Bar.Y(.C(0, 1, 2.0), 3)
switch b {
// CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt: [[Y:bb[0-9]+]], case #Bar.Z!enumelt: [[Z:bb[0-9]+]]
case .Y(.A(var x, _), _), .Y(.B(_, var x), _), .Y(.C, var x), .Z(var x, _):
// CHECK: [[Y]]([[Y_TUP:%.*]] : $(Foo, Int)):
// CHECK: ([[Y_F:%.*]], [[Y_X:%.*]]) = destructure_tuple [[Y_TUP]]
// CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt: [[A:bb[0-9]+]], case #Foo.B!enumelt: [[B:bb[0-9]+]], case #Foo.C!enumelt: [[C:bb[0-9]+]]
// CHECK: [[A]]([[A_TUP:%.*]] : $(Int, Double)):
// CHECK: ([[A_X:%.*]], [[A_N:%.*]]) = destructure_tuple [[A_TUP]]
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int)
// CHECK: [[B]]([[B_TUP:%.*]] : $(Double, Int)):
// CHECK: ([[B_N:%.*]], [[B_X:%.*]]) = destructure_tuple [[B_TUP]]
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: br [[CASE_BODY]]([[Y_X]] : $Int)
// CHECK: [[Z]]([[Z_TUP:%.*]] : $(Int, Foo)):
// CHECK: ([[Z_X:%.*]], [[Z_F:%.*]]) = destructure_tuple [[Z_TUP]]
// CHECK: br [[CASE_BODY]]([[Z_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
// CHECK: store [[BODY_X]] to [trivial] [[BOX_X:%.*]] : $*Int
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[BOX_X]]
// CHECK: [[FUNC_AAA:%.*]] = function_ref @$s10switch_var3aaa1xySiz_tF
// CHECK: apply [[FUNC_AAA]]([[WRITE]])
aaa(x: &x)
}
}
// rdar://problem/29252758 -- local decls must not be reemitted.
func test_against_reemission(x: Bar) {
switch x {
case .Y(let a, _), .Z(_, let a):
let b = a
}
}
class C {}
class D: C {}
func f(_: D) -> Bool { return true }
// CHECK-LABEL: sil hidden [ossa] @{{.*}}test_multiple_patterns_value_semantics
func test_multiple_patterns_value_semantics(_ y: C) {
switch y {
// CHECK: checked_cast_br {{%.*}} : $C to D, [[AS_D:bb[0-9]+]], [[NOT_AS_D:bb[0-9]+]]
// CHECK: [[AS_D]]({{.*}}):
// CHECK: cond_br {{%.*}}, [[F_TRUE:bb[0-9]+]], [[F_FALSE:bb[0-9]+]]
// CHECK: [[F_TRUE]]:
// CHECK: [[BINDING:%.*]] = copy_value [[ORIG:%.*]] :
// CHECK: destroy_value [[ORIG]]
// CHECK: br {{bb[0-9]+}}([[BINDING]]
case let x as D where f(x), let x as D: break
default: break
}
}
| 0ea186fc04b9c47f9690f918d120dea0 | 37.32636 | 155 | 0.511317 | false | false | false | false |
dutchcoders/stacktray | refs/heads/v2 | StackTray/Import/ImportController.swift | mit | 1 | //
// ImportController.swift
// stacktray
//
// Created by Ruben Cagnie on 3/5/15.
// Copyright (c) 2015 dutchcoders. All rights reserved.
//
import Cocoa
import CoreData
public class ImportController: NSObject {
///Users/ruben/Library/Containers/io.dutchcoders.stacktray/Data/Documents/StackTray.sqlite
//DocumentsDirectory
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "io.dutchcoders.stacktray" in the user's Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)
let appSupportURL = urls[urls.count - 1] as! NSURL
return appSupportURL.URLByAppendingPathComponent("io.dutchcoders.stacktray")
}()
public func importLegacyData(accountController: AccountController) -> Bool{
println("App Dir: \(applicationDocumentsDirectory)")
if let context = managedObjectContext {
let fetchRequest = NSFetchRequest(entityName: "Stack")
var error: NSError?
if let stacks = context.executeFetchRequest(fetchRequest, error: &error) as? [Stack] {
println("Got \(stacks.count)")
for stack in stacks {
let account = AWSAccount(name: stack.title, accessKey: stack.accessKey, secretKey: stack.secretKey, region: stack.region)
accountController.createAccount(account, callback: { (error, account) -> Void in
if error != nil {
println("Error: \(error!)")
}
})
}
} else {
println("No stacks found")
}
} else {
println("No Managed Context")
}
return true
}
/** Managed Object Model */
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("StackTray", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
/** Persistance Coordinator */
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. (The directory for the store is created, if necessary.) This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
let fileManager = NSFileManager.defaultManager()
var shouldFail = false
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
// Make sure the application files directory is there
let propertiesOpt = self.applicationDocumentsDirectory.resourceValuesForKeys([NSURLIsDirectoryKey], error: &error)
if let properties = propertiesOpt {
if !properties[NSURLIsDirectoryKey]!.boolValue {
failureReason = "Expected a folder to store application data, found a file \(self.applicationDocumentsDirectory.path)."
shouldFail = true
}
} else if error!.code == NSFileReadNoSuchFileError {
error = nil
fileManager.createDirectoryAtPath(self.applicationDocumentsDirectory.path!, withIntermediateDirectories: true, attributes: nil, error: &error)
}
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator?
if !shouldFail && (error == nil) {
coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Data/Documents/StackTray.sqlite")
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: [NSMigratePersistentStoresAutomaticallyOption:true, NSInferMappingModelAutomaticallyOption:true], error: &error) == nil {
coordinator = nil
}
}
if shouldFail || (error != nil) {
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
if error != nil {
dict[NSUnderlyingErrorKey] = error
}
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject] as [NSObject : AnyObject])
println("Error: \(error)")
return nil
} else {
return coordinator
}
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
}
| 58dbaf91133d5dde3fde664e1d1720d8 | 48.948276 | 346 | 0.653435 | false | false | false | false |
LYM-mg/MGDS_Swift | refs/heads/master | MGDS_Swift/MGDS_Swift/Class/Home/DouYu/Controller/DetailGameViewController.swift | mit | 1 | //
// DetailGameViewController.swift
// MGDYZB
//
// Created by i-Techsys.com on 17/4/8.
// Copyright © 2017年 ming. All rights reserved.
//
import UIKit
import SafariServices
import MJRefresh
private let KDetailCellItemW = (MGScreenW - 3 * (kItemMargin/2)) / 2
class DetailGameViewController: UIViewController {
// MARK: - 懒加载属性
fileprivate lazy var detailGameVM : DetailGameViewModel = DetailGameViewModel()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
// 1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: KDetailCellItemW, height: kNormalItemH)
layout.minimumLineSpacing = 2
layout.minimumInteritemSpacing = kItemMargin/2
layout.sectionInset = UIEdgeInsets(top: 5, left: kItemMargin/2, bottom: 0, right: kItemMargin/2)
// 2.创建UICollectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.dataSource = self
collectionView.delegate = self
return collectionView
}()
// MARK: - 系统方法
convenience init(tag_id: String) {
self.init(nibName: nil, bundle: nil)
detailGameVM.tag_id = tag_id // 这个tag_id是用作url参数用的,具体你看ViewModel的两个url分析
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "具体游戏"
setUpMainView()
setUpRefresh()
if #available(iOS 9, *) {
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self, sourceView: self.view)
}
}
}
func setUpMainView() {
view.addSubview(collectionView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
// MARK: - loadData
extension DetailGameViewController {
fileprivate func loadData() {
// 1.请求数据
detailGameVM.loadDetailGameData { [weak self] (err) in
// 1.1.刷新表格
self!.collectionView.mj_header?.endRefreshing()
self!.collectionView.mj_footer?.endRefreshing()
self?.collectionView.reloadData()
}
}
fileprivate func setUpRefresh() {
// MARK: - 下拉
self.collectionView.mj_header = MJRefreshGifHeader(refreshingBlock: { [weak self]() -> Void in
self!.detailGameVM.anchorGroups.removeAll()
self!.detailGameVM.offset = 0
self!.loadData()
})
// MARK: - 上拉
self.collectionView.mj_footer = MJRefreshAutoGifFooter(refreshingBlock: {[weak self] () -> Void in
self!.detailGameVM.offset += 20
self!.loadData()
})
self.collectionView.mj_header?.isAutomaticallyChangeAlpha = true
self.collectionView.mj_header?.beginRefreshing()
self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
}
}
// MARK: - UICollectionViewDataSource
extension DetailGameViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return detailGameVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return detailGameVM.anchorGroups[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 1.获取cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
if detailGameVM.anchorGroups.count > 0 {
cell.anchor = detailGameVM.anchorGroups[indexPath.section].anchors[indexPath.item]
}
return cell
}
}
// MARK: - UICollectionViewDelegate
extension DetailGameViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 1.取出对应的主播信息
let anchor = detailGameVM.anchorGroups[indexPath.section].anchors[indexPath.item]
// 2.判断是秀场房间&普通房间
anchor.isVertical == 0 ? pushNormalRoomVc(anchor: anchor) : presentShowRoomVc(anchor: anchor)
}
fileprivate func presentShowRoomVc(anchor: AnchorModel) {
if #available(iOS 9.0, *) {
// 1.创建SFSafariViewController
let safariVC = SFSafariViewController(url: URL(string: anchor.jumpUrl)!, entersReaderIfAvailable: true)
// 2.以Modal方式弹出
present(safariVC, animated: true, completion: nil)
} else {
let webVC = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl)
present(webVC, animated: true, completion: nil)
}
}
fileprivate func pushNormalRoomVc(anchor: AnchorModel) {
// 1.创建WebViewController
let webVC = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl)
webVC.navigationController?.setNavigationBarHidden(true, animated: true)
// 2.以Push方式弹出
navigationController?.pushViewController(webVC, animated: true)
}
}
// MARK: - UIViewControllerPreviewingDelegate
extension DetailGameViewController: UIViewControllerPreviewingDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = collectionView.indexPathForItem(at: location) else { return nil }
guard let cell = collectionView.cellForItem(at: indexPath) else { return nil }
if #available(iOS 9.0, *) {
previewingContext.sourceRect = cell.frame
}
var vc = UIViewController()
let anchor = detailGameVM.anchorGroups[indexPath.section].anchors[indexPath.item]
if anchor.isVertical == 0 {
if #available(iOS 9, *) {
vc = SFSafariViewController(url: URL(string: anchor.jumpUrl)!, entersReaderIfAvailable: true)
} else {
vc = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl)
}
}else {
vc = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl)
}
return vc
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
show(viewControllerToCommit, sender: nil)
}
}
| eab4cfce5c20755ccfed562890d9525d | 37.116667 | 143 | 0.664189 | false | false | false | false |
cliffpanos/True-Pass-iOS | refs/heads/master | iOSApp/CheckInWatchKitApp Extension/Primary Controllers/MapViewInterfaceController.swift | apache-2.0 | 1 | //
// MapViewInterfaceController.swift
// TruePassWatchKitApp Extension
//
// Created by Cliff Panos on 4/16/17.
// Copyright © 2017 Clifford Panos. All rights reserved.
//
import WatchKit
import Foundation
import CoreLocation
class MapViewInterfaceController: ManagedInterfaceController, CLLocationManagerDelegate {
@IBOutlet var mapView: WKInterfaceMap!
static var instance: MapViewInterfaceController?
var checkInLocations = [CLLocationCoordinate2D]()
var locationManager: CLLocationManager!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
MapViewInterfaceController.instance = self
// Configure interface objects here.
locationManager = CLLocationManager()
locationManager.delegate = self
getCoreLocations()
locationManager.startUpdatingLocation()
}
func getCoreLocations() {
ExtensionDelegate.session?.sendMessage([WCD.KEY : WCD.mapLocationsRequest], replyHandler: {
message in
guard message[WCD.KEY] as? String == WCD.mapLocationsRequest, let latitude = message["latitude"], let longitude = message["longitude"] else {
return
}
self.checkInLocations = [CLLocationCoordinate2D(latitude: latitude as! CLLocationDegrees, longitude: longitude as! CLLocationDegrees)]
for location in self.checkInLocations {
self.mapView.addAnnotation(location, with: .red)
}
let region = MKCoordinateRegion(center: self.checkInLocations[0], span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005))
self.mapView.setRegion(region)
}, errorHandler: {error in print(error)})
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
if checkInLocations.count == 0 {
getCoreLocations()
}
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
| 1b576c358d70b0f44f31ff2ec0c7691a | 32.938462 | 153 | 0.664551 | false | false | false | false |
erikmartens/NearbyWeather | refs/heads/develop | NearbyWeather/Scenes/Settings Scene/Table View Cells/Settings Imaged Dual Label Subtitle Cell/SettingsImagedDualLabelSubtitleCell.swift | mit | 1 | //
// SettingsImagedDualLabelSubtitleCell.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 20.03.22.
// Copyright © 2022 Erik Maximilian Martens. All rights reserved.
//
import UIKit
import RxSwift
// MARK: - Definitions
private extension SettingsImagedDualLabelSubtitleCell {
struct Definitions {
static let labelHeight: CGFloat = 20
}
}
// MARK: - Class Definition
final class SettingsImagedDualLabelSubtitleCell: UITableViewCell, BaseCell {
typealias CellViewModel = SettingsImagedDualLabelSubtitleCellViewModel
private typealias CellContentInsets = Constants.Dimensions.Spacing.ContentInsets
private typealias CellInterelementSpacing = Constants.Dimensions.Spacing.InterElementSpacing
// MARK: - UIComponents
private lazy var leadingImageBackgroundColorView = Factory.View.make(fromType: .cellPrefix)
private lazy var leadingImageView = Factory.ImageView.make(fromType: .cellPrefix)
private lazy var contentLabel = Factory.Label.make(fromType: .body(textColor: Constants.Theme.Color.ViewElement.Label.titleDark))
private lazy var descriptionLabel = Factory.Label.make(fromType: .subtitle(numberOfLines: 1, textColor: Constants.Theme.Color.ViewElement.Label.subtitleDark))
// MARK: - Assets
private var disposeBag = DisposeBag()
// MARK: - Properties
var cellViewModel: CellViewModel?
// MARK: - Initialization
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
layoutUserInterface()
setupAppearance()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
printDebugMessage(
domain: String(describing: self),
message: "was deinitialized",
type: .info
)
}
// MARK: - Cell Life Cycle
func configure(with cellViewModel: BaseCellViewModelProtocol?) {
guard let cellViewModel = cellViewModel as? SettingsImagedDualLabelSubtitleCellViewModel else {
return
}
self.cellViewModel = cellViewModel
cellViewModel.observeEvents()
bindContentFromViewModel(cellViewModel)
bindUserInputToViewModel(cellViewModel)
}
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
}
}
// MARK: - ViewModel Bindings
extension SettingsImagedDualLabelSubtitleCell {
func bindContentFromViewModel(_ cellViewModel: CellViewModel) {
cellViewModel.cellModelDriver
.drive(onNext: { [setContent] in setContent($0) })
.disposed(by: disposeBag)
}
}
// MARK: - Cell Composition
private extension SettingsImagedDualLabelSubtitleCell {
func setContent(for cellModel: SettingsImagedDualLabelSubtitleCellModel) {
leadingImageBackgroundColorView.backgroundColor = cellModel.symbolImageBackgroundColor
leadingImageView.image = Factory.Image.make(fromType: .cellSymbol(systemImageName: cellModel.symbolImageName))
contentLabel.text = cellModel.contentLabelText
descriptionLabel.text = cellModel.descriptionLabelText
selectionStyle = (cellModel.isSelectable ?? false) ? .default : .none
accessoryType = (cellModel.isDisclosable ?? false) ? .disclosureIndicator : .none
}
func layoutUserInterface() {
separatorInset = UIEdgeInsets(
top: 0,
left: CellContentInsets.leading(from: .extraLarge)
+ Constants.Dimensions.TableCellImage.backgroundWidth
+ CellInterelementSpacing.xDistance(from: .medium),
bottom: 0,
right: 0
)
contentView.addSubview(leadingImageBackgroundColorView, constraints: [
leadingImageBackgroundColorView.heightAnchor.constraint(equalToConstant: Constants.Dimensions.TableCellImage.backgroundHeight),
leadingImageBackgroundColorView.widthAnchor.constraint(equalToConstant: Constants.Dimensions.TableCellImage.backgroundWidth),
leadingImageBackgroundColorView.topAnchor.constraint(greaterThanOrEqualTo: contentView.topAnchor, constant: CellContentInsets.top(from: .medium)),
leadingImageBackgroundColorView.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -CellContentInsets.bottom(from: .medium)),
leadingImageBackgroundColorView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: CellContentInsets.leading(from: .extraLarge)),
leadingImageBackgroundColorView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
])
leadingImageBackgroundColorView.addSubview(leadingImageView, constraints: [
leadingImageView.heightAnchor.constraint(equalToConstant: Constants.Dimensions.TableCellImage.foregroundHeight),
leadingImageView.widthAnchor.constraint(equalToConstant: Constants.Dimensions.TableCellImage.foregroundWidth),
leadingImageView.centerYAnchor.constraint(equalTo: leadingImageBackgroundColorView.centerYAnchor),
leadingImageView.centerXAnchor.constraint(equalTo: leadingImageBackgroundColorView.centerXAnchor)
])
contentView.addSubview(contentLabel, constraints: [
contentLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Definitions.labelHeight),
contentLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: CellContentInsets.top(from: .medium)),
contentLabel.leadingAnchor.constraint(equalTo: leadingImageBackgroundColorView.trailingAnchor, constant: CellInterelementSpacing.xDistance(from: .medium)),
contentLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -CellContentInsets.trailing(from: .large))
])
contentView.addSubview(descriptionLabel, constraints: [
descriptionLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Definitions.labelHeight),
descriptionLabel.topAnchor.constraint(equalTo: contentLabel.bottomAnchor, constant: CellInterelementSpacing.yDistance(from: .small)),
descriptionLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -CellContentInsets.bottom(from: .medium)),
descriptionLabel.leadingAnchor.constraint(equalTo: leadingImageBackgroundColorView.trailingAnchor, constant: CellInterelementSpacing.xDistance(from: .medium)),
descriptionLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -CellContentInsets.trailing(from: .large))
])
}
func setupAppearance() {
backgroundColor = Constants.Theme.Color.ViewElement.primaryBackground
contentView.backgroundColor = .clear
}
}
| bb2c03fe52b68e0b410c3f847d0cc73d | 41.54902 | 165 | 0.779109 | false | false | false | false |
anilkumarbp/ringcentral-swift-NEW | refs/heads/master | ringcentral-swift-develop-anilkumarbp/lib/subscription/Subscription.swift | mit | 1 | import Foundation
import PubNub
class Subscription: NSObject, PNObjectEventListener {
/// Fields of subscription
private let platform: Platform!
var pubnub: PubNub?
private var eventFilters: [String] = []
var subscription: ISubscription?
var function: ((arg: String) -> Void) = {(arg) in }
/// Initializes a subscription with Platform
///
/// :param: platform Authorized platform
init(platform: Platform) {
self.platform = platform
}
/// Structure holding information about how PubNub is delivered
struct IDeliveryMode {
var transportType: String = "PubNub"
var encryption: Bool = false
var address: String = ""
var subscriberKey: String = ""
var secretKey: String = ""
var encryptionKey: String = ""
}
/// Structure holding information about the details of PubNub
struct ISubscription {
var eventFilters: [String] = []
var expirationTime: String = ""
var expiresIn: NSNumber = 0
var deliveryMode: IDeliveryMode = IDeliveryMode()
var id: String = ""
var creationTime: String = ""
var status: String = ""
var uri: String = ""
}
/// Returns PubNub object
///
/// :returns: PubNub object
func getPubNub() -> PubNub? {
return pubnub
}
/// Returns the platform
///
/// :returns: Platform
func getPlatform() -> Platform {
return platform
}
/// Adds event for PubNub
///
/// :param: events List of events to add
/// :returns: Subscription
func addEvents(events: [String]) -> Subscription {
for event in events {
self.eventFilters.append(event)
}
return self
}
/// Sets events for PubNub (deletes all previous ones)
///
/// :param: events List of events to set
/// :returns: Subscription
func setevents(events: [String]) -> Subscription {
self.eventFilters = events
return self
}
/// Registers for a new subscription or renews an old one
///
/// :param: options List of options for PubNub
func register(options: [String: AnyObject] = [String: AnyObject]()) {
if (isSubscribed()) {
return renew(options)
} else {
return subscribe(options)
}
}
// getFullEventFilters()
/// Renews the subscription
///
/// :param: options List of options for PubNub
func renew(options: [String: AnyObject]) {
if let events = options["eventFilters"] {
self.eventFilters = events as! [String]
} else if let events = options["events"] {
self.eventFilters = events as! [String]
} else {
self.eventFilters = [
"/restapi/v1.0/account/~/extension/~/presence",
"/restapi/v1.0/account/~/extension/~/message-store"
]
}
platform.apiCall([
"method": "PUT",
"url": "restapi/v1.0/subscription/" + subscription!.id,
"body": [
"eventFilters": getFullEventFilters()
]
]) {
(data, response, error) in
let dictionary = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSDictionary
if let error = dictionary["errorCode"] {
self.subscribe(options)
} else {
self.subscription!.expiresIn = dictionary["expiresIn"] as! NSNumber
self.subscription!.expirationTime = dictionary["expirationTime"] as! String
}
}
}
/// Subscribes to a channel with given events
///
/// :param: options Options for PubNub
func subscribe(options: [String: AnyObject]) {
if let events = options["eventFilters"] {
self.eventFilters = events as! [String]
} else if let events = options["events"] {
self.eventFilters = events as! [String]
} else {
self.eventFilters = [
"/restapi/v1.0/account/~/extension/~/presence",
"/restapi/v1.0/account/~/extension/~/message-store"
]
}
platform.apiCall([
"method": "POST",
"url": "/restapi/v1.0/subscription",
"body": [
"eventFilters": getFullEventFilters(),
"deliveryMode": [
"transportType": "PubNub",
"encryption": "false"
]
]
]) {
(data, response, error) in
let dictionary = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSDictionary
var sub = ISubscription()
sub.eventFilters = dictionary["eventFilters"] as! [String]
self.eventFilters = dictionary["eventFilters"] as! [String]
sub.expirationTime = dictionary["expirationTime"] as! String
sub.expiresIn = dictionary["expiresIn"] as! NSNumber
sub.id = dictionary["id"] as! String
sub.creationTime = dictionary["creationTime"] as! String
sub.status = dictionary["status"] as! String
sub.uri = dictionary["uri"] as! String
self.subscription = sub
var del = IDeliveryMode()
var dictDelivery = dictionary["deliveryMode"] as! NSDictionary
del.transportType = dictDelivery["transportType"] as! String
del.encryption = dictDelivery["encryption"] as! Bool
del.address = dictDelivery["address"] as! String
del.subscriberKey = dictDelivery["subscriberKey"] as! String
del.secretKey = dictDelivery["secretKey"] as! String
del.encryptionKey = dictDelivery["encryptionKey"] as! String
self.subscription!.deliveryMode = del
self.subscribeAtPubnub()
}
}
/// Unsubscribes from the current subscription
func destroy() {
if let sub = self.subscription {
unsubscribe()
}
}
/// Sets a method that will run after every PubNub callback
///
/// :param: functionHolder Function to be ran after every PubNub callback
func setMethod(functionHolder: ((arg: String) -> Void)) {
self.function = functionHolder
}
/// Checks if currently subscribed
///
/// :returns: Bool of if currently subscribed
func isSubscribed() -> Bool {
if let sub = self.subscription {
let dil = sub.deliveryMode
return dil.subscriberKey != "" && dil.address != ""
}
return false
}
/// Emits events
func emit(event: String) -> AnyObject {
return ""
}
/// Returns all the event filters
///
/// :returns: [String] of all the event filters
private func getFullEventFilters() -> [String] {
return eventFilters
}
/// Updates the subscription with the one passed in
///
/// :param: subscription New subscription passed in
private func updateSubscription(subscription: ISubscription) {
self.subscription = subscription
}
/// Unsubscribes from subscription
private func unsubscribe() {
if let channel = subscription?.deliveryMode.address {
pubnub?.unsubscribeFromChannelGroups([channel], withPresence: true)
}
self.subscription = nil
self.eventFilters = []
self.pubnub = nil
if let sub = subscription {
platform.apiCall([
"method": "DELETE",
"url": "/restapi/v1.0/subscription/" + sub.id,
"body": [
"eventFilters": getFullEventFilters(),
"deliveryMode": [
"transportType": "PubNub",
"encryption": "false"
]
]
])
}
}
/// Subscribes to a channel given the settings
private func subscribeAtPubnub() {
let config = PNConfiguration( publishKey: "", subscribeKey: subscription!.deliveryMode.subscriberKey)
self.pubnub = PubNub.clientWithConfiguration(config)
self.pubnub?.addListener(self)
self.pubnub?.subscribeToChannels([subscription!.deliveryMode.address], withPresence: true)
}
/// Notifies
private func notify() {
}
/// Method that PubNub calls when receiving a message back from Subscription
///
/// :param: client The client of the receiver
/// :param: message Message being received back
func client(client: PubNub!, didReceiveMessage message: PNMessageResult!) {
var base64Message = message.data.message as! String
var base64Key = self.subscription!.deliveryMode.encryptionKey
let key = [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00] as [UInt8]
let iv = Cipher.randomIV(AES.blockSize)
let decrypted = AES(key: base64ToByteArray(base64Key), iv: [0x00], blockMode: .ECB)?.decrypt(base64ToByteArray(base64Message), padding: PKCS7())
var endMarker = NSData(bytes: (decrypted as [UInt8]!), length: decrypted!.count)
if let str: String = NSString(data: endMarker, encoding: NSUTF8StringEncoding) as? String {
self.function(arg: str)
} else {
println("error")
}
}
/// Converts base64 to byte array
///
/// :param: base64String base64 String to be converted
/// :returns: [UInt8] byte array
private func base64ToByteArray(base64String: String) -> [UInt8] {
let nsdata: NSData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))!
var bytes = [UInt8](count: nsdata.length, repeatedValue: 0)
nsdata.getBytes(&bytes)
return bytes
}
/// Converts byte array to base64
///
/// :param: bytes byte array to be converted
/// :returns: String of the base64
private func byteArrayToBase64(bytes: [UInt8]) -> String {
let nsdata = NSData(bytes: bytes, length: bytes.count)
let base64Encoded = nsdata.base64EncodedStringWithOptions(nil);
return base64Encoded;
}
/// Converts a dictionary represented as a String into a NSDictionary
///
/// :param: string Dictionary represented as a String
/// :returns: NSDictionary of the String representation of a Dictionary
private func stringToDict(string: String) -> NSDictionary {
var data: NSData = string.dataUsingEncoding(NSUTF8StringEncoding)!
return NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as! NSDictionary
}
}
| 3195b83cc6c7c3bb1c7e0abee5a7f3aa | 34.731629 | 152 | 0.566345 | false | false | false | false |
doubleencore/XcodeIssueGenerator | refs/heads/master | XcodeIssueGeneratorTests/ArgumentParserTests.swift | mit | 1 | //
// ArgumentParserTests.swift
//
// Copyright (c) 2016 POSSIBLE Mobile (https://possiblemobile.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
/**
Test parsing arguments that would be passed into the app like this:
XcodeIssueGenerator -w TODO,WARNING -e CRITICAL -b Release -x Vendor/,ThirdParty/
*/
class ArgumentParserTests: XCTestCase {
var sourceRoot: String!
override func setUp() {
let environmentVariables = ProcessInfo.processInfo.environment
sourceRoot = environmentVariables["SRCROOT"]
}
func testWarningTags() {
let arguments = ["XcodeIssueGenerator", "-w", "TODO, WARNING, FIXME"]
let argumentParser = ArgumentParser(sourceRoot: sourceRoot)
_ = argumentParser.parse(arguments)
XCTAssertEqual(argumentParser.warningTags!, ["TODO", "WARNING", "FIXME"], "Warning tags should match TODO, WARNING, and FIXME.")
}
func testErrorTags() {
let arguments = ["XcodeIssueGenerator", "-e", "FIXME,CRITICAL"]
let argumentParser = ArgumentParser(sourceRoot: sourceRoot)
_ = argumentParser.parse(arguments)
XCTAssertEqual(argumentParser.errorTags!, ["FIXME", "CRITICAL"], "Error tags should match FIXME and CRITICAL.")
}
func testBuildConfiguration() {
let arguments = ["XcodeIssueGenerator", "-b", "ADHOC"]
let argumentParser = ArgumentParser(sourceRoot: sourceRoot)
_ = argumentParser.parse(arguments)
XCTAssertEqual(argumentParser.buildConfig!, "ADHOC", "Build configuration should be ADHOC.")
}
func testExcludeURLs() {
let arguments = ["XcodeIssueGenerator", "-w", "FIXME,CRITICAL", "-x", "XcodeIssueGenerator/Exclude Me/, WHAT/"]
// Also testing invalid exclude directory "WHAT/"
let argumentParser = ArgumentParser(sourceRoot: sourceRoot)
_ = argumentParser.parse(arguments)
XCTAssertTrue(argumentParser.excludeURLs.count == 1, "Although we provided two exclude directories, we expect to parse one exclude directory because the other doesn't exist on disk.")
}
func testMissingExcludeURLs() {
let arguments = ["XcodeIssueGenerator", "-w", "FIXME,CRITICAL", "-x"]
// Also testing invalid exclude directory "WHAT/"
let argumentParser = ArgumentParser(sourceRoot: sourceRoot)
_ = argumentParser.parse(arguments)
XCTAssertTrue(argumentParser.excludeURLs.count == 0, "Missing exclude directories should result in zero excludeURLs.")
}
func testEverything() {
let arguments = ["XcodeIssueGenerator", "-w", "TODO,WARNING", "-e", "FIXME,CRITICAL", "-b", "ADHOC", "-x", "XcodeIssueGenerator/Exclude Me/, XcodeIssueGenerator/"]
let argumentParser = ArgumentParser(sourceRoot: sourceRoot)
_ = argumentParser.parse(arguments)
XCTAssertEqual(argumentParser.warningTags!, ["TODO", "WARNING"], "Warning tags should match TODO and WARNING.")
XCTAssertEqual(argumentParser.errorTags!, ["FIXME", "CRITICAL"], "Error tags should match FIXME and CRITICAL.")
XCTAssertEqual(argumentParser.buildConfig!, "ADHOC", "Build configuration should be ADHOC.")
XCTAssertTrue(argumentParser.excludeURLs.count == 2, "We expect to parse two exclude directories.")
}
func testTooFewArguments() {
let arguments = ["XcodeIssueGenerator"]
let argumentParser = ArgumentParser(sourceRoot: sourceRoot)
XCTAssertFalse(argumentParser.parse(arguments), "Too few arguments for valid program execution.")
}
func testInvalidArguments() {
let arguments = ["XcodeIssueGenerator", "-t", "NOPE"]
let argumentParser = ArgumentParser(sourceRoot: sourceRoot)
XCTAssertFalse(argumentParser.parse(arguments), "Invalid arguments for program execution.")
}
}
| 4d4b597c0f7de7d849a7c2adc4bce79a | 41.824561 | 191 | 0.704629 | false | true | false | false |
joakim666/chainbuilderapp | refs/heads/master | chainbuilder/CalendarContainerViewController.swift | apache-2.0 | 1 | //
// CalendarContainerViewController.swift
// chainbuilder
//
// Created by Joakim Ek on 2017-02-10.
// Copyright © 2017 Morrdusk. All rights reserved.
//
import UIKit
import RealmSwift
struct Thresholds {
struct SwipeVelocity {
static let horizontal = CGFloat(1000.0)
static let vertical = CGFloat(1000.0)
}
struct PanPercentage {
static let horizontal = CGFloat(0.15)
static let vertical = CGFloat(0.06)
}
}
enum Direction : Int {
case up
case right
case down
case left
}
class CalendarContainerViewController: UIViewController {
var panOrigin: CGPoint?
var slotsViewModel: SlotsViewModel?
var activeSlotIndicator: ActiveSlotIndicator?
// the currently showing calendar view controller
var currentCalendarViewController: CalendarViewController?
var defaultInteractionController: AWPercentDrivenInteractiveTransition?
var transitionContext: PrivateTransitionContext?
// This is where subclasses should create their custom view hierarchy if they aren't using a nib. Should never be called directly.
override func loadView() {
let rootView = UIView()
rootView.backgroundColor = UIColor.white
rootView.clipsToBounds = true
self.view = rootView
self.activeSlotIndicator = ActiveSlotIndicator(self.slotsViewModel!)
self.view.addSubview(self.activeSlotIndicator!.view)
refresh()
}
// Called after the view has been loaded. For view controllers created in code, this is after -loadView. For view controllers unarchived from a nib, this is after the view is set.
override func viewDidLoad() {
super.viewDidLoad()
if self.currentCalendarViewController == nil {
if let slotsViewModel = self.slotsViewModel {
if let vc = slotsViewModel.newViewControllerForSlotAt(index: slotsViewModel.activeSlot, currentDateViewModel: CurrentDateViewModel()) {
changeViewController(toViewController: vc)
refresh()
}
else {
log.warning("Failed to get view controller instance for slow \(slotsViewModel.activeSlot) even though the slot passed isValidSlot()")
}
}
else {
log.warning("No slotsViewModel set")
}
}
addPan()
}
override func viewWillLayoutSubviews() {
self.view.fillSuperview()
if let current = currentCalendarViewController {
current.view.fillSuperview()
}
}
func refresh() {
self.activeSlotIndicator?.refresh()
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
}
func addPan() {
log.debug("Adding UIPanGestureRecognizer")
let pr = UIPanGestureRecognizer(target: self, action: #selector(CalendarContainerViewController.handlePan(_:)))
self.view.addGestureRecognizer(pr)
}
func panRight() -> Bool {
var res = false
if let currentCalendarViewController = self.currentCalendarViewController {
if let newViewController = currentCalendarViewController.panRight() {
changeViewController(toViewController: newViewController, direction: Direction.left)
res = true
}
}
return res
}
func panLeft() -> Bool {
var res = false
if let currentCalendarViewController = self.currentCalendarViewController {
if let newViewController = currentCalendarViewController.panLeft() {
changeViewController(toViewController: newViewController, direction: Direction.right)
res = true
}
}
return res
}
func panDown() -> Bool {
guard slotsViewModel!.isValidSlot(index: slotsViewModel!.activeSlot-1) else {
log.debug("Trying to pan to slot with index \(self.slotsViewModel!.activeSlot-1) which is not valid")
return false
}
let currentDateViewModel = self.currentCalendarViewController?.currentDateViewModel ?? CurrentDateViewModel()
guard let vc = slotsViewModel!.newViewControllerForSlotAt(index: slotsViewModel!.activeSlot-1, currentDateViewModel: currentDateViewModel) else {
log.warning("Failed to get view controller instance for slow \(self.slotsViewModel!.activeSlot-1) even though the slot passed isValidSlot()")
return false
}
slotsViewModel!.activeSlot -= 1
changeViewController(toViewController: vc, direction: Direction.up)
return true
}
func panUp() -> Bool {
guard slotsViewModel!.isValidSlot(index: slotsViewModel!.activeSlot+1) else {
log.debug("Trying to pan to slot with index \(self.slotsViewModel!.activeSlot+1) which is not valid")
return false
}
let currentDateViewModel = self.currentCalendarViewController?.currentDateViewModel ?? CurrentDateViewModel()
guard let vc = slotsViewModel!.newViewControllerForSlotAt(index: self.slotsViewModel!.activeSlot+1, currentDateViewModel: currentDateViewModel) else {
log.warning("Failed to get view controller instance for slow \(self.slotsViewModel!.activeSlot+1) even though the slot passed isValidSlot()")
return false
}
self.slotsViewModel!.activeSlot += 1
changeViewController(toViewController: vc, direction: Direction.down)
return true
}
func handlePan(_ sender: UIPanGestureRecognizer) {
struct Context { // TODO remove inner struct later
static var currentDirection: Direction = Direction.left
static var animationActive: Bool = false
}
// get the translation in the view
let t = sender.translation(in: sender.view)
// detect swipe gesture
if sender.state == UIGestureRecognizerState.began {
let velocity = sender.velocity(in: sender.view)
self.panOrigin = sender.location(in: nil) // nil => indicates the window
if fabs(velocity.x) > fabs(velocity.y) {
// horizontal movement was largest
if velocity.x > 0 {
// panning right
log.debug("Panning right")
Context.currentDirection = Direction.right
if panRight() {
Context.animationActive = true
}
else {
Context.animationActive = false
// TODO show bounce animation
}
}
else if velocity.x < 0 {
// panning left
log.debug("Panning left")
Context.currentDirection = Direction.left
if panLeft() {
Context.animationActive = true
}
else {
Context.animationActive = false
// TODO show bounce animation
}
}
}
else {
// vertical movement was largest
if velocity.y > 0 {
// panning down => go to chain above
log.debug("Panning down")
Context.currentDirection = Direction.down
if panDown() {
Context.animationActive = true
}
else {
Context.animationActive = false
// TODO bounce animation
}
}
else if velocity.y < 0 {
// panning up => go to chain below
log.debug("Panning up")
Context.currentDirection = Direction.up
if panUp() {
Context.animationActive = true
}
else {
Context.animationActive = false
// TODO bounce animation
}
}
}
}
else if sender.state == UIGestureRecognizerState.changed {
guard Context.animationActive else {
return
}
let loc = sender.location(in: nil) // nil => indicates the window
if let panOrigin = self.panOrigin {
if Context.currentDirection == Direction.up && loc.y > panOrigin.y {
// the user has reversed direction and moved past start of pan
log.debug("Reversed from up to down")
cancelInteractiveTransition() {
_ = self.panDown()
}
// change direction immediately, and not in the closure above, to avoid multiple calls
Context.currentDirection = Direction.down
}
else if Context.currentDirection == Direction.down && loc.y < panOrigin.y {
// the user has reversed direction and moved past start of pan
log.debug("Reversed from down to up")
cancelInteractiveTransition() {
_ = self.panUp()
}
// change direction immediately, and not in the closure above, to avoid multiple calls
Context.currentDirection = Direction.up
}
else if Context.currentDirection == Direction.left && loc.x > panOrigin.x {
// the user has reversed direction and moved past start of pan
log.debug("Reversed from left to right")
cancelInteractiveTransition() {
_ = self.panRight()
}
// change direction immediately, and not in the closure above, to avoid multiple calls
Context.currentDirection = Direction.right
}
else if Context.currentDirection == Direction.right && loc.x < panOrigin.x {
// the user has reversed direction and moved past start of pan
log.debug("Reversed from right to left")
cancelInteractiveTransition() {
_ = self.panLeft()
}
// change direction immediately, and not in the closure above, to avoid multiple calls
Context.currentDirection = Direction.left
}
else {
// update the percentage completed of the animation
let percent = (Context.currentDirection == Direction.up || Context.currentDirection == Direction.down) ?
fabs(t.y / sender.view!.bounds.size.height) :
fabs(t.x / sender.view!.bounds.size.width)
let modifier: CGFloat = Context.currentDirection == Direction.up || Context.currentDirection == Direction.down ? 1.0 : 0.5
self.defaultInteractionController!.updateInteractiveTransition(percentComplete: percent * modifier)
}
}
}
else if sender.state == UIGestureRecognizerState.ended {
guard Context.animationActive else {
return
}
let velocity = sender.velocity(in: sender.view)
if Context.currentDirection == Direction.up || Context.currentDirection == Direction.down {
if self.defaultInteractionController!.percentComplete > Thresholds.PanPercentage.vertical ||
fabs(velocity.y) > Thresholds.SwipeVelocity.vertical {
self.defaultInteractionController!.finishInteractiveTransition()
}
else {
self.defaultInteractionController!.cancelInteractiveTransition()
}
}
else {
if Context.currentDirection == Direction.left || Context.currentDirection == Direction.right {
if self.defaultInteractionController!.percentComplete > Thresholds.PanPercentage.horizontal ||
fabs(velocity.x) > Thresholds.SwipeVelocity.horizontal {
self.defaultInteractionController!.finishInteractiveTransition()
}
else {
self.defaultInteractionController!.cancelInteractiveTransition()
}
}
}
Context.animationActive = false // TODO right place to reset value?
}
}
func cancelInteractiveTransition(completion: (() -> Void)?) {
if let completion = completion {
let cb = transitionContext?.completionBlock
transitionContext?.completionBlock = { (didComplete: Bool) -> Void in
log.debug(("New completion block, calling old"))
if let oldCallback = cb {
oldCallback(didComplete)
}
log.debug("Doing new stuff")
completion()
}
self.defaultInteractionController!.cancelInteractiveTransition()
}
}
// Initiate a change to a new calendar view controller
//
// If no previous view controler exists, just shows the view controller. Otherwise it's animated with an interactive pan-controlled animation
func changeViewController(toViewController: CalendarViewController, direction: Direction? = nil) {
let fromViewController = self.childViewControllers.count > 0 ? self.childViewControllers[0] : nil
guard self.isViewLoaded else {
log.debug("view is not loaded")
return
}
if let toView = toViewController.view {
fromViewController?.willMove(toParentViewController: nil)
self.addChildViewController(toViewController)
// If this is the initial presentation, add the new child with no animation.
if fromViewController == nil {
self.view.addSubview(toView)
toView.fillSuperview()
toViewController.didMove(toParentViewController: self)
self.currentCalendarViewController = toViewController
return
}
guard let direction = direction else {
// no direction given, make transition without animation
self.view.addSubview(toView)
toView.fillSuperview()
toViewController.didMove(toParentViewController: self)
fromViewController?.view.removeFromSuperview()
fromViewController?.removeFromParentViewController()
toViewController.didMove(toParentViewController: self)
self.currentCalendarViewController = toViewController
return
}
log.debug("Animate transition")
// Animate the transition by calling the animator with our private transition context
let animator: UIViewControllerAnimatedTransitioning = SlideInWithSpringAnimator(direction: direction)
self.transitionContext = PrivateTransitionContext(fromViewController: fromViewController!, toViewController: toViewController, direction: direction)
guard let transitionContext = self.transitionContext else {
log.warning("Failed to create transition context")
return
}
self.defaultInteractionController = AWPercentDrivenInteractiveTransition(animator: animator)
transitionContext.isInteractive = true
transitionContext.completionBlock = { (didComplete: Bool) -> Void in
if didComplete {
// finished normally
fromViewController?.view.removeFromSuperview()
fromViewController?.removeFromParentViewController()
toViewController.didMove(toParentViewController: self)
// update the currently showing calendar view controller when the animation has finished
self.currentCalendarViewController = toViewController
self.refresh()
}
else {
// was cancelled
toViewController.view.removeFromSuperview()
toViewController.removeFromParentViewController() // needed?
self.refresh()
}
animator.animationEnded?(didComplete)
}
if transitionContext.isInteractive {
self.defaultInteractionController!.startInteractiveTransition(transitionContext)
}
else {
animator.animateTransition(using: transitionContext)
}
}
}
}
// Own custom implementation of a UIViewControllerContextTransitioning for use in a view container controller setup.
// Based on code from https://github.com/objcio/issue-12-custom-container-transitions/blob/stage-2/Container%20Transitions/ContainerViewController.m
// and the tutorial here https://www.objc.io/issues/12-animations/custom-container-view-controller-transitions/
class PrivateTransitionContext: NSObject, UIViewControllerContextTransitioning {
private var privateViewControllers = [UITransitionContextViewControllerKey: UIViewController]()
private var privateDisappearingFromRect: CGRect
private var privateAppearingFromRect: CGRect
private var privateDisappearingToRect: CGRect
private var privateAppearingToRect: CGRect
var containerView: UIView
var isAnimated = true
var isInteractive = false
var transitionWasCancelled = false
let presentationStyle = UIModalPresentationStyle.custom
let targetTransform = CGAffineTransform.identity
// first parameter didComplete
var completionBlock: ((_: Bool) -> Void)?
init?(fromViewController: UIViewController, toViewController: UIViewController, direction: Direction) {
log.debug("Init")
guard fromViewController.isViewLoaded else {
log.error("The fromViewController view must reside in the container view upon initializing the transition context")
return nil
}
guard fromViewController.view.superview != nil else {
log.error("The fromViewController view must reside in the container view upon initializing the transition context")
return nil
}
self.containerView = fromViewController.view.superview! // protected by guard statement above
self.privateViewControllers[UITransitionContextViewControllerKey.from] = fromViewController
self.privateViewControllers[UITransitionContextViewControllerKey.to] = toViewController
let dx: CGFloat
let dy: CGFloat
if direction == Direction.left || direction == Direction.right {
dx = direction == Direction.left ? -self.containerView.bounds.size.width : self.containerView.bounds.size.width
dy = 0
}
else { // it's up or down
dx = 0
dy = direction == Direction.up ? -self.containerView.bounds.size.height : self.containerView.bounds.size.height
}
self.privateDisappearingFromRect = self.containerView.bounds
self.privateAppearingToRect = self.containerView.bounds
self.privateDisappearingToRect = self.containerView.bounds.offsetBy(dx: dx, dy: dy)
self.privateAppearingFromRect = self.containerView.bounds.offsetBy(dx: -dx, dy: -dy)
}
func completeTransition(_ didComplete: Bool) {
if let completionBlock = completionBlock {
completionBlock(didComplete)
}
}
func updateInteractiveTransition(_ percentComplete: CGFloat) {}
func finishInteractiveTransition() {
self.transitionWasCancelled = false
}
func cancelInteractiveTransition() {
self.transitionWasCancelled = true
}
func pauseInteractiveTransition() {}
func initialFrame(for vc: UIViewController) -> CGRect {
if let fromVC = self.viewController(forKey: UITransitionContextViewControllerKey.from) {
if fromVC.isEqual(vc) {
return self.privateDisappearingFromRect
}
else {
return self.privateAppearingFromRect
}
}
else {
return self.privateAppearingFromRect
}
}
func finalFrame(for vc: UIViewController) -> CGRect {
if let fromVC = self.viewController(forKey: UITransitionContextViewControllerKey.from) {
if fromVC.isEqual(vc) {
return self.privateDisappearingToRect
}
else {
return self.privateAppearingToRect
}
}
else {
return self.privateAppearingToRect
}
}
func viewController(forKey key: UITransitionContextViewControllerKey) -> UIViewController? {
return self.privateViewControllers[key]
}
@available(iOS 8.0, *)
public func view(forKey key: UITransitionContextViewKey) -> UIView? {
switch key {
case UITransitionContextViewKey.from:
if let vc = viewController(forKey: UITransitionContextViewControllerKey.from) {
return vc.view
}
case UITransitionContextViewKey.to:
if let vc = viewController(forKey: UITransitionContextViewControllerKey.to) {
return vc.view
}
default:
return nil
}
return nil
}
}
| 8ce9dbe345fb464d252b0b52ce3f9413 | 39.86 | 183 | 0.584079 | false | false | false | false |
izotx/iTenWired-Swift | refs/heads/master | Conference App/AnnotationDetailViewController.swift | bsd-2-clause | 1 | // Copyright (c) 2016, Izotx
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Izotx nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// AnnotationDetailViewController.swift
// Conference App
//
// Created by Julian L on 4/13/16.
import UIKit
import MapKit
import CoreLocation
class AnnotationDetailViewController: UIViewController {
/// Received from MapViewController.swift in form of AddAnnotation()
var receivedAnnotation: AddAnnotation?
@IBOutlet var pointTitle: UILabel!
@IBOutlet var pointInfo: UILabel!
/// Dismiss button, not needed since navigation is working
@IBAction func dismissView(sender: AnyObject) {
if self.navigationController != nil {
navigationController?.popViewControllerAnimated(true)
}
else {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
/// Get Directions to Annotation Location
@IBAction func getDirections(sender: AnyObject) {
if let mainLatitude = receivedAnnotation?.coordinate.latitude, let mainLongitude = receivedAnnotation?.coordinate.longitude, let mainName = receivedAnnotation?.title {
let localLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(mainLatitude, mainLongitude)
let placemark = MKPlacemark(coordinate: localLocation, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = mainName
let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving]
mapItem.openInMapsWithLaunchOptions(launchOptions)
}
}
override func viewDidLoad() {
super.viewDidLoad()
UIConfig() // Configures the UI with the Itenwired Colors
if let annotationName = receivedAnnotation?.title, let annotationInfo = receivedAnnotation?.info {
pointTitle.text = annotationName
pointInfo.text = annotationInfo
}
}
internal func UIConfig(){
self.view.backgroundColor = ItenWiredStyle.background.color.mainColor
self.pointTitle.textColor = ItenWiredStyle.text.color.mainColor
self.pointInfo.textColor = ItenWiredStyle.text.color.mainColor
self.navigationController?.navigationBarHidden = false
}
}
| 11676286499e477acb42304708bb584e | 43.418605 | 175 | 0.713351 | false | false | false | false |
ilyahal/VKMusic | refs/heads/master | VkPlaylist/PopularMusicTableViewController.swift | mit | 1 | //
// PopularMusicTableViewController.swift
// VkPlaylist
//
// MIT License
//
// Copyright (c) 2016 Ilya Khalyapin
//
// 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 PopularMusicTableViewController: MusicFromInternetTableViewController {
/// Запрос на получение данных с сервера
override var getRequest: (() -> Void)! {
return getPopularAudio
}
/// Статус выполнения запроса к серверу
override var requestManagerStatus: RequestManagerObject.State {
return RequestManager.sharedInstance.getPopularAudio.state
}
/// Ошибки при выполнении запроса к серверу
override var requestManagerError: RequestManagerObject.ErrorRequest {
return RequestManager.sharedInstance.getPopularAudio.error
}
override func viewDidLoad() {
super.viewDidLoad()
if VKAPIManager.isAuthorized {
getRequest()
}
}
// MARK: Выполнение запроса на получение популярных аудиозаписей
/// Запрос на получение популярных аудиозаписей с сервера
func getPopularAudio() {
RequestManager.sharedInstance.getPopularAudio.performRequest() { success in
self.playlistIdentifier = NSUUID().UUIDString
self.music = DataManager.sharedInstance.popularMusic.array
self.reloadTableView()
if let refreshControl = self.refreshControl {
if refreshControl.refreshing { // Если данные обновляются
refreshControl.endRefreshing() // Говорим что обновление завершено
}
}
if !success {
switch self.requestManagerError {
case .UnknownError:
let alertController = UIAlertController(title: "Ошибка", message: "Произошла какая-то ошибка, попробуйте еще раз...", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "ОК", style: .Default, handler: nil)
alertController.addAction(okAction)
dispatch_async(dispatch_get_main_queue()) {
self.presentViewController(alertController, animated: false, completion: nil)
}
default:
break
}
}
}
}
// MARK: Получение ячеек для строк таблицы helpers
// Текст для ячейки с сообщением о том, что сервер вернул пустой массив
override var noResultsLabelText: String {
return "Нет популярных"
}
// Текст для ячейки с сообщением о необходимости авторизоваться
override var noAuthorizedLabelText: String {
return "Необходимо авторизоваться"
}
}
| bad88cf2f1c24476f35031c96a9cea27 | 36.826923 | 161 | 0.650229 | false | false | false | false |
hikelee/hotel | refs/heads/master | Sources/Common/Models/User.swift | mit | 1 | import Vapor
import Fluent
import HTTP
public final class User: RestModel {
public static var entity: String {
return "common_user"
}
public var id: Node?
public var name: String?
public var salt:String?
public var password: String?
public var title: String?
public var exists: Bool = false //used in fluent
public convenience init(node: Node, in context: Context) throws {
try self.init(node:node)
}
public init(node: Node) throws {
id = try? node.extract("id")
title = try? node.extract("title")
name = try? node.extract("name")
salt = try? node.extract("salt")
password = try? node.extract("password")
}
public func makeNode() throws -> Node {
return try Node.init(
node:[ "id": id,
"title": title,
"name": name,
"salt": salt,
"password": password,
]
)
}
public func validate(isCreate: Bool) throws ->[String:String] {
var result:[String:String]=[:]
if name?.isEmpty ?? true {result["name"] = "必填项"}
if isCreate {
if password?.isEmpty ?? true {result["password"] = "必填项"}
}
if title?.isEmpty ?? true {result["title"] = "必填项"}
return result
}
}
| 05d9cb0c13619c3a96babd556dab909d | 27.404255 | 69 | 0.549064 | false | false | false | false |
BrunoMazzo/CocoaHeadsApp | refs/heads/master | CocoaHeadsApp/Classes/AppCoordinator.swift | mit | 2 | import UIKit
class AppCoordinator: ParentCoordinator, CoordinatorDelegate {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
var childrenCoordinator = [Coordinator]()
func start() -> UIViewController {
let meetupCoordinator = MeetupCoordinator(delegate: self)
childrenCoordinator.append(meetupCoordinator)
let meetupStartViewController = meetupCoordinator.start()
window.rootViewController = meetupStartViewController
window.makeKeyAndVisible()
return meetupStartViewController
}
} | 3414988d5bb59154a43b189e2857709d | 31.5 | 65 | 0.708904 | false | false | false | false |
tombcz/numberthink | refs/heads/master | NumberThink/AppDelegate.swift | mit | 1 |
import UIKit
import CoreData
//import SQLite3 // when Xcode 9 is released, we can use this and remove the Bridging-Header.h file
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
AppDelegate.migrate()
AppDelegate.setupDataFile(fileName:"words.csv")
return true
}
//
// Copies the file with the given name from the bundle into the Documents folder
// if it does not already exist.
//
static func setupDataFile(fileName:(String)) {
let documentsURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let fileURL = documentsURL.appendingPathComponent(fileName)
if !( (try? fileURL.checkResourceIsReachable()) ?? false) {
let bundleURL = Bundle.main.resourceURL?.appendingPathComponent(fileName)
try? FileManager.default.copyItem(atPath: (bundleURL?.path)!, toPath: fileURL.path)
}
}
//
// Migrates a user's custom peg word list from pre-v5 versions of the app. We
// just check to see if the old sqlite database exists, and if so, extract the
// word list, write our simple CSV file, and then rename the database file.
//
static func migrate() {
let documentsURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let dbURL = documentsURL.appendingPathComponent("numberthink.sql")
if ((try? dbURL.checkResourceIsReachable()) ?? false) {
var words = [String:String]()
var db: OpaquePointer?
if sqlite3_open(dbURL.path, &db) == SQLITE_OK {
var statement: OpaquePointer?
if sqlite3_prepare_v2(db, "select word, number from tb_Peg", -1, &statement, nil) == SQLITE_OK {
while sqlite3_step(statement) == SQLITE_ROW {
let word = String(cString:sqlite3_column_text(statement, 0))
let number = String(cString:sqlite3_column_text(statement, 1))
words[word] = number
}
sqlite3_finalize(statement)
statement = nil
}
}
if words.count > 0 {
var csv = String()
for tuple in words {
csv.append("\(tuple.value),\(tuple.key)\n")
}
let csvURL = documentsURL.appendingPathComponent("words.csv")
try? csv.write(to: csvURL, atomically: false, encoding: .utf8)
}
let newDbURL = documentsURL.appendingPathComponent("numberthink_old.sql")
try? FileManager.default.moveItem(at: dbURL, to: newDbURL)
}
}
}
| f4bd12a33b917d5190541d29b97912aa | 43.25 | 144 | 0.604852 | false | false | false | false |
khoren93/SwiftHub | refs/heads/master | SwiftHub/Modules/User Details/ContributionsCell.swift | mit | 1 | //
// ContributionsCell.swift
// SwiftHub
//
// Created by Sygnoos9 on 5/12/20.
// Copyright © 2020 Khoren Markosyan. All rights reserved.
//
import UIKit
import RxSwift
class ContributionsCell: DefaultTableViewCell {
lazy var containerStackView: StackView = {
let views: [UIView] = [self.stackView, self.contributionsView]
let view = StackView(arrangedSubviews: views)
view.spacing = inset
view.axis = .vertical
return view
}()
lazy var contributionsView: ContributionsView = {
let view = ContributionsView()
return view
}()
override func makeUI() {
super.makeUI()
leftImageView.contentMode = .center
leftImageView.cornerRadius = 0
leftImageView.snp.updateConstraints { (make) in
make.size.equalTo(30)
}
detailLabel.isHidden = true
secondDetailLabel.textAlignment = .right
textsStackView.axis = .horizontal
textsStackView.distribution = .fillEqually
stackView.snp.removeConstraints()
containerView.addSubview(containerStackView)
containerStackView.snp.makeConstraints({ (make) in
make.edges.equalToSuperview().inset(inset)
})
rightImageView.theme.tintColor = themeService.attribute { $0.secondary }
}
override func bind(to viewModel: TableViewCellViewModel) {
super.bind(to: viewModel)
guard let viewModel = viewModel as? ContributionsCellViewModel else { return }
cellDisposeBag = DisposeBag()
viewModel.contributionCalendar.bind(to: contributionsView.calendar).disposed(by: cellDisposeBag)
viewModel.contributionCalendar.map { $0 == nil }.bind(to: contributionsView.rx.isHidden).disposed(by: cellDisposeBag)
}
}
| 25fe993fb1705b64d6d8dc9155b95941 | 31 | 125 | 0.672433 | false | false | false | false |
Jillderon/daily-deals | refs/heads/master | DailyDeals/FilterDealViewController.swift | mit | 1 | //
// FilterDealViewController.swift
// DailyDeals
//
// Description:
// This ViewController displays a pickerView where the user can select a category.
// Only deals of this category will be showed in the MapViewController.
//
// Created by practicum on 12/01/17.
// Copyright © 2017 Jill de Ron. All rights reserved.
//
import UIKit
import FirebaseDatabase
class FilterDealViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
// MARK: Outlet.
@IBOutlet weak var pickerView: UIPickerView!
// MARK: Variables.
let dealsCategories = ["All Deals", "Shopping", "Food", "Hotels", "Activities", "Party", "Other"]
var category = String()
var deals = [Deal]()
// MARK: Actions.
@IBAction func didTouchFilter(_ sender: Any) {
filterDeals()
NotificationCenter.default.post(name: Notification.Name(rawValue: "annotationsFiltered"), object: deals)
self.navigationController!.popViewController(animated: true)
}
// MARK: Standard functions.
override func viewDidLoad() {
super.viewDidLoad()
// Needed to let pickerView function correctly.
pickerView.delegate = self
pickerView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: PickerView Functions.
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let str = dealsCategories[row]
return NSAttributedString(string: str, attributes: [NSForegroundColorAttributeName:UIColor.white])
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dealsCategories.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.category = dealsCategories[row]
}
private func filterDeals() {
// Temporary variable to store filtered deals in.
// Filtered deals are deals that belong to the selected category.
var filteredDeals = [Deal]()
if self.category == "All Deals" || self.category == "" {
filteredDeals = self.deals
} else {
for deal in deals {
if deal.category == category {
filteredDeals.append(deal)
}
}
}
self.deals = filteredDeals
}
}
| 1c6f805e6eeb5b3790b170f1879a2c20 | 31.146341 | 133 | 0.641123 | false | false | false | false |
MaartenBrijker/project | refs/heads/back | project/External/AudioKit-master/AudioKit/Common/User Interface/AKNodeOutputPlot.swift | apache-2.0 | 1 | //
// AKNodeOutputPlot.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
/// Plot the output from any node in an signal processing graph
@IBDesignable
public class AKNodeOutputPlot: EZAudioPlot {
internal func setupNode(input: AKNode?) {
input?.avAudioNode.installTapOnBus(0, bufferSize: bufferSize, format: AudioKit.format) { [weak self] (buffer, time) -> Void in
if let strongSelf = self {
buffer.frameLength = strongSelf.bufferSize
let offset = Int(buffer.frameCapacity - buffer.frameLength)
let tail = buffer.floatChannelData[0]
strongSelf.updateBuffer(&tail[offset], withBufferSize: strongSelf.bufferSize)
}
}
}
internal let bufferSize: UInt32 = 512
/// The node whose output to graph
public var node: AKNode? {
willSet {
node?.avAudioNode.removeTapOnBus(0)
}
didSet {
setupNode(node)
}
}
deinit {
node?.avAudioNode.removeTapOnBus(0)
}
/// Required coder-based initialization (for use with Interface Builder)
///
/// - parameter coder: NSCoder
///
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupNode(nil)
}
/// Initialize the plot with the output from a given node and optional plot size
///
/// - parameter input: AKNode from which to get the plot data
/// - parameter width: Width of the view
/// - parameter height: Height of the view
///
public init(_ input: AKNode, frame: CGRect) {
super.init(frame: frame)
self.plotType = .Buffer
self.backgroundColor = AKColor.whiteColor()
self.shouldCenterYAxis = true
setupNode(input)
}
}
| 45b3181d3076dc66b4ab2711e17f7743 | 28.19697 | 134 | 0.615464 | false | false | false | false |
auth0/Auth0.swift | refs/heads/master | Auth0Tests/LoggerSpec.swift | mit | 1 | import Foundation
import Quick
import Nimble
@testable import Auth0
class LoggerSpec: QuickSpec {
override func spec() {
it("should build with default output") {
let logger = DefaultLogger()
expect(logger.output as? DefaultOutput).toNot(beNil())
}
var logger: Logger!
var output: SpyOutput!
beforeEach {
output = SpyOutput()
logger = DefaultLogger(output: output)
}
describe("request") {
var request: URLRequest!
beforeEach {
request = URLRequest(url: URL(string: "https://auth0.com")!)
request.httpMethod = "POST"
request.allHTTPHeaderFields = ["Content-Type": "application/json"]
}
it("should log request basic info") {
logger.trace(request: request, session: URLSession.shared)
expect(output.messages.first) == "POST https://auth0.com HTTP/1.1"
}
it("should log request header") {
logger.trace(request: request, session: URLSession.shared)
expect(output.messages).to(contain("Content-Type: application/json"))
}
it("should log additional request header") {
let sessionConfig = URLSession.shared.configuration
sessionConfig.httpAdditionalHeaders = ["Accept": "application/json"]
let urlSession = URLSession(configuration: sessionConfig)
logger.trace(request: request, session: urlSession)
expect(output.messages).to(contain("Accept: application/json"))
}
it("should log request body") {
let json = "{key: \"\(UUID().uuidString)\"}"
request.httpBody = json.data(using: .utf8)
logger.trace(request: request, session: URLSession.shared)
expect(output.messages).to(contain(json))
}
it("should log nothing for invalid request") {
request.url = nil
logger.trace(request: request, session: URLSession.shared)
expect(output.messages).to(beEmpty())
}
}
describe("response") {
var response: HTTPURLResponse!
beforeEach {
response = HTTPURLResponse(url: URL(string: "https://auth0.com")!, statusCode: 200, httpVersion: nil, headerFields: ["Content-Type": "application/json"])
}
it("should log response basic info") {
logger.trace(response: response, data: nil)
expect(output.messages.first) == "HTTP/1.1 200"
}
it("should log response header") {
logger.trace(response: response, data: nil)
expect(output.messages).to(contain("Content-Type: application/json"))
}
it("should log response body") {
let json = "{key: \"\(UUID().uuidString)\"}"
logger.trace(response: response, data: json.data(using: .utf8))
expect(output.messages).to(contain(json))
}
it("should log nothing for non http response") {
let response = URLResponse()
logger.trace(response: response, data: nil)
expect(output.messages).to(beEmpty())
}
}
describe("url") {
it("should log url") {
logger.trace(url: URL(string: "https://samples.auth0.com/callback")!, source: nil)
expect(output.messages.first) == "URL: https://samples.auth0.com/callback"
}
it("should log url with source") {
logger.trace(url: URL(string: "https://samples.auth0.com/callback")!, source: "Safari")
expect(output.messages.first) == "Safari: https://samples.auth0.com/callback"
}
}
}
}
class SpyOutput: LoggerOutput {
var messages: [String] = []
func log(message: String) {
messages.append(message)
}
func newLine() { }
}
| 8576066970d2bfa93e596c082f625d8a | 32.617886 | 169 | 0.545828 | false | false | false | false |
DDSSwiftTech/SwiftGtk | refs/heads/master | Sources/Widget.swift | mit | 2 | //
// Copyright © 2015 Tomas Linhart. All rights reserved.
//
import CGtk
open class Widget {
private var signals: [(UInt, Any)] = []
var widgetPointer: UnsafeMutablePointer<GtkWidget>?
public weak var parentWidget: Widget? {
willSet {
}
didSet {
if parentWidget != nil {
didMoveToParent()
} else {
didMoveFromParent()
removeSignals()
}
}
}
init() {
widgetPointer = nil
}
deinit {
removeSignals()
}
private func removeSignals() {
for (handlerId, _) in signals {
disconnectSignal(widgetPointer, handlerId: handlerId)
}
signals = []
}
func didMoveToParent() {
}
func didMoveFromParent() {
}
/// Adds a signal that is not carrying any additional information.
func addSignal(name: String, callback: @escaping SignalCallbackZero) {
let box = SignalBoxZero(callback: callback)
let handler: @convention(c) (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void = { sender, data in
let box = unsafeBitCast(data, to: SignalBoxZero.self)
box.callback()
}
let handlerId = connectSignal(widgetPointer, name: name, data: Unmanaged.passUnretained(box).toOpaque(), handler: unsafeBitCast(handler, to: GCallback.self))
signals.append((handlerId, box))
}
func addSignal(name: String, callback: @escaping SignalCallbackOne) {
let box = SignalBoxOne(callback: callback)
let handler: @convention(c) (UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void = { sender, pointer, data in
let box = unsafeBitCast(data, to: SignalBoxOne.self)
box.callback(pointer)
}
let handlerId = connectSignal(widgetPointer, name: name, data: Unmanaged.passUnretained(box).toOpaque(), handler: unsafeBitCast(handler, to: GCallback.self))
signals.append((handlerId, box))
}
func addSignal(name: String, callback: @escaping SignalCallbackTwo) {
let box = SignalBoxTwo(callback: callback)
let handler: @convention(c) (UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void = { sender, pointer1, pointer2, data in
let box = unsafeBitCast(data, to: SignalBoxTwo.self)
box.callback(pointer1, pointer2)
}
let handlerId = connectSignal(widgetPointer, name: name, data: Unmanaged.passUnretained(box).toOpaque(), handler: unsafeBitCast(handler, to: GCallback.self))
signals.append((handlerId, box))
}
func addSignal(name: String, callback: @escaping SignalCallbackThree) {
let box = SignalBoxThree(callback: callback)
let handler: @convention(c) (UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void = { sender, pointer1, pointer2, pointer3, data in
let box = unsafeBitCast(data, to: SignalBoxThree.self)
box.callback(pointer1, pointer2, pointer3)
}
let handlerId = connectSignal(widgetPointer, name: name, data: Unmanaged.passUnretained(box).toOpaque(), handler: unsafeBitCast(handler, to: GCallback.self))
signals.append((handlerId, box))
}
func addSignal(name: String, callback: @escaping SignalCallbackFour) {
let box = SignalBoxFour(callback: callback)
let handler: @convention(c) (UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void = { sender, pointer1, pointer2, pointer3, pointer4, data in
let box = unsafeBitCast(data, to: SignalBoxFour.self)
box.callback(pointer1, pointer2, pointer3, pointer4)
}
let handlerId = connectSignal(widgetPointer, name: name, data: Unmanaged.passUnretained(box).toOpaque(), handler: unsafeBitCast(handler, to: GCallback.self))
signals.append((handlerId, box))
}
func addSignal(name: String, callback: @escaping SignalCallbackFive) {
let box = SignalBoxFive(callback: callback)
let handler: @convention(c) (UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void = { sender, pointer1, pointer2, pointer3, pointer4, pointer5, data in
let box = unsafeBitCast(data, to: SignalBoxFive.self)
box.callback(pointer1, pointer2, pointer3, pointer4, pointer5)
}
let handlerId = connectSignal(widgetPointer, name: name, data: Unmanaged.passUnretained(box).toOpaque(), handler: unsafeBitCast(handler, to: GCallback.self))
signals.append((handlerId, box))
}
func addSignal(name: String, callback: @escaping SignalCallbackSix) {
let box = SignalBoxSix(callback: callback)
let handler: @convention(c) (UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void = { sender, pointer1, pointer2, pointer3, pointer4, pointer5, pointer6, data in
let box = unsafeBitCast(data, to: SignalBoxSix.self)
box.callback(pointer1, pointer2, pointer3, pointer4, pointer5, pointer6)
}
let handlerId = connectSignal(widgetPointer, name: name, data: Unmanaged.passUnretained(box).toOpaque(), handler: unsafeBitCast(handler, to: GCallback.self))
signals.append((handlerId, box))
}
public func showAll() {
gtk_widget_show_all(widgetPointer)
}
public func showNow() {
gtk_widget_show_now(widgetPointer)
}
public func show() {
gtk_widget_show(widgetPointer)
}
public func hide() {
gtk_widget_hide(widgetPointer)
}
public var opacity: Double {
get {
return gtk_widget_get_opacity(widgetPointer)
}
set {
gtk_widget_set_opacity(widgetPointer, newValue)
}
}
}
| 1b594ff3f8590f825abf55d16349adfd | 38.582278 | 324 | 0.674448 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/SILGen/import_as_member.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -emit-silgen -I %S/../IDE/Inputs/custom-modules %s | %FileCheck %s
// REQUIRES: objc_interop
import ImportAsMember.A
import ImportAsMember.Class
public func returnGlobalVar() -> Double {
return Struct1.globalVar
}
// CHECK-LABEL: sil {{.*}}returnGlobalVar{{.*}} () -> Double {
// CHECK: %0 = global_addr @IAMStruct1GlobalVar : $*Double
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] %0 : $*Double
// CHECK: [[VAL:%.*]] = load [trivial] [[READ]] : $*Double
// CHECK: return [[VAL]] : $Double
// CHECK-NEXT: }
// N.B. Whether by design or due to a bug, nullable NSString globals
// still import as non-null.
public func returnStringGlobalVar() -> String {
return Panda.cutenessFactor
}
// CHECK-LABEL: sil {{.*}}returnStringGlobalVar{{.*}} () -> @owned String {
// CHECK: %0 = global_addr @PKPandaCutenessFactor : $*NSString
// CHECK: [[VAL:%.*]] = load [copy] %0 : $*NSString
// CHECK: [[BRIDGE:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: [[RESULT:%.*]] = apply [[BRIDGE]](
// CHECK: return [[RESULT]] : $String
// CHECK-NEXT: }
public func returnNullableStringGlobalVar() -> String? {
return Panda.cuddlynessFactor
}
// CHECK-LABEL: sil {{.*}}returnNullableStringGlobalVar{{.*}} () -> @owned Optional<String> {
// CHECK: %0 = global_addr @PKPandaCuddlynessFactor : $*NSString
// CHECK: [[VAL:%.*]] = load [copy] %0 : $*NSString
// CHECK: [[BRIDGE:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: [[RESULT:%.*]] = apply [[BRIDGE]](
// CHECK: [[SOME:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[RESULT]]
// CHECK: return [[SOME]] : $Optional<String>
// CHECK-NEXT: }
// CHECK-LABEL: sil {{.*}}useClass{{.*}}
// CHECK: bb0([[D:%[0-9]+]] : $Double, [[OPTS:%[0-9]+]] : $SomeClass.Options):
public func useClass(d: Double, opts: SomeClass.Options) {
// CHECK: [[CTOR:%[0-9]+]] = function_ref @MakeIAMSomeClass : $@convention(c) (Double) -> @autoreleased SomeClass
// CHECK: [[OBJ:%[0-9]+]] = apply [[CTOR]]([[D]])
let o = SomeClass(value: d)
// CHECK: [[APPLY_FN:%[0-9]+]] = function_ref @IAMSomeClassApplyOptions : $@convention(c) (SomeClass, SomeClass.Options) -> ()
// CHECK: [[BORROWED_OBJ:%.*]] = begin_borrow [[OBJ]]
// CHECK: apply [[APPLY_FN]]([[BORROWED_OBJ]], [[OPTS]])
// CHECK: end_borrow [[BORROWED_OBJ]] from [[OBJ]]
// CHECK: destroy_value [[OBJ]]
o.applyOptions(opts)
}
extension SomeClass {
// CHECK-LABEL: sil hidden @_T0So9SomeClassC16import_as_memberEABSd6double_tcfc
// CHECK: bb0([[DOUBLE:%[0-9]+]] : $Double
// CHECK-NOT: value_metatype
// CHECK: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass
// CHECK: apply [[FNREF]]([[DOUBLE]])
convenience init(double: Double) {
self.init(value: double)
}
}
public func useSpecialInit() -> Struct1 {
// FIXME: the below triggers an assert, due to number or params mismatch
// return Struct1(specialLabel:())
}
| 6c4805282aa97e22aadabd88b3a502df | 41.633803 | 128 | 0.64255 | false | false | false | false |
crescentflare/AppConfigSwift | refs/heads/master | AppConfigSwift/Classes/Helper/AppConfigOrderedDictionary.swift | mit | 1 | //
// AppConfigOrderedDictionary.swift
// AppConfigSwift Pod
//
// Library helper: fixed order dictionary
// Works like a dictionary but has a fixed order and is always mutable
//
public struct AppConfigOrderedDictionary<Tk: Hashable, Tv> {
// --
// MARK: Members
// --
var keys: [Tk] = []
var values: [Tk: Tv] = [:]
// --
// MARK: Initialization
// --
public init() { }
// --
// MARK: Implementation
// --
public func allKeys() -> [Tk] {
return keys
}
public mutating func removeAllObjects() {
keys.removeAll()
values.removeAll()
}
// --
// MARK: Indexing
// --
subscript(key: Tk) -> Tv? {
get {
return self.values[key]
}
set (newValue) {
// Remove value if key is nil
if newValue == nil {
self.values.removeValue(forKey: key)
self.keys = self.keys.filter {$0 != key}
return
}
// Add or replace value
let oldValue = self.values.updateValue(newValue!, forKey: key)
if oldValue == nil {
self.keys.append(key)
}
}
}
// --
// MARK: Describe object
// --
var description: String {
var result = "{\n"
for i in 0..<self.keys.count {
let key = self.keys[i]
if let item = self[key] {
result += "[\(i)]: \(key) => \(item)\n"
}
}
result += "}"
return result
}
}
| f0b93da572be2e8547ba202650f719c1 | 19.469136 | 74 | 0.446924 | false | false | false | false |
kaojohnny/CoreStore | refs/heads/master | CoreStoreDemo/CoreStoreDemo/Transactions Demo/TransactionsDemoViewController.swift | mit | 1 | //
// TransactionsDemoViewController.swift
// CoreStoreDemo
//
// Created by John Rommel Estropia on 2015/05/24.
// Copyright © 2015 John Rommel Estropia. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
import AddressBookUI
import CoreStore
import GCDKit
private struct Static {
static let placeController: ObjectMonitor<Place> = {
try! CoreStore.addStorageAndWait(
SQLiteStore(
fileName: "PlaceDemo.sqlite",
configuration: "TransactionsDemo",
localStorageOptions: .RecreateStoreOnModelMismatch
)
)
var place = CoreStore.fetchOne(From(Place))
if place == nil {
CoreStore.beginSynchronous { (transaction) -> Void in
let place = transaction.create(Into(Place))
place.setInitialValues()
transaction.commitAndWait()
}
place = CoreStore.fetchOne(From(Place))
}
return CoreStore.monitorObject(place!)
}()
}
// MARK: - TransactionsDemoViewController
class TransactionsDemoViewController: UIViewController, MKMapViewDelegate, ObjectObserver {
// MARK: NSObject
deinit {
Static.placeController.removeObserver(self)
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
let longPressGesture = UILongPressGestureRecognizer(
target: self,
action: #selector(self.longPressGestureRecognized(_:))
)
self.mapView?.addGestureRecognizer(longPressGesture)
Static.placeController.addObserver(self)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .Refresh,
target: self,
action: #selector(self.refreshButtonTapped(_:))
)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let alert = UIAlertController(
title: "Transactions Demo",
message: "This demo shows how to use the 3 types of transactions to save updates: synchronous, asynchronous, and unsafe.\n\nTap and hold on the map to change the pin location.",
preferredStyle: .Alert
)
alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let mapView = self.mapView, let place = Static.placeController.object {
mapView.addAnnotation(place)
mapView.setCenterCoordinate(place.coordinate, animated: false)
mapView.selectAnnotation(place, animated: false)
}
}
// MARK: MKMapViewDelegate
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "MKAnnotationView"
var annotationView: MKPinAnnotationView! = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? MKPinAnnotationView
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView.enabled = true
annotationView.canShowCallout = true
annotationView.animatesDrop = true
}
else {
annotationView.annotation = annotation
}
return annotationView
}
// MARK: ObjectObserver
func objectMonitor(monitor: ObjectMonitor<Place>, willUpdateObject object: Place) {
// none
}
func objectMonitor(monitor: ObjectMonitor<Place>, didUpdateObject object: Place, changedPersistentKeys: Set<KeyPath>) {
if let mapView = self.mapView {
mapView.removeAnnotations(mapView.annotations ?? [])
mapView.addAnnotation(object)
mapView.setCenterCoordinate(object.coordinate, animated: true)
mapView.selectAnnotation(object, animated: true)
if changedPersistentKeys.contains("latitude") || changedPersistentKeys.contains("longitude") {
self.geocodePlace(object)
}
}
}
func objectMonitor(monitor: ObjectMonitor<Place>, didDeleteObject object: Place) {
// none
}
// MARK: Private
var geocoder: CLGeocoder?
@IBOutlet weak var mapView: MKMapView?
@IBAction dynamic func longPressGestureRecognized(sender: AnyObject?) {
if let mapView = self.mapView, let gesture = sender as? UILongPressGestureRecognizer where gesture.state == .Began {
let coordinate = mapView.convertPoint(
gesture.locationInView(mapView),
toCoordinateFromView: mapView
)
CoreStore.beginAsynchronous { (transaction) -> Void in
let place = transaction.edit(Static.placeController.object)
place?.coordinate = coordinate
transaction.commit { (_) -> Void in }
}
}
}
@IBAction dynamic func refreshButtonTapped(sender: AnyObject?) {
CoreStore.beginSynchronous { (transaction) -> Void in
let place = transaction.edit(Static.placeController.object)
place?.setInitialValues()
transaction.commitAndWait()
}
}
func geocodePlace(place: Place) {
let transaction = CoreStore.beginUnsafe()
self.geocoder?.cancelGeocode()
let geocoder = CLGeocoder()
self.geocoder = geocoder
geocoder.reverseGeocodeLocation(
CLLocation(latitude: place.latitude, longitude: place.longitude),
completionHandler: { [weak self] (placemarks, error) -> Void in
if let placemark = placemarks?.first, let addressDictionary = placemark.addressDictionary {
let place = transaction.edit(Static.placeController.object)
place?.title = placemark.name
place?.subtitle = ABCreateStringWithAddressDictionary(addressDictionary, true)
transaction.commit { (_) -> Void in }
}
self?.geocoder = nil
}
)
}
}
| bb1dcbf3edd0de4b61bcf827bb3c1e77 | 30.607477 | 189 | 0.58974 | false | false | false | false |
zmian/xcore.swift | refs/heads/main | Sources/Xcore/Cocoa/Extensions/CoreAnimation+Extensions.swift | mit | 1 | //
// Xcore
// Copyright © 2016 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
import QuartzCore
extension CATransaction {
/// A function to group animation transactions and call completion handler when
/// animations for this transaction group are completed.
///
/// - Parameters:
/// - animations: The block that have animations that must be completed before
/// completion handler is called.
/// - completion: A closure object called when animations for this transaction
/// group are completed.
public static func animation(_ animations: () -> Void, completion: (() -> Void)?) {
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
animations()
CATransaction.commit()
}
/// Disables transition animation.
///
/// - Parameter work: The transition code that you want to perform without
/// animation.
public static func performWithoutAnimation(_ work: () -> Void) {
CATransaction.begin()
CATransaction.setDisableActions(true)
work()
CATransaction.commit()
}
}
// MARK: - CATransitionType
extension CATransitionType {
public static let none = Self(rawValue: "")
}
// MARK: - CAMediaTimingFunction
extension CAMediaTimingFunction {
public static let `default` = CAMediaTimingFunction(name: .default)
public static let linear = CAMediaTimingFunction(name: .linear)
public static let easeIn = CAMediaTimingFunction(name: .easeIn)
public static let easeOut = CAMediaTimingFunction(name: .easeOut)
public static let easeInEaseOut = CAMediaTimingFunction(name: .easeInEaseOut)
}
// MARK: - CATransition
extension CATransition {
public static var fade: CATransition {
CATransition().apply {
$0.duration = .default
$0.timingFunction = .easeInEaseOut
$0.type = .fade
}
}
}
// MARK: - CALayer
extension CALayer {
/// A convenience method to return the color at given point in `self`.
///
/// - Parameter point: The point to use to detect color.
/// - Returns: `UIColor` at the specified point.
public func color(at point: CGPoint) -> UIColor {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
var pixel: [UInt8] = [0, 0, 0, 0]
let context = CGContext(
data: &pixel,
width: 1,
height: 1,
bitsPerComponent: 8,
bytesPerRow: 4,
space: colorSpace,
bitmapInfo: bitmapInfo.rawValue
)!
context.translateBy(x: -point.x, y: -point.y)
render(in: context)
return UIColor(
red: CGFloat(pixel[0]) / 255,
green: CGFloat(pixel[1]) / 255,
blue: CGFloat(pixel[2]) / 255,
alpha: CGFloat(pixel[3]) / 255
)
}
}
extension CGColor {
public var uiColor: UIColor {
UIColor(cgColor: self)
}
}
| b1a5935ca12bbd51aac1e0ab3aed187c | 29.267327 | 92 | 0.629375 | false | false | false | false |
SusanDoggie/Doggie | refs/heads/main | Tests/DoggieTests/FourierSpeedTest.swift | mit | 1 | //
// FourierSpeedTest.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Doggie
import XCTest
#if canImport(Accelerate)
import Accelerate
#endif
class FourierSpeedTest: XCTestCase {
func testHalfRadix2CooleyTukeySpeed() {
for log2n in 15...20 {
var sample = [Double](repeating: 0, count: 1 << log2n)
for i in sample.indices {
sample[i] = Double.random(in: 0..<1)
}
var result = [Complex](repeating: Complex(), count: sample.count >> 1)
print("N:", 1 << log2n, terminator: "\t")
var times: [Double] = []
for _ in 0...5 {
let start_t = clock()
HalfRadix2CooleyTukey(log2n, sample, 1, sample.count, &result, 1)
let end_t = clock()
times.append(Double(end_t - start_t) / Double(CLOCKS_PER_SEC))
}
print(times.map { "\($0)" }.joined(separator: "\t"))
}
}
func testRadix2CooleyTukeySpeed() {
for log2n in 15...20 {
var sample = [Double](repeating: 0, count: 1 << log2n)
for i in sample.indices {
sample[i] = Double.random(in: 0..<1)
}
var result = [Complex](repeating: Complex(), count: sample.count)
print("N:", 1 << log2n, terminator: "\t")
var times: [Double] = []
for _ in 0...5 {
let start_t = clock()
Radix2CooleyTukey(log2n, sample, 1, sample.count, &result, 1)
let end_t = clock()
times.append(Double(end_t - start_t) / Double(CLOCKS_PER_SEC))
}
print(times.map { "\($0)" }.joined(separator: "\t"))
}
}
func testRadix2CooleyTukeyComplexSpeed() {
for log2n in 15...20 {
var sample = [Complex](repeating: Complex(), count: 1 << log2n)
for i in sample.indices {
sample[i] = Complex(real: Double.random(in: 0..<1), imag: Double.random(in: 0..<1))
}
var result = [Complex](repeating: Complex(), count: sample.count)
print("N:", 1 << log2n, terminator: "\t")
var times: [Double] = []
for _ in 0...5 {
let start_t = clock()
Radix2CooleyTukey(log2n, sample, 1, sample.count, &result, 1)
let end_t = clock()
times.append(Double(end_t - start_t) / Double(CLOCKS_PER_SEC))
}
print(times.map { "\($0)" }.joined(separator: "\t"))
}
}
#if canImport(Accelerate)
func testZripSpeed() {
for log2n in 15...20 {
let setup = vDSP_create_fftsetupD(vDSP_Length(log2n), FFTRadix(kFFTRadix2))!
var sample = [Double](repeating: 0, count: 1 << log2n)
for i in sample.indices {
sample[i] = Double.random(in: 0..<1)
}
print("N:", 1 << log2n, terminator: "\t")
var times: [Double] = []
for _ in 0...5 {
let start_t = clock()
sample.withUnsafeMutableBufferPointer { sample in
var input = DSPDoubleSplitComplex(realp: sample.baseAddress!, imagp: sample.baseAddress!.successor())
vDSP_fft_zripD(setup, &input, 2, vDSP_Length(log2n), FFTDirection(kFFTDirection_Forward))
}
let end_t = clock()
times.append(Double(end_t - start_t) / Double(CLOCKS_PER_SEC))
}
print(times.map { "\($0)" }.joined(separator: "\t"))
vDSP_destroy_fftsetupD(setup)
}
}
func testZropSpeed() {
for log2n in 15...20 {
let setup = vDSP_create_fftsetupD(vDSP_Length(log2n), FFTRadix(kFFTRadix2))!
var sample = [Double](repeating: 0, count: 1 << log2n)
for i in sample.indices {
sample[i] = Double.random(in: 0..<1)
}
var result = [Double](repeating: 0, count: sample.count << 1)
print("N:", 1 << log2n, terminator: "\t")
var times: [Double] = []
for _ in 0...5 {
let start_t = clock()
sample.withUnsafeMutableBufferPointer { sample in
result.withUnsafeMutableBufferPointer { result in
var input = DSPDoubleSplitComplex(realp: sample.baseAddress!, imagp: sample.baseAddress!.successor())
var output = DSPDoubleSplitComplex(realp: result.baseAddress!, imagp: result.baseAddress!.successor())
vDSP_fft_zropD(setup, &input, 2, &output, 2, vDSP_Length(log2n), FFTDirection(kFFTDirection_Forward))
}
}
let end_t = clock()
times.append(Double(end_t - start_t) / Double(CLOCKS_PER_SEC))
}
print(times.map { "\($0)" }.joined(separator: "\t"))
vDSP_destroy_fftsetupD(setup)
}
}
func testZopSpeed() {
for log2n in 15...20 {
let setup = vDSP_create_fftsetupD(vDSP_Length(log2n), FFTRadix(kFFTRadix2))!
var sample = [Double](repeating: 0, count: 2 << log2n)
for i in sample.indices {
sample[i] = Double.random(in: 0..<1)
}
var result = [Double](repeating: 0, count: sample.count)
print("N:", 1 << log2n, terminator: "\t")
var times: [Double] = []
for _ in 0...5 {
let start_t = clock()
sample.withUnsafeMutableBufferPointer { sample in
result.withUnsafeMutableBufferPointer { result in
var input = DSPDoubleSplitComplex(realp: sample.baseAddress!, imagp: sample.baseAddress!.successor())
var output = DSPDoubleSplitComplex(realp: result.baseAddress!, imagp: result.baseAddress!.successor())
vDSP_fft_zopD(setup, &input, 2, &output, 2, vDSP_Length(log2n), FFTDirection(kFFTDirection_Forward))
}
}
let end_t = clock()
times.append(Double(end_t - start_t) / Double(CLOCKS_PER_SEC))
}
print(times.map { "\($0)" }.joined(separator: "\t"))
vDSP_destroy_fftsetupD(setup)
}
}
#endif
}
| 7864721f27a7a09d9b557d0409854ab0 | 35.076596 | 126 | 0.4862 | false | false | false | false |
KnuffApp/Knuff-iOS | refs/heads/master | Knuff/Views/DeviceView.swift | mit | 1 | //
// DeviceView.swift
// Knuff
//
// Created by Simon Blommegard on 14/04/15.
// Copyright (c) 2015 Bowtie. All rights reserved.
//
import UIKit
class DeviceView: UIImageView {
let screenshotView: UIImageView
let screenshotClockView: UILabel
convenience init() {
let phone = (UIDevice.current.userInterfaceIdiom == .phone)
self.init(image: UIImage(named: phone ? "Phone" : "Pad"))
}
override init(image: UIImage?) {
let phone = (UIDevice.current.userInterfaceIdiom == .phone)
screenshotView = UIImageView(image: UIImage(named: phone ? "Phone Push" : "Pad Push"))
screenshotClockView = UILabel()
super.init(image: image)
screenshotClockView.font = UIFont(name: "HelveticaNeue-Light", size: 4)
screenshotClockView.textColor = UIColor(white: 1, alpha: 0.6)
screenshotClockView.text = "14:24"
screenshotClockView.sizeToFit()
addSubview(screenshotView)
// screenshotView.addSubview(screenshotClockView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let phone = (UIDevice.current.userInterfaceIdiom == .phone)
screenshotView.frame.origin = CGPoint(
x: phone ? 22:23,
y: 7
)
}
}
| ab70cb06c5618c93fd48e78bc5005af7 | 24.326923 | 90 | 0.678056 | false | false | false | false |
XQS6LB3A/LyricsX | refs/heads/master | LyricsX/Component/TouchBarArtworkViewController.swift | gpl-3.0 | 2 | //
// TouchBarCurrentPlayingItem.swift
// LyricsX - https://github.com/ddddxxx/LyricsX
//
// 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 https://mozilla.org/MPL/2.0/.
//
import AppKit
import CXShim
import MusicPlayer
class TouchBarArtworkViewController: NSViewController {
let artworkView = NSImageView()
private var cancelBag = Set<AnyCancellable>()
override func loadView() {
view = artworkView
}
override func viewDidLoad() {
selectedPlayer.currentTrackWillChange
.signal()
.receive(on: DispatchQueue.main.cx)
.invoke(TouchBarArtworkViewController.updateArtworkImage, weaklyOn: self)
.store(in: &cancelBag)
updateArtworkImage()
}
func updateArtworkImage() {
if let image = selectedPlayer.currentTrack?.artwork ?? selectedPlayer.name?.icon {
let size = CGSize(width: 30, height: 30)
self.artworkView.image = NSImage(size: size, flipped: false) { rect in
image.draw(in: rect)
return true
}
} else {
// TODO: Placeholder
self.artworkView.image = nil
}
}
}
| 86ceff886295c8b6fd74b5d2e0b1ec84 | 28.644444 | 90 | 0.61919 | false | false | false | false |
hujewelz/modelSwift | refs/heads/master | ModelSwift/Classes/Type.swift | mit | 1 | //
// Type.swift
// Pods
//
// Created by jewelz on 2017/3/24.
//
//
import Foundation
public enum Type<Value> {
case some(Value)
case array(Value)
case int
case string
case double
case float
case bool
case none
public var value: Any.Type? {
switch self {
case .some(let v):
return v as? Any.Type
case .int:
return Int.self
case .float:
return Float.self
case .double:
return Double.self
case .string:
return String.self
case .bool:
return Bool.self
case .none:
return nil
case .array(let v):
if v is String.Type {
return String.self
} else if v is Int.Type {
return Int.self
} else if v is Float.Type {
return Float.self
} else if v is Double.Type {
return Double.self
} else if v is Bool.Type {
return Bool.self
} else {
return v as? Any.Type
}
}
}
}
public struct Image {
public let subject: Any
/// type of the reflecting subject
public var subjectType: Type<Any> {
let mirror = Mirror(reflecting: subject)
return typeOf(mirror.subjectType)
}
/// An element of the reflected instance's structure. The optional
/// `label` may be used to represent the name
/// of a stored property, and `type` is the stored property`s type.
public typealias Child = (label: String?, type: Type<Any>)
public typealias Children = [Child]
public init(reflecting subject: Any) {
self.subject = subject
}
/// A collection of `Child` elements describing the structure of the
/// reflected subject.
public var children: Children {
var results = [Child]()
let mirror = Mirror(reflecting: self.subject)
for (lab, value) in mirror.children {
let v = (lab, self.subjectType(of: value))
results.append(v)
}
return results
}
private func subjectType(of subject: Any) -> Type<Any> {
let mirror = Mirror(reflecting: subject)
let subjectType = mirror.subjectType
return typeOf(subjectType)
}
private func typeOf(_ subjectType: Any.Type) -> Type<Any> {
//print("subject type: \(subjectType)")
if subjectType is Int.Type || subjectType is Optional<Int>.Type {
return .int
} else if subjectType is String.Type || subjectType is Optional<String>.Type {
return .string
} else if subjectType is Float.Type || subjectType is Optional<Float>.Type {
return .float
} else if subjectType is Double.Type || subjectType is Optional<Double>.Type {
return .double
} else if subjectType is Bool.Type || subjectType is Optional<Bool>.Type {
return .bool
} else if subjectType is Array<String>.Type || subjectType is Optional<Array<String>>.Type {
return .array(String.self)
} else if subjectType is Array<Int>.Type || subjectType is Optional<Array<Int>>.Type {
return .array(Int.self)
} else if subjectType is Array<Float>.Type || subjectType is Optional<Array<Float>>.Type {
return .array(Float.self)
} else if subjectType is Array<Bool>.Type || subjectType is Optional<Array<Bool>>.Type {
return .array(Bool.self)
} else if subjectType is Array<Double>.Type || subjectType is Optional<Array<Double>>.Type {
return .array(Double.self)
}
return .some(subjectType)
}
}
| 9907ce6f6a216077e6334873a6a302aa | 29.07874 | 100 | 0.56466 | false | false | false | false |
sebcode/SwiftHelperKit | refs/heads/master | Tests/IniParserTest.swift | mit | 1 | //
// IniParserTest.swift
// SwiftHelperKit
//
// Copyright © 2015 Sebastian Volland. All rights reserved.
//
import XCTest
@testable import SwiftHelperKit
class IniParserTest: BaseTest {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testParse() {
var ret = IniParser.parse(string: "")
XCTAssertEqual(0, ret.count)
let data = "[credentials]\n"
+ "access_key = access123\n"
+ "secret = secret123\n"
+ "\n"
+ "[config]\n"
+ "\n"
+ "data = 1\n"
+ "test = 2\n"
ret = IniParser.parse(string: data)
XCTAssertEqual(2, ret.count)
XCTAssertEqual(2, ret["config"]!.count)
XCTAssertEqual(2, ret["credentials"]!.count)
if let credentials = ret["credentials"] {
XCTAssertEqual("access123", credentials["access_key"]!)
XCTAssertEqual("secret123", credentials["secret"]!)
}
}
}
| 4e8fbc7ae4de076de677ed1eed33c4d1 | 21.630435 | 67 | 0.544669 | false | true | false | false |
zmarvin/EnjoyMusic | refs/heads/master | Pods/Macaw/Source/model/draw/Color.swift | mit | 1 | import Foundation
open class Color: Fill {
open let val: Int
open static let white: Color = Color( val: 0xFFFFFF )
open static let silver: Color = Color( val: 0xC0C0C0 )
open static let gray: Color = Color( val: 0x808080 )
open static let black: Color = Color( val: 0 )
open static let red: Color = Color( val: 0xFF0000 )
open static let maroon: Color = Color( val: 0x800000 )
open static let yellow: Color = Color( val: 0xFFFF00 )
open static let olive: Color = Color( val: 0x808000 )
open static let lime: Color = Color( val: 0x00FF00 )
open static let green: Color = Color( val: 0x008000 )
open static let aqua: Color = Color( val: 0x00FFFF )
open static let teal: Color = Color( val: 0x008080 )
open static let blue: Color = Color( val: 0x0000FF )
open static let navy: Color = Color( val: 0x000080 )
open static let fuchsia: Color = Color( val: 0xFF00FF )
open static let purple: Color = Color( val: 0x800080 )
public init(val: Int = 0) {
self.val = val
}
// GENERATED
open func r() -> Int {
return ( ( val >> 16 ) & 0xff )
}
// GENERATED
open func g() -> Int {
return ( ( val >> 8 ) & 0xff )
}
// GENERATED
open func b() -> Int {
return ( val & 0xff )
}
// GENERATED
open func a() -> Int {
return ( 255 - ( ( val >> 24 ) & 0xff ) )
}
// GENERATED
public func with(a a: Double) -> Color {
return Color.rgba(r: r(), g: g(), b: b(), a: a)
}
// GENERATED
open class func rgbt(r: Int, g: Int, b: Int, t: Int) -> Color {
return Color( val: ( ( ( ( ( t & 0xff ) << 24 ) | ( ( r & 0xff ) << 16 ) ) | ( ( g & 0xff ) << 8 ) ) | ( b & 0xff ) ) )
}
// GENERATED
open class func rgba(r: Int, g: Int, b: Int, a: Double) -> Color {
return rgbt( r: r, g: g, b: b, t: Int( ( ( 1 - a ) * 255 ) ) )
}
// GENERATED
open class func rgb(r: Int, g: Int, b: Int) -> Color {
return rgbt( r: r, g: g, b: b, t: 0 )
}
}
| 94d85cca02917fc26af21a5e92811753 | 26.75 | 121 | 0.589825 | false | false | false | false |
qvik/qvik-network-ios | refs/heads/develop | QvikNetwork/CachedImageView.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2015-2016 Qvik (www.qvik.fi)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import QvikSwift
import QvikUi
/**
An UIImageView that retrieves the image from ImageCache (default shared instance).
If you set ```placeholderImage```, it will be displayed while the main image loads.
If you set ```thumbnailData```, the thumbnail will be displayed while the main image loads
unless ```placeholderImage``` is set.
If you set ```fadeInColor```, it will be displayed while the main image loads, unless
```placeholderImage``` or ```thumbnailData``` are set.
Example setup:
```swift
cachedImageView.imageUrl = myImageDescriptor?.scaledUrl
cachedImageView.thumbnailData = myImageDescriptor?.thumbnailData
cachedImageView.thumbnailDominantColor = myImageDescriptor?.dominantColor
```
*/
open class CachedImageView: QvikImageView {
/// Placeholder image view; used to display a temporary image (smaller or thumbnail) while actual image loads
fileprivate var placeholderImageView: UIImageView?
/// Duration for fading in the loaded image, in case it is asynchronously loaded.
open var imageFadeInDuration: TimeInterval = 0.3
/// JPEG thumbnail data for the image. Should set this before layout cycle.
open var thumbnailData: Data? = nil {
didSet {
reset()
setNeedsLayout()
}
}
/// Dominant color of the image (and thumbnail). If set, will be displayed while thumbnail image is loaded.
open var thumbnailDominantColor: UIColor?
/// Preview thumbnail blur radius (size of the convolution kernel)
open var thumbnailBlurRadius = 7.0
/// Whether caching thumbnail images is enabled. Disable for less memory usage but poorer reuse performance.
open var enableThumbnailCaching = true
/// Fade-in timeout for the thumbnail in case it was loaded asynchronously, in seconds.
open var thumbnailFadeInDuration: TimeInterval = 0.1 {
didSet {
assert(thumbnailFadeInDuration >= 0.0, "Must not use a negative value!")
}
}
/// Color for a fade-in view; used in case ```thumbnailData``` is not set
@IBInspectable
open var fadeInColor: UIColor? = nil {
didSet {
reset()
setNeedsLayout()
}
}
/// Placeholder image; displayed while actual image loads.
open var placeholderImage: UIImage? = nil {
didSet {
reset()
setNeedsLayout()
}
}
/// ImageCache instance to use. Default value is the shared instance.
open var imageCache = ImageCache.default
/// Callback to be called when the image changes.
open var imageChangedCallback: (() -> Void)?
/// Whether to automaticallty respond to image load notification
open var ignoreLoadNotification = false
override open var image: UIImage? {
didSet {
imageChangedCallback?()
}
}
/// Image URL. Setting this will cause the view to automatically load the image
open var imageUrl: String? = nil {
didSet {
assert(Thread.isMainThread, "Must be called on main thread!")
reset()
setNeedsLayout()
if let imageUrl = imageUrl, !imageUrl.isEmpty {
if imageUrl == oldValue {
// No need to do anything
return
}
self.image = imageCache.getImage(url: imageUrl, loadPolicy: .network)
} else {
self.image = nil
}
}
}
/// Load the thumbnail image from either in-memory cache or from the JPEG data.
fileprivate func loadThumbnail(fromData: Data, completionCallback: @escaping ((_ thumbnail: UIImage?, _ async: Bool) -> Void)) {
var md5: String?
if enableThumbnailCaching {
md5 = self.thumbnailData?.md5().toHexString()
guard let md5 = md5 else {
log.error("Failed to calculate md5 string out of thumb data!")
completionCallback(nil, false)
return
}
// Check if the image is present in in-memory cache
if let thumbImage = ImageCache.default.getImage(url: md5, loadPolicy: .memory) {
completionCallback(thumbImage, false)
return
}
}
// Not in cache; load asynchronously
runInBackground {
let thumbImage = jpegThumbnailDataToImage(data: fromData, maxSize: self.frame.size, thumbnailBlurRadius: self.thumbnailBlurRadius)
if let thumbImage = thumbImage, self.enableThumbnailCaching {
// Put into in-memory cache
ImageCache.default.putImage(image: thumbImage, url: md5!, storeOnDisk: false)
}
runOnMainThread {
completionCallback(thumbImage, true)
}
}
}
/// Resets all the properties (extra views etc) to the original state
fileprivate func reset() {
placeholderImageView?.removeFromSuperview()
placeholderImageView = nil
}
/**
The image for this image view has been loaded into the in-memory cache and is available
for use. The default behavior is to set the image object property from the cache for display.
Extending classes may override this to change the default behavior.
*/
open func imageLoaded() {
if let imageUrl = self.imageUrl {
if let image = ImageCache.default.getImage(url: imageUrl, loadPolicy: .memory) {
// Image loaded & found
self.image = image
// Fade out the thumbnail view
UIView.animate(withDuration: imageFadeInDuration, animations: {
self.placeholderImageView?.alpha = 0.0
}, completion: { _ in
// Remove placeholder views to save memory
self.reset()
})
}
}
}
@objc func imageLoadedNotification(_ notification: Notification) {
assert(Thread.isMainThread, "Must be called on main thread!")
if ignoreLoadNotification {
return
}
if let imageUrl = (notification as NSNotification).userInfo?[ImageCache.urlParam] as? String {
if imageUrl == self.imageUrl {
imageLoaded()
}
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override open func layoutSubviews() {
super.layoutSubviews()
if image == nil {
// No image yet; show a placeholder / thumbnail image if present
if let placeholderImage = placeholderImage {
if placeholderImageView == nil {
placeholderImageView = UIImageView(frame: self.bounds)
placeholderImageView!.contentMode = self.contentMode
placeholderImageView!.image = placeholderImage
insertSubview(placeholderImageView!, at: 0)
}
} else if let thumbnailData = thumbnailData {
if placeholderImageView == nil {
placeholderImageView = UIImageView(frame: self.bounds)
placeholderImageView!.contentMode = self.contentMode
let backgroundColor = thumbnailDominantColor ?? (fadeInColor ?? UIColor.white)
placeholderImageView?.backgroundColor = backgroundColor
loadThumbnail(fromData: thumbnailData) { (thumbnailImage, async) in
self.placeholderImageView?.image = thumbnailImage
if async {
// Fade in the thumbnail
self.placeholderImageView?.alpha = 0
UIView.animate(withDuration: self.thumbnailFadeInDuration, animations: {
self.placeholderImageView?.alpha = 1
}, completion: { _ in
})
}
}
insertSubview(placeholderImageView!, at: 0)
}
} else if let fadeInColor = fadeInColor, placeholderImageView == nil {
// No placeholderImage/thumbnailData data set; show a colored fade-in view
if placeholderImageView == nil {
placeholderImageView = UIImageView(frame: self.bounds)
placeholderImageView!.backgroundColor = fadeInColor
insertSubview(placeholderImageView!, at: 0)
}
}
}
placeholderImageView?.frame = self.frame
}
fileprivate func commonInit() {
NotificationCenter.default.addObserver(self, selector: #selector(imageLoadedNotification), name: NSNotification.Name(rawValue: ImageCache.cacheImageLoadedNotification), object: nil)
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
}
| 9f9ec56a11c1f7e31a8191ea2c910a0a | 36.814545 | 189 | 0.610732 | false | false | false | false |
mercadopago/px-ios | refs/heads/develop | MercadoPagoSDK/MercadoPagoSDK/Flows/OneTap/UI/PXOneTapViewModel+Summary.swift | mit | 1 | import Foundation
extension PXOneTapViewModel {
func shouldShowSummaryModal() -> Bool {
let itemsCount = buildOneTapItemComponents().count
return itemsCount > 0 || hasDiscount()
}
func hasDiscount() -> Bool {
return amountHelper.discount != nil
}
func getSummaryProps() -> [PXSummaryRowProps]? {
let currency: PXCurrency = SiteManager.shared.getCurrency()
let itemComponentsModel = buildOneTapItemComponents()
var props = [PXSummaryRowProps]()
for itemComponent in itemComponentsModel {
if let title = itemComponent.getTitle(), let amountPrice = itemComponent.getUnitAmountPrice() {
var totalAmount: Double = amountPrice
var titleWithQty = title
if let qty = itemComponent.props.quantity {
if qty > 1 {
titleWithQty = "\(qty) \(title)"
} else {
titleWithQty = "\(title)"
}
totalAmount = amountPrice * Double(qty)
}
let formatedAmount = Utils.getAmountFormatted(amount: totalAmount, thousandSeparator: currency.getThousandsSeparatorOrDefault(), decimalSeparator: currency.getDecimalSeparatorOrDefault(), addingCurrencySymbol: currency.getCurrencySymbolOrDefault(), addingParenthesis: false)
props.append((title: titleWithQty, subTitle: itemComponent.getDescription(), rightText: formatedAmount, backgroundColor: nil))
}
}
return props
}
}
| 49de6217f4d2a65519086f5f56c21bfa | 41.891892 | 290 | 0.616887 | false | false | false | false |
ffried/FFCoreData | refs/heads/master | Sources/FFCoreData/UIKit/DataSources/TableViewDataSource.swift | apache-2.0 | 1 | //
// TableViewDataSource.swift
// FFCoreData
//
// Created by Florian Friedrich on 13/06/15.
// Copyright 2015 Florian Friedrich
//
// 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.
//
#if canImport(UIKit) && !os(watchOS)
#if canImport(ObjectiveC)
import ObjectiveC
#endif
import protocol Foundation.NSObjectProtocol
import class Foundation.NSObject
import struct Foundation.IndexPath
import let Foundation.NSNotFound
import enum UIKit.UITableViewCellEditingStyle
import protocol UIKit.UITableViewDataSource
import class UIKit.UITableView
import class UIKit.UITableViewCell
import protocol CoreData.NSFetchRequestResult
import class CoreData.NSFetchedResultsController
@objc public protocol TableViewDataSourceDelegate: NSObjectProtocol {
func tableView(_ tableView: UITableView, cellIdentifierForRowAt indexPath: IndexPath) -> String
func tableView(_ tableView: UITableView, configure cell: UITableViewCell, forRowAt indexPath: IndexPath, with object: NSFetchRequestResult?)
// See UITableViewDataSource
@objc optional func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
@objc optional func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String?
@objc(tableView:canEditRowAtIndexPath:)
optional func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool
@objc(tableView:canMoveRowAtIndexPath:)
optional func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool
@objc(sectionIndexTitlesForTableView:)
optional func sectionIndexTitles(for tableView: UITableView) -> [String]?
@objc(tableView:sectionForSectionIndexTitle:atIndex:)
optional func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int
@objc(tableView:commitEditingStyle:forRowAtIndexPath:)
optional func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)
@objc(tableView:moveRowAtIndexPath:toIndexPath:)
optional func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)
}
public final class TableViewDataSource<Result: NSFetchRequestResult>: NSObject, UITableViewDataSource {
public private(set) weak var tableView: UITableView?
public private(set) weak var fetchedResultsController: NSFetchedResultsController<Result>?
public weak var delegate: TableViewDataSourceDelegate?
public required init(tableView: UITableView, controller: NSFetchedResultsController<Result>, delegate: TableViewDataSourceDelegate) {
self.fetchedResultsController = controller
self.tableView = tableView
self.delegate = delegate
super.init()
self.tableView?.dataSource = self
}
// MARK: UITableViewDataSource
@objc(numberOfSectionsInTableView:)
public dynamic func numberOfSections(in tableView: UITableView) -> Int {
fetchedResultsController?.sections?.count ?? 0
}
@objc public dynamic func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
fetchedResultsController?.sections?[section].numberOfObjects ?? 0
}
@objc(tableView:cellForRowAtIndexPath:)
public dynamic func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = delegate?.tableView(tableView, cellIdentifierForRowAt: indexPath) ?? "Cell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
let object = fetchedResultsController?.object(at: indexPath)
delegate?.tableView(tableView, configure: cell, forRowAt: indexPath, with: object)
return cell
}
@objc public dynamic func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let selectorToCheck = #selector(TableViewDataSourceDelegate.tableView(_:titleForHeaderInSection:))
if let delegate = delegate, delegate.responds(to: selectorToCheck) {
return delegate.tableView?(tableView, titleForHeaderInSection: section)
}
if let count = fetchedResultsController?.sections?.count, count > 0 {
return fetchedResultsController?.sections?[section].name
}
return nil
}
@objc public dynamic func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
delegate?.tableView?(tableView, titleForFooterInSection: section)
}
@objc(sectionIndexTitlesForTableView:)
public dynamic func sectionIndexTitles(for tableView: UITableView) -> [String]? {
delegate?.sectionIndexTitles?(for: tableView) ?? fetchedResultsController?.sectionIndexTitles
}
@objc(tableView:sectionForSectionIndexTitle:atIndex:)
public dynamic func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return delegate?.tableView?(tableView, sectionForSectionIndexTitle: title, at: index)
?? fetchedResultsController?.section(forSectionIndexTitle: title, at: index)
?? NSNotFound
}
@objc(tableView:canEditRowAtIndexPath:)
public dynamic func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
delegate?.tableView?(tableView, canEditRowAt: indexPath) ?? true
}
@objc(tableView:canMoveRowAtIndexPath:)
public dynamic func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
let selectorToCheck = #selector(TableViewDataSourceDelegate.tableView(_:moveRowAt:to:))
return delegate?.tableView?(tableView, canMoveRowAt: indexPath) ?? delegate?.responds(to: selectorToCheck) ?? false
}
@objc(tableView:commitEditingStyle:forRowAtIndexPath:)
public dynamic func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
delegate?.tableView?(tableView, commit: editingStyle, forRowAt: indexPath)
}
@objc(tableView:moveRowAtIndexPath:toIndexPath:)
public dynamic func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
delegate?.tableView?(tableView, moveRowAt: sourceIndexPath, to: destinationIndexPath)
}
}
#endif
| 5f09b4d3ebc750dd84f032d665907769 | 47.774648 | 144 | 0.756136 | false | false | false | false |
JGiola/swift-package-manager | refs/heads/master | Sources/Build/BuildPlan.swift | apache-2.0 | 1 | /*
This source file is part of the Swift.org open source project
Copyright 2015 - 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 Swift project authors
*/
import Basic
import Utility
import PackageModel
import PackageGraph
import PackageLoading
import func POSIX.getenv
public struct BuildParameters {
/// Mode for the indexing-while-building feature.
public enum IndexStoreMode: Equatable {
/// Index store should be enabled.
case on
/// Index store should be disabled.
case off
/// Index store should be enabled in debug configuration.
case auto
}
// FIXME: Error handling.
//
/// Path to the module cache directory to use for SwiftPM's own tests.
public static let swiftpmTestCache = resolveSymlinks(try! determineTempDirectory()).appending(component: "org.swift.swiftpm.tests-3")
/// Returns the directory to be used for module cache.
fileprivate var moduleCache: AbsolutePath {
let base: AbsolutePath
// FIXME: We use this hack to let swiftpm's functional test use shared
// cache so it doesn't become painfully slow.
if getenv("IS_SWIFTPM_TEST") != nil {
base = BuildParameters.swiftpmTestCache
} else {
base = buildPath
}
return base.appending(component: "ModuleCache")
}
/// The path to the data directory.
public let dataPath: AbsolutePath
/// The build configuration.
public let configuration: BuildConfiguration
/// The path to the build directory (inside the data directory).
public var buildPath: AbsolutePath {
return dataPath.appending(component: configuration.dirname)
}
/// The path to the index store directory.
public var indexStore: AbsolutePath {
assert(indexStoreMode != .off, "index store is disabled")
return buildPath.appending(components: "index", "store")
}
/// The path to the code coverage directory.
public var codeCovPath: AbsolutePath {
return buildPath.appending(component: "codecov")
}
/// The path to the code coverage profdata file.
public var codeCovDataFile: AbsolutePath {
return codeCovPath.appending(component: "default.profdata")
}
/// The toolchain.
public let toolchain: Toolchain
/// Destination triple.
public let triple: Triple
/// Extra build flags.
public let flags: BuildFlags
/// Extra flags to pass to Swift compiler.
public var swiftCompilerFlags: [String] {
var flags = self.flags.cCompilerFlags.flatMap({ ["-Xcc", $0] })
flags += self.flags.swiftCompilerFlags
flags += verbosity.ccArgs
return flags
}
/// Extra flags to pass to linker.
public var linkerFlags: [String] {
// Arguments that can be passed directly to the Swift compiler and
// doesn't require -Xlinker prefix.
//
// We do this to avoid sending flags like linker search path at the end
// of the search list.
let directSwiftLinkerArgs = ["-L"]
var flags: [String] = []
var it = self.flags.linkerFlags.makeIterator()
while let flag = it.next() {
if directSwiftLinkerArgs.contains(flag) {
// `-L <value>` variant.
flags.append(flag)
guard let nextFlag = it.next() else {
// We expected a flag but don't have one.
continue
}
flags.append(nextFlag)
} else if directSwiftLinkerArgs.contains(where: { flag.hasPrefix($0) }) {
// `-L<value>` variant.
flags.append(flag)
} else {
flags += ["-Xlinker", flag]
}
}
return flags
}
/// The tools version to use.
public let toolsVersion: ToolsVersion
/// If should link the Swift stdlib statically.
public let shouldLinkStaticSwiftStdlib: Bool
/// Which compiler sanitizers should be enabled
public let sanitizers: EnabledSanitizers
/// If should enable llbuild manifest caching.
public let shouldEnableManifestCaching: Bool
/// The mode to use for indexing-while-building feature.
public let indexStoreMode: IndexStoreMode
/// Whether to enable code coverage.
public let enableCodeCoverage: Bool
/// Checks if stdout stream is tty.
fileprivate let isTTY: Bool = {
guard let stream = stdoutStream.stream as? LocalFileOutputByteStream else {
return false
}
return TerminalController.isTTY(stream)
}()
public var regenerateManifestToken: AbsolutePath {
return dataPath.appending(components: "..", "regenerate-token")
}
public var llbuildManifest: AbsolutePath {
return dataPath.appending(components: "..", configuration.dirname + ".yaml")
}
public init(
dataPath: AbsolutePath,
configuration: BuildConfiguration,
toolchain: Toolchain,
destinationTriple: Triple = Triple.hostTriple,
flags: BuildFlags,
toolsVersion: ToolsVersion = ToolsVersion.currentToolsVersion,
shouldLinkStaticSwiftStdlib: Bool = false,
shouldEnableManifestCaching: Bool = false,
sanitizers: EnabledSanitizers = EnabledSanitizers(),
enableCodeCoverage: Bool = false,
indexStoreMode: IndexStoreMode = .auto
) {
self.dataPath = dataPath
self.configuration = configuration
self.toolchain = toolchain
self.triple = destinationTriple
self.flags = flags
self.toolsVersion = toolsVersion
self.shouldLinkStaticSwiftStdlib = shouldLinkStaticSwiftStdlib
self.shouldEnableManifestCaching = shouldEnableManifestCaching
self.sanitizers = sanitizers
self.enableCodeCoverage = enableCodeCoverage
self.indexStoreMode = indexStoreMode
}
/// Returns the compiler arguments for the index store, if enabled.
fileprivate var indexStoreArguments: [String] {
let addIndexStoreArguments: Bool
switch indexStoreMode {
case .on:
addIndexStoreArguments = true
case .off:
addIndexStoreArguments = false
case .auto:
addIndexStoreArguments = configuration == .debug
}
if addIndexStoreArguments {
return ["-index-store-path", indexStore.asString]
}
return []
}
/// Computes the target triple arguments for a given resolved target.
fileprivate func targetTripleArgs(for target: ResolvedTarget) -> [String] {
var args = ["-target"]
// Compute the triple string for Darwin platform using the platform version.
if triple.isDarwin() {
guard let macOSSupportedPlatform = target.underlyingTarget.getSupportedPlatform(for: .macOS) else {
fatalError("the target \(target) doesn't support building for macOS")
}
args += [triple.tripleString(forPlatformVersion: macOSSupportedPlatform.version.versionString)]
} else {
args += [triple.tripleString]
}
return args
}
/// The current platform we're building for.
var currentPlatform: PackageModel.Platform {
if self.triple.isDarwin() {
return .macOS
} else {
return .linux
}
}
/// Returns the scoped view of build settings for a given target.
fileprivate func createScope(for target: ResolvedTarget) -> BuildSettings.Scope {
return BuildSettings.Scope(target.underlyingTarget.buildSettings, boundCondition: (currentPlatform, configuration))
}
}
/// A target description which can either be for a Swift or Clang target.
public enum TargetBuildDescription {
/// Swift target description.
case swift(SwiftTargetBuildDescription)
/// Clang target description.
case clang(ClangTargetBuildDescription)
/// The objects in this target.
var objects: [AbsolutePath] {
switch self {
case .swift(let target):
return target.objects
case .clang(let target):
return target.objects
}
}
}
/// Target description for a Clang target i.e. C language family target.
public final class ClangTargetBuildDescription {
/// The target described by this target.
public let target: ResolvedTarget
/// The underlying clang target.
public var clangTarget: ClangTarget {
return target.underlyingTarget as! ClangTarget
}
/// The build parameters.
let buildParameters: BuildParameters
/// The modulemap file for this target, if any.
private(set) var moduleMap: AbsolutePath?
/// Path to the temporary directory for this target.
var tempsPath: AbsolutePath {
return buildParameters.buildPath.appending(component: target.c99name + ".build")
}
/// The objects in this target.
var objects: [AbsolutePath] {
return compilePaths().map({ $0.object })
}
/// Any addition flags to be added. These flags are expected to be computed during build planning.
fileprivate var additionalFlags: [String] = []
/// The filesystem to operate on.
let fileSystem: FileSystem
/// If this target is a test target.
public var isTestTarget: Bool {
return target.type == .test
}
/// Create a new target description with target and build parameters.
init(target: ResolvedTarget, buildParameters: BuildParameters, fileSystem: FileSystem = localFileSystem) throws {
assert(target.underlyingTarget is ClangTarget, "underlying target type mismatch \(target)")
self.fileSystem = fileSystem
self.target = target
self.buildParameters = buildParameters
// Try computing modulemap path for a C library.
if target.type == .library {
self.moduleMap = try computeModulemapPath()
}
}
/// An array of tuple containing filename, source, object and dependency path for each of the source in this target.
public func compilePaths()
-> [(filename: RelativePath, source: AbsolutePath, object: AbsolutePath, deps: AbsolutePath)]
{
return target.sources.relativePaths.map({ source in
let path = target.sources.root.appending(source)
let object = tempsPath.appending(RelativePath(source.asString + ".o"))
let deps = tempsPath.appending(RelativePath(source.asString + ".d"))
return (source, path, object, deps)
})
}
/// Builds up basic compilation arguments for this target.
public func basicArguments() -> [String] {
var args = [String]()
// Only enable ARC on macOS.
if buildParameters.triple.isDarwin() {
args += ["-fobjc-arc"]
}
args += buildParameters.targetTripleArgs(for: target)
args += buildParameters.toolchain.extraCCFlags
args += optimizationArguments
args += activeCompilationConditions
args += ["-fblocks"]
// Enable index store, if appropriate.
//
// This feature is not widely available in OSS clang. So, we only enable
// index store for Apple's clang or if explicitly asked to.
if Process.env.keys.contains("SWIFTPM_ENABLE_CLANG_INDEX_STORE") {
args += buildParameters.indexStoreArguments
} else if buildParameters.triple.isDarwin(), (try? buildParameters.toolchain._isClangCompilerVendorApple()) == true {
args += buildParameters.indexStoreArguments
}
if !buildParameters.triple.isWindows() {
// Using modules currently conflicts with the Windows SDKs.
args += ["-fmodules", "-fmodule-name=" + target.c99name]
}
args += ["-I", clangTarget.includeDir.asString]
args += additionalFlags
if !buildParameters.triple.isWindows() {
args += moduleCacheArgs
}
args += buildParameters.sanitizers.compileCFlags()
// Add agruments from declared build settings.
args += self.buildSettingsFlags()
// User arguments (from -Xcc and -Xcxx below) should follow generated arguments to allow user overrides
args += buildParameters.flags.cCompilerFlags
// Add extra C++ flags if this target contains C++ files.
if clangTarget.isCXX {
args += self.buildParameters.flags.cxxCompilerFlags
}
return args
}
/// Returns the build flags from the declared build settings.
private func buildSettingsFlags() -> [String] {
let scope = buildParameters.createScope(for: target)
var flags: [String] = []
// C defines.
let cDefines = scope.evaluate(.GCC_PREPROCESSOR_DEFINITIONS)
flags += cDefines.map({ "-D" + $0 })
// Header search paths.
let headerSearchPaths = scope.evaluate(.HEADER_SEARCH_PATHS)
flags += headerSearchPaths.map({
"-I" + target.sources.root.appending(RelativePath($0)).asString
})
// Frameworks.
let frameworks = scope.evaluate(.LINK_FRAMEWORKS)
flags += frameworks.flatMap({ ["-framework", $0] })
// Other C flags.
flags += scope.evaluate(.OTHER_CFLAGS)
// Other CXX flags.
flags += scope.evaluate(.OTHER_CPLUSPLUSFLAGS)
return flags
}
/// Optimization arguments according to the build configuration.
private var optimizationArguments: [String] {
switch buildParameters.configuration {
case .debug:
if buildParameters.triple.isWindows() {
return ["-g", "-gcodeview", "-O0"]
} else {
return ["-g", "-O0"]
}
case .release:
return ["-O2"]
}
}
/// A list of compilation conditions to enable for conditional compilation expressions.
private var activeCompilationConditions: [String] {
var compilationConditions = ["-DSWIFT_PACKAGE=1"]
switch buildParameters.configuration {
case .debug:
compilationConditions += ["-DDEBUG=1"]
case .release:
break
}
return compilationConditions
}
/// Helper function to compute the modulemap path.
///
/// This function either returns path to user provided modulemap or tries to automatically generates it.
private func computeModulemapPath() throws -> AbsolutePath {
// If user provided the modulemap, we're done.
if fileSystem.isFile(clangTarget.moduleMapPath) {
return clangTarget.moduleMapPath
} else {
// Otherwise try to generate one.
var moduleMapGenerator = ModuleMapGenerator(for: clangTarget, fileSystem: fileSystem)
// FIXME: We should probably only warn if we're unable to generate the modulemap
// because the clang target is still a valid, it just can't be imported from Swift targets.
try moduleMapGenerator.generateModuleMap(inDir: tempsPath)
return tempsPath.appending(component: moduleMapFilename)
}
}
/// Module cache arguments.
private var moduleCacheArgs: [String] {
return ["-fmodules-cache-path=" + buildParameters.moduleCache.asString]
}
}
/// Target description for a Swift target.
public final class SwiftTargetBuildDescription {
/// The target described by this target.
public let target: ResolvedTarget
/// The build parameters.
let buildParameters: BuildParameters
/// Path to the temporary directory for this target.
var tempsPath: AbsolutePath {
return buildParameters.buildPath.appending(component: target.c99name + ".build")
}
/// The objects in this target.
var objects: [AbsolutePath] {
return target.sources.relativePaths.map({ tempsPath.appending(RelativePath($0.asString + ".o")) })
}
/// The path to the swiftmodule file after compilation.
var moduleOutputPath: AbsolutePath {
return buildParameters.buildPath.appending(component: target.c99name + ".swiftmodule")
}
/// Any addition flags to be added. These flags are expected to be computed during build planning.
fileprivate var additionalFlags: [String] = []
/// The swift version for this target.
var swiftVersion: SwiftLanguageVersion {
return (target.underlyingTarget as! SwiftTarget).swiftVersion
}
/// If this target is a test target.
public let isTestTarget: Bool
/// Create a new target description with target and build parameters.
init(target: ResolvedTarget, buildParameters: BuildParameters, isTestTarget: Bool? = nil) {
assert(target.underlyingTarget is SwiftTarget, "underlying target type mismatch \(target)")
self.target = target
self.buildParameters = buildParameters
// Unless mentioned explicitly, use the target type to determine if this is a test target.
self.isTestTarget = isTestTarget ?? (target.type == .test)
}
/// The arguments needed to compile this target.
public func compileArguments() -> [String] {
var args = [String]()
args += buildParameters.targetTripleArgs(for: target)
args += ["-swift-version", swiftVersion.rawValue]
// Enable batch mode in debug mode.
//
// Technically, it should be enabled whenever WMO is off but we
// don't currently make that distinction in SwiftPM
switch buildParameters.configuration {
case .debug:
args += ["-enable-batch-mode"]
case .release: break
}
args += buildParameters.indexStoreArguments
args += buildParameters.toolchain.extraSwiftCFlags
args += optimizationArguments
args += ["-j\(SwiftCompilerTool.numThreads)"]
args += activeCompilationConditions
args += additionalFlags
args += moduleCacheArgs
args += buildParameters.sanitizers.compileSwiftFlags()
// Add arguments needed for code coverage if it is enabled.
if buildParameters.enableCodeCoverage {
args += ["-profile-coverage-mapping", "-profile-generate"]
}
// Add arguments to colorize output if stdout is tty
if buildParameters.isTTY {
args += ["-Xfrontend", "-color-diagnostics"]
}
// Add agruments from declared build settings.
args += self.buildSettingsFlags()
// User arguments (from -Xswiftc) should follow generated arguments to allow user overrides
args += buildParameters.swiftCompilerFlags
return args
}
/// Returns the build flags from the declared build settings.
private func buildSettingsFlags() -> [String] {
let scope = buildParameters.createScope(for: target)
var flags: [String] = []
// Swift defines.
let swiftDefines = scope.evaluate(.SWIFT_ACTIVE_COMPILATION_CONDITIONS)
flags += swiftDefines.map({ "-D" + $0 })
// Frameworks.
let frameworks = scope.evaluate(.LINK_FRAMEWORKS)
flags += frameworks.flatMap({ ["-framework", $0] })
// Other Swift flags.
flags += scope.evaluate(.OTHER_SWIFT_FLAGS)
// Add C flags by prefixing them with -Xcc.
//
// C defines.
let cDefines = scope.evaluate(.GCC_PREPROCESSOR_DEFINITIONS)
flags += cDefines.flatMap({ ["-Xcc", "-D" + $0] })
// Header search paths.
let headerSearchPaths = scope.evaluate(.HEADER_SEARCH_PATHS)
flags += headerSearchPaths.flatMap({ path -> [String] in
let path = target.sources.root.appending(RelativePath(path)).asString
return ["-Xcc", "-I" + path]
})
// Other C flags.
flags += scope.evaluate(.OTHER_CFLAGS).flatMap({ ["-Xcc", $0] })
return flags
}
/// A list of compilation conditions to enable for conditional compilation expressions.
private var activeCompilationConditions: [String] {
var compilationConditions = ["-DSWIFT_PACKAGE"]
switch buildParameters.configuration {
case .debug:
compilationConditions += ["-DDEBUG"]
case .release:
break
}
return compilationConditions
}
/// Optimization arguments according to the build configuration.
private var optimizationArguments: [String] {
switch buildParameters.configuration {
case .debug:
return ["-Onone", "-g", "-enable-testing"]
case .release:
return ["-O"]
}
}
/// Module cache arguments.
private var moduleCacheArgs: [String] {
return ["-module-cache-path", buildParameters.moduleCache.asString]
}
}
/// The build description for a product.
public final class ProductBuildDescription {
/// The reference to the product.
public let product: ResolvedProduct
/// The build parameters.
let buildParameters: BuildParameters
/// The path to the product binary produced.
public var binary: AbsolutePath {
return buildParameters.buildPath.appending(outname)
}
/// The output name of the product.
public var outname: RelativePath {
let name = product.name
switch product.type {
case .executable:
if buildParameters.triple.isWindows() {
return RelativePath("\(name).exe")
} else {
return RelativePath(name)
}
case .library(.static):
return RelativePath("lib\(name).a")
case .library(.dynamic):
return RelativePath("lib\(name).\(self.buildParameters.toolchain.dynamicLibraryExtension)")
case .library(.automatic):
fatalError()
case .test:
let base = "\(name).xctest"
if buildParameters.triple.isDarwin() {
return RelativePath("\(base)/Contents/MacOS/\(name)")
} else {
return RelativePath(base)
}
}
}
/// The objects in this product.
///
// Computed during build planning.
fileprivate(set) var objects = SortedArray<AbsolutePath>()
/// The dynamic libraries this product needs to link with.
// Computed during build planning.
fileprivate(set) var dylibs: [ProductBuildDescription] = []
/// Any additional flags to be added. These flags are expected to be computed during build planning.
fileprivate var additionalFlags: [String] = []
/// The list of targets that are going to be linked statically in this product.
fileprivate var staticTargets: [ResolvedTarget] = []
/// Path to the temporary directory for this product.
var tempsPath: AbsolutePath {
return buildParameters.buildPath.appending(component: product.name + ".product")
}
/// Path to the link filelist file.
var linkFileListPath: AbsolutePath {
return tempsPath.appending(component: "Objects.LinkFileList")
}
/// Create a build description for a product.
init(product: ResolvedProduct, buildParameters: BuildParameters) {
assert(product.type != .library(.automatic), "Automatic type libraries should not be described.")
self.product = product
self.buildParameters = buildParameters
}
/// Strips the arguments which should *never* be passed to Swift compiler
/// when we're linking the product.
///
/// We might want to get rid of this method once Swift driver can strip the
/// flags itself, <rdar://problem/31215562>.
private func stripInvalidArguments(_ args: [String]) -> [String] {
let invalidArguments: Set<String> = ["-wmo", "-whole-module-optimization"]
return args.filter({ !invalidArguments.contains($0) })
}
/// The arguments to link and create this product.
public func linkArguments() -> [String] {
var args = [buildParameters.toolchain.swiftCompiler.asString]
args += buildParameters.toolchain.extraSwiftCFlags
args += buildParameters.sanitizers.linkSwiftFlags()
args += additionalFlags
if buildParameters.configuration == .debug {
if buildParameters.triple.isWindows() {
args += ["-Xlinker","-debug"]
} else {
args += ["-g"]
}
}
args += ["-L", buildParameters.buildPath.asString]
args += ["-o", binary.asString]
args += ["-module-name", product.name.spm_mangledToC99ExtendedIdentifier()]
args += dylibs.map({ "-l" + $0.product.name })
// Add arguements needed for code coverage if it is enabled.
if buildParameters.enableCodeCoverage {
args += ["-profile-coverage-mapping", "-profile-generate"]
}
switch product.type {
case .library(.automatic):
fatalError()
case .library(.static):
// No arguments for static libraries.
return []
case .test:
// Test products are bundle on macOS, executable on linux.
if buildParameters.triple.isDarwin() {
args += ["-Xlinker", "-bundle"]
} else {
args += ["-emit-executable"]
}
case .library(.dynamic):
args += ["-emit-library"]
case .executable:
// Link the Swift stdlib statically if requested.
if buildParameters.shouldLinkStaticSwiftStdlib {
// FIXME: This does not work for linux yet (SR-648).
#if os(macOS)
args += ["-static-stdlib"]
#endif
}
args += ["-emit-executable"]
}
// On linux, set rpath such that dynamic libraries are looked up
// adjacent to the product. This happens by default on macOS.
if buildParameters.triple.isLinux() {
args += ["-Xlinker", "-rpath=$ORIGIN"]
}
args += ["@" + linkFileListPath.asString]
// Add agruments from declared build settings.
args += self.buildSettingsFlags()
// User arguments (from -Xlinker and -Xswiftc) should follow generated arguments to allow user overrides
args += buildParameters.linkerFlags
args += stripInvalidArguments(buildParameters.swiftCompilerFlags)
return args
}
/// Writes link filelist to the filesystem.
func writeLinkFilelist(_ fs: FileSystem) throws {
let stream = BufferedOutputByteStream()
for object in objects {
stream <<< object.asString.spm_shellEscaped() <<< "\n"
}
try fs.createDirectory(linkFileListPath.parentDirectory, recursive: true)
try fs.writeFileContents(linkFileListPath, bytes: stream.bytes)
}
/// Returns the build flags from the declared build settings.
private func buildSettingsFlags() -> [String] {
var flags: [String] = []
// Linked libraries.
let libraries = OrderedSet(staticTargets.reduce([]) {
$0 + buildParameters.createScope(for: $1).evaluate(.LINK_LIBRARIES)
})
flags += libraries.map({ "-l" + $0 })
// Linked frameworks.
let frameworks = OrderedSet(staticTargets.reduce([]) {
$0 + buildParameters.createScope(for: $1).evaluate(.LINK_FRAMEWORKS)
})
flags += frameworks.flatMap({ ["-framework", $0] })
// Other linker flags.
for target in staticTargets {
let scope = buildParameters.createScope(for: target)
flags += scope.evaluate(.OTHER_LDFLAGS)
}
return flags
}
}
/// A build plan for a package graph.
public class BuildPlan {
public enum Error: Swift.Error, CustomStringConvertible, Equatable {
/// The linux main file is missing.
case missingLinuxMain
/// There is no buildable target in the graph.
case noBuildableTarget
public var description: String {
switch self {
case .missingLinuxMain:
return "missing LinuxMain.swift file in the Tests directory"
case .noBuildableTarget:
return "the package does not contain a buildable target"
}
}
}
/// The build parameters.
public let buildParameters: BuildParameters
/// The package graph.
public let graph: PackageGraph
/// The target build description map.
public let targetMap: [ResolvedTarget: TargetBuildDescription]
/// The product build description map.
public let productMap: [ResolvedProduct: ProductBuildDescription]
/// The build targets.
public var targets: AnySequence<TargetBuildDescription> {
return AnySequence(targetMap.values)
}
/// The products in this plan.
public var buildProducts: AnySequence<ProductBuildDescription> {
return AnySequence(productMap.values)
}
/// The filesystem to operate on.
let fileSystem: FileSystem
/// Diagnostics Engine to emit diagnostics
let diagnostics: DiagnosticsEngine
/// Create a build plan with build parameters and a package graph.
public init(
buildParameters: BuildParameters,
graph: PackageGraph,
diagnostics: DiagnosticsEngine,
fileSystem: FileSystem = localFileSystem
) throws {
self.buildParameters = buildParameters
self.graph = graph
self.diagnostics = diagnostics
self.fileSystem = fileSystem
// Create build target description for each target which we need to plan.
var targetMap = [ResolvedTarget: TargetBuildDescription]()
for target in graph.allTargets {
switch target.underlyingTarget {
case is SwiftTarget:
targetMap[target] = .swift(SwiftTargetBuildDescription(target: target, buildParameters: buildParameters))
case is ClangTarget:
targetMap[target] = try .clang(ClangTargetBuildDescription(
target: target,
buildParameters: buildParameters,
fileSystem: fileSystem))
case is SystemLibraryTarget:
break
default:
fatalError("unhandled \(target.underlyingTarget)")
}
}
/// Ensure we have at least one buildable target.
guard !targetMap.isEmpty else {
throw Error.noBuildableTarget
}
if buildParameters.triple.isLinux() {
// FIXME: Create a target for LinuxMain file on linux.
// This will go away once it is possible to auto detect tests.
let testProducts = graph.allProducts.filter({ $0.type == .test })
for product in testProducts {
guard let linuxMainTarget = product.linuxMainTarget else {
throw Error.missingLinuxMain
}
let target = SwiftTargetBuildDescription(
target: linuxMainTarget, buildParameters: buildParameters, isTestTarget: true)
targetMap[linuxMainTarget] = .swift(target)
}
}
var productMap: [ResolvedProduct: ProductBuildDescription] = [:]
// Create product description for each product we have in the package graph except
// for automatic libraries because they don't produce any output.
for product in graph.allProducts where product.type != .library(.automatic) {
productMap[product] = ProductBuildDescription(
product: product, buildParameters: buildParameters)
}
self.productMap = productMap
self.targetMap = targetMap
// Finally plan these targets.
try plan()
}
/// Plan the targets and products.
private func plan() throws {
// Plan targets.
for buildTarget in targets {
switch buildTarget {
case .swift(let target):
try plan(swiftTarget: target)
case .clang(let target):
plan(clangTarget: target)
}
}
// Plan products.
for buildProduct in buildProducts {
try plan(buildProduct)
}
// FIXME: We need to find out if any product has a target on which it depends
// both static and dynamically and then issue a suitable diagnostic or auto
// handle that situation.
}
/// Plan a product.
private func plan(_ buildProduct: ProductBuildDescription) throws {
// Compute the product's dependency.
let dependencies = computeDependencies(of: buildProduct.product)
// Add flags for system targets.
for systemModule in dependencies.systemModules {
guard case let target as SystemLibraryTarget = systemModule.underlyingTarget else {
fatalError("This should not be possible.")
}
// Add pkgConfig libs arguments.
buildProduct.additionalFlags += pkgConfig(for: target).libs
}
// Link C++ if needed.
// Note: This will come from build settings in future.
for target in dependencies.staticTargets {
if case let target as ClangTarget = target.underlyingTarget, target.isCXX {
buildProduct.additionalFlags += self.buildParameters.toolchain.extraCPPFlags
break
}
}
buildProduct.staticTargets = dependencies.staticTargets
buildProduct.dylibs = dependencies.dylibs.map({ productMap[$0]! })
buildProduct.objects += dependencies.staticTargets.flatMap({ targetMap[$0]!.objects })
// Write the link filelist file.
//
// FIXME: We should write this as a custom llbuild task once we adopt it
// as a library.
try buildProduct.writeLinkFilelist(fileSystem)
}
/// Computes the dependencies of a product.
private func computeDependencies(
of product: ResolvedProduct
) -> (
dylibs: [ResolvedProduct],
staticTargets: [ResolvedTarget],
systemModules: [ResolvedTarget]
) {
// Sort the product targets in topological order.
let nodes = product.targets.map(ResolvedTarget.Dependency.target)
let allTargets = try! topologicalSort(nodes, successors: { dependency in
switch dependency {
// Include all the depenencies of a target.
case .target(let target):
return target.dependencies
// For a product dependency, we only include its content only if we
// need to statically link it.
case .product(let product):
switch product.type {
case .library(.automatic), .library(.static):
return product.targets.map(ResolvedTarget.Dependency.target)
case .library(.dynamic), .test, .executable:
return []
}
}
})
// Create empty arrays to collect our results.
var linkLibraries = [ResolvedProduct]()
var staticTargets = [ResolvedTarget]()
var systemModules = [ResolvedTarget]()
for dependency in allTargets {
switch dependency {
case .target(let target):
switch target.type {
// Include executable and tests only if they're top level contents
// of the product. Otherwise they are just build time dependency.
case .executable, .test:
if product.targets.contains(target) {
staticTargets.append(target)
}
// Library targets should always be included.
case .library:
staticTargets.append(target)
// Add system target targets to system targets array.
case .systemModule:
systemModules.append(target)
}
case .product(let product):
// Add the dynamic products to array of libraries to link.
if product.type == .library(.dynamic) {
linkLibraries.append(product)
}
}
}
if buildParameters.triple.isLinux() {
if product.type == .test {
product.linuxMainTarget.map({ staticTargets.append($0) })
}
}
return (linkLibraries, staticTargets, systemModules)
}
/// Plan a Clang target.
private func plan(clangTarget: ClangTargetBuildDescription) {
for dependency in clangTarget.target.recursiveDependencies() {
switch dependency.underlyingTarget {
case let target as ClangTarget where target.type == .library:
// Setup search paths for C dependencies:
clangTarget.additionalFlags += ["-I", target.includeDir.asString]
case let target as SystemLibraryTarget:
clangTarget.additionalFlags += ["-fmodule-map-file=\(target.moduleMapPath.asString)"]
clangTarget.additionalFlags += pkgConfig(for: target).cFlags
default: continue
}
}
}
/// Plan a Swift target.
private func plan(swiftTarget: SwiftTargetBuildDescription) throws {
// We need to iterate recursive dependencies because Swift compiler needs to see all the targets a target
// depends on.
for dependency in swiftTarget.target.recursiveDependencies() {
switch dependency.underlyingTarget {
case let underlyingTarget as ClangTarget where underlyingTarget.type == .library:
guard case let .clang(target)? = targetMap[dependency] else {
fatalError("unexpected clang target \(underlyingTarget)")
}
// Add the path to modulemap of the dependency. Currently we require that all Clang targets have a
// modulemap but we may want to remove that requirement since it is valid for a target to exist without
// one. However, in that case it will not be importable in Swift targets. We may want to emit a warning
// in that case from here.
guard let moduleMap = target.moduleMap else { break }
swiftTarget.additionalFlags += [
"-Xcc", "-fmodule-map-file=\(moduleMap.asString)",
"-I", target.clangTarget.includeDir.asString,
]
case let target as SystemLibraryTarget:
swiftTarget.additionalFlags += ["-Xcc", "-fmodule-map-file=\(target.moduleMapPath.asString)"]
swiftTarget.additionalFlags += pkgConfig(for: target).cFlags
default: break
}
}
}
/// Creates arguments required to launch the Swift REPL that will allow
/// importing the modules in the package graph.
public func createREPLArguments() -> [String] {
let buildPath = buildParameters.buildPath.asString
var arguments = ["-I" + buildPath, "-L" + buildPath]
// Link the special REPL product that contains all of the library targets.
let replProductName = graph.rootPackages[0].manifest.name + Product.replProductSuffix
arguments.append("-l" + replProductName)
// The graph should have the REPL product.
assert(graph.allProducts.first(where: { $0.name == replProductName }) != nil)
// Add the search path to the directory containing the modulemap file.
for target in targets {
switch target {
case .swift: break
case .clang(let targetDescription):
if let includeDir = targetDescription.moduleMap?.parentDirectory {
arguments += ["-I" + includeDir.asString]
}
}
}
// Add search paths from the system library targets.
for target in graph.reachableTargets {
if let systemLib = target.underlyingTarget as? SystemLibraryTarget {
arguments += self.pkgConfig(for: systemLib).cFlags
}
}
return arguments
}
/// Get pkgConfig arguments for a system library target.
private func pkgConfig(for target: SystemLibraryTarget) -> (cFlags: [String], libs: [String]) {
// If we already have these flags, we're done.
if let flags = pkgConfigCache[target] {
return flags
}
// Otherwise, get the result and cache it.
guard let result = pkgConfigArgs(for: target, diagnostics: diagnostics) else {
pkgConfigCache[target] = ([], [])
return pkgConfigCache[target]!
}
// If there is no pc file on system and we have an available provider, emit a warning.
if let provider = result.provider, result.couldNotFindConfigFile {
diagnostics.emit(data: PkgConfigHintDiagnostic(pkgConfigName: result.pkgConfigName, installText: provider.installText))
} else if let error = result.error {
diagnostics.emit(
data: PkgConfigGenericDiagnostic(error: "\(error)"),
location: PkgConfigDiagnosticLocation(pcFile: result.pkgConfigName, target: target.name))
}
pkgConfigCache[target] = (result.cFlags, result.libs)
return pkgConfigCache[target]!
}
/// Cache for pkgConfig flags.
private var pkgConfigCache = [SystemLibraryTarget: (cFlags: [String], libs: [String])]()
}
struct PkgConfigDiagnosticLocation: DiagnosticLocation {
let pcFile: String
let target: String
public var localizedDescription: String {
return "'\(target)' \(pcFile).pc"
}
}
public struct PkgConfigGenericDiagnostic: DiagnosticData {
public static let id = DiagnosticID(
type: PkgConfigGenericDiagnostic.self,
name: "org.swift.diags.pkg-config-generic",
defaultBehavior: .warning,
description: {
$0 <<< { $0.error }
}
)
let error: String
}
public struct PkgConfigHintDiagnostic: DiagnosticData {
public static let id = DiagnosticID(
type: PkgConfigHintDiagnostic.self,
name: "org.swift.diags.pkg-config-hint",
defaultBehavior: .warning,
description: {
$0 <<< "you may be able to install" <<< { $0.pkgConfigName } <<< "using your system-packager:\n"
$0 <<< { $0.installText }
}
)
let pkgConfigName: String
let installText: String
}
| 899b407b754a8731fa50151bd28de72f | 36.158854 | 137 | 0.62415 | false | false | false | false |
jimmya/SwiftServerExample-Common | refs/heads/master | Sources/SwiftExampleCommon/Models/User.swift | mit | 1 | import Foundation
import SwiftyJSON
open class User: NSObject, NSCoding {
public var name: String?
public var email: String?
public var password: String?
public var id: String?
public override init() {
self.name = nil
self.email = nil
self.password = nil
self.id = nil
}
public init?(jsonData: JSON) {
guard let name = jsonData["name"].string,
let email = jsonData["email"].string,
let id = jsonData["id"].string else {
return nil
}
self.name = name
self.email = email
self.id = id
self.password = jsonData["password"].string
}
public required convenience init(coder decoder: NSCoder) {
self.init()
name = decoder.decodeObject(forKey: "name") as? String
email = decoder.decodeObject(forKey: "email") as? String
password = decoder.decodeObject(forKey: "password") as? String
id = decoder.decodeObject(forKey: "id") as? String
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(email, forKey: "email")
aCoder.encode(password, forKey: "password")
aCoder.encode(id, forKey: "id")
}
}
| 1a82ecaae054d3d2ea5c215576dbafa8 | 28.227273 | 70 | 0.587092 | false | false | false | false |
grandiere/box | refs/heads/master | box/Model/Help/Release/MHelpReleaseIntro.swift | mit | 1 | import UIKit
class MHelpReleaseIntro:MHelpProtocol
{
private let attributedString:NSAttributedString
init()
{
let attributesTitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.bold(size:20),
NSForegroundColorAttributeName:UIColor.white]
let attributesDescription:[String:AnyObject] = [
NSFontAttributeName:UIFont.regular(size:18),
NSForegroundColorAttributeName:UIColor(white:1, alpha:0.8)]
let stringTitle:NSAttributedString = NSAttributedString(
string:NSLocalizedString("MHelpReleaseIntro_title", comment:""),
attributes:attributesTitle)
let stringDescription:NSAttributedString = NSAttributedString(
string:NSLocalizedString("MHelpReleaseIntro_description", comment:""),
attributes:attributesDescription)
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
mutableString.append(stringTitle)
mutableString.append(stringDescription)
attributedString = mutableString
}
var message:NSAttributedString
{
get
{
return attributedString
}
}
var image:UIImage
{
get
{
return #imageLiteral(resourceName: "assetHelpBasicRelease")
}
}
}
| 35c6d679204576df39b2b2623d8d5989 | 29.931818 | 82 | 0.650992 | false | false | false | false |
chenzhuanglong/CZLPractice | refs/heads/master | ZLSPAR/ZLSPAR/Classer/Mine/View/ZLMineTableViewCell.swift | mit | 1 | //
// ZLMineTableViewCell.swift
// ZLSPAR
//
// Created by yuzeux on 2017/12/11.
// Copyright © 2017年 晶石. All rights reserved.
//
import UIKit
class ZLMineTableViewCell: UITableViewCell {
let mineLabel : UILabel = UILabel.init()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// 设置选中cell时无高亮等效果
self.selectionStyle = .none
self.backgroundColor = RandomColor
mineLabel.textColor = RandomColor
mineLabel.font = UIFont.systemFont(ofSize: 20)
mineLabel.textAlignment = .center
mineLabel.frame = CGRect.init(x: 0, y: 0, width: ZLScreenWidth, height: 100)
self.addSubview(mineLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
}
public func addMineTitle(title:String){
mineLabel.text = title
}
}
| c398a61cb37059da6c5b44c2518804f5 | 21.44898 | 84 | 0.62 | false | false | false | false |
CodaFi/swift-compiler-crashes | refs/heads/master | crashes-duplicates/14837-swift-parser-skipsingle.swift | mit | 11 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
for {
let a = {
{
class
case ,
{
[Void{
var f = {
case ,
{
{
enum e {
class
let d<g : Int = (
for
func f: B
[B<T : B
case ,
func b<T where H.h : Int = B<T where H.h == (
func a( {
class
= nil
class
func a {
{
let t: a {
let : String = nil
var b = [Void{
println( ) {
class
struct c
class B
case ,
class
for {
case ,
protocol B {
let d{
for
let : Int = B<T.e : c<h == B<T : B<g : B<b<g : Int = {
class
println( {
class
for
{
class d<T : Int = {
= (t: String = {
for {
let t: P {
case ,
class
{
class B<T : P {
if true {
case ,
class
var f = (
func a = nil
let : String = (
var d where H.h : A? {
( {
protocol B {
init(
class c : String = nil
case ,
class A
var f = [Void{
case c,
case c<T : B<g : d = [Void{
case ,
func a {
class d<T : A
( {
func b<T where H.e : B
struct c,
class A
let d<b<T : Int = {
enum e : {
for c : c<j : d = e.h : {
class d{
case ,
{
let d<T.e {
= nil
class
func a {
class c : B<T where h: d where H.e : d = B
func a( {
case ,
case c<h : String = [B<g : A? {
( {
println( ) {
let d<T where h: a {
( {
{
func a = nil
( ) {
if true {
if true {
func f: A
func a {
for
var f: Int = e.e {
class B
class B<j : A
class
class B
let a = (
class A
{
class
for
for {
var f: {
func f: Int = {
{
{
var b = (
class A {
class d<T where h: B<j : A
var f = (
= B<T where h: P {
( {
( ) {
case ,
{
init(t: {
case ,
func f: c
var b = B
func a {
class B<T : c,
class B<T>
if true {
{
for c : P {
class
case ,
class
class
class d{
init(t: {
enum e : P {
func a( {
case ,
[B<j : String = nil
class B
var f = nil
class A {
for c {
{
class B<j : a {
let a = [Void{
class
{
[Void{
protocol B {
class d<T>
{
var f = e.h : a {
if true {
var f: P {
struct c<b<b<h : String = {
case ,
class B<j : A? {
struct c,
protocol B {
let d<j : c
= B<g : P {
class
var f: B
var f = [B
let a {
let a = (t: B<j : a {
class B
class A
let a = [Void{
protocol B {
case ,
let a {
class B<T.h : {
let : A
class c {
{
class
protocol B {
class A
class A {
let d{
( {
for
class
init(
class
case ,
{
init(
class c : A
case ,
let : A
var d where h: d = nil
protocol B {
class d<T.e {
let a {
func b<j : d where H.e : A
for
for {
class
| c6a5612027ec67ba750b4f526cf445ce | 9.735849 | 87 | 0.56239 | false | false | false | false |
icapps/ios_objective_c_workshop | refs/heads/master | Students/Naomi/ObjcTextInput/Pods/Faro/Sources/Service/ServiceQueue.swift | mit | 2 | //
// ServiceQueue.swift
// Pods
//
// Created by Stijn Willems on 20/04/2017.
//
//
import Foundation
enum ServiceQueueError: Error, CustomDebugStringConvertible {
case invalidSession(message: String, request: URLRequest)
var debugDescription: String {
switch self {
case .invalidSession(message: let message, request: let request):
return "📡🔥 you tried to perform a \(request) on a session that is invalid\nmessage: \(message)"
}
}
}
open class ServiceQueue {
var taskQueue: Set<URLSessionDataTask>
var failedTasks: Set<URLSessionTask>?
let session: FaroURLSession
private let final: (_ failedTasks: Set<URLSessionTask>?)->()
/// Creates a queue that lasts until final is called. When all request in the queue are finished the session becomes invalid.
/// For future queued request you have to create a new DeprecatedServiceQueue instance.
/// - parameter session: a session must have a backendConfiguration set.
/// - parameter final: closure is callen when all requests are performed.
public init (session: FaroURLSession, final: @escaping(_ failedTasks: Set<URLSessionTask>?)->()) {
taskQueue = Set<URLSessionDataTask>()
self.final = final
self.session = session
}
/// Gets a model(s) from the service and decodes it using native `Decodable` protocol.
/// Provide a type, that can be an array, to decode the data received from the service into type 'M'
/// - parameter type: Generic type to decode the returend data to. If service returns no response data use type `Service.NoResponseData`
@discardableResult
open func perform<M>(_ type: M.Type, call: Call, autoStart: Bool = false, complete: @escaping(@escaping () throws -> (M)) -> Void) -> URLSessionDataTask? where M: Decodable {
let config = session.backendConfiguration
guard let request = call.request(with: config) else {
complete {
let error = CallError.invalidUrl("\(config.baseURL)/\(call.path)", call: call)
self.handleError(error)
throw error
}
return nil
}
var task: URLSessionDataTask?
task = session.session.dataTask(with: request, completionHandler: {[weak self] (data, response, error) in
guard let task = task else {
let error = ServiceQueueError.invalidSession(message: "Task should never be nil!", request: request)
self?.handleError(error)
self?.invalidateAndCancel()
complete {throw error}
return
}
let error = raisesServiceError(data: data, urlResponse: response, error: error, for: request)
guard let `self` = self else {
print("📡⁉️ \(ServiceQueue.self) was released before all taks completed")
complete {throw ServiceError.networkError(-1, data: data, request: request)}
return
}
guard error == nil else {
complete {
self.handleError(error)
self.cleanupQueue(for: task, didFail: true)
self.shouldCallFinal()
throw error!
}
return
}
guard type.self != Service.NoResponseData.self else {
complete {
// Constructing a no data data with an empty response
let data = """
{}
""".data(using: .utf8)!
return try config.decoder.decode(M.self, from: data)
}
self.cleanupQueue(for: task, didFail: true)
self.shouldCallFinal()
return
}
guard let returnData = data else {
complete {
let error = ServiceError.invalidResponseData(data, call: call)
self.handleError(error)
self.cleanupQueue(for: task, didFail: true)
self.shouldCallFinal()
throw error
}
return
}
complete {
do {
let result = try config.decoder.decode(M.self, from: returnData)
self.cleanupQueue(for: task)
self.shouldCallFinal()
return result
} catch let error as DecodingError {
let error = ServiceError.decodingError(error, inData: returnData, call: call)
self.handleError(error)
self.cleanupQueue(for: task, didFail: true)
self.shouldCallFinal()
throw error
}
}
})
// Add task to queue if it could be created
guard let taskForQueue = task else {
print("📡⁉️ no task created")
return nil
}
add(taskForQueue)
guard autoStart else {
return task
}
// At this point we always have a task, force unwrap is then allowed.
task?.resume()
return task
}
// MARK: - Update model instead of create
open func performUpdate<M>(on model: M, call: Call, autoStart: Bool = false, complete: @escaping(@escaping () throws -> ()) -> Void) -> URLSessionDataTask? where M: Decodable & Updatable {
let task = perform(M.self, call: call, autoStart: autoStart) { (resultFunction) in
complete {
let serviceModel = try resultFunction()
try model.update(serviceModel)
return
}
}
return task
}
open func performUpdate<M>(on modelArray: [M],call: Call, autoStart: Bool = false, complete: @escaping(@escaping () throws -> ()) -> Void) -> URLSessionDataTask? where M: Decodable & Updatable {
let task = perform([M].self, call: call, autoStart: autoStart) { (resultFunction) in
complete {
var serviceModels = Set(try resultFunction())
try modelArray.forEach { element in
try element.update(array: Array(serviceModels))
serviceModels.remove(element)
}
return
}
}
return task
}
// MARK: Error
/// Prints the error and throws it
/// Possible to override this to have custom behaviour for your app.
open func handleError(_ error: Error?) {
print(error)
}
// MARK: - Interact with tasks
open var hasOustandingTasks: Bool {
get {
return taskQueue.count > 0
}
}
open func resumeAll() {
taskQueue.filter { $0.state != .running || $0.state != .completed}.forEach { $0.resume()}
}
// MARK: - Private
private func add(_ task: URLSessionDataTask?) {
guard let createdTask = task else {
return
}
taskQueue.insert(createdTask)
}
private func cleanupQueue(for task: URLSessionDataTask?, didFail: Bool = false) {
if let task = task {
let _ = taskQueue.remove(task)
if(didFail) {
if failedTasks == nil {
failedTasks = Set<URLSessionTask>()
}
failedTasks?.insert(task)
}
}
}
private func shouldCallFinal() {
if !hasOustandingTasks {
final(failedTasks)
session.session.finishTasksAndInvalidate()
}
}
// MARK: - Invalidate session overrides
open func invalidateAndCancel() {
taskQueue.removeAll()
failedTasks?.removeAll()
session.session.invalidateAndCancel()
}
deinit {
session.session.finishTasksAndInvalidate()
}
}
| b7fe674c5ee927226bd90daf6ac9f0ed | 33.592105 | 199 | 0.559402 | false | false | false | false |
Eonil/EditorLegacy | refs/heads/master | Modules/SQLite3/Sources/MidLevel/Statement.swift | mit | 2 | //
// Statement.swift
// EonilSQLite3
//
// Created by Hoon H. on 9/15/14.
//
//
import Foundation
/// MARK:
/// MARK: Public Interfaces
/// MARK:
extension Statement {
}
/// MARK: Introspection
extension Statement: Printable {
public var description: String {
get {
return "Statement(\(_core.sql()))"
}
}
}
/// MARK: Execution Iteration
extension Statement {
public func execute(parameters:[Value]) -> Execution {
precondition(!running, "You cannot execute a statement which already started manual stepping.")
precondition(_execution == nil || _execution!.running == false, "Previous execution of this statement-list is not finished. You cannot re-execute this statement-list until it once fully finished.")
Debug.log("EonilSQLte3 executes: \(self), parameters: \(parameters)")
self.reset()
self.bind(parameters)
let x = Execution(self)
_execution = x
return x
}
public func execute(parameters:[Query.ParameterValueEvaluation]) -> Execution {
let ps2 = parameters.map {$0()}
return execute(ps2)
}
public func execute() -> Execution {
return execute([] as [Value])
}
}
/// MARK:
/// MARK: Internal/Private Implementations
/// MARK:
/// Comments for Maintainers
/// ------------------------
/// This can't be a `SequenceType`, but `GeneratorType` because
/// there's only one iteration context can be exist at once. It
/// is impossible to create multiple context from a statement.
///
/// You should keep `Statement` object alive while you're running
/// an `Execution`. If the statement dies before the execution
/// finishes, the program will crash. `Connection` object does not
/// retain the statement object, and you're responsible to keep
/// it alive.
public final class Statement {
unowned let connection:Connection
init(connection:Connection, core:Core.Statement) {
self.connection = connection
_core = core
_rowidx = -1
}
deinit {
// It's fine to deinitialise execution while running. SQLite3 handles them well.
_core.finalize()
}
////
private let _core:Core.Statement
private var _rowidx:Int ///< Counted for validation.
private var _started = false
private var _finished = false
private var _execution = nil as Execution?
}
extension Statement {
var running:Bool {
get {
return _started && !_finished
}
}
func step() -> Bool {
_started = true
_rowidx++
if _core.step() {
return true
} else {
_finished = true
_execution = nil
return false
}
}
func reset() {
_started = false
_finished = false
_execution = nil
_rowidx = -1
_core.reset()
}
func bind(parameters:[Value]) {
for i in 0..<parameters.count {
let v = parameters[i]
let (n1, f1) = Int.addWithOverflow(i, 1)
precondition(f1 == false)
precondition(IntMax(n1) < IntMax(Int32.max))
let n2 = Int32(n1)
switch v {
case let Value.Null: _core.bindNull(at: n2)
case let Value.Integer(s): _core.bindInt64(s, at: n2)
case let Value.Float(s): _core.bindDouble(s, at: n2)
case let Value.Text(s): _core.bindText(s, at: n2)
case let Value.Blob(s): _core.bindBytes(s, at: n2)
}
}
}
}
extension Statement {
/// Set to `class` to prevent copying.
public final class Execution {
private unowned let s:Statement ///< Circularly retains `Statement` to keep the statement alive while this execution is running. This will be broke when the execution finishes.
private init(_ statement:Statement) {
s = statement
}
var statement:Statement {
get {
return s
}
}
var running:Bool {
get {
return statement.running
}
}
/// Run all at once.
/// The statement shouldn't produce any result.
public func all() {
precondition(statement._started == false, "You cannot call this method on once started execution.")
while statement.step() {
assert(statement.numberOfFields == 0, "This statement shouldn't produce any result columns.")
}
}
/// Returns snapshot of all rows at once. You can call this only on fresh new `Execution`.
/// Once started and unfinished execution cannot be used.
/// If you want to avoid collecting of all rows, then you have to iterate this
/// manually yourself.
public func allArrays() -> [[Value]] {
precondition(statement._started == false, "You cannot call this method on once started execution.")
return arrays().generate() >>>> collect
}
/// Returns snapshot of all rows at once. You can call this only on fresh new `Execution`.
/// Once started and unfinished execution cannot be used.
/// If you want to avoid collecting of all rows, then you have to iterate this
/// manually yourself.
public func allDictionaries() -> [[String:Value]] {
precondition(statement._started == false, "You cannot call this method on once started execution.")
return dictionaries().generate() >>>> collect
}
/// Returns enumerable array view. Represents a row as an array of values. Only field values, no clumn names.
public func arrays() -> ArrayView {
return ArrayView(statement)
}
/// Returns enumerable dictionary view. Represents a row as a dictionary of column names and field values.
public func dictionaries() -> DictionaryView {
return DictionaryView(statement)
}
}
}
extension Statement.Execution {
/// Provides most essential data iteration.
/// Shows only value part. You optionally can
/// take column names.
public final class ArrayView: SequenceType {
unowned let statement:Statement
init(_ s:Statement) {
self.statement = s
s.step()
}
public lazy var columns:[String] = {
var cs = [] as [String]
cs.reserveCapacity(self.statement.numberOfFields)
for i in 0..<self.statement.numberOfFields {
cs.append(self.statement.columnNameAtIndex(i))
}
return cs
}()
public func generate() -> GeneratorOf<[Value]> {
let s = statement
return GeneratorOf {
if s.running {
var a1 = [] as [Value]
s.numberOfFields >>>> a1.reserveCapacity
for i in 0..<s.numberOfFields {
s.columnValueAtIndex(i) >>>> a1.append
}
s.step()
return a1
} else {
return nil
}
}
}
}
/// Provides convenient dictionary form.
public final class DictionaryView: SequenceType {
unowned let statement:Statement
private var _columns = nil as [String]?
public var columns:[String] {
get {
return _columns!
}
}
init(_ s:Statement) {
self.statement = s
statement.step()
if statement.running {
var cs = [] as [String]
cs.reserveCapacity(statement.numberOfFields)
for i in 0..<self.statement.numberOfFields {
cs.append(self.statement.columnNameAtIndex(i))
}
_columns = cs
}
}
public func generate() -> GeneratorOf<[String:Value]> {
let s = statement
let cs = _columns
return GeneratorOf {
if s.running {
var d1 = [:] as [String:Value]
for i in 0..<s.numberOfFields {
d1[cs![i]] = s.columnValueAtIndex(i)
}
s.step()
return d1
} else {
return nil
}
}
}
}
}
extension Statement {
var numberOfFields:Int {
get {
precondition(_core.dataCount().toIntMax() <= Int.max.toIntMax())
return Int(_core.dataCount())
}
}
/// 0-based indexing.
subscript(index:Int) -> Value {
get {
return index >>>> columnValueAtIndex
}
}
subscript(column:String) -> Value? {
get {
for i in 0..<numberOfFields {
let n = columnNameAtIndex(i)
if n == column {
return self[i]
}
}
return nil
}
}
func columnNameAtIndex(index:Int) -> String {
precondition(index.toIntMax() <= Int32.max.toIntMax())
return _core.columnName(Int32(index))
}
func columnValueAtIndex(index:Int) -> Value {
precondition(_core.null == false)
precondition(index < numberOfFields)
let idx2 = Int32(index)
let t2 = _core.columnType(idx2)
if t2 == Core.ColumnTypeCode.null { return Value.Null }
if t2 == Core.ColumnTypeCode.integer { return Value(_core.columnInt64(at: idx2)) }
if t2 == Core.ColumnTypeCode.float { return Value(_core.columnDouble(at: idx2)) }
if t2 == Core.ColumnTypeCode.text { return Value(_core.columnText(at: idx2)) }
if t2 == Core.ColumnTypeCode.blob { return Value(_core.columnBlob(at: idx2)) }
Core.Common.crash(message: "Unknown column type code discovered; \(t2)")
}
}
/// MARK:
/// MARK: Private Stuffs
private func snapshotFieldNamesOfRow(r:Statement) -> [String] {
let c = r.numberOfFields
var m = [] as [String]
m.reserveCapacity(c)
for i in 0..<c {
m.append(r.columnNameAtIndex(i))
}
return m
}
private func snapshotFieldValuesOfRow(r:Statement) -> [Value] {
let c = r.numberOfFields
var m = [] as [Value]
m.reserveCapacity(c)
for i in 0..<c {
m.append(r.columnValueAtIndex(i))
}
return m
}
private func snapshotFieldNamesAndValuesOfRow(r:Statement) -> [(String,Value)] {
let c = r.numberOfFields
var m = [] as [(String,Value)]
m.reserveCapacity(c)
for i in 0..<c {
m.append((r.columnNameAtIndex(i), r.columnValueAtIndex(i)))
}
return m
}
private func snapshotRowAsDictionary(r:Statement) -> [String:Value] {
let ks = snapshotFieldNamesOfRow(r)
let vs = snapshotFieldValuesOfRow(r)
return combine(ks, vs)
}
private struct StatementFieldValuesGenerator: GeneratorType {
unowned private let s:Statement
init(_ s:Statement) {
self.s = s
}
func next() -> [Value]? {
if s.step() {
return snapshotFieldValuesOfRow(s)
} else {
return nil
}
}
}
| 3205bcbbb0471e0398a74717b31510b5 | 15.19398 | 199 | 0.650764 | false | false | false | false |
crazypoo/PTools | refs/heads/master | Pods/CryptoSwift/Sources/CryptoSwift/BlockDecryptor.swift | mit | 2 | // CryptoSwift
//
// Copyright (C) 2014-2022 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
public class BlockDecryptor: Cryptor, Updatable {
@usableFromInline
let blockSize: Int
@usableFromInline
let padding: Padding
@usableFromInline
var worker: CipherModeWorker
@usableFromInline
var accumulated = Array<UInt8>()
@usableFromInline
init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws {
self.blockSize = blockSize
self.padding = padding
self.worker = worker
}
@inlinable
public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
self.accumulated += bytes
// If a worker (eg GCM) can combine ciphertext + tag
// we need to remove tag from the ciphertext.
if !isLast && self.accumulated.count < self.blockSize + self.worker.additionalBufferSize {
return []
}
let accumulatedWithoutSuffix: Array<UInt8>
if self.worker.additionalBufferSize > 0 {
// FIXME: how slow is that?
accumulatedWithoutSuffix = Array(self.accumulated.prefix(self.accumulated.count - self.worker.additionalBufferSize))
} else {
accumulatedWithoutSuffix = self.accumulated
}
var processedBytesCount = 0
var plaintext = Array<UInt8>(reserveCapacity: accumulatedWithoutSuffix.count)
// Processing in a block-size manner. It's good for block modes, but bad for stream modes.
for var chunk in accumulatedWithoutSuffix.batched(by: self.blockSize) {
if isLast || (accumulatedWithoutSuffix.count - processedBytesCount) >= blockSize {
let isLastChunk = processedBytesCount + chunk.count == accumulatedWithoutSuffix.count
if isLast, isLastChunk, var finalizingWorker = worker as? FinalizingDecryptModeWorker {
chunk = try finalizingWorker.willDecryptLast(bytes: chunk + accumulated.suffix(worker.additionalBufferSize)) // tag size
}
if !chunk.isEmpty {
plaintext += worker.decrypt(block: chunk)
}
if isLast, isLastChunk, var finalizingWorker = worker as? FinalizingDecryptModeWorker {
plaintext = Array(try finalizingWorker.didDecryptLast(bytes: plaintext.slice))
}
processedBytesCount += chunk.count
}
}
accumulated.removeFirst(processedBytesCount) // super-slow
if isLast {
if accumulatedWithoutSuffix.isEmpty, var finalizingWorker = worker as? FinalizingDecryptModeWorker {
try finalizingWorker.willDecryptLast(bytes: self.accumulated.suffix(self.worker.additionalBufferSize))
plaintext = Array(try finalizingWorker.didDecryptLast(bytes: plaintext.slice))
}
plaintext = self.padding.remove(from: plaintext, blockSize: self.blockSize)
}
return plaintext
}
public func seek(to position: Int) throws {
guard var worker = self.worker as? SeekableModeWorker else {
fatalError("Not supported")
}
try worker.seek(to: position)
self.worker = worker
accumulated = []
}
}
| 016eba1439b42bdecfc35b034b27f467 | 38.112245 | 217 | 0.722932 | false | false | false | false |
suguru/Cheetah | refs/heads/master | CheetahExample/CheetahExample/ViewController.swift | mit | 1 | //
// ViewController.swift
// CheetahExample
//
// Created by Suguru Namura on 2015/08/19.
// Copyright © 2015年 Suguru Namura.
//
import UIKit
import Cheetah
class ViewController: UIViewController {
let easeIns = [
Easings.linear,
Easings.easeInSine,
Easings.easeInQuad,
Easings.easeInQuart,
Easings.easeInQuint,
Easings.easeInCirc,
Easings.easeInCubic,
Easings.easeInExpo,
Easings.easeInBack,
Easings.easeInBounce,
Easings.easeInElastic,
]
let easeOuts = [
Easings.linear,
Easings.easeOutSine,
Easings.easeOutQuad,
Easings.easeOutQuart,
Easings.easeOutQuint,
Easings.easeOutCirc,
Easings.easeOutCubic,
Easings.easeOutExpo,
Easings.easeOutBack,
Easings.easeOutBounce,
Easings.easeOutElastic,
]
var box: UIView!
var box2: UIView!
var label: UILabel!
var boxes: [UIView]!
var sboxes: [UIView]!
@IBOutlet weak var autolayoutBox: UIView!
@IBOutlet weak var autolayoutBottom: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Create view
box = UIView(frame:CGRect(x: 50,y: 50,width: 50,height: 50))
box.backgroundColor = UIColor.blue
view.addSubview(box)
box2 = UIView(frame: CGRect(x: 150, y: 50, width: 50, height: 50))
box2.backgroundColor = UIColor.blue
view.addSubview(box2)
label = UILabel(frame: CGRect(x: 200, y: 100, width: 200, height: 40))
label.text = "HELLO CHEETAH!"
view.addSubview(label)
boxes = [UIView]()
boxes.reserveCapacity(easeOuts.count)
for i in 0..<easeOuts.count {
let ebox = UIView(frame: CGRect(x: 20, y: 200 + 25 * CGFloat(i), width: 20, height: 20))
ebox.backgroundColor = UIColor.brown
view.addSubview(ebox)
boxes.append(ebox)
}
sboxes = [UIView]()
sboxes.reserveCapacity(3)
for i in 0..<sboxes.capacity {
let sbox = UIView(frame: CGRect(x: 20, y: 200 + 25 * CGFloat(i+easeOuts.count+1), width: 20, height: 20))
sbox.backgroundColor = UIColor.green
view.addSubview(sbox)
sboxes.append(sbox)
}
startAnimate()
}
func startAnimate() {
/*
box.cheetah
.rotate(1).duration(1)
.scale(2).duration(2)
.move(100, 100).duration(2)
.wait()
.move(-100, -100).duration(1)
.run()
*/
box.cheetah
.rotate(M_PI_2)
.run()
box2.cheetah
.borderWidth(5)
.borderColor(UIColor.red)
.cornerRadius(25)
.wait()
.borderWidth(0)
.borderColor(UIColor.black)
.cornerRadius(0)
.run()
label.cheetah
.move(0, 30).duration(0.5).easeOutBack
.textColor(UIColor.red)
.wait(1)
.move(0, -30).duration(0.5).easeOutBack
.textColor(UIColor.blue)
.wait(1)
.run()
for i in 0..<boxes.count {
let box = boxes[i]
box.cheetah
.move(200, 0)
.ease(easeOuts[i])
.duration(2)
.rotate(5)
//.rotate(M_PI*2)
.ease(easeOuts[i])
.duration(2)
.wait()
.move(-190, 0)
.ease(easeIns[i])
.duration(2)
.rotate(5)
//.rotate(-M_PI*2)
.ease(easeIns[i])
.duration(2)
.wait()
.run()
//.forever
}
sboxes[0].cheetah
.move(200, 0)
.spring()
.duration(2)
.wait()
.move(-200, 0)
.spring()
.duration(2)
.run()
sboxes[1].cheetah
.move(200, 0)
.spring(tension: 100, friction: 2)
.duration(2)
.wait()
.move(-200, 0)
.spring(tension: 100, friction: 2)
.duration(2)
.run()
sboxes[2].cheetah
.move(200, 0)
.spring(tension: 10, friction: 8)
.duration(2)
.wait()
.move(-200, 0)
.spring(tension: 10, friction: 8)
.duration(2)
.run()
autolayoutBox.cheetah
.constraint(autolayoutBottom, constant: 100)
.duration(2)
.run()
}
@IBAction func didTapAnimate(_ sender: AnyObject) {
startAnimate()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 066a246038e688a463c465f158bb4afe | 26.335025 | 117 | 0.467781 | false | false | false | false |
KarmaPulse/KPGallery | refs/heads/master | Sources/KP_Photo.swift | mit | 1 | //
// KP_Photo.swift
// Kboard_Gallery
//
// Created by Jose De Jesus Garfias Lopez on 8/10/17.
// Copyright © 2017 Karmapulse. All rights reserved.
//
import UIKit
class KP_Photo: UIView {
var id = -1;
var image = "";
var username = "";
var name = "";
init (frame : CGRect, id: Int, image: String, username: String, name: String) {
super.init(frame : frame);
// Init Vars
self.id = id;
self.image = image;
self.username = username;
self.name = name;
// Init Gestures
let touch = UITapGestureRecognizer(target: self, action: #selector(onTouchView));
touch.allowedPressTypes = [NSNumber(value: UIPressType.playPause.rawValue)]; // for tvOS
self.addGestureRecognizer(touch);
// Load & Construct View
self.reloadView();
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented");
}
func reloadView() {
let url = URL(string: self.image);
self.getDataFromUrl(url: url!) { (data, response, error) in
guard let data = data, error == nil else { return }
DispatchQueue.main.async() { () -> Void in
if let img = UIImage(data:data as Data) {
let resizedImg = img.resizeImage(targetSize: CGSize(width: self.frame.width, height: self.frame.height));
let imgV = UIImageView(image: resizedImg);
//self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: resizedImg.size.width, height: resizedImg.size.height);
self.addSubview(imgV);
}
}
}
}
func onTouchView() {
print("Touched");
}
func getDataFromUrl(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) {
URLSession.shared.dataTask(with: url) {
(data, response, error) in
completion(data, response, error)
}.resume();
}
}
extension UIImage {
func resizeImage(targetSize: CGSize) -> UIImage {
let size = self.size
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
self.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
| ce068d5024578f0f9d03ce2e813d5fb1 | 34.322222 | 152 | 0.592325 | false | false | false | false |
ishkawa/DIKit | refs/heads/master | Sources/DIGenKit/CodeGenerator.swift | mit | 1 | //
// CodeGenerator.swift
// dikitgenTests
//
// Created by Yosuke Ishikawa on 2017/09/16.
//
import Foundation
import SourceKittenFramework
public final class CodeGenerator {
let moduleNames: [String]
let resolvers: [Resolver]
public convenience init(path: String, excluding exclusions: [String] = []) throws {
try self.init(files: files(atPath: path, excluding: exclusions))
}
public init(files: [File]) throws {
let types = try Array(files
.map { file in
return try Structure(file: file)
.substructures
.compactMap { Type(structure: $0, file: file) }
}
.joined())
let imports = try Array(files
.map { file -> [Import] in
return try Import.imports(from: file)
}
.joined())
.reduce([] as [Import]) { imports, newImport in
return imports.contains(where: { $0.moduleName == newImport.moduleName })
? imports
: imports + [newImport]
}
let resolvers = try types
.compactMap { type -> Resolver? in
do {
return try Resolver(type: type, allTypes: types)
} catch let error as Resolver.Error where error.reason == .protocolConformanceNotFound {
return nil
} catch {
throw error
}
}
self.moduleNames = imports.map({ $0.moduleName }).sorted(by: <)
self.resolvers = resolvers.sorted { (lhs, rhs) in return lhs.name < rhs.name }
}
public func generate() throws -> String {
class Buffer {
var result = ""
var indentCount = 0
func append(_ string: String) {
for line in string.components(separatedBy: .newlines) {
guard !line.isEmpty else {
result += "\n"
continue
}
var indent = ""
if indentCount > 0 {
indent = Array(repeating: " ", count: indentCount).joined()
}
result += "\(indent)\(line)\n"
}
}
}
let buffer = Buffer()
buffer.append("""
//
// Resolver.swift
// Generated by dikitgen.
//
""")
buffer.append("")
if !moduleNames.isEmpty {
for moduleName in moduleNames {
buffer.append("import \(moduleName)")
}
buffer.append("")
}
for resolver in resolvers {
buffer.append("extension \(resolver.name) {")
buffer.indentCount += 1
for method in resolver.sortedGeneratedMethods {
buffer.append("")
buffer.append("func \(method.name)(\(method.parametersDeclaration)) -> \(method.returnTypeName) {")
buffer.indentCount += 1
for line in method.bodyLines {
buffer.append(line)
}
buffer.indentCount -= 1
buffer.append("}")
}
buffer.append("")
buffer.indentCount -= 1
buffer.append("}")
}
return buffer.result
}
}
private func files(atPath path: String, excluding exclusions: [String]) -> [File] {
let exclusions = exclusions.map { $0.last == "/" ? $0 : $0 + "/" }
let url = URL(fileURLWithPath: path)
let fileManager = FileManager.default
var files = [] as [File]
var isDirectory = false as ObjCBool
if fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory) {
if isDirectory.boolValue {
let enumerator = fileManager.enumerator(atPath: path)
while let subpath = enumerator?.nextObject() as? String {
if exclusions.contains(where: { subpath.hasPrefix($0) }) { continue }
let url = url.appendingPathComponent(subpath)
if url.pathExtension == "swift", let file = File(path: url.path), file.contents.contains("DIKit") {
files.append(file)
}
}
} else if let file = File(path: url.path) {
files.append(file)
}
}
return files
}
| a8590aa790560284b3bda24d48339386 | 30.59589 | 115 | 0.482766 | false | false | false | false |
cxchope/NyaaCatAPP_iOS | refs/heads/master | nyaacatapp/BrowserVC.swift | gpl-3.0 | 1 | //
// BrowserVC.swift
// nyaacatapp
//
// Created by 神楽坂雅詩 on 16/3/27.
// Copyright © 2016年 KagurazakaYashi. All rights reserved.
//
import UIKit
import WebKit
class BrowserVC: UIViewController , WKNavigationDelegate, WKUIDelegate {
//可由外部设置,在加载网页前
var 缓存策略:NSURLRequest.CachePolicy = 全局_缓存策略
var 超时时间:TimeInterval = 30
var 屏蔽长按菜单:Bool = true
var 在外部浏览器打开网页中的链接:Bool = true
var 允许刷新按钮 = true
//
var 浏览器:WKWebView? = nil
var 进度条:UIProgressView = UIProgressView()
var 右上按钮:UIBarButtonItem? = nil
var 请求网址:String = "about:blank"
var 当前Tab:Int = 0
var 刷新限制计时器:MSWeakTimer? = nil
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidDisappear(_ animated: Bool) {
if (self.navigationController == nil || self.navigationController!.tabBarController == nil || 当前Tab == self.navigationController!.tabBarController!.selectedIndex) {
卸载浏览器()
}
}
func 装入网页(_ 网址:String, 标题:String) {
请求网址 = 网址
self.title = 标题
let 要加载的浏览器URL:URL = URL(string: 请求网址)!
let 网络请求:NSMutableURLRequest = NSMutableURLRequest(url: 要加载的浏览器URL, cachePolicy: 缓存策略, timeoutInterval: 超时时间)
if (浏览器 == nil) {
创建UI()
装入浏览器()
}
浏览器!.load(网络请求 as URLRequest)
}
func 装入资料(_ html:String, 标题:String) {
self.title = 标题
if (浏览器 == nil) {
创建UI()
装入浏览器()
}
浏览器!.loadHTMLString(html, baseURL: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func 创建UI() {
当前Tab = self.navigationController!.tabBarController!.selectedIndex
self.view.backgroundColor = UIColor.white
if (允许刷新按钮 == true) {
右上按钮 = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(self.右上按钮点击))
navigationItem.rightBarButtonItem = 右上按钮
}
if(UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone){
进度条.frame = CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y + 64, width: self.view.frame.width,height: 2)
} else {
进度条.frame = CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y + 69, width: self.view.frame.width,height: 2)
}
进度条.backgroundColor = UIColor.white
self.view.addSubview(进度条)
}
func 右上按钮点击() {
let 要加载的浏览器URL:URL = URL(string: 请求网址)!
let 网络请求:NSMutableURLRequest = NSMutableURLRequest(url: 要加载的浏览器URL, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 超时时间)
浏览器!.load(网络请求 as URLRequest)
//防止疯狂刷新
右上按钮?.isEnabled = false
刷新限制计时器 = MSWeakTimer.scheduledTimer(withTimeInterval: 1.0, target: self, selector: #selector(self.恢复右上按钮), userInfo: nil, repeats: false, dispatchQueue: DispatchQueue.main)
}
func 恢复右上按钮() {
右上按钮?.isEnabled = true
刷新限制计时器 = nil
}
func 卸载浏览器() {
if (浏览器 != nil) {
浏览器!.navigationDelegate = nil
浏览器!.uiDelegate = nil
浏览器!.removeObserver(self, forKeyPath: "estimatedProgress")
浏览器!.removeFromSuperview()
浏览器 = nil
}
}
func 装入浏览器() {
let 浏览器设置:WKWebViewConfiguration = WKWebViewConfiguration()
if (屏蔽长按菜单 == true) {
let 禁止长按菜单JS:String = "document.body.style.webkitTouchCallout='none';"
let 禁止长按菜单:WKUserScript = WKUserScript(source: 禁止长按菜单JS, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
浏览器设置.userContentController.addUserScript(禁止长按菜单)
}
浏览器设置.allowsPictureInPictureMediaPlayback = false
浏览器设置.allowsInlineMediaPlayback = false
浏览器设置.allowsAirPlayForMediaPlayback = false
浏览器设置.requiresUserActionForMediaPlayback = false
浏览器设置.suppressesIncrementalRendering = false
浏览器设置.applicationNameForUserAgent = 全局_浏览器标识
let 浏览器偏好设置:WKPreferences = WKPreferences()
浏览器偏好设置.javaScriptCanOpenWindowsAutomatically = false
浏览器偏好设置.javaScriptEnabled = false
浏览器设置.preferences = 浏览器偏好设置
浏览器设置.selectionGranularity = .dynamic
let 浏览器坐标:CGRect = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.height)
浏览器 = WKWebView(frame: 浏览器坐标, configuration: 浏览器设置)
浏览器?.backgroundColor = UIColor.white
浏览器!.navigationDelegate = self
浏览器!.uiDelegate = self
self.view.insertSubview(浏览器!, at: 0)
浏览器!.translatesAutoresizingMaskIntoConstraints = false
let 左约束 = NSLayoutConstraint(item: 浏览器!, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1, constant: 0)
let 右约束 = NSLayoutConstraint(item: 浏览器!, attribute: .right, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1, constant: 0)
let 上约束 = NSLayoutConstraint(item: 浏览器!, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 0)
let 下约束 = NSLayoutConstraint(item: 浏览器!, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 0)
self.view.addConstraints([左约束,右约束,上约束,下约束])
浏览器!.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
}
func observeValue(forKeyPath keyPath: String?, of object: AnyObject?, change: [NSKeyValueChangeKey : AnyObject]?, context: UnsafeMutableRawPointer) {
if (keyPath == "estimatedProgress"){
self.进度条.setProgress(Float(浏览器!.estimatedProgress), animated: true)
}
if (浏览器!.estimatedProgress == 1 && self.进度条.isHidden == false){
self.进度条.isHidden = true
} else if (浏览器!.estimatedProgress < 1 && self.进度条.isHidden == true){
self.进度条.isHidden = false
}
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
卸载浏览器()
let 提示:UIAlertController = UIAlertController(title: "信息载入失败", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
let 取消按钮 = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { (动作:UIAlertAction) -> Void in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.navigationController?.popViewController(animated: true)
})
提示.addAction(取消按钮)
self.present(提示, animated: true, completion: nil)
}
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if (在外部浏览器打开网页中的链接 == true) {
let 即将转到网址:String = navigationAction.request.url!.absoluteString
let ob:OpenBrowser = OpenBrowser()
ob.打开浏览器(即将转到网址)
} else {
webView.load(navigationAction.request)
}
return nil
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//NSLog("observeValue=\(keyPath), object=\(object)")
}
/*
// 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.
}
*/
}
| e773b1ade290288840b0507f7ce53a9a | 41.356021 | 187 | 0.654265 | false | false | false | false |
kaich/CKAlertView | refs/heads/master | CKAlertView/Classes/Core/CKAlertViewAnimator.swift | mit | 1 | //
// CKAlertViewAnimator.swift
// Pods
//
// Created by mac on 17/2/9.
//
//
import UIKit
public protocol CKAlertViewAnimatable {
init(alertView :CKAlertView?)
var alertView :CKAlertView? {get}
/// 显示动画
///
/// - Parameter completeBlock: 动画结束回调
func show(completeBlock :(() -> ())?)
/// 消失动画
///
/// - Parameter completeBlock: 动画结束回调
func dismiss(completeBlock :(() -> ())?)
}
public enum CKAlertViewAnimatorType {
case fade, spring, ripple, dropDown, `default`
}
//MARK: - 动画效果
/// 透明度
public class CKAlertViewFadeAnimator: CKAlertViewAnimatable {
public var alertView :CKAlertView?
required public init(alertView: CKAlertView?) {
self.alertView = alertView
}
public func show(completeBlock :(() -> ())?) {
alertView?.view.alpha = 0
alertView?.containerView.layoutIfNeeded()
UIView.animate(withDuration: 0.3, animations: {
if let alertView = self.alertView {
alertView.view.alpha = 1
}
}) { (isOK) in
if let completeBlock = completeBlock {
completeBlock()
}
}
}
public func dismiss(completeBlock: (() -> ())?) {
UIView.animate(withDuration: 0.3, animations: {
if let alertView = self.alertView {
alertView.view.alpha = 0
}
}) { (_) in
if let completeBlock = completeBlock {
completeBlock()
}
}
}
}
/// 弹簧缩放
public class CKAlertViewSpringAnimator: CKAlertViewAnimatable {
public var alertView :CKAlertView?
required public init(alertView: CKAlertView?) {
self.alertView = alertView
}
public func show(completeBlock :(() -> ())?) {
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.65, initialSpringVelocity: 1, options: .curveLinear, animations: {
if let alertView = self.alertView {
alertView.view.alpha = 1
alertView.containerView.layoutIfNeeded()
}
}) { _ in
if let completeBlock = completeBlock {
completeBlock()
}
}
}
public func dismiss(completeBlock: (() -> ())?) {
UIView.animate(withDuration: 0.3, animations: {
if let alertView = self.alertView {
alertView.view.alpha = 0
}
}) { (_) in
if let completeBlock = completeBlock {
completeBlock()
}
}
}
}
/// 波纹
public class CKAlertViewRippleAnimator: NSObject, CKAlertViewAnimatable, CAAnimationDelegate {
public var alertView: CKAlertView?
var isAnimating = false
required public init(alertView: CKAlertView?) {
self.alertView = alertView
}
public func show(completeBlock :(() -> ())?) {
guard isAnimating == false else {
return
}
if let containerView = alertView?.containerView , let overlayView = alertView?.overlayView{
containerView.layoutIfNeeded()
overlayView.layer.opacity = 1
let maskWidth = sqrt(pow(containerView.bounds.height, 2) + pow(containerView.bounds.width, 2))
let maskLayer = CALayer()
maskLayer.frame = CGRect(x: 0, y: 0, width: maskWidth, height: maskWidth)
maskLayer.cornerRadius = maskWidth / 2
maskLayer.backgroundColor = UIColor.white.cgColor
maskLayer.position = CGPoint(x: containerView.frame.width / 2 , y: containerView.frame.height / 2)
alertView?.containerView.layer.mask = maskLayer
CATransaction.begin()
isAnimating = true
CATransaction.setCompletionBlock({
self.isAnimating = false
if let completeBlock = completeBlock {
completeBlock()
}
})
let scaleRate = 20.0 / maskWidth
let containerAnimation = CABasicAnimation(keyPath: "transform.scale")
containerAnimation.fromValue = scaleRate
containerAnimation.toValue = 1
containerAnimation.duration = 0.3
containerAnimation.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeInEaseOut)
maskLayer.add(containerAnimation, forKey: "scale")
let overlayAnimation = CABasicAnimation(keyPath: "opacity")
overlayAnimation.fromValue = 0
overlayAnimation.toValue = 1
overlayAnimation.duration = 0.3
overlayView.layer.add(overlayAnimation, forKey: "opacity")
CATransaction.commit()
}
}
public func dismiss(completeBlock: (() -> ())?) {
guard isAnimating == false else {
return
}
if let _ = alertView?.containerView , let overlayView = alertView?.overlayView, let maskLayer = alertView?.containerView.layer.mask {
overlayView.layer.opacity = 0
let scaleRate :CGFloat = 0.0
maskLayer.transform = CATransform3DMakeScale(scaleRate, scaleRate, 1)
CATransaction.begin()
isAnimating = true
CATransaction.setCompletionBlock({
self.isAnimating = false
if let completeBlock = completeBlock {
completeBlock()
}
})
let containerAnimation = CABasicAnimation(keyPath: "transform.scale")
containerAnimation.fromValue = 1
containerAnimation.toValue = scaleRate
containerAnimation.duration = 0.3
containerAnimation.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeInEaseOut)
maskLayer.add(containerAnimation, forKey: "scale")
let overlayAnimation = CABasicAnimation(keyPath: "opacity")
overlayAnimation.fromValue = 1
overlayAnimation.toValue = 0
overlayAnimation.duration = 0.3
overlayView.layer.add(overlayAnimation, forKey: "opacity")
CATransaction.commit()
}
}
}
//落下
public class CKAlertDropDownAnimator: NSObject, CKAlertViewAnimatable {
public var alertView: CKAlertView?
lazy var animator: UIDynamicAnimator = {
return UIDynamicAnimator(referenceView: (self.alertView?.view)!)
}()
required public init(alertView: CKAlertView?) {
self.alertView = alertView
}
public func show(completeBlock :(() -> ())?) {
if let alert = alertView ,let containerView = alertView?.containerView , let overlayView = alertView?.overlayView, let view = alertView?.view {
containerView.snp.remakeConstraints({ (make) in
make.centerX.equalTo(view)
make.bottom.equalTo(view.snp.top)
if alert.config.isFixedContentWidth {
make.width.equalTo(alert.config.contentWidth)
}
})
view.layoutIfNeeded()
self.animator.removeAllBehaviors()
let gravity = UIGravityBehavior(items: [containerView])
gravity.magnitude = 6
animator.addBehavior(gravity)
let sreenHeight = UIScreen.main.bounds.height
let bottom = (sreenHeight - containerView.bounds.height)/2
let boundaryCollision = UICollisionBehavior(items: [containerView])
boundaryCollision.setTranslatesReferenceBoundsIntoBoundary(with: UIEdgeInsets(top: -sreenHeight, left: 0, bottom: bottom, right: 0))
animator.addBehavior(boundaryCollision)
let bounce = UIDynamicItemBehavior(items: [containerView])
bounce.elasticity = 0.4
bounce.density = 200
bounce.resistance = 2
animator.addBehavior(bounce)
UIView .animate(withDuration: 0.5, animations: {
overlayView.layer.opacity = 1
}, completion: { (_) in
if let completeBlock = completeBlock {
completeBlock()
}
})
}
}
public func dismiss(completeBlock: (() -> ())?) {
if let alert = alertView, let containerView = alertView?.containerView , let overlayView = alertView?.overlayView, let view = alertView?.view {
containerView.snp.remakeConstraints({ (make) in
make.center.equalTo(view)
if alert.config.isFixedContentWidth {
make.width.equalTo(alert.config.contentWidth)
}
})
view.layoutIfNeeded()
self.animator.removeAllBehaviors()
let gravity = UIGravityBehavior(items: [containerView])
gravity.magnitude = 4
animator.addBehavior(gravity)
UIView .animate(withDuration: 0.5, animations: {
overlayView.layer.opacity = 0
}, completion: { (_) in
if let completeBlock = completeBlock {
completeBlock()
}
})
}
}
}
| 2c74d55238e66e5da35920a37cac10fb | 33.309091 | 152 | 0.56778 | false | false | false | false |
3ph/SplitSlider | refs/heads/master | SplitSlider/Classes/SplitSliderThumb.swift | mit | 1 | //
// SplitSliderThumb.swift
// SplitSlider
//
// Created by Tomas Friml on 23/06/17.
//
// MIT License
//
// Copyright (c) 2017 Tomas Friml
//
// 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 class SplitSliderThumb: CALayer {
/// Size of the thumb
public var size: CGFloat = 20 {
didSet {
setNeedsDisplay()
}
}
/// Color of the the thumb
public var color: UIColor = UIColor.yellow {
didSet {
setNeedsDisplay()
}
}
public override init() {
super.init()
initialize()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
public override init(layer: Any) {
super.init(layer: layer)
initialize()
}
public override func draw(in ctx: CGContext) {
let path = UIBezierPath(roundedRect: bounds, cornerRadius: size / 2).cgPath
ctx.addPath(path)
ctx.setFillColor(color.cgColor)
ctx.fillPath()
}
// MARK: - Private
fileprivate func initialize() {
backgroundColor = UIColor.clear.cgColor
contentsScale = UIScreen.main.scale
}
}
| aca089b424293dd624407b202e7d95c9 | 28.405063 | 83 | 0.642273 | false | false | false | false |
tutsplus/CoreDataSwift-AsynchronousFetching | refs/heads/master | Done/AddToDoViewController.swift | bsd-2-clause | 5 | //
// AddToDoViewController.swift
// Done
//
// Created by Bart Jacobs on 19/10/15.
// Copyright © 2015 Envato Tuts+. All rights reserved.
//
import UIKit
import CoreData
class AddToDoViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
var managedObjectContext: NSManagedObjectContext!
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: -
// MARK: Actions
@IBAction func cancel(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func save(sender: AnyObject) {
let name = textField.text
if let isEmpty = name?.isEmpty where isEmpty == false {
// Create Entity
let entity = NSEntityDescription.entityForName("Item", inManagedObjectContext: self.managedObjectContext)
// Initialize Record
let record = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: self.managedObjectContext)
// Populate Record
record.setValue(name, forKey: "name")
record.setValue(NSDate(), forKey: "createdAt")
do {
// Save Record
try record.managedObjectContext?.save()
// Dismiss View Controller
dismissViewControllerAnimated(true, completion: nil)
} catch {
let saveError = error as NSError
print("\(saveError), \(saveError.userInfo)")
// Show Alert View
showAlertWithTitle("Warning", message: "Your to-do could not be saved.", cancelButtonTitle: "OK")
}
} else {
// Show Alert View
showAlertWithTitle("Warning", message: "Your to-do needs a name.", cancelButtonTitle: "OK")
}
}
// MARK: -
// MARK: Helper Methods
private func showAlertWithTitle(title: String, message: String, cancelButtonTitle: String) {
// Initialize Alert Controller
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
// Configure Alert Controller
alertController.addAction(UIAlertAction(title: cancelButtonTitle, style: .Default, handler: nil))
// Present Alert Controller
presentViewController(alertController, animated: true, completion: nil)
}
}
| 4d902ae1f39a1c0b9cd4749d9380ac36 | 32.746667 | 117 | 0.595812 | false | false | false | false |
IBAnimatable/IBAnimatable | refs/heads/master | IBAnimatableApp/IBAnimatableApp/Playground/Transitions/TransitionPushedViewController.swift | mit | 2 | //
// Created by Jake Lin on 5/13/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
import IBAnimatable
final class TransitionPushedViewController: UIViewController {
@IBOutlet fileprivate var gestureLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if let animatableView = view as? AnimatableView {
animatableView.predefinedGradient = makeRandomGradient()
}
configureGestureLabel()
}
}
private extension TransitionPushedViewController {
func configureGestureLabel() {
// Shows nothing by default
gestureLabel.text = "to pop"
guard let navigationController = navigationController as? AnimatableNavigationController else {
return
}
// No gesture for this animator
if case .none = navigationController.interactiveGestureType {
return
}
if case .none = navigationController.transitionAnimationType {
return
}
gestureLabel.text = retrieveGestureText(interactiveGestureType: navigationController.interactiveGestureType,
transitionAnimationType: navigationController.transitionAnimationType,
exit: "pop")
}
}
| bca07d8e2e1ea3fc1a55e355bfa9915d | 25.297872 | 114 | 0.692557 | false | false | false | false |
See-Ku/SK4Toolkit | refs/heads/master | SK4Toolkit/SK4Toolkit.swift | mit | 1 | //
// SK4Toolkit.swift
// SK4Toolkit
//
// Created by See.Ku on 2016/03/23.
// Copyright (c) 2016 AxeRoad. All rights reserved.
//
import UIKit
// /////////////////////////////////////////////////////////////
// MARK: - 各種定数
/// SK4Toolkitで使用する定数
public struct SK4ToolkitConst {
/// SK4Toolkitのバージョン
public static let version = "2.8.2"
/// テーブルビューの最大幅
public static var tableViewMaxWidth = 560
/// テーブルビューの背景色
public static var tableViewBackColor = UIColor(white: 0.75, alpha: 1.0)
}
// /////////////////////////////////////////////////////////////
// MARK: - UIBarButtonItem
/// 標準のUIBarButtonItemを作成
public func sk4BarButtonItem(title title: String, target: AnyObject? = nil, action: Selector = nil) -> UIBarButtonItem {
return UIBarButtonItem(title: title, style: .Plain, target: target, action: action)
}
/// Image付きのUIBarButtonItemを作成
public func sk4BarButtonItem(image image: String, target: AnyObject? = nil, action: Selector = nil) -> UIBarButtonItem {
let img = UIImage(named: image)
return UIBarButtonItem(image: img, style: .Plain, target: target, action: action)
}
/// SystemItemを使ったUIBarButtonItemを作成
public func sk4BarButtonItem(system system: UIBarButtonSystemItem, target: AnyObject? = nil, action: Selector = nil) -> UIBarButtonItem {
return UIBarButtonItem(barButtonSystemItem: system, target: target, action: action)
}
// /////////////////////////////////////////////////////////////
// MARK: - UIAlertController
/// シンプルな形式のUIAlertControllerを表示
public func sk4AlertView(title title: String?, message: String?, vc: UIViewController, handler: ((UIAlertAction!) -> Void)? = nil) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: handler)
alert.addAction(action)
vc.presentViewController(alert, animated: true, completion: nil)
}
// /////////////////////////////////////////////////////////////
// MARK: - GUI関係
/// UIWindowを取得 ※UIWindowにaddSubview()した場合、removeFromSuperview()が必要になる
public func sk4GetWindow() -> UIWindow? {
let app = UIApplication.sharedApplication()
if let win = app.keyWindow {
return win
}
if app.windows.count != 0 {
return app.windows[0]
}
return nil
}
/// 指定されたViewのAutoLayoutをオフにする
public func sk4AutoLayoutOff(view: UIView) {
// 制約を全て削除
let ar = view.constraints
view.removeConstraints(ar)
// 基準になるViewは自動変換を使わない
view.translatesAutoresizingMaskIntoConstraints = false
// 子Viewは自動変換をONに
for child in view.subviews {
child.translatesAutoresizingMaskIntoConstraints = true
}
}
/// 最大幅を制限する制約を設定
public func sk4LimitWidthConstraints(viewController: UIViewController, view: UIView, maxWidth: Int) {
let base = viewController.view
let maker = SK4ConstraintMaker(viewController: viewController)
maker.addOverlay(view, baseItem: base, maxWidth: maxWidth)
base.addConstraints(maker.constraints)
}
/// ステータスバーの高さを取得
public func sk4StatusBarHeight() -> CGFloat {
return UIApplication.sharedApplication().statusBarFrame.size.height
}
/// ナビゲーションバーの高さを取得
public func sk4NavigationBarHeight(vc: UIViewController) -> CGFloat {
return vc.navigationController?.navigationBar.frame.size.height ?? 44
}
/// タブバーの高さを取得
public func sk4TabBarHeight(vc: UIViewController) -> CGFloat {
return vc.tabBarController?.tabBar.frame.size.height ?? 49
}
// /////////////////////////////////////////////////////////////
// MARK: - システムディレクトリ取得
/// ドキュメントディレクトリへのパスを取得
public func sk4GetDocumentDirectory() -> String {
return sk4GetSearchPathDirectory(.DocumentDirectory)
}
/// ドキュメントディレクトリへのパスにファイル名を連結して取得
public func sk4GetDocumentDirectory(fn: String) -> String {
let path = sk4GetDocumentDirectory()
return path.sk4AppendingPath(fn)
}
/// ライブラリディレクトリへのパスを取得
public func sk4GetLibraryDirectory() -> String {
return sk4GetSearchPathDirectory(.LibraryDirectory)
}
/// キャッシュディレクトリへのパスを取得
public func sk4GetCachesDirectory() -> String {
return sk4GetSearchPathDirectory(.CachesDirectory)
}
/// テンポラリディレクトリへのパスを取得
public func sk4GetTemporaryDirectory() -> String {
return NSTemporaryDirectory()
}
/// システムで用意されたディレクトリへのパスを取得
public func sk4GetSearchPathDirectory(dir: NSSearchPathDirectory) -> String {
let paths = NSSearchPathForDirectoriesInDomains(dir, .UserDomainMask, true)
return paths[0] + "/"
}
// /////////////////////////////////////////////////////////////
// MARK: - ファイル操作
/// ファイルの有無をチェック
public func sk4IsFileExists(path: String) -> Bool {
let man = NSFileManager.defaultManager()
return man.fileExistsAtPath(path)
}
/// ファイルを移動
public func sk4MoveFile(src src: String, dst: String) -> Bool {
do {
let man = NSFileManager.defaultManager()
try man.moveItemAtPath(src, toPath: dst)
return true
} catch {
sk4DebugLog("moveItemAtPath error \(src) -> \(dst): \(error)")
return false
}
}
/// ファイルをコピー
public func sk4CopyFile(src src: String, dst: String) -> Bool {
do {
let man = NSFileManager.defaultManager()
try man.copyItemAtPath(src, toPath: dst)
return true
} catch {
sk4DebugLog("copyItemAtPath error \(src) -> \(dst): \(error)")
return false
}
}
/// ファイルを削除
public func sk4DeleteFile(path: String) -> Bool {
do {
let man = NSFileManager.defaultManager()
try man.removeItemAtPath(path)
return true
} catch {
sk4DebugLog("removeItemAtPath error \(path): \(error)")
return false
}
}
/// ファイルの一覧を作成
public func sk4FileListAtPath(path: String, ext: String? = nil) -> [String] {
do {
let man = NSFileManager.defaultManager()
let ar = try man.contentsOfDirectoryAtPath(path)
// 拡張子が指定されている場合、マッチするものだけを選択
if let ext = ext {
let ext_ok = ext.sk4Trim(".")
return ar.filter() { fn in
return fn.nsString.pathExtension == ext_ok
}
} else {
return ar
}
} catch {
sk4DebugLog("contentsOfDirectoryAtPath error \(path): \(error)")
return []
}
}
/// ファイルの情報を取得
public func sk4FileAttributesAtPath(path: String) -> NSDictionary? {
let man = NSFileManager.defaultManager()
do {
let info = try man.attributesOfItemAtPath(path) as NSDictionary
return info
} catch {
return nil
}
}
/// ファイルサイズを文字列に変換
public func sk4FileSizeString(size: UInt64) -> String {
// 数字部分が3桁になるように調整したバージョン
// ※実はZBが使われる事はない
let units = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB"]
var size = size
for i in 0..<units.count-1 {
// 3桁以下ならそのまま出力
if size < 1000 {
return "\(size) \(units[i])"
}
// 次の単位で2桁未満か?
if size < 1024 * 10 {
// 小数点以下1桁で四捨五入
let tmp = round((Double(size) * 10) / 1024) / 10
let num: String
if tmp < 10.0 {
num = String(format: "%0.1f", tmp)
} else {
num = String(format: "%0.0f", tmp)
}
return "\(num) \(units[i+1])"
}
size /= 1024
}
return "\(size) YB"
}
// /////////////////////////////////////////////////////////////
// MARK: - 乱数
/// 乱数を取得
public func sk4Random(max: Int) -> Int {
let tmp = UInt32(max)
return Int(arc4random_uniform(tmp))
}
/// 乱数を取得
public func sk4Random(max: CGFloat) -> CGFloat {
let tmp = UInt32(max)
return CGFloat(arc4random_uniform(tmp))
}
/// 範囲を指定して乱数を取得
public func sk4Random(range: Range<Int>) -> Int {
let tmp = UInt32(range.endIndex - range.startIndex)
return Int(arc4random_uniform(tmp)) + range.startIndex
}
// /////////////////////////////////////////////////////////////
// MARK: - 数学
/// アスペクト比を保ったまま転送する転送先の矩形を求める
func sk4AspectFit(toRect toRect: CGRect, fromRect: CGRect) -> CGRect {
if fromRect.width == 0 || fromRect.height == 0 {
return CGRect.zero
}
let ax = toRect.width / fromRect.width
let ay = toRect.height / fromRect.height
let rate = min(ax, ay)
let wx = fromRect.width * rate
let wy = fromRect.height * rate
let px = toRect.origin.x + (toRect.width - wx) / 2
let py = toRect.origin.y + (toRect.height - wy) / 2
return CGRect(x: px, y: py, width: wx, height: wy)
}
/// 誤差の範囲内で一致するか?
public func sk4NearlyEqual<T: SignedNumberType>(v0: T, _ v1: T, dif: T) -> Bool {
if abs(v0 - v1) <= dif {
return true
} else {
return false
}
}
// /////////////////////////////////////////////////////////////
// MARK: - Array
/// 範囲内の場合だけ取得
public func sk4SafeGet<T>(array: Array<T>, index: Int) -> T? {
if 0 <= index && index < array.count {
return array[index]
} else {
return nil
}
}
// /////////////////////////////////////////////////////////////
// MARK: - Date & Time
/// うるう年か?
public func sk4IsLeapYear(year: Int) -> Bool {
if year % 400 == 0 {
return true
}
if year % 100 == 0 {
return false
}
if year % 4 == 0 {
return true
}
return false
}
/// 指定された月の日数を取得
/// month: 1 = 1月
public func sk4MonthDays(year year: Int, month: Int) -> Int {
let ar = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if month == 2 && sk4IsLeapYear(year) {
return 29
} else {
return ar[month-1]
}
}
// /////////////////////////////////////////////////////////////
// MARK: - その他
/// DEBUGが設定されている時のみ、メッセージを出力。
/// ※Xcodeの設定が必要: Other Swift Flags -> [-D DEBUG]
public func sk4DebugLog(@autoclosure message: () -> String, function: String = #function) {
#if DEBUG
print("\(message()) - \(function)")
#endif
}
/// バージョン情報を取得
public func sk4VersionString() -> String {
let bundle = NSBundle.mainBundle()
if let str = bundle.objectForInfoDictionaryKey("CFBundleShortVersionString") as? String {
#if DEBUG
return str + "[D]"
#else
return str
#endif
} else {
assertionFailure("objectForInfoDictionaryKey error: CFBundleShortVersionString")
return ""
}
}
/// バンドルされたリソースをNSDataとして読み込み
public func sk4DataFromResource(name: String, ofType: String? = nil) -> NSData? {
let bundle = NSBundle.mainBundle()
if let path = bundle.pathForResource(name, ofType: ofType) {
return NSData(contentsOfFile: path)
} else {
sk4DebugLog("pathForResource error \(name) \(ofType):")
return nil
}
}
/// 指定されたURLを開く
public func sk4OpenURL(path: String) -> Bool {
if let url = NSURL(string: path) {
UIApplication.sharedApplication().openURL(url)
return true
} else {
return false
}
}
// /////////////////////////////////////////////////////////////
/// iPadで動作しているか?
public func sk4IsPad() -> Bool {
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
return true
} else {
return false
}
}
/// iPhoneで動作しているか?
public func sk4IsPhone() -> Bool {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return true
} else {
return false
}
}
/// デバイスは縦向きか?
public func sk4IsPortraitOrientation() -> Bool {
let dir = UIApplication.sharedApplication().statusBarOrientation
if dir == .Portrait || dir == .PortraitUpsideDown {
return true
} else {
return false
}
}
// eof
| 61956e25e147f42055cb0b2980dc356d | 22.668904 | 137 | 0.649055 | false | false | false | false |
behrang/SwiftParsec | refs/heads/master | example-json/main.swift | mit | 1 | import Parsec
enum Json {
case null
case bool(Bool)
case number(Double)
case string(String)
case array([Json])
case object([String: Json])
}
func jsonFile () -> StringParser<Json> {
return ( spaces >>> value <<< eof )()
}
func value () -> StringParser<Json> {
return ( str
<|> number
<|> object
<|> array
<|> bool
<|> null
<?> "json value" )()
}
func str () -> StringParser<Json> {
return ( quotedString >>- { s in create(.string(s)) } )()
}
func quotedString () -> StringParser<String> {
return ( between(quote, quote, many(quotedCharacter))
>>- { cs in create(String(cs)) } <<< spaces <?> "quoted string" )()
}
func quote () -> StringParser<Character> {
return ( char("\"") <?> "double quote" )()
}
func quotedCharacter () -> StringParser<Character> {
var chars = "\"\\"
for i in 0x00...0x1f {
chars += String(UnicodeScalar(i)!)
}
for i in 0x7f...0x9f {
chars += String(UnicodeScalar(i)!)
}
return ( noneOf(chars)
<|> attempt(string("\\\"")) >>> create("\"")
<|> attempt(string("\\\\")) >>> create("\\")
<|> attempt(string("\\/")) >>> create("/")
<|> attempt(string("\\b")) >>> create("\u{8}")
<|> attempt(string("\\f")) >>> create("\u{c}")
<|> attempt(string("\\n")) >>> create("\n")
<|> attempt(string("\\r")) >>> create("\r")
<|> attempt(string("\\t")) >>> create("\t")
<|> attempt(string("\\u") >>> count(4, hexDigit) >>- { hds in
let code = String(hds)
let i = Int(code, radix: 16)!
return create(Character(UnicodeScalar(i)!))
}) )()
}
func number () -> StringParser<Json> {
return ( numberSign >>- { sign in
numberFixed >>- { fixed in
numberFraction >>- { fraction in
numberExponent >>- { exponent in
let s = sign + fixed + fraction + exponent
if let d = Double(s) {
return create(.number(d))
} else {
return fail("invalid number \(s)")
}
}
}
}
} <<< spaces <?> "number" )()
}
func numberSign () -> StringParser<String> {
return option("+", string("-"))()
}
func numberFixed () -> StringParser<String> {
return ( string("0") <|> many1(digit) >>- { create(String($0)) } )()
}
func numberFraction () -> StringParser<String> {
return ( char(".") >>> many1(digit) >>- { create("." + String($0)) }
<|> create("") )()
}
func numberExponent () -> StringParser<String> {
return ( oneOf("eE") >>> option("+", oneOf("+-")) >>- { sign in
many1(digit) >>- { digits in create("e" + String(sign) + String(digits)) }
}
<|> create("") )()
}
func object () -> StringParser<Json> {
return ( between(leftBrace, rightBrace, sepBy(pair, comma)) >>- { ps in
var r: [String: Json] = [:]
ps.forEach { p in r[p.0] = p.1 }
return create(.object(r))
} <?> "object" )()
}
func leftBrace () -> StringParser<Character> {
return ( char("{") <<< spaces <?> "open curly bracket" )()
}
func rightBrace () -> StringParser<Character> {
return ( char("}") <<< spaces <?> "close curly bracket" )()
}
func comma () -> StringParser<Character> {
return ( char(",") <<< spaces <?> "comma" )()
}
func colon () -> StringParser<Character> {
return ( char(":") <<< spaces <?> "colon" )()
}
func pair () -> StringParser<(String, Json)> {
return ( quotedString >>- { k in
return colon >>> value >>- { v in
create((k, v))
}
} <?> "key:value pair" )()
}
func array () -> StringParser<Json> {
return ( between(leftBracket, rightBracket, sepBy(value, comma))
>>- { js in create(.array(js)) }
<?> "array" )()
}
func leftBracket () -> StringParser<Character> {
return ( char("[") <<< spaces <?> "open square bracket" )()
}
func rightBracket () -> StringParser<Character> {
return ( char("]") <<< spaces <?> "close square bracket" )()
}
func bool () -> StringParser<Json> {
return ( (string("true") >>> create(.bool(true)) <<< spaces <?> "true")
<|> (string("false") >>> create(.bool(false)) <<< spaces <?> "false") )()
}
func null () -> StringParser<Json> {
return ( string("null") >>> create(.null) <<< spaces <?> "null" )()
}
func main () {
if CommandLine.arguments.count != 2 {
print("Usage: \(CommandLine.arguments[0]) json_file")
} else {
let result = try! parse(jsonFile, contentsOfFile: CommandLine.arguments[1])
switch result {
case let .left(err): print(err)
case let .right(x): print(format(x))
}
}
}
func format (_ data: Json) -> String {
switch data {
case .null: return "null"
case let .bool(b): return b ? "true" : "false"
case let .number(n): return String(n)
case let .string(s): return "\"\(s)\""
case let .array(a): return "[\(a.map(format).joined(separator: ","))]"
case let .object(o):
return "{\(o.map{ k, v in "\"\(k)\":\(format(v))" }.joined(separator: ","))}"
}
}
main()
| 57e22b7620fc7c635310e8beaa29ceab | 26.435754 | 81 | 0.541641 | false | false | false | false |
darkerk/v2ex | refs/heads/master | V2EX/App/AppSetting.swift | mit | 1 | //
// AppSetting.swift
// V2EX
//
// Created by darker on 2017/3/21.
// Copyright © 2017年 darker. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
import SafariServices
import SKPhotoBrowser
struct AppSetting {
static var isCameraEnabled: Bool {
let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
return status != .restricted && status != .denied
}
static var isAlbumEnabled: Bool {
let status = PHPhotoLibrary.authorizationStatus()
return status != .restricted && status != .denied
}
static func openWebBrowser(from viewController: UIViewController, URL: URL) {
let browser = SFSafariViewController(url: URL)
viewController.present(browser, animated: true, completion: nil)
}
static func openPhotoBrowser(from viewController: UIViewController, src: String) {
let photo = SKPhoto.photoWithImageURL(src)
photo.shouldCachePhotoURLImage = true
let browser = SKPhotoBrowser(photos: [photo])
browser.initializePageIndex(0)
viewController.present(browser, animated: true, completion: nil)
}
}
| 70c727aa559d077fd21071f1d6c8ac83 | 29.282051 | 86 | 0.686706 | false | false | false | false |
frootloops/swift | refs/heads/master | test/SILOptimizer/exclusivity_static_diagnostics.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -enforce-exclusivity=checked -swift-version 4 -emit-sil -primary-file %s -o /dev/null -verify
import Swift
func takesTwoInouts<T>(_ p1: inout T, _ p2: inout T) { }
func simpleInoutDiagnostic() {
var i = 7
// FIXME: This diagnostic should be removed if static enforcement is
// turned on by default.
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
takesTwoInouts(&i, &i)
}
func inoutOnInoutParameter(p: inout Int) {
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'p', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
takesTwoInouts(&p, &p)
}
func swapNoSuppression(_ i: Int, _ j: Int) {
var a: [Int] = [1, 2, 3]
// expected-error@+2{{overlapping accesses to 'a', but modification requires exclusive access; consider calling MutableCollection.swapAt(_:_:)}}
// expected-note@+1{{conflicting access is here}}
swap(&a[i], &a[j])
}
class SomeClass { }
struct StructWithMutatingMethodThatTakesSelfInout {
var f = SomeClass()
mutating func mutate(_ other: inout StructWithMutatingMethodThatTakesSelfInout) { }
mutating func mutate(_ other: inout SomeClass) { }
mutating func callMutatingMethodThatTakesSelfInout() {
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'self', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
mutate(&self)
}
mutating func callMutatingMethodThatTakesSelfStoredPropInout() {
// expected-error@+2{{overlapping accesses to 'self', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
mutate(&self.f)
}
}
var globalStruct1 = StructWithMutatingMethodThatTakesSelfInout()
func callMutatingMethodThatTakesGlobalStoredPropInout() {
// expected-error@+2{{overlapping accesses to 'globalStruct1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
globalStruct1.mutate(&globalStruct1.f)
}
class ClassWithFinalStoredProp {
final var s1: StructWithMutatingMethodThatTakesSelfInout = StructWithMutatingMethodThatTakesSelfInout()
final var s2: StructWithMutatingMethodThatTakesSelfInout = StructWithMutatingMethodThatTakesSelfInout()
func callMutatingMethodThatTakesClassStoredPropInout() {
s1.mutate(&s2.f) // no-warning
// expected-error@+2{{overlapping accesses to 's1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
s1.mutate(&s1.f)
let local1 = self
// expected-error@+2{{overlapping accesses to 's1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
local1.s1.mutate(&local1.s1.f)
}
}
func violationWithGenericType<T>(_ p: T) {
var local = p
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
takesTwoInouts(&local, &local)
}
// Helper.
struct StructWithTwoStoredProp {
var f1: Int = 7
var f2: Int = 8
}
// Take an unsafe pointer to a stored property while accessing another stored property.
func violationWithUnsafePointer(_ s: inout StructWithTwoStoredProp) {
withUnsafePointer(to: &s.f1) { (ptr) in
// expected-warning@-1 {{overlapping accesses to 's.f1', but modification requires exclusive access; consider copying to a local variable}}
_ = s.f1
// expected-note@-1 {{conflicting access is here}}
}
// Statically treat accesses to separate stored properties in structs as
// accessing separate storage.
withUnsafePointer(to: &s.f1) { (ptr) in // no-error
_ = s.f2
}
}
// Tests for Fix-Its to replace swap(&collection[a], &collection[b]) with
// collection.swapAt(a, b)
struct StructWithField {
var f = 12
}
struct StructWithFixits {
var arrayProp: [Int] = [1, 2, 3]
var dictionaryProp: [Int : Int] = [0 : 10, 1 : 11]
mutating
func shouldHaveFixIts<T>(_ i: Int, _ j: Int, _ param: T, _ paramIndex: T.Index) where T : MutableCollection {
var array1 = [1, 2, 3]
// expected-error@+2{{overlapping accesses}}{{5-41=array1.swapAt(i + 5, j - 2)}}
// expected-note@+1{{conflicting access is here}}
swap(&array1[i + 5], &array1[j - 2])
// expected-error@+2{{overlapping accesses}}{{5-49=self.arrayProp.swapAt(i, j)}}
// expected-note@+1{{conflicting access is here}}
swap(&self.arrayProp[i], &self.arrayProp[j])
var localOfGenericType = param
// expected-error@+2{{overlapping accesses}}{{5-75=localOfGenericType.swapAt(paramIndex, paramIndex)}}
// expected-note@+1{{conflicting access is here}}
swap(&localOfGenericType[paramIndex], &localOfGenericType[paramIndex])
// expected-error@+2{{overlapping accesses}}{{5-39=array1.swapAt(i, j)}}
// expected-note@+1{{conflicting access is here}}
Swift.swap(&array1[i], &array1[j]) // no-crash
}
mutating
func shouldHaveNoFixIts(_ i: Int, _ j: Int) {
var s = StructWithField()
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
swap(&s.f, &s.f)
var array1 = [1, 2, 3]
var array2 = [1, 2, 3]
// Swapping between different arrays should cannot have the
// Fix-It.
swap(&array1[i], &array2[j]) // no-warning no-fixit
swap(&array1[i], &self.arrayProp[j]) // no-warning no-fixit
// Dictionaries aren't MutableCollections so don't support swapAt().
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
swap(&dictionaryProp[i], &dictionaryProp[j])
// We could safely Fix-It this but don't now because the left and
// right bases are not textually identical.
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
swap(&self.arrayProp[i], &arrayProp[j])
// We could safely Fix-It this but we're not that heroic.
// We don't suppress when swap() is used as a value
let mySwap: (inout Int, inout Int) -> () = swap
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
mySwap(&array1[i], &array1[j])
func myOtherSwap<T>(_ a: inout T, _ b: inout T) {
swap(&a, &b) // no-warning
}
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
mySwap(&array1[i], &array1[j])
}
}
func takesInoutAndNoEscapeClosure<T>(_ p: inout T, _ c: () -> ()) { }
func callsTakesInoutAndNoEscapeClosure() {
var local = 5
takesInoutAndNoEscapeClosure(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
local = 8 // expected-note {{conflicting access is here}}
}
}
func takesInoutAndNoEscapeClosureThatThrows<T>(_ p: inout T, _ c: () throws -> ()) { }
func callsTakesInoutAndNoEscapeClosureThatThrowsWithNonThrowingClosure() {
var local = 5
takesInoutAndNoEscapeClosureThatThrows(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
local = 8 // expected-note {{conflicting access is here}}
}
}
func takesInoutAndNoEscapeClosureAndThrows<T>(_ p: inout T, _ c: () -> ()) throws { }
func callsTakesInoutAndNoEscapeClosureAndThrows() {
var local = 5
try! takesInoutAndNoEscapeClosureAndThrows(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
local = 8 // expected-note {{conflicting access is here}}
}
}
func takesTwoNoEscapeClosures(_ c1: () -> (), _ c2: () -> ()) { }
func callsTakesTwoNoEscapeClosures() {
var local = 7
takesTwoNoEscapeClosures({local = 8}, {local = 9}) // no-error
_ = local
}
func takesInoutAndEscapingClosure<T>(_ p: inout T, _ c: @escaping () -> ()) { }
func callsTakesInoutAndEscapingClosure() {
var local = 5
takesInoutAndEscapingClosure(&local) { // no-error
local = 8
}
}
func callsClosureLiteralImmediately() {
var i = 7;
// Closure literals that are called immediately are considered nonescaping
_ = ({ (p: inout Int) in
i
// expected-note@-1 {{conflicting access is here}}
}
)(&i)
// expected-error@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
}
func callsStoredClosureLiteral() {
var i = 7;
let c = { (p: inout Int) in i}
// Closure literals that are stored and later called are treated as escaping
// We don't expect a static exclusivity diagnostic here, but the issue
// will be caught at run time
_ = c(&i) // no-error
}
func takesUnsafePointerAndNoEscapeClosure<T>(_ p: UnsafePointer<T>, _ c: () -> ()) { }
func callsTakesUnsafePointerAndNoEscapeClosure() {
var local = 1
takesUnsafePointerAndNoEscapeClosure(&local) { // expected-note {{conflicting access is here}}
local = 2 // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
}
}
func takesThrowingAutoClosureReturningGeneric<T: Equatable>(_ : @autoclosure () throws -> T) { }
func takesInoutAndClosure<T>(_: inout T, _ : () -> ()) { }
func callsTakesThrowingAutoClosureReturningGeneric() {
var i = 0
takesInoutAndClosure(&i) { // expected-error {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
takesThrowingAutoClosureReturningGeneric(i) // expected-note {{conflicting access is here}}
}
}
struct StructWithMutatingMethodThatTakesAutoclosure {
var f = 2
mutating func takesAutoclosure(_ p: @autoclosure () throws -> ()) rethrows { }
}
func conflictOnSubPathInNoEscapeAutoclosure() {
var s = StructWithMutatingMethodThatTakesAutoclosure()
s.takesAutoclosure(s.f = 2)
// expected-error@-1 {{overlapping accesses to 's', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2 {{conflicting access is here}}
}
func conflictOnWholeInNoEscapeAutoclosure() {
var s = StructWithMutatingMethodThatTakesAutoclosure()
takesInoutAndNoEscapeClosure(&s.f) {
// expected-error@-1 {{overlapping accesses to 's.f', but modification requires exclusive access; consider copying to a local variable}}
s = StructWithMutatingMethodThatTakesAutoclosure()
// expected-note@-1 {{conflicting access is here}}
}
}
struct ParameterizedStruct<T> {
mutating func takesFunctionWithGenericReturnType(_ f: (Int) -> T) {}
}
func testReabstractionThunk(p1: inout ParameterizedStruct<Int>,
p2: inout ParameterizedStruct<Int>) {
// Since takesFunctionWithGenericReturnType() takes a closure with a generic
// return type it expects the value to be returned @out. But the closure
// here has an 'Int' return type, so the compiler uses a reabstraction thunk
// to pass the closure to the method.
// This tests that we still detect access violations for closures passed
// using a reabstraction thunk.
p1.takesFunctionWithGenericReturnType { _ in
// expected-warning@-1 {{overlapping accesses to 'p1', but modification requires exclusive access; consider copying to a local variable}}
p2 = p1
// expected-note@-1 {{conflicting access is here}}
return 3
}
}
func takesInoutAndClosureWithGenericArg<T>(_ p: inout Int, _ c: (T) -> Int) { }
func callsTakesInoutAndClosureWithGenericArg() {
var i = 7
takesInoutAndClosureWithGenericArg(&i) { (p: Int) in
// expected-warning@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
return i + p
// expected-note@-1 {{conflicting access is here}}
}
}
func takesInoutAndClosureTakingNonOptional(_ p: inout Int, _ c: (Int) -> ()) { }
func callsTakesInoutAndClosureTakingNonOptionalWithClosureTakingOptional() {
var i = 7
// Test for the thunk converting an (Int?) -> () to an (Int) -> ()
takesInoutAndClosureTakingNonOptional(&i) { (p: Int?) in
// expected-warning@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
i = 8
// expected-note@-1 {{conflicting access is here}}
}
}
func inoutSeparateStructStoredProperties() {
var s = StructWithTwoStoredProp()
takesTwoInouts(&s.f1, &s.f2) // no-error
}
func inoutSameStoredProperty() {
var s = StructWithTwoStoredProp()
takesTwoInouts(&s.f1, &s.f1)
// expected-error@-1{{overlapping accesses to 's.f1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
func inoutSeparateTupleElements() {
var t = (1, 4)
takesTwoInouts(&t.0, &t.1) // no-error
}
func inoutSameTupleElement() {
var t = (1, 4)
takesTwoInouts(&t.0, &t.0)
// expected-error@-1{{overlapping accesses to 't.0', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
func inoutSameTupleNamedElement() {
var t = (name1: 1, name2: 4)
takesTwoInouts(&t.name2, &t.name2)
// expected-error@-1{{overlapping accesses to 't.name2', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
func inoutSamePropertyInSameTuple() {
var t = (name1: 1, name2: StructWithTwoStoredProp())
takesTwoInouts(&t.name2.f1, &t.name2.f1)
// expected-error@-1{{overlapping accesses to 't.name2.f1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
// Noescape closures and separate stored structs
func callsTakesInoutAndNoEscapeClosureNoWarningOnSeparateStored() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local.f1) {
local.f2 = 8 // no-error
}
}
func callsTakesInoutAndNoEscapeClosureWarningOnSameStoredProp() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}}
local.f1 = 8 // expected-note {{conflicting access is here}}
}
}
func callsTakesInoutAndNoEscapeClosureWarningOnAggregateAndStoredProp() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
local.f1 = 8 // expected-note {{conflicting access is here}}
}
}
func callsTakesInoutAndNoEscapeClosureWarningOnStoredPropAndAggregate() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}}
local = StructWithTwoStoredProp() // expected-note {{conflicting access is here}}
}
}
func callsTakesInoutAndNoEscapeClosureWarningOnStoredPropAndBothPropertyAndAggregate() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}}
local.f1 = 8
// We want the diagnostic on the access for the aggregate and not the projection.
local = StructWithTwoStoredProp() // expected-note {{conflicting access is here}}
}
}
func callsTakesInoutAndNoEscapeClosureWarningOnStoredPropAndBothAggregateAndProperty() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}}
// We want the diagnostic on the access for the aggregate and not the projection.
local = StructWithTwoStoredProp() // expected-note {{conflicting access is here}}
local.f1 = 8
}
}
struct MyStruct<T> {
var prop = 7
mutating func inoutBoundGenericStruct() {
takesTwoInouts(&prop, &prop)
// expected-error@-1{{overlapping accesses to 'self.prop', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
}
| 0985c9411a02b83fee540362bc5fff4d | 39.303241 | 190 | 0.716386 | false | false | false | false |
nheagy/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/Blog/WPStyleGuide+Sharing.swift | gpl-2.0 | 1 | import Foundation
import WordPressShared
/// A WPStyleGuide extension with styles and methods specific to the
/// Sharing feature.
///
extension WPStyleGuide
{
/// Create an UIImageView showing the notice gridicon.
///
/// - Returns: A UIImageView
///
public class func sharingCellWarningAccessoryImageView() -> UIImageView {
let imageSize = 20.0
let horizontalPadding = 8.0;
let imageView = UIImageView(frame:CGRect(x: 0, y: 0, width: imageSize + horizontalPadding, height: imageSize))
let noticeImage = UIImage(named: "gridicons-notice")
imageView.image = noticeImage?.imageWithRenderingMode(.AlwaysTemplate)
imageView.tintColor = jazzyOrange()
imageView.contentMode = .Right
return imageView
}
/// Creates an icon for the specified service, or a the default social icon.
///
/// - Parameters:
/// - service: The name of the service.
///
/// - Returns: A template UIImage that can be tinted by a UIImageView's tintColor property.
///
public class func iconForService(service: NSString) -> UIImage {
let name = service.lowercaseString.stringByReplacingOccurrencesOfString("_", withString: "-")
var iconName: String
// Handle special cases
switch name {
case "print" :
iconName = "gridicons-print"
case "email" :
iconName = "gridicons-mail"
case "google-plus-one" :
iconName = "social-google-plus"
case "press-this" :
iconName = "social-wordpress"
default :
iconName = "social-\(name)"
}
var image = UIImage(named: iconName)
if image == nil {
image = UIImage(named: "social-default")
}
return image!.imageWithRenderingMode(.AlwaysTemplate)
}
/// Get's the tint color to use for the specified service when it is connected.
///
/// - Parameters:
/// - service: The name of the service.
///
/// - Returns: The tint color for the service, or the default color.
///
public class func tintColorForConnectedService(service: String) -> UIColor {
guard let name = SharingServiceNames(rawValue: service) else {
return WPStyleGuide.wordPressBlue()
}
switch name {
case .Facebook:
return UIColor(fromRGBAColorWithRed: 59.0, green: 89.0, blue: 152.0, alpha:1)
case .Twitter:
return UIColor(fromRGBAColorWithRed: 85, green: 172, blue: 238, alpha:1)
case .Google:
return UIColor(fromRGBAColorWithRed: 220, green: 78, blue: 65, alpha:1)
case .LinkedIn:
return UIColor(fromRGBAColorWithRed: 0, green: 119, blue: 181, alpha:1)
case .Tumblr:
return UIColor(fromRGBAColorWithRed: 53, green: 70, blue: 92, alpha:1)
case .Path:
return UIColor(fromRGBAColorWithRed: 238, green: 52, blue: 35, alpha:1)
}
}
enum SharingServiceNames: String {
case Facebook = "facebook"
case Twitter = "twitter"
case Google = "google_plus"
case LinkedIn = "linkedin"
case Tumblr = "tumblr"
case Path = "path"
}
}
| baa7f8c121c5f2f0d1080a3a41f643c2 | 32.885417 | 118 | 0.610513 | false | false | false | false |
Jnosh/swift | refs/heads/master | stdlib/public/core/StringHashable.swift | apache-2.0 | 11 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftShims
#if _runtime(_ObjC)
@_silgen_name("swift_stdlib_NSStringHashValue")
func _stdlib_NSStringHashValue(_ str: AnyObject, _ isASCII: Bool) -> Int
@_silgen_name("swift_stdlib_NSStringHashValuePointer")
func _stdlib_NSStringHashValuePointer(_ str: OpaquePointer, _ isASCII: Bool) -> Int
@_silgen_name("swift_stdlib_CFStringHashCString")
func _stdlib_CFStringHashCString(_ str: OpaquePointer, _ len: Int) -> Int
#endif
extension Unicode {
internal static func hashASCII(
_ string: UnsafeBufferPointer<UInt8>
) -> Int {
let collationTable = _swift_stdlib_unicode_getASCIICollationTable()
var hasher = _SipHash13Context(key: _Hashing.secretKey)
for c in string {
_precondition(c <= 127)
let element = collationTable[Int(c)]
// Ignore zero valued collation elements. They don't participate in the
// ordering relation.
if element != 0 {
hasher.append(element)
}
}
return hasher._finalizeAndReturnIntHash()
}
internal static func hashUTF16(
_ string: UnsafeBufferPointer<UInt16>
) -> Int {
let collationIterator = _swift_stdlib_unicodeCollationIterator_create(
string.baseAddress!,
UInt32(string.count))
defer { _swift_stdlib_unicodeCollationIterator_delete(collationIterator) }
var hasher = _SipHash13Context(key: _Hashing.secretKey)
while true {
var hitEnd = false
let element =
_swift_stdlib_unicodeCollationIterator_next(collationIterator, &hitEnd)
if hitEnd {
break
}
// Ignore zero valued collation elements. They don't participate in the
// ordering relation.
if element != 0 {
hasher.append(element)
}
}
return hasher._finalizeAndReturnIntHash()
}
}
@inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
internal func _hashString(_ string: String) -> Int {
let core = string._core
#if _runtime(_ObjC)
// Mix random bits into NSString's hash so that clients don't rely on
// Swift.String.hashValue and NSString.hash being the same.
#if arch(i386) || arch(arm)
let hashOffset = Int(bitPattern: 0x88dd_cc21)
#else
let hashOffset = Int(bitPattern: 0x429b_1266_88dd_cc21)
#endif
// If we have a contiguous string then we can use the stack optimization.
let isASCII = core.isASCII
if core.hasContiguousStorage {
if isASCII {
return hashOffset ^ _stdlib_CFStringHashCString(
OpaquePointer(core.startASCII), core.count)
} else {
let stackAllocated = _NSContiguousString(core)
return hashOffset ^ stackAllocated._unsafeWithNotEscapedSelfPointer {
return _stdlib_NSStringHashValuePointer($0, false)
}
}
} else {
let cocoaString = unsafeBitCast(
string._bridgeToObjectiveCImpl(), to: _NSStringCore.self)
return hashOffset ^ _stdlib_NSStringHashValue(cocoaString, isASCII)
}
#else
if let asciiBuffer = core.asciiBuffer {
return Unicode.hashASCII(UnsafeBufferPointer(
start: asciiBuffer.baseAddress!,
count: asciiBuffer.count))
} else {
return Unicode.hashUTF16(
UnsafeBufferPointer(start: core.startUTF16, count: core.count))
}
#endif
}
extension String : Hashable {
/// The string's hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
public var hashValue: Int {
return _hashString(self)
}
}
| 908fae81d3ee5a98aad5654eddfd28ee | 32.5 | 83 | 0.666915 | false | false | false | false |
WangWenzhuang/ZKStatusBarNotification | refs/heads/master | Demo/Demo/ViewController.swift | mit | 1 | //
// ViewController.swift
// Demo
//
// Created by 王文壮 on 2017/4/25.
// Copyright © 2017年 WangWenzhuang. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
var screenWidth: CGFloat {
get {
return UIScreen.main.bounds.size.width
}
}
let cellIdentifier = "cell"
lazy var actionTexts = ["showInfo", "showError", "showSuccess"]
lazy var headerTexts = ["方法"]
override func viewDidLoad() {
super.viewDidLoad()
let backBarButtonItem = UIBarButtonItem()
backBarButtonItem.title = ""
self.navigationItem.backBarButtonItem = backBarButtonItem
self.title = "ZKStatusBarNotification"
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.actionTexts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier)
cell?.accessoryType = .none
cell?.textLabel?.text = self.actionTexts[indexPath.row]
return cell!
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
if indexPath.section == 0 {
if indexPath.row == 0 {
ZKStatusBarNotification.showInfo("Star 一下吧😙😙😙")
} else if indexPath.row == 1 {
ZKStatusBarNotification.showError("出现错误了😢😢😢")
} else if indexPath.row == 2 {
ZKStatusBarNotification.showSuccess("操作成功👏👏👏")
}
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.headerTexts[section]
}
}
| 5645795742bc5fca3833a991dcc0e92a | 31.838235 | 109 | 0.642185 | false | false | false | false |
TouchInstinct/LeadKit | refs/heads/master | TITransitions/Sources/PanelTransition/Controllers/PresentationController.swift | apache-2.0 | 1 | //
// Copyright (c) 2020 Touch Instinct
//
// 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
open class PresentationController: UIPresentationController {
private let presentStyle: PresentStyle
private let driver: TransitionDriver?
override open var shouldPresentInFullscreen: Bool {
false
}
override open var frameOfPresentedViewInContainerView: CGRect {
calculatePresentedFrame(for: presentStyle)
}
public init(driver: TransitionDriver?,
presentStyle: PresentStyle,
presentedViewController: UIViewController,
presenting: UIViewController?) {
self.driver = driver
self.presentStyle = presentStyle
super.init(presentedViewController: presentedViewController, presenting: presenting)
}
override open func presentationTransitionWillBegin() {
super.presentationTransitionWillBegin()
if let presentedView = presentedView {
containerView?.addSubview(presentedView)
}
}
override open func containerViewDidLayoutSubviews() {
super.containerViewDidLayoutSubviews()
presentedView?.frame = frameOfPresentedViewInContainerView
}
override open func presentationTransitionDidEnd(_ completed: Bool) {
super.presentationTransitionDidEnd(completed)
if completed {
driver?.direction = .dismiss
}
}
}
private extension PresentationController {
func calculatePresentedFrame(for style: PresentStyle) -> CGRect {
guard let bounds = containerView?.bounds else {
return .zero
}
switch style {
case .fullScreen:
return CGRect(x: .zero, y: .zero, width: bounds.width, height: bounds.height)
case .halfScreen:
let halfHeight = bounds.height / 2
return CGRect(x: .zero, y: halfHeight, width: bounds.width, height: halfHeight)
case let .customInsets(insets):
return calculateCustomFrame(insets: insets)
case let .customHeight(height):
return CGRect(x: .zero, y: bounds.height - height, width: bounds.width, height: height)
}
}
func calculateCustomFrame(insets: UIEdgeInsets) -> CGRect {
guard let bounds = containerView?.bounds else {
return .zero
}
let origin = CGPoint(x: insets.left, y: insets.top)
let size = CGSize(width: bounds.width - insets.right - insets.left,
height: bounds.height - insets.top - insets.bottom)
return CGRect(origin: origin, size: size)
}
}
| c3142a3021212ea1aa1bbce1371ead6c | 36.41 | 99 | 0.670409 | false | false | false | false |
OpenSourceContributions/SwiftOCR | refs/heads/master | framework/SwiftOCR/GPUImage2-master/examples/iOS/SimpleImageFilter/SimpleImageFilter/ViewController.swift | apache-2.0 | 1 | import UIKit
import GPUImage
class ViewController: UIViewController {
@IBOutlet weak var renderView: RenderView!
var picture:PictureInput!
var filter:SaturationAdjustment!
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Filtering image for saving
var input1 = UIImage(named:"WID-small.jpg")
var input2 = UIImage(named:"Lambeau.jpg")
//let input1 = PictureInput(imageName:"WID-small.jpg")
//let input2 = PictureInput(imageName:"Lambeau.jpg")
let alphaBlend = AlphaBlend()
//input1.addTarget(alphaBlend)
//input2.addTarget(alphaBlend)
//alphaBlend.addTarget(input1)
//alphaBlend.addTarget(input2)
alphaBlend.mix = 0.5;
//input1.processImage(synchronously: true)
//input2.processImage(synchronously: true)
input1 = input1?.filterWithOperation(alphaBlend)
input2 = input2?.filterWithOperation(alphaBlend)
//let output = PictureOutput();
//output.encodedImageFormat = PictureFileFormat.png
//output.imageAvailableCallback = {image in
// Do something with the image
//UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
// print("Ret2")
//}
//input1 --> alphaBlend
//input2 --> alphaBlend --> output
//input1.processImage(synchronously: true)
//input2.processImage(synchronously: true)
// Filtering image for display
///picture = PictureInput(image:UIImage(named:"WID-small.jpg")!)
//filter = SaturationAdjustment()
//picture --> filter --> renderView
//picture.processImage()
print("Ret1", input2)
}
}
| f0c949b5862fb8f5aa4c4dc8d798d067 | 29.8 | 72 | 0.595779 | false | false | false | false |
justinhester/hacking-with-swift | refs/heads/master | src/Project08/Project8/ViewController.swift | gpl-3.0 | 1 | //
// ViewController.swift
// Project8
//
// Created by Justin Lawrence Hester on 1/24/16.
// Copyright © 2016 Justin Lawrence Hester. All rights reserved.
//
import UIKit
import GameplayKit
class ViewController: UIViewController {
@IBOutlet weak var cluesLabel: UILabel!
@IBOutlet weak var answersLabel: UILabel!
@IBOutlet weak var currentAnswer: UITextField!
@IBOutlet weak var scoreLabel: UILabel!
/* Arrays to help with configuring the 5 x 4 grid of UIButtons. */
var letterButtons = [UIButton]()
var activatedButtons = [UIButton]()
var solutions = [String]()
let DEFAULT_TEXT = "Tap letters to guess"
/* Integers to keep track of user progress. */
var score: Int = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
var level = 1
override func viewDidLoad() {
super.viewDidLoad()
/* Add IBOutlets and IBActions for the 5 x 4 grid of UIButtons. */
for subview in view.subviews where subview.tag == 1001 {
let btn = subview as! UIButton
letterButtons.append(btn)
/* The colon after "letterTapped" means the method takes one parameter. */
btn.addTarget(self, action: #selector(ViewController.letterTapped(_:)), for: .touchUpInside)
}
loadLevel()
}
func loadLevel() {
var clueString = ""
var solutionString = ""
var letterBits = [String]()
if let levelFilePath = Bundle.main.path(forResource: "level\(level)", ofType: "txt") {
if let levelContents = try? String(contentsOfFile: levelFilePath) {
var lines = levelContents.components(separatedBy: "\n")
lines = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: lines) as! [String]
for (index, line) in lines.enumerated() {
/* Read each line in level .txt file and update appropriate arrays. */
let parts = line.components(separatedBy: ": ")
let answer = parts[0]
let clue = parts[1]
clueString += "\(index + 1). \(clue)\n"
let solutionWord = answer.replacingOccurrences(of: "|", with: "")
solutionString += "\(solutionWord.characters.count) letters\n"
solutions.append(solutionWord)
let bits = answer.components(separatedBy: "|")
letterBits += bits
}
/* Configure buttons and labels. */
cluesLabel.text = clueString.trimmingCharacters(in: .whitespacesAndNewlines)
answersLabel.text = solutionString.trimmingCharacters(in: .whitespacesAndNewlines)
letterBits = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: letterBits) as! [String]
letterButtons = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: letterButtons) as! [UIButton]
if letterBits.count == letterButtons.count {
for i in 0 ..< letterButtons.count {
letterButtons[i].setTitle(letterBits[i], for: UIControlState())
}
}
}
}
}
func letterTapped(_ btn: UIButton) {
/* Remove default text on first turn. */
if currentAnswer.text! == DEFAULT_TEXT {
currentAnswer.text = ""
}
currentAnswer.text = currentAnswer.text! + btn.titleLabel!.text!
activatedButtons.append(btn)
btn.isHidden = true
}
@IBAction func submitTapped(_ sender: UIButton) {
if let solutionPosition = solutions.index(of: currentAnswer.text!) {
activatedButtons.removeAll()
/* Update answers label. */
var splitClues = answersLabel.text!.components(separatedBy: "\n")
splitClues[solutionPosition] = currentAnswer.text!
answersLabel.text = splitClues.joined(separator: "\n")
/* Update clues label. */
splitClues = cluesLabel.text!.components(separatedBy: "\n")
splitClues[solutionPosition] = "CORRECT!"
cluesLabel.text = splitClues.joined(separator: "\n")
currentAnswer.text = ""
score += 1
if score % 7 == 0 {
let ac = UIAlertController(
title: "Well done!",
message: "Are you ready for the next level?",
preferredStyle: .alert
)
ac.addAction(
UIAlertAction(
title: "Let's go!",
style: .default,
handler: levelUp
)
)
present(ac, animated: true, completion: nil)
}
}
}
@IBAction func clearTapped(_ sender: UIButton) {
currentAnswer.text = ""
for btn in activatedButtons {
btn.isHidden = false
}
activatedButtons.removeAll()
/* Reset default text. */
currentAnswer.text = DEFAULT_TEXT
}
func levelUp(_ action: UIAlertAction!) {
level += 1
solutions.removeAll(keepingCapacity: true)
loadLevel()
for btn in letterButtons {
btn.isHidden = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 37a1e1c34300f30b8b95521fb869ed21 | 33.358824 | 119 | 0.533641 | false | false | false | false |
codeflows/SceneLauncher | refs/heads/master | src/OSCService.swift | mit | 1 | import Foundation
import ReactiveCocoa
import LlamaKit
class OSCService : NSObject, OSCServerDelegate {
private let client = OSCClient()
private let localServer = OSCServer()
private let incomingMessagesSink: SinkOf<Event<OSCMessage, NoError>>
let incomingMessagesSignal: Signal<OSCMessage, NoError>
override init() {
(incomingMessagesSignal, incomingMessagesSink) = Signal<OSCMessage, NoError>.pipe()
super.init()
localServer.delegate = self
ensureConnected()
let serverAddressChanges = Settings.serverAddress.producer
|> skip(1)
|> ignoreNil
|> skipRepeats
serverAddressChanges
|> start(
next: { _ in self.ensureConnected() },
error: { _ in () }
)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationEnteringForeground", name: UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationEnteringBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
// OSCService public interface
func sendMessage(message: OSCMessage) {
if let serverAddress = Settings.serverAddress.value {
NSLog("[OSCService] Sending message \(message)")
client.sendMessage(message, to: "udp://\(serverAddress):9000")
} else {
NSLog("[OSCService] WARNING: Server address not configured, not sending message \(message)")
}
}
func handleMessage(incomingMessage: OSCMessage!) {
if let message = incomingMessage {
if shouldLog(message) {
NSLog("[OSCService] Received message \(message)")
}
incomingMessagesSink.put(Event.Next(Box(message)))
}
}
func ensureConnected() {
// TODO This is currently public so that we can call it when manually refreshing scenes.
// Ideally, connections would be automatically kept alive in the background.
NSLog("[OSCService] Ensuring we're able to communicate with Ableton at \(Settings.serverAddress.value)")
startLocalServerIfNecessary()
registerWithLiveOSC()
}
// OSCServer callback
func handleDisconnect(error: NSError!) {
NSLog("[OSCService] Local UDP server socket was disconnected: Error: \(error)")
}
// NSNotificationCenter handlers
func applicationEnteringForeground() {
NSLog("[OSCService] Application entering foreground, starting local UDP server")
ensureConnected()
}
func applicationEnteringBackground() {
NSLog("[OSCService] Application entering background, stopping local UDP server")
stopLocalServer()
}
// Private members
private func startLocalServerIfNecessary() {
if(localServer.isClosed()) {
localServer.listen(0)
NSLog("[OSCService] Started local server on port \(localServer.getPort())")
} else {
NSLog("[OSCService] Local server already running at port \(localServer.getPort())")
}
}
private func stopLocalServer() {
localServer.stop()
}
private func registerWithLiveOSC() {
sendMessage(OSCMessage(address: "/remix/set_peer", arguments: ["", localServer.getPort()]))
}
private func shouldLog(message: OSCMessage) -> Bool {
return message.address != "/live/track/meter" && message.address != "/live/device/param"
}
}
extension OSCMessage: Printable {
override public var description: String {
return "\(address) \(arguments)"
}
} | 1f0664d94346910b53445df2e492d286 | 30.504587 | 166 | 0.701136 | false | false | false | false |
honghaoz/UW-Quest-iOS | refs/heads/master | UW Quest/Network/QuestClientPersonalInformation.swift | apache-2.0 | 1 | //
// QuestClientPersonalInformation.swift
// UW Quest
//
// Created by Honghao Zhang on 3/2/15.
// Copyright (c) 2015 Honghao. All rights reserved.
//
import Foundation
// Personal Information
let kPersonalInfoAddressURL = "https://quest.pecs.uwaterloo.ca/psc/SS/ACADEMIC/HRMS/c/CC_PORTFOLIO.SS_CC_ADDRESSES.GBL"
let kPersonalInfoNameURL = "https://quest.pecs.uwaterloo.ca/psc/SS/ACADEMIC/HRMS/c/CC_PORTFOLIO.SS_CC_NAMES.GBL"
let kPersonalInfoPhoneNumbersURL = "https://quest.pecs.uwaterloo.ca/psc/SS/ACADEMIC/HRMS/c/CC_PORTFOLIO.SS_CC_PERS_PHONE.GBL"
let kPersonalInfoEmailsURL = "https://quest.pecs.uwaterloo.ca/psc/SS/ACADEMIC/HRMS/c/CC_PORTFOLIO.SS_CC_EMAIL_ADDR.GBL"
let kPersonalInfoEnergencyURL = "https://quest.pecs.uwaterloo.ca/psc/SS/ACADEMIC/HRMS/c/CC_PORTFOLIO.SS_CC_EMERG_CNTCT.GBL"
let kPersonalInfoDemographicInfoURL = "https://quest.pecs.uwaterloo.ca/psc/SS/ACADEMIC/HRMS/c/CC_PORTFOLIO.SS_CC_DEMOG_DATA.GBL"
let kPersonalInfoCitizenshipURL = "https://quest.pecs.uwaterloo.ca/psc/SS/ACADEMIC/HRMS/c/UW_SS_MENU.UW_SS_CC_VISA_DOC.GBL"
let kPersonalInfoAbsenceDeclarationURL = "https://quest.pecs.uwaterloo.ca/psc/SS/ACADEMIC/HRMS/c/CC_PORTFOLIO.UW_SS_CC_ABSENCE.GBL"
// MARK: Personal Information
extension QuestClient {
func getPersonalInformation(type: PersonalInformationType, success:(data: AnyObject!) -> (), failure:(errorMessage: String, error: NSError?) -> ()) {
var parameters: Dictionary<String, String>!
var parseFunction: ((AnyObject) -> JSON?)!
var successClosure: (response: AnyObject?, json: JSON?) -> () = { (response, json) -> () in
if json == nil {
failure(errorMessage: "Parse Error", error: NSError(domain: "Parse Error", code: 0, userInfo: nil))
} else {
success(data: json!.rawValue)
}
}
switch type {
case .Addresses:
logVerbose(".Addresses")
parameters = [
"Page": "SS_ADDRESSES",
"Action": "C"
]
getPersonalInformationWithParameters(parameters, kPersonalInfoAddressURL, parseAddress, successClosure, failure)
case .Names:
logVerbose(".Names")
parameters = [
"Page": "SS_CC_NAME",
"Action": "C"
]
getPersonalInformationWithParameters(parameters, kPersonalInfoNameURL,parseName, successClosure, failure)
case .PhoneNumbers:
logVerbose(".PhoneNumbers")
parameters = [
"Page": "SS_CC_PERS_PHONE",
"Action": "U"
]
getPersonalInformationWithParameters(parameters, kPersonalInfoPhoneNumbersURL, parsePhoneNumbers, successClosure, failure)
case .EmailAddresses:
logVerbose(".Emails")
parameters = [
"Page": "SS_CC_EMAIL_ADDR",
"Action": "U"
]
getPersonalInformationWithParameters(parameters, kPersonalInfoEmailsURL, parseEmails, successClosure, failure)
case .EmergencyContacts:
logVerbose(".EmergencyContacts")
parameters = [
"Page": "SS_CC_EMRG_CNTCT_L",
"Action": "U"
]
getPersonalInformationWithParameters(parameters, kPersonalInfoEnergencyURL, parseEmergencyContacts, successClosure, failure)
case .DemographicInformation:
logVerbose(".DemographicInformation")
parameters = [
"Page": "SS_CC_DEMOG_DATA",
"Action": "U"
]
getPersonalInformationWithParameters(parameters, kPersonalInfoDemographicInfoURL, parseDemographicInfo, successClosure, failure)
case .CitizenshipImmigrationDocuments:
logVerbose(".CitizenshipImmigrationDocuments")
parameters = [
"Page": "UW_SS_CC_VISA_DOC",
"Action": "U"
]
getPersonalInformationWithParameters(parameters, kPersonalInfoCitizenshipURL, parseCitizenship, successClosure, failure)
default: assert(false, "Wrong PersonalInformation Type")
}
}
func postPersonalInformation(success: ((response: AnyObject?, json: JSON?) -> ())? = nil, failure: ((errorMessage: String, error: NSError) -> ())? = nil) {
logVerbose()
if currentPostPage == .PersonalInformation {
success?(response: nil, json: nil)
return
}
var parameters = self.getBasicParameters()
parameters["ICAction"] = "DERIVED_SSS_SCL_SS_DEMO_SUM_LINK"
self.POST(kStudentCenterURL_HRMS, parameters: parameters, success: { (task, response) -> Void in
logInfo("Success")
self.currentStateNum += 1
self.currentPostPage = .PersonalInformation
success?(response: response, json: nil)
}, failure: { (task, error) -> Void in
logError("Failed: \(error.localizedDescription)")
failure?(errorMessage: "POST Personal Information Failed", error: error)
})
}
func getPersonalInformationWithParameters(parameters: Dictionary<String, String>,
_ urlString: String,
_ parseFunction: (AnyObject) -> JSON?,
_ success: ((response: AnyObject?, json: JSON?) -> ())? = nil,
_ failure: ((errorMessage: String, error: NSError) -> ())? = nil) {
logVerbose()
if currentPostPage != .PersonalInformation {
self.postPersonalInformation(success: { (response, json) -> () in
self.getPersonalInformationWithParameters(parameters, urlString, parseFunction,success, failure)
}, failure: failure)
return
}
self.GET(urlString, parameters: parameters, success: { (task, response) -> Void in
if self.updateState(response) {
logInfo("Success")
success?(response: response, json: parseFunction(response))
} else {
failure?(errorMessage: "Update State Failed", error: NSError(domain: "PersonalInformation", code: 1000, userInfo: nil))
}
}, failure: {(task, error) -> Void in
logError("Failed: \(error.localizedDescription)")
failure?(errorMessage: "POST Personal Information Failed", error: error)
})
}
/**
Parse address response to JSON data
[{"Address Type": "...", "Address": "..."} ...]
:param: response network response
:returns: JSON data
*/
func parseAddress(response: AnyObject) -> JSON? {
let html = getHtmlContentFromResponse(response)
if html == nil {
return nil
}
let addressElements = html!.searchWithXPathQuery("//*/table[@id='SCC_ADDR_H$scroll$0']//*/table//tr[position()>1]")
var dataArray = [Dictionary<String, String>]()
var i = 0
while i < addressElements.count {
let eachAddressRow = addressElements[i]
let columns = eachAddressRow.childrenWithTagName("td")
if columns.count < 3 { return JSON(dataArray) }
let typeRaw: String = (columns[0] as! TFHppleElement).raw
var type: String? = typeRaw.stringByConvertingHTMLToPlainText()
if type == nil { return JSON(dataArray) }
// type = type!.clearNewLines()
let addressRaw: String = (columns[1] as! TFHppleElement).raw
var address: String? = addressRaw.stringByConvertingHTMLToPlainText()
if address == nil { return JSON(dataArray) }
// address = address!.clearNewLines()
var addrDict = [
"Address Type": type!,
"Address": address!
]
dataArray.append(addrDict)
i++
}
return JSON(dataArray)
}
/**
Parse address response to JSON data
{"Message": "...", "Data": [{"Name Type": "...", "Name": "..."}]}
:param: response network response
:returns: JSON data
*/
func parseName(response: AnyObject) -> JSON? {
let html = getHtmlContentFromResponse(response)
if html == nil {
return nil
}
var resultDict: Dictionary<String, AnyObject> = [
"Message": "",
"Data": [Dictionary<String, String>]()
]
// Message
//*[@class="PAPAGEINSTRUCTIONS"]
let messageElements = html!.searchWithXPathQuery("//*[@class='PAPAGEINSTRUCTIONS']")
if messageElements.count > 0 {
let message: String? = (messageElements[0] as TFHppleElement).text()
if message != nil {
resultDict["Message"] = message
}
}
// Names
//*[@id="SCC_NAMES_H$scroll$0"]//*/table//tr[position()>1]
let nameRows = html!.searchWithXPathQuery("//*[@id='SCC_NAMES_H$scroll$0']//*/table//tr[position()>1]")
var dataArray = [Dictionary<String, String>]()
var i = 0
while i < nameRows.count {
let eachNameRow = nameRows[i]
let columns = eachNameRow.childrenWithTagName("td")
if columns.count < 2 { return JSON(resultDict) }
let typeRaw: String = (columns[0] as! TFHppleElement).raw
var type: String? = typeRaw.stringByConvertingHTMLToPlainText()
if type == nil { return JSON(resultDict) }
let nameRaw: String = (columns[1] as! TFHppleElement).raw
var name: String? = nameRaw.stringByConvertingHTMLToPlainText()
if name == nil { return JSON(resultDict) }
var nameDict = [
"Name Type": type!,
"Name": name!
]
dataArray.append(nameDict)
resultDict["Data"] = dataArray
i++
}
return JSON(resultDict)
}
/**
Parse address response to JSON data
[{"Phone Type": "Business", "Telephone": "519/781-2862", "Ext": "", "Country": "001", "Preferred": "Y"}]
:param: response network response
:returns: JSON data
*/
func parsePhoneNumbers(response: AnyObject) -> JSON? {
let html = getHtmlContentFromResponse(response)
if html == nil {
return nil
}
// Phone number table
let phoneTables = html!.searchWithXPathQuery("//*[@id='SCC_PERS_PHN_H$scroll$0']")
if phoneTables.count == 0 {
return JSON([])
} else {
let phoneTable = phoneTables[0] as TFHppleElement
let tableArray = phoneTable.table2DArray()
var dataArray = [Dictionary<String, String>]()
if tableArray != nil {
for i in 1 ..< tableArray!.count {
var dict = Dictionary<String, String>()
for j in 0 ..< 5 {
dict[tableArray![0][j]] = tableArray![i][j]
}
dataArray.append(dict)
}
}
return JSON(dataArray)
}
}
/**
Parse email address response to JSON data
{
'alternate_email_address': {
'data': [{'email_address': '[email protected]',
'email_type': 'Home'}
],
'description': 'The Admissions Office will use the Home email address to communicate with you as an applicant.'
},
'description': 'Email is the primary means of communication used by the University. It is important for you to keep your email address up to date.',
'campus_email_address': {
'data': [{'delivered_to': '[email protected]',
'campus_email': '[email protected]'}
],
'description': 'This is the official email address the University community will use to communicate with you as a student.'}
}
:param: response network response
:returns: JSON data
*/
func parseEmails(response: AnyObject) -> JSON? {
let html = getHtmlContentFromResponse(response)
if html == nil {
return nil
}
var responseDictionary = [String: AnyObject]()
// Description
let descriptionElements = html!.searchWithXPathQuery("//*[@id='win0div$ICField55']")
if descriptionElements.count == 0 {
responseDictionary["description"] = ""
} else {
responseDictionary["description"] = descriptionElements[0].raw.stringByConvertingHTMLToPlainText()
}
// Campus email
var campusEmailDict = [String: AnyObject]()
let campusDescriptionElements = html!.searchWithXPathQuery("//*[@id='win0div$ICField59']")
if campusDescriptionElements.count == 0 {
campusEmailDict["description"] = ""
} else {
campusEmailDict["description"] = campusDescriptionElements[0].raw.stringByConvertingHTMLToPlainText()
}
var dataArray = [Dictionary<String, String>]()
let campusEmailTableElements = html!.searchWithXPathQuery("//*[@id='win0divUW_RTG_EMAIL_VW$0']")
if campusEmailTableElements.count > 0 {
let tableArray = campusEmailTableElements[0].table2DArray()
if tableArray != nil {
for i in 1 ..< tableArray!.count {
var dict = Dictionary<String, String>()
for j in 0 ..< 2 {
dict[tableArray![0][j]] = tableArray![i][j]
}
dataArray.append(dict)
}
}
}
campusEmailDict["data"] = dataArray
responseDictionary["campus_email_address"] = campusEmailDict
// Alternative email
var alterEmailDict = [String: AnyObject]()
let alterDescriptionElements = html!.searchWithXPathQuery("//*[@id='win0div$ICField72']")
if alterDescriptionElements.count == 0 {
alterEmailDict["description"] = ""
} else {
alterEmailDict["description"] = alterDescriptionElements[0].raw.stringByConvertingHTMLToPlainText()
}
dataArray = [Dictionary<String, String>]()
let alterEmailTableElements = html!.searchWithXPathQuery("//*[@id='win0divSCC_EMAIL_H$0']")
if alterEmailTableElements.count > 0 {
let tableArray = alterEmailTableElements[0].table2DArray()
if tableArray != nil {
for i in 1 ..< tableArray!.count {
var dict = Dictionary<String, String>()
for j in 0 ..< 2 {
dict[tableArray![0][j]] = tableArray![i][j]
}
dataArray.append(dict)
}
}
}
alterEmailDict["data"] = dataArray
responseDictionary["alternate_email_address"] = alterEmailDict
return JSON(responseDictionary)
}
/**
[{'relationship': 'Friend', 'extension': '-', 'country': '001', 'phone': '519/781-2862', 'primary_contact': u'Y', 'contact_name': 'Wenchao Wang'},
{'relationship': 'Other', 'extension': '-', 'country': '001', 'phone': '519/781-2862', 'primary_contact': u'N', 'contact_name': 'Yansong Li'}
]
:param: response response network response
:returns: JSON data
*/
func parseEmergencyContacts(response: AnyObject) -> JSON? {
let html = getHtmlContentFromResponse(response)
if html == nil {
return nil
}
//*[@id="win0divSCC_EMERG_CNT_H$0"]
let tables = html!.searchWithXPathQuery("//*[@id='win0divSCC_EMERG_CNT_H$0']")
if tables.count == 0 {
return JSON([])
} else {
let contactTable = tables[0] as TFHppleElement
let tableArray = contactTable.table2DArray()
var dataArray = [Dictionary<String, String>]()
if tableArray != nil {
for i in 1 ..< tableArray!.count {
var dict = Dictionary<String, String>()
for j in 0 ..< 6 {
dict[tableArray![0][j]] = tableArray![i][j]
}
dataArray.append(dict)
}
}
return JSON(dataArray)
}
}
/**
["Demographic Information": {
"ID": "11111111"
"Gender": "Male"
Date of Birth: 01/01/1900
Birth Country: ""
Birth State: ""
Marital Status: Single
Military Status: ""
},
"National Identification Number": {
Country: Canada
National ID Type: SIN
National ID
},
"Ethnicity": {
Ethnic Group: ""
Description: ""
Primary: ""
},
"Citizenship Information": {
Description Student Permit
Country Canada
Description Citizen
Country China
}
"Driver's License": {
License #
Country
State
}
Visa or Permit Data: {
*Type: Student Visa - Visa
Country: Canada
}, ...
]
"message": "If any of the information above is wrong, contact your administrative office."
:param: response response network response
:returns: JSON data
*/
func parseDemographicInfo(response: AnyObject) -> JSON? {
let html = getHtmlContentFromResponse(response)
if html == nil {
return nil
}
var responseDictionary = [String: AnyObject]()
// Demographic
//*[@id="ACE_$ICField45"]
var tables = html!.searchWithXPathQuery("//*[@id='ACE_$ICField45']")
if tables.count == 0 {
return JSON(responseDictionary)
} else {
var demoTuples = [[String]]()
let demoTable = tables[0] as TFHppleElement
let tableArray = demoTable.table2DArray()
logDebug("\(tableArray)")
if tableArray != nil {
var oneDArray = transform2dTo1d(tableArray!)
var i: Int = 0
logDebug("\(oneDArray)")
// FIXME: Array is changeable
while i < oneDArray.count {
let t = [oneDArray[i], oneDArray[i + 1]]
demoTuples.append(t)
i += 2
}
}
responseDictionary["Demographic Information"] = demoTuples
}
// National Identification Number
//*[@id="ACE_$ICField1$0"]
tables = html!.searchWithXPathQuery("//*[@id='ACE_$ICField1$0']")
if tables.count == 0 {
return JSON(responseDictionary)
} else {
let table = tables[0] as TFHppleElement
let tableArray = table.table2DArray()
var tuples = [[String]]()
if tableArray != nil {
// [["", "", "", "", "", "", ""], ["", "Country", "National ID Type", "National ID"], ["", "Canada", "SIN", " "]]
for i in 2 ..< tableArray!.count {
for j in 1 ..< tableArray![i].count {
tuples.append([tableArray![1][j], tableArray![i][j]])
}
}
}
responseDictionary["National Identification Number"] = tuples
}
// Ethnicity
//*[@id="ACE_ETHNICITY$0"]
tables = html!.searchWithXPathQuery("//*[@id='ACE_ETHNICITY$0']")
if tables.count == 0 {
return JSON(responseDictionary)
} else {
let table = tables[0] as TFHppleElement
let tableArray = table.table2DArray()
var tuples = [[String]]()
if tableArray != nil {
// [["", "", "", "", "", "", ""], ["", "Ethnic Group", "Description", "Primary"], ["", " ", " ", " "]]
for i in 2 ..< tableArray!.count {
for j in 1 ..< tableArray![i].count {
tuples.append([tableArray![1][j], tableArray![i][j]])
}
}
}
responseDictionary["Ethnicity"] = tuples
}
// Citizenship Information
//*[@id="ACE_CITIZENSHIP$0"]
tables = html!.searchWithXPathQuery("//*[@id='ACE_CITIZENSHIP$0']")
if tables.count == 0 {
return JSON(responseDictionary)
} else {
let table = tables[0] as TFHppleElement
let tableArray = table.table2DArray()
// [["", "", "", "", ""],
// ["", "Description", "", "Country"],
// ["", "Student Permit"],
// ["", "Canada"],
// ["", "Description", "Country"],
// ["", "Citizen"],
// ["", "China"]]
var tuples = [[String]]()
if tableArray != nil {
var i: Int = 2
while i < tableArray!.count {
tuples.append([tableArray![i][1], tableArray![i + 1][1]])
i += 3
}
}
responseDictionary["Citizenship Information"] = tuples
}
// Driver's License
//*[@id="ACE_DRIVERS_LIC$0"]
//*[@id="win0divDRIVERS_LIC_VW_DRIVERS_LIC_NBRlbl$0"]
//*[@id="win0divDRIVERS_LIC_VW_DRIVERS_LIC_NBR$0"]
//*[@id="win0divCOUNTRY_TBL_DESCR$28$lbl$0"]
//*[@id="win0divCOUNTRY_TBL_DESCR$28$$0"]
//*[@id="win0divDRIVERS_LIC_VW_STATElbl$0"]
//*[@id="win0divDRIVERS_LIC_VW_STATE$0"]
var tuples = [[String]]()
tuples.append(
[
html!.plainTextForXPathQuery("//*[@id='win0divDRIVERS_LIC_VW_DRIVERS_LIC_NBRlbl$0']"),
html!.plainTextForXPathQuery("//*[@id='win0divDRIVERS_LIC_VW_DRIVERS_LIC_NBR$0']")
]
)
tuples.append(
[
html!.plainTextForXPathQuery("//*[@id='win0divCOUNTRY_TBL_DESCR$28$lbl$0']"),
html!.plainTextForXPathQuery("//*[@id='win0divCOUNTRY_TBL_DESCR$28$$0']")
]
)
tuples.append(
[
html!.plainTextForXPathQuery("//*[@id='win0divDRIVERS_LIC_VW_STATElbl$0']"),
html!.plainTextForXPathQuery("//*[@id='win0divDRIVERS_LIC_VW_STATE$0']")
]
)
responseDictionary["Driver's License"] = tuples
// Visa or Permit Data
//*[@id="VISA_PERMIT_TBL_DESCR$0"]
//*[@id="PSXLATITEM_XLATLONGNAME$36$$0"]
//*[@id="COUNTRY_TBL_DESCR$32$$0"]
tuples = [[String]]()
var i: Int = 0
var basicXPathString1: NSString = "//*[@id='VISA_PERMIT_TBL_DESCR$%d']"
var basicXPathString2: NSString = "//*[@id='PSXLATITEM_XLATLONGNAME$36$$%d']"
var basicXPathString3: NSString = "//*[@id='COUNTRY_TBL_DESCR$32$$%d']"
while html!.peekAtSearchWithXPathQuery(NSString(format: basicXPathString1, i) as String) != nil {
tuples.append(
[
"Type",
html!.peekAtSearchWithXPathQuery(NSString(format: basicXPathString1, i) as String)!.raw.stringByConvertingHTMLToPlainText().trimmed() + " - " + html!.peekAtSearchWithXPathQuery(NSString(format: basicXPathString2, i) as String)!.raw.stringByConvertingHTMLToPlainText().trimmed()
]
)
tuples.append(
[
"Country",
html!.peekAtSearchWithXPathQuery(NSString(format: basicXPathString3, i) as String)!.raw.stringByConvertingHTMLToPlainText().trimmed()
]
)
i += 1
}
responseDictionary["Visa or Permit Data"] = tuples
// Message
//*[@id="win0div$ICField37"]
responseDictionary["Message"] = html!.plainTextForXPathQuery("//*[@id='win0div$ICField37']")
return JSON(responseDictionary)
}
/**
[
{"Type": "Required Documentation",
"Data": [
{
"Title": "Canada - Student Visa",
"Date Received": "09/13/2013",
"Expiration Date": "09/13/2013"
},
...
]
},
...
]
:param: response response network response
:returns: JSON data
*/
func parseCitizenship(response: AnyObject) -> JSON? {
let html = getHtmlContentFromResponse(response)
if html == nil {
return nil
}
var dataArray = [Dictionary<String, AnyObject>]()
//*[@id="win0divVISA_PMT_SUPPRT$0"]
let basicQueryString: NSString = "//*[@id='win0divVISA_PMT_SUPPRT$%d']//table"
var i: Int = 0
var tables = html!.searchWithXPathQuery(NSString(format: basicQueryString, i) as String)
while tables.count >= 2 {
var headerTable = tables[0] as TFHppleElement
var docDict = Dictionary<String, AnyObject>()
// Get header
var type = headerTable.displayableString()?.trimmed()
docDict["Type"] = type
var datas = [Dictionary<String, String>]()
docDict["Data"] = datas
for x in 1 ..< tables.count {
var contentTable = tables[x] as TFHppleElement
// Content
let contentArray = contentTable.table2DArray()
if contentArray == nil || contentArray!.count < 2 { return JSON(dataArray) }
// [[" ", " ", "Date Received ", "Expiration Date "],
// ["Canada", "Student Visa", "2013/09/13", "2015/12/31"]]
// ...
for j in 1 ..< contentArray!.count {
if !(contentArray![0].count == 4) { return JSON(dataArray) }
var visaDict = Dictionary<String, String>()
visaDict["Title"] = contentArray![j][0] + " - " + contentArray![j][1]
visaDict[contentArray![0][2]] = contentArray![j][2]
visaDict[contentArray![0][3]] = contentArray![j][3]
datas.append(visaDict)
}
}
docDict["Data"] = datas
dataArray.append(docDict)
i += 1
tables = html!.searchWithXPathQuery(NSString(format: basicQueryString, i) as String)
}
return JSON(dataArray)
}
} | 1717a9d3a26d36ce696702e29fb54ec8 | 38.472511 | 297 | 0.540017 | false | false | false | false |
gpancio/iOS-Prototypes | refs/heads/master | GPUIKit/GPUIKit/Classes/MultiSelectTableViewController.swift | mit | 1 | //
// MultiSelectTableViewController.swift
// GPUIKit
//
// Created by Graham Pancio on 2016-04-27.
// Copyright © 2016 Graham Pancio. All rights reserved.
//
import UIKit
public protocol SelectionListener: class {
func selectionChanged(option: (String, Bool))
}
public class MultiSelectTableViewController: UITableViewController {
/**
The options to display. This should be a dictionary where the keys are the titles to display
and the values denote whether that option is selected.
*/
public var options = [String:Bool]() {
didSet {
optionsArray = [String](options.keys)
}
}
var optionsArray = [String]()
public weak var listener: SelectionListener?
@IBAction func checkboxPressed(sender: AnyObject) {
let option: String = optionsArray[sender.tag]
if let oldValue: Bool = options[option] {
options.updateValue(!oldValue, forKey: option)
listener?.selectionChanged(option, !oldValue)
}
}
override public func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
// MARK: - Table view data source
override public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return options.count
}
override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("multiselectCell", forIndexPath: indexPath)
configureCell(cell, atIndexPath: indexPath)
return cell
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
if let customCell = cell.contentView.subviews[0] as? CheckboxLabelView {
let option = optionsArray[indexPath.row]
customCell.title = option
customCell.checked = options[option] ?? false
customCell.checkboxTag = indexPath.row
customCell.checkbox.addTarget(self, action: #selector(checkboxPressed), forControlEvents: .TouchUpInside)
}
}
}
| 7c763698de3037559da4503a15dcf237 | 33.184211 | 125 | 0.669746 | false | false | false | false |
RedMadRobot/input-mask-ios | refs/heads/master | Source/InputMask/InputMaskTests/Classes/Mask/EndlessIntegerCase.swift | mit | 1 | //
// Project «InputMask»
// Created by Jeorge Taflanidi
//
import XCTest
@testable import InputMask
class EndlessIntegerCase: MaskTestCase {
override func format() -> String {
return "[0…]"
}
func testInit_correctFormat_maskInitialized() {
XCTAssertNotNil(try self.mask())
}
func testInit_correctFormat_measureTime() {
self.measure {
var masks: [Mask] = []
for _ in 1...1000 {
masks.append(
try! self.mask()
)
}
}
}
func testGetOrCreate_correctFormat_measureTime() {
self.measure {
var masks: [Mask] = []
for _ in 1...1000 {
masks.append(
try! Mask.getOrCreate(withFormat: self.format())
)
}
}
}
func testGetPlaceholder_allSet_returnsCorrectPlaceholder() {
let placeholder: String = try! self.mask().placeholder
XCTAssertEqual(placeholder, "0")
}
func testAcceptableTextLength_allSet_returnsCorrectCount() {
let acceptableTextLength: Int = try! self.mask().acceptableTextLength
XCTAssertEqual(acceptableTextLength, 2)
}
func testTotalTextLength_allSet_returnsCorrectCount() {
let totalTextLength: Int = try! self.mask().totalTextLength
XCTAssertEqual(totalTextLength, 2)
}
func testAcceptableValueLength_allSet_returnsCorrectCount() {
let acceptableValueLength: Int = try! self.mask().acceptableValueLength
XCTAssertEqual(acceptableValueLength, 2)
}
func testTotalValueLength_allSet_returnsCorrectCount() {
let totalValueLength: Int = try! self.mask().totalValueLength
XCTAssertEqual(totalValueLength, 2)
}
func testApply_J_returns_emptyString() {
let inputString: String = "J"
let inputCaret: String.Index = inputString.endIndex
let expectedString: String = ""
let expectedCaret: String.Index = expectedString.endIndex
let expectedValue: String = expectedString
let result: Mask.Result = try! self.mask().apply(
toText: CaretString(
string: inputString,
caretPosition: inputCaret,
caretGravity: .forward(autocomplete: false)
)
)
XCTAssertEqual(expectedString, result.formattedText.string)
XCTAssertEqual(expectedCaret, result.formattedText.caretPosition)
XCTAssertEqual(expectedValue, result.extractedValue)
XCTAssertEqual(false, result.complete)
}
func testApply_Je_returns_emptyString() {
let inputString: String = "Je"
let inputCaret: String.Index = inputString.endIndex
let expectedString: String = ""
let expectedCaret: String.Index = expectedString.endIndex
let expectedValue: String = expectedString
let result: Mask.Result = try! self.mask().apply(
toText: CaretString(
string: inputString,
caretPosition: inputCaret,
caretGravity: .forward(autocomplete: false)
)
)
XCTAssertEqual(expectedString, result.formattedText.string)
XCTAssertEqual(expectedCaret, result.formattedText.caretPosition)
XCTAssertEqual(expectedValue, result.extractedValue)
XCTAssertEqual(false, result.complete)
}
func testApply_Jeo_returns_emptyString() {
let inputString: String = "Jeo"
let inputCaret: String.Index = inputString.endIndex
let expectedString: String = ""
let expectedCaret: String.Index = expectedString.endIndex
let expectedValue: String = expectedString
let result: Mask.Result = try! self.mask().apply(
toText: CaretString(
string: inputString,
caretPosition: inputCaret,
caretGravity: .forward(autocomplete: false)
)
)
XCTAssertEqual(expectedString, result.formattedText.string)
XCTAssertEqual(expectedCaret, result.formattedText.caretPosition)
XCTAssertEqual(expectedValue, result.extractedValue)
XCTAssertEqual(false, result.complete)
}
func testApply_1_returns_1() {
let inputString: String = "1"
let inputCaret: String.Index = inputString.endIndex
let expectedString: String = "1"
let expectedCaret: String.Index = expectedString.endIndex
let expectedValue: String = expectedString
let result: Mask.Result = try! self.mask().apply(
toText: CaretString(
string: inputString,
caretPosition: inputCaret,
caretGravity: .forward(autocomplete: false)
)
)
XCTAssertEqual(expectedString, result.formattedText.string)
XCTAssertEqual(expectedCaret, result.formattedText.caretPosition)
XCTAssertEqual(expectedValue, result.extractedValue)
XCTAssertEqual(true, result.complete)
}
func testApply_12_returns_12() {
let inputString: String = "12"
let inputCaret: String.Index = inputString.endIndex
let expectedString: String = "12"
let expectedCaret: String.Index = expectedString.endIndex
let expectedValue: String = expectedString
let result: Mask.Result = try! self.mask().apply(
toText: CaretString(
string: inputString,
caretPosition: inputCaret,
caretGravity: .forward(autocomplete: false)
)
)
XCTAssertEqual(expectedString, result.formattedText.string)
XCTAssertEqual(expectedCaret, result.formattedText.caretPosition)
XCTAssertEqual(expectedValue, result.extractedValue)
XCTAssertEqual(true, result.complete)
}
func testApply_123_returns_123() {
let inputString: String = "123"
let inputCaret: String.Index = inputString.endIndex
let expectedString: String = "123"
let expectedCaret: String.Index = expectedString.endIndex
let expectedValue: String = expectedString
let result: Mask.Result = try! self.mask().apply(
toText: CaretString(
string: inputString,
caretPosition: inputCaret,
caretGravity: .forward(autocomplete: false)
)
)
XCTAssertEqual(expectedString, result.formattedText.string)
XCTAssertEqual(expectedCaret, result.formattedText.caretPosition)
XCTAssertEqual(expectedValue, result.extractedValue)
XCTAssertEqual(true, result.complete)
}
func testApply_1Jeorge2_returns_12() {
let inputString: String = "1Jeorge2"
let inputCaret: String.Index = inputString.endIndex
let expectedString: String = "12"
let expectedCaret: String.Index = expectedString.endIndex
let expectedValue: String = expectedString
let result: Mask.Result = try! self.mask().apply(
toText: CaretString(
string: inputString,
caretPosition: inputCaret,
caretGravity: .forward(autocomplete: false)
)
)
XCTAssertEqual(expectedString, result.formattedText.string)
XCTAssertEqual(expectedCaret, result.formattedText.caretPosition)
XCTAssertEqual(expectedValue, result.extractedValue)
XCTAssertEqual(true, result.complete)
}
func testApply_1Jeorge23_returns_123() {
let inputString: String = "1Jeorge23"
let inputCaret: String.Index = inputString.endIndex
let expectedString: String = "123"
let expectedCaret: String.Index = expectedString.endIndex
let expectedValue: String = expectedString
let result: Mask.Result = try! self.mask().apply(
toText: CaretString(
string: inputString,
caretPosition: inputCaret,
caretGravity: .forward(autocomplete: false)
)
)
XCTAssertEqual(expectedString, result.formattedText.string)
XCTAssertEqual(expectedCaret, result.formattedText.caretPosition)
XCTAssertEqual(expectedValue, result.extractedValue)
XCTAssertEqual(true, result.complete)
}
}
| a6eda7bd7f92bf6aba9aaefa74d3f5d6 | 34.15873 | 79 | 0.59684 | false | true | false | false |
dreamsxin/swift | refs/heads/master | test/DebugInfo/mangling.swift | apache-2.0 | 3 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s
// Type:
// Swift.Dictionary<Swift.Int64, Swift.String>
func markUsed<T>(_ t: T) {}
// Variable:
// mangling.myDict : Swift.Dictionary<Swift.Int64, Swift.String>
// CHECK: !DIGlobalVariable(name: "myDict",
// CHECK-SAME: linkageName: "_Tv8mangling6myDictGVs10DictionaryVs5Int64SS_",
// CHECK-SAME: line: [[@LINE+3]]
// CHECK-SAME: type: ![[DT:[0-9]+]]
// CHECK: ![[DT]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Dictionary"
var myDict = Dictionary<Int64, String>()
myDict[12] = "Hello!"
// mangling.myTuple1 : (Name : Swift.String, Id : Swift.Int64)
// CHECK: !DIGlobalVariable(name: "myTuple1",
// CHECK-SAME: linkageName: "_Tv8mangling8myTuple1T4NameSS2IdVs5Int64_",
// CHECK-SAME: line: [[@LINE+3]]
// CHECK-SAME: type: ![[TT1:[0-9]+]]
// CHECK: ![[TT1]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_TtT4NameSS2IdVs5Int64_"
var myTuple1 : (Name: String, Id: Int64) = ("A", 1)
// mangling.myTuple2 : (Swift.String, Id : Swift.Int64)
// CHECK: !DIGlobalVariable(name: "myTuple2",
// CHECK-SAME: linkageName: "_Tv8mangling8myTuple2TSS2IdVs5Int64_",
// CHECK-SAME: line: [[@LINE+3]]
// CHECK-SAME: type: ![[TT2:[0-9]+]]
// CHECK: ![[TT2]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_TtTSS2IdVs5Int64_"
var myTuple2 : ( String, Id: Int64) = ("B", 2)
// mangling.myTuple3 : (Swift.String, Swift.Int64)
// CHECK: !DIGlobalVariable(name: "myTuple3",
// CHECK-SAME: linkageName: "_Tv8mangling8myTuple3TSSVs5Int64_",
// CHECK-SAME: line: [[@LINE+3]]
// CHECK-SAME: type: ![[TT3:[0-9]+]]
// CHECK: ![[TT3]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_TtTSSVs5Int64_"
var myTuple3 : ( String, Int64) = ("C", 3)
markUsed(myTuple1.Id)
markUsed(myTuple2.Id)
markUsed({ $0.1 }(myTuple3))
| c6aa322557637131d1edced1a0d3ffa8 | 45 | 97 | 0.621636 | false | false | false | false |
harlanhaskins/trill | refs/heads/master | Sources/Source/String+Escaping.swift | mit | 2 | ///
/// String+Escaping.swift
///
/// Copyright 2016-2017 the Trill project authors.
/// Licensed under the MIT License.
///
/// Full license text available at https://github.com/trill-lang/trill
///
import Foundation
extension StringProtocol {
public func escaped() -> String {
var s = ""
for c in self {
switch c {
case "\n": s += "\\n"
case "\t": s += "\\t"
case "\"": s += "\\\""
default: s.append(c)
}
}
return s
}
public func unescaped() -> String {
var s = ""
var nextCharIsEscaped = false
for c in self {
if c == "\\" {
nextCharIsEscaped = true
continue
}
if nextCharIsEscaped {
switch c {
case "n": s.append("\n")
case "t": s.append("\t")
case "\"": s.append("\"")
default: s.append(c)
}
} else {
s.append(c)
}
nextCharIsEscaped = false
}
return s
}
}
| 9f369d63e3167bfebdce1cede8685027 | 18.833333 | 70 | 0.50105 | false | false | false | false |
RMizin/PigeonMessenger-project | refs/heads/main | FalconMessenger/ChatsControllers/GroupAdminPanelTableViewCell.swift | gpl-3.0 | 1 | //
// GroupAdminControlsTableViewCell.swift
// Pigeon-project
//
// Created by Roman Mizin on 3/22/18.
// Copyright © 2018 Roman Mizin. All rights reserved.
//
import UIKit
class GroupAdminPanelTableViewCell: UITableViewCell {
var button: ControlButton = {
var button = ControlButton()
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
backgroundColor = ThemeManager.currentTheme().generalBackgroundColor
selectionColor = .clear
addSubview(button)
button.topAnchor.constraint(equalTo: topAnchor, constant: 5).isActive = true
button.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -5).isActive = true
if #available(iOS 11.0, *) {
button.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 10).isActive = true
button.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -10).isActive = true
} else {
button.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true
button.rightAnchor.constraint(equalTo: rightAnchor, constant: -10).isActive = true
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
}
}
| 3d61732691b4e136932e9095090db16f | 30.933333 | 108 | 0.740431 | false | false | false | false |
victorlin/ReactiveCocoa | refs/heads/master | ReactiveCocoa/Swift/Atomic.swift | mit | 1 | //
// Atomic.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-06-10.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Foundation
final class PosixThreadMutex: NSLocking {
private var mutex = pthread_mutex_t()
init() {
let result = pthread_mutex_init(&mutex, nil)
precondition(result == 0, "Failed to initialize mutex with error \(result).")
}
deinit {
let result = pthread_mutex_destroy(&mutex)
precondition(result == 0, "Failed to destroy mutex with error \(result).")
}
func lock() {
let result = pthread_mutex_lock(&mutex)
precondition(result == 0, "Failed to lock \(self) with error \(result).")
}
func unlock() {
let result = pthread_mutex_unlock(&mutex)
precondition(result == 0, "Failed to unlock \(self) with error \(result).")
}
}
/// An atomic variable.
public final class Atomic<Value>: AtomicProtocol {
private let lock: PosixThreadMutex
private var _value: Value
/// Initialize the variable with the given initial value.
///
/// - parameters:
/// - value: Initial value for `self`.
public init(_ value: Value) {
_value = value
lock = PosixThreadMutex()
}
/// Atomically modifies the variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
public func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result {
lock.lock()
defer { lock.unlock() }
return try action(&_value)
}
/// Atomically perform an arbitrary action using the current value of the
/// variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
public func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result {
lock.lock()
defer { lock.unlock() }
return try action(_value)
}
}
/// An atomic variable which uses a recursive lock.
internal final class RecursiveAtomic<Value>: AtomicProtocol {
private let lock: NSRecursiveLock
private var _value: Value
private let didSetObserver: ((Value) -> Void)?
/// Initialize the variable with the given initial value.
///
/// - parameters:
/// - value: Initial value for `self`.
/// - name: An optional name used to create the recursive lock.
/// - action: An optional closure which would be invoked every time the
/// value of `self` is mutated.
internal init(_ value: Value, name: StaticString? = nil, didSet action: ((Value) -> Void)? = nil) {
_value = value
lock = NSRecursiveLock()
lock.name = name.map(String.init(describing:))
didSetObserver = action
}
/// Atomically modifies the variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result {
lock.lock()
defer {
didSetObserver?(_value)
lock.unlock()
}
return try action(&_value)
}
/// Atomically perform an arbitrary action using the current value of the
/// variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result {
lock.lock()
defer { lock.unlock() }
return try action(_value)
}
}
public protocol AtomicProtocol: class {
associatedtype Value
@discardableResult
func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result
@discardableResult
func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result
}
extension AtomicProtocol {
/// Atomically get or set the value of the variable.
public var value: Value {
get {
return withValue { $0 }
}
set(newValue) {
swap(newValue)
}
}
/// Atomically replace the contents of the variable.
///
/// - parameters:
/// - newValue: A new value for the variable.
///
/// - returns: The old value.
@discardableResult
public func swap(_ newValue: Value) -> Value {
return modify { (value: inout Value) in
let oldValue = value
value = newValue
return oldValue
}
}
}
| 0f90b4b36a3b608070e907f51c4330ef | 24.142012 | 100 | 0.667922 | false | false | false | false |
blochberger/swift-sodium | refs/heads/master | Sodium/Auth.swift | isc | 3 | import Foundation
import Clibsodium
public struct Auth {
public let Bytes = Int(crypto_auth_bytes())
public typealias SecretKey = Key
}
extension Auth {
/**
Computes an authentication tag for a message using a key
- Parameter message: The message to authenticate.
- Parameter secretKey: The key required to create and verify messages.
- Returns: The computed authentication tag.
*/
public func tag(message: Bytes, secretKey: SecretKey) -> Bytes? {
guard secretKey.count == KeyBytes else { return nil }
var tag = Array<UInt8>(count: Bytes)
guard .SUCCESS == crypto_auth (
&tag,
message, UInt64(message.count),
secretKey
).exitCode else { return nil }
return tag
}
/**
Verifies that an authentication tag is valid for a message and a key
- Parameter message: The message to verify.
- Parameter secretKey: The key required to create and verify messages.
- Parameter tag: The authentication tag.
- Returns: `true` if the verification is successful.
*/
public func verify(message: Bytes, secretKey: SecretKey, tag: Bytes) -> Bool {
guard secretKey.count == KeyBytes else {
return false
}
return .SUCCESS == crypto_auth_verify (
tag,
message, UInt64(message.count),
secretKey
).exitCode
}
}
extension Auth: SecretKeyGenerator {
public var KeyBytes: Int { return Int(crypto_auth_keybytes()) }
public typealias Key = Bytes
public static let keygen: (_ k: UnsafeMutablePointer<UInt8>) -> Void = crypto_auth_keygen
}
| 77305953728676e07910bc8317adea61 | 28.350877 | 93 | 0.635386 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | refs/heads/master | Libraries/SnapKit/Source/View+SnapKit.swift | apache-2.0 | 3 | //
// SnapKit
//
// Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS)
import UIKit
public typealias View = UIView
#else
import AppKit
public typealias View = NSView
#endif
/**
Used to expose public API on views
*/
public extension View {
/// left edge
public var snp_left: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Left) }
/// top edge
public var snp_top: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Top) }
/// right edge
public var snp_right: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Right) }
/// bottom edge
public var snp_bottom: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Bottom) }
/// leading edge
public var snp_leading: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Leading) }
/// trailing edge
public var snp_trailing: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Trailing) }
/// width dimension
public var snp_width: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Width) }
/// height dimension
public var snp_height: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Height) }
/// centerX position
public var snp_centerX: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterX) }
/// centerY position
public var snp_centerY: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterY) }
/// baseline position
public var snp_baseline: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Baseline) }
/// first baseline position
@available(iOS 8.0, *)
public var snp_firstBaseline: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.FirstBaseline) }
/// left margin
@available(iOS 8.0, *)
public var snp_leftMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.LeftMargin) }
/// right margin
@available(iOS 8.0, *)
public var snp_rightMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.RightMargin) }
/// top margin
@available(iOS 8.0, *)
public var snp_topMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.TopMargin) }
/// bottom margin
@available(iOS 8.0, *)
public var snp_bottomMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.BottomMargin) }
/// leading margin
@available(iOS 8.0, *)
public var snp_leadingMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.LeadingMargin) }
/// trailing margin
@available(iOS 8.0, *)
public var snp_trailingMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.TrailingMargin) }
/// centerX within margins
@available(iOS 8.0, *)
public var snp_centerXWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterXWithinMargins) }
/// centerY within margins
@available(iOS 8.0, *)
public var snp_centerYWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterYWithinMargins) }
// top + left + bottom + right edges
public var snp_edges: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Edges) }
// width + height dimensions
public var snp_size: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Size) }
// centerX + centerY positions
public var snp_center: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Center) }
// top + left + bottom + right margins
@available(iOS 8.0, *)
public var snp_margins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Margins) }
// centerX + centerY within margins
@available(iOS 8.0, *)
public var snp_centerWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterWithinMargins) }
/**
Prepares constraints with a `ConstraintMaker` and returns the made constraints but does not install them.
:param: closure that will be passed the `ConstraintMaker` to make the constraints with
:returns: the constraints made
*/
public func snp_prepareConstraints(file: String = #file, line: UInt = #line, @noescape closure: (make: ConstraintMaker) -> Void) -> [Constraint] {
return ConstraintMaker.prepareConstraints(view: self, file: file, line: line, closure: closure)
}
/**
Makes constraints with a `ConstraintMaker` and installs them along side any previous made constraints.
:param: closure that will be passed the `ConstraintMaker` to make the constraints with
*/
public func snp_makeConstraints(file: String = #file, line: UInt = #line, @noescape closure: (make: ConstraintMaker) -> Void) -> Void {
ConstraintMaker.makeConstraints(view: self, file: file, line: line, closure: closure)
}
/**
Updates constraints with a `ConstraintMaker` that will replace existing constraints that match and install new ones.
For constraints to match only the constant can be updated.
:param: closure that will be passed the `ConstraintMaker` to update the constraints with
*/
public func snp_updateConstraints(file: String = #file, line: UInt = #line, @noescape closure: (make: ConstraintMaker) -> Void) -> Void {
ConstraintMaker.updateConstraints(view: self, file: file, line: line, closure: closure)
}
/**
Remakes constraints with a `ConstraintMaker` that will first remove all previously made constraints and make and install new ones.
:param: closure that will be passed the `ConstraintMaker` to remake the constraints with
*/
public func snp_remakeConstraints(file: String = #file, line: UInt = #line, @noescape closure: (make: ConstraintMaker) -> Void) -> Void {
ConstraintMaker.remakeConstraints(view: self, file: file, line: line, closure: closure)
}
/**
Removes all previously made constraints.
*/
public func snp_removeConstraints() {
ConstraintMaker.removeConstraints(view: self)
}
internal var snp_installedLayoutConstraints: [LayoutConstraint] {
get {
if let constraints = objc_getAssociatedObject(self, &installedLayoutConstraintsKey) as? [LayoutConstraint] {
return constraints
}
return []
}
set {
objc_setAssociatedObject(self, &installedLayoutConstraintsKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
private var installedLayoutConstraintsKey = ""
| 2792dce49977e41deae9f69a2975ace2 | 45.136612 | 150 | 0.712543 | false | false | false | false |
hisui/ReactiveSwift | refs/heads/master | ReactiveSwiftTests/SubjectTests.swift | mit | 1 | // Copyright (c) 2014 segfault.jp. All rights reserved.
import XCTest
import ReactiveSwift
class SubjectTests: XCTestCase {
func testGenralUse() {
let exec = FakeExecutor()
let subj = Subject(1)
var received1: Packet<Int> = .Done
let chan1 = subj.unwrap.open(exec.newContext()) { $0.subscribe { received1 = $0 }}
XCTAssertEqual(1, subj.subscribers)
XCTAssertTrue(received1.value == nil)
exec.consumeAll()
XCTAssertTrue(received1.value == 1)
var received2: Packet<Int> = .Done
let chan2 = subj.unwrap.open(exec.newContext()) { $0.subscribe { received2 = $0 }}
XCTAssertEqual(2, subj.subscribers)
XCTAssertTrue(received2.value == nil)
exec.consumeAll()
XCTAssertTrue(received2.value == 1)
subj.value = 2
XCTAssertTrue(received1.value == 1)
XCTAssertTrue(received2.value == 1)
exec.consumeAll()
XCTAssertTrue(received1.value == 2)
XCTAssertTrue(received2.value == 2)
chan1.close()
chan2.close()
XCTAssertEqual(0, subj.subscribers)
exec.consumeAll()
XCTAssertEqual(0, subj.subscribers)
}
func testDisposingSubjectCausesCloseAllSubscriptions() {
let exec = FakeExecutor()
var subj = Subject(1)
var received1: Packet<Int>? = nil
var received2: Packet<Int>? = nil
let chan1 = subj.unwrap.open(exec.newContext()) { $0.subscribe { received1 = $0 }}
let chan2 = subj.unwrap.open(exec.newContext()) { $0.subscribe { received2 = $0 }}
exec.consumeAll()
XCTAssertEqual(2, subj.subscribers)
XCTAssertTrue(received1!.value == 1)
XCTAssertTrue(received2!.value == 1)
// overwrite the old `Subject`
subj = Subject(2)
exec.consumeAll()
XCTAssertTrue(received1!.value == nil)
XCTAssertTrue(received2!.value == nil)
}
func testBiMap() {
let exec = FakeExecutor()
let a = Subject(1)
let b = a.bimap({ $0 * 2 }, { $0 / 2 }, exec.newContext())
XCTAssertEqual(1, a.value)
XCTAssertEqual(2, b.value)
a.value = 2
XCTAssertEqual(2, a.value)
XCTAssertEqual(2, b.value)
exec.consumeAll()
XCTAssertEqual(1, a.subscribers)
XCTAssertEqual(1, b.subscribers)
XCTAssertEqual(2, a.value)
XCTAssertEqual(4, b.value)
b.value = 6
XCTAssertEqual(2, a.value)
XCTAssertEqual(6, b.value)
exec.consumeAll()
XCTAssertEqual(3, a.value)
XCTAssertEqual(6, b.value)
}
}
| 1700df1736ab268fc53c07dcc3541b66 | 25.590909 | 90 | 0.539145 | false | true | false | false |
LuAndreCast/iOS_WatchProjects | refs/heads/master | watchOS3/HKworkout/Error.swift | mit | 1 | //
// Error.swift
// HealthWatchExample
//
// Created by Luis Castillo on 8/5/16.
// Copyright © 2016 LC. All rights reserved.
//
import Foundation
struct Errors {
//MARK: - HealthStore
struct healthStore
{
static let domain:String = "healthkit.healthStore"
struct unknown
{
static let code = 100
static let description = [NSLocalizedDescriptionKey : "unknown"]
func toString()->String
{
return "unknown"
}
}
struct avaliableData
{
static let code = 101
static let description = [NSLocalizedDescriptionKey : "Health Store Data is Not avaliable"]
}
struct permission
{
static let code = 102
static let description = [NSLocalizedDescriptionKey : "Health Store permission not granted"]
func toString()->String
{
return "permission"
}
}
}//eo
struct heartRate
{
static let domain:String = "healthkit.heartRate"
struct unknown
{
static let code = 200
static let description = [NSLocalizedDescriptionKey : "unknown"]
func toString()->String
{
return "unknown"
}
}
struct quantity
{
static let code = 201
static let description = [NSLocalizedDescriptionKey : "un-able to create Heart rate quantity type"]
}
}//eo
struct workOut
{
static let domain:String = "healthkit.workout"
struct unknown
{
static let code = 300
static let description = [NSLocalizedDescriptionKey : "unknown"]
func toString()->String
{
return "unknown"
}
}
struct start
{
static let code = 301
static let description = [NSLocalizedDescriptionKey : "un-able to start workout"]
}
struct end
{
static let code = 302
static let description = [NSLocalizedDescriptionKey : "un-able to end workout"]
}
}//eo
//MARK: - Monitoring
struct monitoring
{
static let domain:String = ""
struct unknown
{
static let code = 400
static let description = [NSLocalizedDescriptionKey : "unknown"]
func toString()->String
{
return "unknown"
}
}
struct type
{
static let code = 401
static let description = [ NSLocalizedDescriptionKey: "un-able to init type"]
}
struct query
{
static let code = 402
static let description = [ NSLocalizedDescriptionKey: "un-able to query sample"]
}
}
//MARK: - WCSESSION
struct wcSession
{
static let domain:String = "watchconnectivity.wcession"
struct unknown
{
static let code = 500
static let description = [NSLocalizedDescriptionKey : "unknown"]
func toString()->String
{
return "unknown"
}
}
struct supported
{
static let code = 501
static let description = [NSLocalizedDescriptionKey : "wcsession is not supported"]
}
struct reachable
{
static let code = 502
static let description = [NSLocalizedDescriptionKey : "wcsession is not reachable"]
}
}//eo
}
| 0d45fd2b593a1ede0d52350c463e3df8 | 25.971631 | 112 | 0.500131 | false | false | false | false |
niekang/WeiBo | refs/heads/master | WeiBo/Class/Utils/Manger/WBUserAccont.swift | apache-2.0 | 1 | //
// WBUserAccont.swift
// WeiBo
//
// Created by 聂康 on 2017/6/21.
// Copyright © 2017年 com.nk. All rights reserved.
//
import Foundation
import HandyJSON
class WBUserAccont: BaseModel {
static let shared = WBUserAccont()
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!.appending("/user")
var access_token:String?
var expires_in:Int = 0
var remind_in:String?
/// 用户昵称
var screen_name: String?
/// 用户头像地址
var profile_image_url: String?
var uid:String?
required init() {
super.init()
//从本地加载用户信息
guard let json = NSData(contentsOfFile: path),
let dict = try? JSONSerialization.jsonObject(with: json as Data, options: []) as? [String:AnyObject] else {
return
}
reset(dict, shouldUpdate: true)
}
//跳转登录界面
func login(modelVC:UIViewController? = (UIApplication.shared.delegate as! AppDelegate).window?.rootViewController) {
guard let modelVC = modelVC else{
return
}
let oauthVC = WBOAuthViewController()
let nav = WBNavigationController(rootViewController: oauthVC)
modelVC.present(nav, animated: true, completion: nil)
}
func reset(_ dict: [String: Any], shouldUpdate: Bool = false) {
self.access_token = nil
self.uid = nil
self.remind_in = nil
self.screen_name = nil
self.profile_image_url = nil
self.expires_in = 0
if(shouldUpdate) {
update(dict)
}
}
func update(_ dict: [String: Any]) {
if let access_token = dict["access_token"] as? String {
self.access_token = access_token
}
if let uid = dict["uid"] as? String {
self.uid = uid
}
if let remind_in = dict["remind_in"] as? String {
self.remind_in = remind_in
}
if let screen_name = dict["screen_name"] as? String {
self.screen_name = screen_name
}
if let profile_image_url = dict["profile_image_url"] as? String {
self.profile_image_url = profile_image_url
}
if let expires_in = dict["expires_in"] as? Int {
self.expires_in = expires_in
}
}
}
// MARK: - OAuth授权
extension WBUserAccont {
/// 请求用户授权信息
///
/// - Parameters:
/// - code: 授权码
/// - completion: 返回授权是否成功
func requestToken(code:String, completion:@escaping ((Bool) -> Void)) {
let params = [
"client_id": WBAPPkey,
"client_secret": WBAppSecret,
"grant_type": "authorization_code",
"code": code,
"redirect_uri": WBRedirectURL
]
HttpClient.shared.post(urlString: WBAPI_Auth, params: params, success: { (userAccount: WBUserAccont) in
guard let dict = userAccount.toJSON() else {
return
}
self.reset(dict, shouldUpdate: true)
//请求用户信息
self.requestUserInfo(completion: { (isSuccess, json) in
guard let dict = json as? [String:Any] else {
return
}
//给当前模型赋值
self.update(dict)
//将用户信息保存在本地
self.saveAccout()
completion(isSuccess)
})
}) { (_, _) in
completion(false)
}
}
/// 请求用户信息
///
/// - Parameter completion: 完成回调
func requestUserInfo(completion:@escaping ((Bool, Any?) -> Void)) {
let params = ["uid":uid ?? ""]
HttpClient.shared.get(urlString: WBAPI_UserInfo, params: params, success: { (user: WBUser) in
completion(true, user.toJSON())
}) { (error, _) in
completion(false, error)
}
}
/// 保存用户信息
///
/// - Parameter json: 用户信息的json数据
func saveAccout() {
let json = (self.toJSON()) ?? [:]
guard let jsonData = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
return
}
(jsonData as NSData).write(toFile: path, atomically: true)
}
}
| 6b9a02eaa8f87b67fad97284103e687f | 26.477707 | 120 | 0.534075 | false | false | false | false |
exyte/Macaw-Examples | refs/heads/master | DesignAwardedApps/Zova/Zova/Nodes/ActivityCircle.swift | mit | 1 | import Foundation
import Macaw
class ActivityCircle: Group {
let mainCircle: Shape
let score: Text
let icon: Text
let shadows: Group
let emojis: EmojisCircle
init() {
mainCircle = Shape(
form: Circle(r: 60),
fill: mainColor,
stroke: Stroke(fill: Color.white, width: 1.0)
)
score = Text(
text: "3",
font: Font(name: lightFont, size: 40),
fill: Color.white,
align: .mid,
baseline: .mid
)
icon = Text(
text: "⚡",
font: Font(name: regularFont, size: 24),
fill: Color.white,
align: .mid,
place: Transform.move(dx: 0.0, dy: 30.0)
)
shadows = [
Point(x: 0, y: 35),
Point(x: -25, y: 25),
Point(x: 25, y: 25),
Point(x: 25, y: -25),
Point(x: -25, y: -25),
Point(x: -40, y: 0),
Point(x: 40, y: 0),
Point(x: 0, y: -35)
].map { place in
return Shape(
form: Circle(r: 40),
fill: Color.white.with(a: 0.8),
place: Transform.move(dx: place.x, dy: place.y)
)
}.group()
emojis = EmojisCircle()
super.init(contents: [shadows, mainCircle, score, icon, emojis])
}
func customize(during: Double) -> Animation {
let lightAnimation = [
emojis.open(during: during),
shadows.placeVar.animation(to: Transform.scale(sx: 0.5, sy: 0.5), during: during),
mainCircle.opacityVar.animation(to: 1.0, during: during),
score.placeVar.animation(to: Transform.move(dx: 0, dy: -20), during: during),
score.opacityVar.animation(to: 0.0, during: during),
icon.placeVar.animation(to: Transform.move(dx: 0, dy: -30).scale(sx: 2.0, sy: 2.0), during: during),
].combine()
return lightAnimation
}
}
| 31c75bf5502e1bef5b6b603a6bfcd4ea | 29.294118 | 112 | 0.481068 | false | false | false | false |
pabloroca/NewsApp | refs/heads/master | NewsApp/Application/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// NewsApp
//
// Created by Pablo Roca Rozas on 28/03/2017.
// Copyright © 2017 PR2Studio. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
print("Docs folder: "+NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!)
DataManager().setUpLocalStorage()
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
splitViewController.delegate = self
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:.
}
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
| 5d6742923409980f4c840e3e2c978926 | 54.375 | 285 | 0.748025 | false | false | false | false |
adrfer/swift | refs/heads/master | test/1_stdlib/DictionaryLiteral.swift | apache-2.0 | 4 | //===--- DictionaryLiteral.swift ------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import SwiftExperimental
import Foundation
import StdlibUnittest
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif
// Check that the generic parameters are called 'Key' and 'Value'.
protocol TestProtocol1 {}
extension DictionaryLiteral where Key : TestProtocol1, Value : TestProtocol1 {
var _keyAndValueAreTestProtocol1: Bool {
fatalError("not implemented")
}
}
var strings: DictionaryLiteral = ["a": "1", "b": "Foo"]
expectType(DictionaryLiteral<String, String>.self, &strings)
var stringNSStringLiteral: DictionaryLiteral = [
"a": "1", "b": "Foo" as NSString]
expectType(DictionaryLiteral<String, NSString>.self, &stringNSStringLiteral)
let aString = "1"
let anNSString = "Foo" as NSString
var stringNSStringLet: DictionaryLiteral = [ "a": aString, "b": anNSString]
expectType(DictionaryLiteral<String, NSString>.self, &stringNSStringLet)
var hetero1: DictionaryLiteral = ["a": 1, "b": "Foo" as NSString]
expectType(DictionaryLiteral<String, NSObject>.self, &hetero1)
var hetero2: DictionaryLiteral = ["a": 1, "b": "Foo"]
expectType(DictionaryLiteral<String, NSObject>.self, &hetero2)
| f7d2674aaf616655c8ad4c7f11bc0bc4 | 34.5 | 80 | 0.702139 | false | true | false | false |
anhnc55/fantastic-swift-library | refs/heads/master | Example/Pods/Material/Sources/iOS/Material+UIImage+Resize.swift | mit | 2 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Material nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public extension UIImage {
/**
:name: internalResize
*/
private func internalResize(toWidth tw: CGFloat = 0, toHeight th: CGFloat = 0) -> UIImage? {
var w: CGFloat?
var h: CGFloat?
if 0 < tw {
h = height * tw / width
} else if 0 < th {
w = width * th / height
}
let g: UIImage?
let t: CGRect = CGRectMake(0, 0, nil == w ? tw : w!, nil == h ? th : h!)
UIGraphicsBeginImageContextWithOptions(t.size, false, MaterialDevice.scale)
drawInRect(t, blendMode: .Normal, alpha: 1)
g = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return g
}
/**
:name: resize
*/
public func resize(toWidth w: CGFloat) -> UIImage? {
return internalResize(toWidth: w)
}
/**
:name: resize
*/
public func resize(toHeight h: CGFloat) -> UIImage? {
return internalResize(toHeight: h)
}
}
| 9d9b3fc5df96ffe51fa1d859254fd45d | 33.885714 | 93 | 0.733415 | false | false | false | false |
karimsallam/Reactive | refs/heads/master | Reactive/Reactive/ReactiveViewController.swift | apache-2.0 | 1 | //
// ReactiveViewController.swift
// RealTimeMenu
//
// Created by Karim Sallam on 18/11/2016.
// Copyright © 2016 Karim Sallam. All rights reserved.
//
import UIKit
import ReactiveSwift
open class ReactiveViewController: UIViewController {
public let reactiveState = MutableProperty<ReactiveState>(.loading)
public let viewState = MutableProperty<ViewState>(.Invisible)
public var reactiveIdentifier = UUID().uuidString
open override func viewDidLoad() {
super.viewDidLoad()
bind()
reactiveState.value = .ready
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewState.value = .WillBecomeVisible
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
viewState.value = .Visible
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
viewState.value = .WillBecomeInvisible
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
viewState.value = .Invisible
}
open func bind() {
// Do nothing.
}
deinit {
debugPrint("\(NSStringFromClass(type(of: self))) deallocated")
}
}
extension ReactiveViewController: ReactiveUserInterface {
open func prepareForReuse() {
// Do nothing.
}
}
| bf47bc3a3ed1f9973b52654905fcc076 | 23.533333 | 71 | 0.650136 | false | false | false | false |
sunflash/SwiftHTTPClient | refs/heads/master | HTTPClient/Classes/Extension/UIImageView+Extension.swift | mit | 1 | //
// UIImageView+Extension.swift
// HTTPClient
//
// Created by Min Wu on 07/05/2017.
// Copyright © 2017 Min WU. All rights reserved.
//
import Foundation
import UIKit
/// Extension to `UIImageView`
extension UIImageView {
/// Convenience function to display image from web url
///
/// - Parameters:
/// - url: url for image
/// - placeholder: placeholder image, optional
public func displayImage(from url: URL, withPlaceholder placeholder: UIImage? = nil) {
self.image = placeholder
URLSession.shared.dataTask(with: url) { (data, _, _) in
guard let imageData = data, let image = UIImage(data: imageData) else {return}
GCD.main.queue.async {self.image = image}
}.resume()
}
}
| a6061fc975910feb0472b2f642435dfd | 27.333333 | 90 | 0.635294 | false | false | false | false |
thomas-bennett/emotion-tracker | refs/heads/master | Emotion Tracker/EmotionsDataStore.swift | apache-2.0 | 1 | //
// EmotionsDataStore.swift
// Emotion Tracker
//
// Created by Thomas Bennett on 7/7/14.
// Copyright (c) 2014 Thomas Bennett. All rights reserved.
//
import Foundation
class EmotionsDataStore {
var emotionRecords: Dictionary<Emotion, EmotionRecord[]>
let dataPath: NSString
var wasDataModified = false
init() {
let (dataPath, isPreviousFile) = EmotionsDataStore.createDataPath()
self.dataPath = dataPath
if (isPreviousFile) {
emotionRecords = EmotionsDataStore.readRecordsFromDataPath(dataPath)
} else {
emotionRecords = Dictionary<Emotion, EmotionRecord[]>()
}
}
func saveToDisk() {
if (!wasDataModified) {
return
}
var data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
archiver.encodeObject(emotionRecords)
archiver.finishEncoding()
data.writeToFile(dataPath, atomically: true)
}
class func readRecordsFromDataPath(dataPath: NSString) -> Dictionary<Emotion, EmotionRecord[]> {
let codedData = NSData(contentsOfFile: dataPath)
let unarchiver = NSKeyedUnarchiver(forReadingWithData: codedData)
let results = unarchiver.decodeObject() as Dictionary<Emotion, EmotionRecord[]>
unarchiver.finishDecoding()
return results
}
class func createDataPath() -> (String, Bool) {
let pathPrefix = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let path = pathPrefix + "/data"
var error: NSError?
let fileManager = NSFileManager.defaultManager()
let doesFileExist = fileManager.fileExistsAtPath(pathPrefix)
if (!doesFileExist) {
fileManager.createDirectoryAtPath(pathPrefix, withIntermediateDirectories: true, attributes: nil, error: &error)
}
if let error = error {
println("Encountered error creating \(path). Error: \(error)")
}
return (path, doesFileExist)
}
func addRecord(emotion: Emotion) {
// TODO: Need to pass in tags
var tags = String[]()
let emotionRecord = EmotionRecord(timestamp: NSDate.date(), emotion: emotion, tags: tags)
if var record = emotionRecords[emotion] {
record.append(emotionRecord)
} else {
let records = [emotionRecord]
emotionRecords[emotion] = records
}
wasDataModified = true
}
}
| 956076cf1d87048a70ae37005c438a03 | 32.205128 | 124 | 0.630116 | false | false | false | false |
yonaskolb/XcodeGen | refs/heads/master | Sources/ProjectSpec/SpecLoader.swift | mit | 1 | import Foundation
import JSONUtilities
import PathKit
import XcodeProj
import Yams
import Version
public class SpecLoader {
var project: Project!
public private(set) var projectDictionary: [String: Any]?
let version: Version
public init(version: Version) {
self.version = version
}
public func loadProject(path: Path, projectRoot: Path? = nil, variables: [String: String] = [:]) throws -> Project {
let spec = try SpecFile(path: path, variables: variables)
let resolvedDictionary = spec.resolvedDictionary()
let project = try Project(basePath: projectRoot ?? spec.basePath, jsonDictionary: resolvedDictionary)
self.project = project
projectDictionary = resolvedDictionary
return project
}
public func validateProjectDictionaryWarnings() throws {
try projectDictionary?.validateWarnings()
}
public func generateCacheFile() throws -> CacheFile? {
guard let projectDictionary = projectDictionary,
let project = project else {
return nil
}
return try CacheFile(
version: version,
projectDictionary: projectDictionary,
project: project
)
}
}
private extension Dictionary where Key == String, Value: Any {
func validateWarnings() throws {
let errors: [SpecValidationError.ValidationError] = []
if !errors.isEmpty {
throw SpecValidationError(errors: errors)
}
}
func hasValueContaining(_ needle: String) -> Bool {
values.contains { value in
switch value {
case let dictionary as JSONDictionary:
return dictionary.hasValueContaining(needle)
case let string as String:
return string.contains(needle)
case let array as [JSONDictionary]:
return array.contains { $0.hasValueContaining(needle) }
case let array as [String]:
return array.contains { $0.contains(needle) }
default:
return false
}
}
}
}
| 3d9d8a929cef2bb987c7bd5c61e7b0e1 | 28.597222 | 120 | 0.622243 | false | false | false | false |
fhchina/firefox-ios | refs/heads/master | Sync/StorageClient.swift | mpl-2.0 | 3 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Alamofire
import Shared
import Account
import XCGLogger
private let log = Logger.syncLogger
// Not an error that indicates a server problem, but merely an
// error that encloses a StorageResponse.
public class StorageResponseError<T>: ErrorType {
public let response: StorageResponse<T>
public init(_ response: StorageResponse<T>) {
self.response = response
}
public var description: String {
return "Error."
}
}
public class RequestError: ErrorType {
public let error: NSError?
public init(_ err: NSError?) {
self.error = err
}
public var description: String {
let str = self.error?.localizedDescription ?? "No description"
return "Request error: \(str)."
}
}
public class BadRequestError<T>: StorageResponseError<T> {
public let request: NSURLRequest
public init(request: NSURLRequest, response: StorageResponse<T>) {
self.request = request
super.init(response)
}
override public var description: String {
return "Bad request."
}
}
public class ServerError<T>: StorageResponseError<T> {
override public var description: String {
return "Server error."
}
override public init(_ response: StorageResponse<T>) {
super.init(response)
}
}
public class NotFound<T>: StorageResponseError<T> {
override public var description: String {
return "Not found. (\(T.self))"
}
override public init(_ response: StorageResponse<T>) {
super.init(response)
}
}
public class RecordParseError: ErrorType {
public var description: String {
return "Failed to parse record."
}
}
public class MalformedMetaGlobalError: ErrorType {
public var description: String {
return "Supplied meta/global for upload did not serialize to valid JSON."
}
}
/**
* Raised when the storage client is refusing to make a request due to a known
* server backoff.
* If you want to bypass this, remove the backoff from the BackoffStorage that
* the storage client is using.
*/
public class ServerInBackoffError: ErrorType {
private let until: Timestamp
public var description: String {
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.ShortStyle
formatter.timeStyle = NSDateFormatterStyle.MediumStyle
let s = formatter.stringFromDate(NSDate.fromTimestamp(self.until))
return "Server in backoff until \(s)."
}
public init(until: Timestamp) {
self.until = until
}
}
// Returns milliseconds. Handles decimals.
private func optionalSecondsHeader(input: AnyObject?) -> Timestamp? {
if input == nil {
return nil
}
if let val = input as? String {
if let timestamp = decimalSecondsStringToTimestamp(val) {
return timestamp
}
}
if let seconds: Double = input as? Double {
// Oh for a BigDecimal library.
return Timestamp(seconds * 1000)
}
if let seconds: NSNumber = input as? NSNumber {
// Who knows.
return seconds.unsignedLongLongValue * 1000
}
return nil
}
private func optionalIntegerHeader(input: AnyObject?) -> Int64? {
if input == nil {
return nil
}
if let val = input as? String {
return NSScanner(string: val).scanLongLong()
}
if let val: Double = input as? Double {
// Oh for a BigDecimal library.
return Int64(val)
}
if let val: NSNumber = input as? NSNumber {
// Who knows.
return val.longLongValue
}
return nil
}
private func optionalUIntegerHeader(input: AnyObject?) -> Timestamp? {
if input == nil {
return nil
}
if let val = input as? String {
return NSScanner(string: val).scanUnsignedLongLong()
}
if let val: Double = input as? Double {
// Oh for a BigDecimal library.
return Timestamp(val)
}
if let val: NSNumber = input as? NSNumber {
// Who knows.
return val.unsignedLongLongValue
}
return nil
}
public struct ResponseMetadata {
public let alert: String?
public let nextOffset: String?
public let records: UInt64?
public let quotaRemaining: Int64?
public let timestampMilliseconds: Timestamp // Non-optional. Server timestamp when handling request.
public let lastModifiedMilliseconds: Timestamp? // Included for all success responses. Collection or record timestamp.
public let backoffMilliseconds: UInt64?
public let retryAfterMilliseconds: UInt64?
public init(response: NSHTTPURLResponse) {
self.init(headers: response.allHeaderFields)
}
public init(headers: [NSObject : AnyObject]) {
alert = headers["X-Weave-Alert"] as? String
nextOffset = headers["X-Weave-Next-Offset"] as? String
records = optionalUIntegerHeader(headers["X-Weave-Records"])
quotaRemaining = optionalIntegerHeader(headers["X-Weave-Quota-Remaining"])
timestampMilliseconds = optionalSecondsHeader(headers["X-Weave-Timestamp"]) ?? 0
lastModifiedMilliseconds = optionalSecondsHeader(headers["X-Last-Modified"])
backoffMilliseconds = optionalSecondsHeader(headers["X-Weave-Backoff"]) ??
optionalSecondsHeader(headers["X-Backoff"])
retryAfterMilliseconds = optionalSecondsHeader(headers["Retry-After"])
}
}
public struct StorageResponse<T> {
public let value: T
public let metadata: ResponseMetadata
init(value: T, metadata: ResponseMetadata) {
self.value = value
self.metadata = metadata
}
init(value: T, response: NSHTTPURLResponse) {
self.value = value
self.metadata = ResponseMetadata(response: response)
}
}
public struct POSTResult {
public let modified: Timestamp
public let success: [GUID]
public let failed: [GUID: [String]]
public static func fromJSON(json: JSON) -> POSTResult? {
if json.isError {
return nil
}
if let mDecimalSeconds = json["modified"].asDouble,
let s = json["success"].asArray,
let f = json["failed"].asDictionary {
var failed = false
let asStringOrFail: JSON -> String = { $0.asString ?? { failed = true; return "" }() }
let asArrOrFail: JSON -> [String] = { $0.asArray?.map(asStringOrFail) ?? { failed = true; return [] }() }
// That's the basic structure. Now let's transform the contents.
let successGUIDs = s.map(asStringOrFail)
if failed {
return nil
}
let failedGUIDs = mapValues(f, asArrOrFail)
if failed {
return nil
}
let msec = Timestamp(1000 * mDecimalSeconds)
return POSTResult(modified: msec, success: successGUIDs, failed: failedGUIDs)
}
return nil
}
}
public typealias Authorizer = (NSMutableURLRequest) -> NSMutableURLRequest
public typealias ResponseHandler = (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void
// TODO: don't be so naïve. Use a combination of uptime and wall clock time.
public protocol BackoffStorage {
var serverBackoffUntilLocalTimestamp: Timestamp? { get set }
func clearServerBackoff()
func isInBackoff(now: Timestamp) -> Timestamp? // Returns 'until' for convenience.
}
// Don't forget to batch downloads.
public class Sync15StorageClient {
private let authorizer: Authorizer
private let serverURI: NSURL
var backoff: BackoffStorage
let workQueue: dispatch_queue_t
let resultQueue: dispatch_queue_t
public init(token: TokenServerToken, workQueue: dispatch_queue_t, resultQueue: dispatch_queue_t, backoff: BackoffStorage) {
self.workQueue = workQueue
self.resultQueue = resultQueue
self.backoff = backoff
// This is a potentially dangerous assumption, but failable initializers up the stack are a giant pain.
self.serverURI = NSURL(string: token.api_endpoint)!
self.authorizer = {
(r: NSMutableURLRequest) -> NSMutableURLRequest in
let helper = HawkHelper(id: token.id, key: token.key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)
r.setValue(helper.getAuthorizationValueFor(r), forHTTPHeaderField: "Authorization")
return r
}
}
public init(serverURI: NSURL, authorizer: Authorizer, workQueue: dispatch_queue_t, resultQueue: dispatch_queue_t, backoff: BackoffStorage) {
self.serverURI = serverURI
self.authorizer = authorizer
self.workQueue = workQueue
self.resultQueue = resultQueue
self.backoff = backoff
}
func updateBackoffFromResponse<T>(response: StorageResponse<T>) {
// N.B., we would not have made this request if a backoff were set, so
// we can safely avoid doing the write if there's no backoff in the
// response.
// This logic will have to change if we ever invalidate that assumption.
if let ms = response.metadata.backoffMilliseconds ?? response.metadata.retryAfterMilliseconds {
log.info("Backing off for \(ms)ms.")
self.backoff.serverBackoffUntilLocalTimestamp = ms + NSDate.now()
}
}
func errorWrap<T>(deferred: Deferred<Result<T>>, handler: ResponseHandler) -> ResponseHandler {
return { (request, response, data, error) in
log.verbose("Response is \(response).")
/**
* Returns true if handled.
*/
func failFromResponse(response: NSHTTPURLResponse?) -> Bool {
// TODO: Swift 2.0 guards.
if response == nil {
// TODO: better error.
log.error("No response")
let result = Result<T>(failure: RecordParseError())
deferred.fill(result)
return true
}
let response = response!
log.debug("Status code: \(response.statusCode).")
let storageResponse = StorageResponse(value: response, metadata: ResponseMetadata(response: response))
self.updateBackoffFromResponse(storageResponse)
if response.statusCode >= 500 {
log.debug("ServerError.")
let result = Result<T>(failure: ServerError(storageResponse))
deferred.fill(result)
return true
}
if response.statusCode == 404 {
log.debug("NotFound<\(T.self)>.")
let result = Result<T>(failure: NotFound(storageResponse))
deferred.fill(result)
return true
}
if response.statusCode >= 400 {
log.debug("BadRequestError.")
let result = Result<T>(failure: BadRequestError(request: request, response: storageResponse))
deferred.fill(result)
return true
}
return false
}
// Check for an error from the request processor.
if let error = error {
log.error("Response: \(response?.statusCode ?? 0). Got error \(error).")
// If we got one, we don't want to hit the response nil case above and
// return a RecordParseError, because a RequestError is more fitting.
if let response = response {
if failFromResponse(response) {
log.error("This was a failure response. Filled specific error type.")
return
}
}
log.error("Filling generic RequestError.")
deferred.fill(Result<T>(failure: RequestError(error)))
return
}
if failFromResponse(response) {
return
}
handler(request, response!, data, error)
}
}
lazy private var alamofire: Alamofire.Manager = {
let ua = UserAgent.syncUserAgent
let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
return Alamofire.Manager.managerWithUserAgent(ua, configuration: configuration)
}()
func requestGET(url: NSURL) -> Request {
let req = NSMutableURLRequest(URL: url)
req.HTTPMethod = Method.GET.rawValue
req.setValue("application/json", forHTTPHeaderField: "Accept")
let authorized: NSMutableURLRequest = self.authorizer(req)
return alamofire.request(authorized)
.validate(contentType: ["application/json"])
}
func requestDELETE(url: NSURL) -> Request {
let req = NSMutableURLRequest(URL: url)
req.HTTPMethod = Method.DELETE.rawValue
req.setValue("1", forHTTPHeaderField: "X-Confirm-Delete")
let authorized: NSMutableURLRequest = self.authorizer(req)
return alamofire.request(authorized)
}
func requestWrite(url: NSURL, method: String, body: String, contentType: String, ifUnmodifiedSince: Timestamp?) -> Request {
let req = NSMutableURLRequest(URL: url)
req.HTTPMethod = method
req.setValue(contentType, forHTTPHeaderField: "Content-Type")
let authorized: NSMutableURLRequest = self.authorizer(req)
if let ifUnmodifiedSince = ifUnmodifiedSince {
req.setValue(millisecondsToDecimalSeconds(ifUnmodifiedSince), forHTTPHeaderField: "X-If-Unmodified-Since")
}
req.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)!
return alamofire.request(authorized)
}
func requestPUT(url: NSURL, body: JSON, ifUnmodifiedSince: Timestamp?) -> Request {
return self.requestWrite(url, method: Method.PUT.rawValue, body: body.toString(pretty: false), contentType: "application/json;charset=utf-8", ifUnmodifiedSince: ifUnmodifiedSince)
}
func requestPOST(url: NSURL, body: JSON, ifUnmodifiedSince: Timestamp?) -> Request {
return self.requestWrite(url, method: Method.POST.rawValue, body: body.toString(pretty: false), contentType: "application/json;charset=utf-8", ifUnmodifiedSince: ifUnmodifiedSince)
}
func requestPOST(url: NSURL, body: [JSON], ifUnmodifiedSince: Timestamp?) -> Request {
let body = "\n".join(body.map { $0.toString(pretty: false) })
return self.requestWrite(url, method: Method.POST.rawValue, body: body, contentType: "application/newlines", ifUnmodifiedSince: ifUnmodifiedSince)
}
/**
* Returns true and fills the provided Deferred if our state shows that we're in backoff.
* Returns false otherwise.
*/
private func checkBackoff<T>(deferred: Deferred<Result<T>>) -> Bool {
if let until = self.backoff.isInBackoff(NSDate.now()) {
deferred.fill(Result<T>(failure: ServerInBackoffError(until: until)))
return true
}
return false
}
private func doOp<T>(op: (NSURL) -> Request, path: String, f: (JSON) -> T?) -> Deferred<Result<StorageResponse<T>>> {
let deferred = Deferred<Result<StorageResponse<T>>>(defaultQueue: self.resultQueue)
if self.checkBackoff(deferred) {
return deferred
}
let req = op(self.serverURI.URLByAppendingPathComponent(path))
let handler = self.errorWrap(deferred) { (_, response, data, error) in
if let json: JSON = data as? JSON {
if let v = f(json) {
let storageResponse = StorageResponse<T>(value: v, response: response!)
deferred.fill(Result(success: storageResponse))
} else {
deferred.fill(Result(failure: RecordParseError()))
}
return
}
deferred.fill(Result(failure: RecordParseError()))
}
req.responseParsedJSON(true, completionHandler: handler)
return deferred
}
// Sync storage responds with a plain timestamp to a PUT, not with a JSON body.
private func putResource<T>(path: String, body: JSON, ifUnmodifiedSince: Timestamp?, parser: (String) -> T?) -> Deferred<Result<StorageResponse<T>>> {
let url = self.serverURI.URLByAppendingPathComponent(path)
return self.putResource(url, body: body, ifUnmodifiedSince: ifUnmodifiedSince, parser: parser)
}
private func putResource<T>(URL: NSURL, body: JSON, ifUnmodifiedSince: Timestamp?, parser: (String) -> T?) -> Deferred<Result<StorageResponse<T>>> {
let deferred = Deferred<Result<StorageResponse<T>>>(defaultQueue: self.resultQueue)
if self.checkBackoff(deferred) {
return deferred
}
let req = self.requestPUT(URL, body: body, ifUnmodifiedSince: ifUnmodifiedSince)
let handler = self.errorWrap(deferred) { (_, response, data, error) in
if let data = data as? String {
if let v = parser(data) {
let storageResponse = StorageResponse<T>(value: v, response: response!)
deferred.fill(Result(success: storageResponse))
} else {
deferred.fill(Result(failure: RecordParseError()))
}
return
}
deferred.fill(Result(failure: RecordParseError()))
}
// Yay Swift.
let stringHandler = { (a, b, c: String?, d) in
return handler(a, b, c, d)
}
req.responseString(encoding: nil, completionHandler: stringHandler)
return deferred
}
private func getResource<T>(path: String, f: (JSON) -> T?) -> Deferred<Result<StorageResponse<T>>> {
return doOp(self.requestGET, path: path, f: f)
}
private func deleteResource<T>(path: String, f: (JSON) -> T?) -> Deferred<Result<StorageResponse<T>>> {
return doOp(self.requestDELETE, path: path, f: f)
}
func getInfoCollections() -> Deferred<Result<StorageResponse<InfoCollections>>> {
return getResource("info/collections", f: InfoCollections.fromJSON)
}
func getMetaGlobal() -> Deferred<Result<StorageResponse<GlobalEnvelope>>> {
return getResource("storage/meta/global", f: { GlobalEnvelope($0) })
}
func uploadMetaGlobal(metaGlobal: MetaGlobal, ifUnmodifiedSince: Timestamp?) -> Deferred<Result<StorageResponse<Timestamp>>> {
let payload = metaGlobal.toPayload()
if payload.isError {
return Deferred(value: Result(failure: MalformedMetaGlobalError()))
}
// TODO finish this!
let record: JSON = JSON(["payload": payload, "id": "global"])
return putResource("storage/meta/global", body: record, ifUnmodifiedSince: ifUnmodifiedSince, parser: decimalSecondsStringToTimestamp)
}
func wipeStorage() -> Deferred<Result<StorageResponse<JSON>>> {
// In Sync 1.5 it's preferred that we delete the root, not /storage.
return deleteResource("", f: { $0 })
}
// TODO: it would be convenient to have the storage client manage Keys,
// but of course we need to use a different set of keys to fetch crypto/keys
// itself.
func clientForCollection<T: CleartextPayloadJSON>(collection: String, encrypter: RecordEncrypter<T>) -> Sync15CollectionClient<T> {
let storage = self.serverURI.URLByAppendingPathComponent("storage", isDirectory: true)
return Sync15CollectionClient(client: self, serverURI: storage, collection: collection, encrypter: encrypter)
}
}
/**
* We'd love to nest this in the overall storage client, but Swift
* forbids the nesting of a generic class inside another class.
*/
public class Sync15CollectionClient<T: CleartextPayloadJSON> {
private let client: Sync15StorageClient
private let encrypter: RecordEncrypter<T>
private let collectionURI: NSURL
private let collectionQueue = dispatch_queue_create("com.mozilla.sync.collectionclient", DISPATCH_QUEUE_SERIAL)
init(client: Sync15StorageClient, serverURI: NSURL, collection: String, encrypter: RecordEncrypter<T>) {
self.client = client
self.encrypter = encrypter
self.collectionURI = serverURI.URLByAppendingPathComponent(collection, isDirectory: false)
}
private func uriForRecord(guid: String) -> NSURL {
return self.collectionURI.URLByAppendingPathComponent(guid)
}
public func post(records: [Record<T>], ifUnmodifiedSince: Timestamp?) -> Deferred<Result<StorageResponse<POSTResult>>> {
let deferred = Deferred<Result<StorageResponse<POSTResult>>>(defaultQueue: client.resultQueue)
if self.client.checkBackoff(deferred) {
return deferred
}
// TODO: charset
// TODO: if any of these fail, we should do _something_. Right now we just ignore them.
let json = optFilter(records.map(self.encrypter.serializer))
let req = client.requestPOST(self.collectionURI, body: json, ifUnmodifiedSince: nil)
req.responseParsedJSON(queue: collectionQueue, partial: true, completionHandler: self.client.errorWrap(deferred) { (_, response, data, error) in
if let json: JSON = data as? JSON,
let result = POSTResult.fromJSON(json) {
let storageResponse = StorageResponse(value: result, response: response!)
deferred.fill(Result(success: storageResponse))
return
} else {
log.warning("Couldn't parse JSON response.")
}
deferred.fill(Result(failure: RecordParseError()))
})
return deferred
}
public func put(record: Record<T>, ifUnmodifiedSince: Timestamp?) -> Deferred<Result<StorageResponse<Timestamp>>> {
if let body = self.encrypter.serializer(record) {
log.debug("Body is \(body)")
log.debug("Original record is \(record)")
return self.client.putResource(uriForRecord(record.id), body: body, ifUnmodifiedSince: ifUnmodifiedSince, parser: decimalSecondsStringToTimestamp)
}
return deferResult(RecordParseError())
}
public func get(guid: String) -> Deferred<Result<StorageResponse<Record<T>>>> {
let deferred = Deferred<Result<StorageResponse<Record<T>>>>(defaultQueue: client.resultQueue)
if self.client.checkBackoff(deferred) {
return deferred
}
let req = client.requestGET(uriForRecord(guid))
req.responseParsedJSON(queue:collectionQueue, partial: true, completionHandler: self.client.errorWrap(deferred) { (_, response, data, error) in
if let json: JSON = data as? JSON {
let envelope = EnvelopeJSON(json)
let record = Record<T>.fromEnvelope(envelope, payloadFactory: self.encrypter.factory)
if let record = record {
let storageResponse = StorageResponse(value: record, response: response!)
deferred.fill(Result(success: storageResponse))
return
}
} else {
log.warning("Couldn't parse JSON response.")
}
deferred.fill(Result(failure: RecordParseError()))
})
return deferred
}
/**
* Unlike every other Sync client, we use the application/json format for fetching
* multiple requests. The others use application/newlines. We don't want to write
* another Serializer, and we're loading everything into memory anyway.
*/
public func getSince(since: Timestamp) -> Deferred<Result<StorageResponse<[Record<T>]>>> {
let deferred = Deferred<Result<StorageResponse<[Record<T>]>>>(defaultQueue: client.resultQueue)
if self.client.checkBackoff(deferred) {
return deferred
}
let req = client.requestGET(self.collectionURI.withQueryParams([
NSURLQueryItem(name: "full", value: "1"),
NSURLQueryItem(name: "newer", value: millisecondsToDecimalSeconds(since))]))
req.responseParsedJSON(queue: collectionQueue, partial: true, completionHandler: self.client.errorWrap(deferred) { (_, response, data, error) in
if let json: JSON = data as? JSON {
func recordify(json: JSON) -> Record<T>? {
let envelope = EnvelopeJSON(json)
return Record<T>.fromEnvelope(envelope, payloadFactory: self.encrypter.factory)
}
if let arr = json.asArray {
let response = StorageResponse(value: optFilter(arr.map(recordify)), response: response!)
deferred.fill(Result(success: response))
return
}
}
deferred.fill(Result(failure: RecordParseError()))
})
return deferred
}
}
| 6fbbe32f2f67840784fd078856c55943 | 36.799401 | 188 | 0.633386 | false | false | false | false |
200895045/XLForm | refs/heads/master | Examples/Swift/Examples/Dates/DatesFormViewController.swift | mit | 33 | //
// DatesFormViewController.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
class DatesFormViewController: XLFormViewController {
private enum Tags : String {
case DateInline = "dateInline"
case TimeInline = "timeInline"
case DateTimeInline = "dateTimeInline"
case CountDownTimerInline = "countDownTimerInline"
case DatePicker = "datePicker"
case Date = "date"
case Time = "time"
case DateTime = "dateTime"
case CountDownTimer = "countDownTimer"
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.initializeForm()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initializeForm()
}
override func viewDidLoad() {
super.viewDidLoad()
let barButton = UIBarButtonItem(title: "Disable", style: UIBarButtonItemStyle.Plain, target: self, action: "disableEnable:")
barButton.possibleTitles = Set(["Disable", "Enable"])
self.navigationItem.rightBarButtonItem = barButton
}
func disableEnable(button : UIBarButtonItem)
{
self.form.disabled = !self.form.disabled
button.title = self.form.disabled ? "Enable" : "Disable"
self.tableView.endEditing(true)
self.tableView.reloadData()
}
func initializeForm() {
let form : XLFormDescriptor
var section : XLFormSectionDescriptor
var row : XLFormRowDescriptor
form = XLFormDescriptor(title: "Date & Time")
section = XLFormSectionDescriptor.formSectionWithTitle("Inline Dates")
form.addFormSection(section)
// Date
row = XLFormRowDescriptor(tag: Tags.DateInline.rawValue, rowType: XLFormRowDescriptorTypeDateInline, title:"Date")
row.value = NSDate()
section.addFormRow(row)
// Time
row = XLFormRowDescriptor(tag: Tags.TimeInline.rawValue, rowType: XLFormRowDescriptorTypeTimeInline, title: "Time")
row.value = NSDate()
section.addFormRow(row)
// DateTime
row = XLFormRowDescriptor(tag: Tags.DateTimeInline.rawValue, rowType: XLFormRowDescriptorTypeDateTimeInline, title: "Date Time")
row.value = NSDate()
section.addFormRow(row)
// CountDownTimer
row = XLFormRowDescriptor(tag: Tags.CountDownTimerInline.rawValue, rowType:XLFormRowDescriptorTypeCountDownTimerInline, title:"Countdown Timer")
row.value = NSDate()
section.addFormRow(row)
section = XLFormSectionDescriptor.formSectionWithTitle("Dates") //
form.addFormSection(section)
// Date
row = XLFormRowDescriptor(tag: Tags.Date.rawValue, rowType:XLFormRowDescriptorTypeDate, title:"Date")
row.value = NSDate()
row.cellConfigAtConfigure["minimumDate"] = NSDate()
row.cellConfigAtConfigure["maximumDate"] = NSDate(timeIntervalSinceNow: 60*60*24*3)
section.addFormRow(row)
// Time
row = XLFormRowDescriptor(tag: Tags.Time.rawValue, rowType: XLFormRowDescriptorTypeTime, title: "Time")
row.cellConfigAtConfigure["minuteInterval"] = 10
row.value = NSDate()
section.addFormRow(row)
// DateTime
row = XLFormRowDescriptor(tag: Tags.DateTime.rawValue, rowType: XLFormRowDescriptorTypeDateTime, title: "Date Time")
row.value = NSDate()
section.addFormRow(row)
// CountDownTimer
row = XLFormRowDescriptor(tag: Tags.CountDownTimer.rawValue, rowType: XLFormRowDescriptorTypeCountDownTimer, title: "Countdown Timer")
row.value = NSDate()
section.addFormRow(row)
section = XLFormSectionDescriptor.formSectionWithTitle("Disabled Dates")
section.footerTitle = "DatesFormViewController.swift"
form.addFormSection(section)
// Date
row = XLFormRowDescriptor(tag: nil, rowType: XLFormRowDescriptorTypeDate, title: "Date")
row.disabled = NSNumber(bool: true)
row.required = true
row.value = NSDate()
section.addFormRow(row)
section = XLFormSectionDescriptor.formSectionWithTitle("DatePicker")
form.addFormSection(section)
// DatePicker
row = XLFormRowDescriptor(tag: Tags.DatePicker.rawValue, rowType:XLFormRowDescriptorTypeDatePicker)
row.cellConfigAtConfigure["datePicker.datePickerMode"] = UIDatePickerMode.Date.rawValue
row.value = NSDate()
section.addFormRow(row)
self.form = form
}
// MARK: - XLFormDescriptorDelegate
override func formRowDescriptorValueHasChanged(formRow: XLFormRowDescriptor!, oldValue: AnyObject!, newValue: AnyObject!) {
super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
if formRow.tag == Tags.DatePicker.rawValue {
let alertView = UIAlertView(title: "DatePicker", message: "Value Has changed!", delegate: self, cancelButtonTitle: "OK")
alertView.show()
}
}
}
| a4fcd57119b7b50450bf55bd19103e86 | 38.404908 | 152 | 0.67305 | false | false | false | false |
BMWB/RRArt-Swift-Test | refs/heads/master | Example/Pods/NVActivityIndicatorView/NVActivityIndicatorView/NVActivityIndicatorShape.swift | apache-2.0 | 11 | //
// NVActivityIndicatorShape.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/22/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
enum NVActivityIndicatorShape {
case Circle
case CircleSemi
case Ring
case RingTwoHalfVertical
case RingTwoHalfHorizontal
case RingThirdFour
case Rectangle
case Triangle
case Line
case Pacman
func createLayerWith(size size: CGSize, color: UIColor) -> CALayer {
let layer: CAShapeLayer = CAShapeLayer()
var path: UIBezierPath = UIBezierPath()
let lineWidth: CGFloat = 2
switch self {
case .Circle:
path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2),
radius: size.width / 2,
startAngle: 0,
endAngle: CGFloat(2 * M_PI),
clockwise: false);
layer.fillColor = color.CGColor
case .CircleSemi:
path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2),
radius: size.width / 2,
startAngle: CGFloat(-M_PI / 6),
endAngle: CGFloat(-5 * M_PI / 6),
clockwise: false)
path.closePath()
layer.fillColor = color.CGColor
case .Ring:
path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2),
radius: size.width / 2,
startAngle: 0,
endAngle: CGFloat(2 * M_PI),
clockwise: false);
layer.fillColor = nil
layer.strokeColor = color.CGColor
layer.lineWidth = lineWidth
case .RingTwoHalfVertical:
path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2),
radius:size.width / 2,
startAngle:CGFloat(-3 * M_PI_4),
endAngle:CGFloat(-M_PI_4),
clockwise:true)
path.moveToPoint(
CGPoint(x: size.width / 2 - size.width / 2 * CGFloat(cos(M_PI_4)),
y: size.height / 2 + size.height / 2 * CGFloat(sin(M_PI_4)))
)
path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2),
radius:size.width / 2,
startAngle:CGFloat(-5 * M_PI_4),
endAngle:CGFloat(-7 * M_PI_4),
clockwise:false)
layer.fillColor = nil
layer.strokeColor = color.CGColor
layer.lineWidth = lineWidth
case .RingTwoHalfHorizontal:
path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2),
radius:size.width / 2,
startAngle:CGFloat(3 * M_PI_4),
endAngle:CGFloat(5 * M_PI_4),
clockwise:true)
path.moveToPoint(
CGPoint(x: size.width / 2 + size.width / 2 * CGFloat(cos(M_PI_4)),
y: size.height / 2 - size.height / 2 * CGFloat(sin(M_PI_4)))
)
path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2),
radius:size.width / 2,
startAngle:CGFloat(-M_PI_4),
endAngle:CGFloat(M_PI_4),
clockwise:true)
layer.fillColor = nil
layer.strokeColor = color.CGColor
layer.lineWidth = lineWidth
case .RingThirdFour:
path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2),
radius: size.width / 2,
startAngle: CGFloat(-3 * M_PI_4),
endAngle: CGFloat(-M_PI_4),
clockwise: false)
layer.fillColor = nil
layer.strokeColor = color.CGColor
layer.lineWidth = 2
case .Rectangle:
path.moveToPoint(CGPoint(x: 0, y: 0))
path.addLineToPoint(CGPoint(x: size.width, y: 0))
path.addLineToPoint(CGPoint(x: size.width, y: size.height))
path.addLineToPoint(CGPoint(x: 0, y: size.height))
layer.fillColor = color.CGColor
case .Triangle:
let offsetY = size.height / 4
path.moveToPoint(CGPoint(x: 0, y: size.height - offsetY))
path.addLineToPoint(CGPoint(x: size.width / 2, y: size.height / 2 - offsetY))
path.addLineToPoint(CGPoint(x: size.width, y: size.height - offsetY))
path.closePath()
layer.fillColor = color.CGColor
case .Line:
path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: size.width, height: size.height),
cornerRadius: size.width / 2)
layer.fillColor = color.CGColor
case .Pacman:
path.addArcWithCenter(CGPoint(x: size.width / 2, y: size.height / 2),
radius: size.width / 4,
startAngle: 0,
endAngle: CGFloat(2 * M_PI),
clockwise: true);
layer.fillColor = nil
layer.strokeColor = color.CGColor
layer.lineWidth = size.width / 2
}
layer.backgroundColor = nil
layer.path = path.CGPath
return layer
}
} | 8edca21d28f6585d82d30fefd247778e | 38.515152 | 104 | 0.532502 | false | false | false | false |
Dywane3Peter/YP | refs/heads/master | YP/Extension/UIDevice+Extend.swift | mit | 1 | //
// UIDevice+Extend.swift
// WXYourSister
//
// Created by 魏翔 on 16/7/28.
// Copyright © 2016年 魏翔. All rights reserved.
//
import UIKit
/** 是否是iPhone 4系列 */
func iPhone4x_320_480() -> Bool{
return isDevice(width: 320, height: 480)
}
/** 是否是iPhone 5系列 */
func iPhone5x_320_568() -> Bool{
return isDevice(width: 320, height: 568)
}
/** 是否是iPhone 6 */
func iPhone6_375_667() -> Bool{
return isDevice(width: 375, height: 667)
}
/** 是否是iPhone 6 Plus */
func iPhone6Plus_414_736_Portait() -> Bool{
return isDevice(width: 414, height: 736)
}
/** 通用方法 */
func isDevice(width: CGFloat, height: CGFloat) -> Bool{
return Screen.width == width && Screen.height == height
}
/** 是否是iOS 7 */
func iOS7() -> Bool{
return (UIDevice.versionName >= 7.0) && (UIDevice.versionName < 8.0)
}
/** 是否是iOS 8 */
func iOS8() -> Bool{
return (UIDevice.versionName >= 8.0) && (UIDevice.versionName < 9.0)
}
/** 是否是iOS 9 */
func iOS9() -> Bool{
return (UIDevice.versionName >= 9.0) && (UIDevice.versionName < 10.0)
}
extension UIDevice{
static var versionName: Float {return (UIDevice.current.systemVersion as NSString).floatValue}
}
| f223be9c87d8380c1d7e3c041958b331 | 20.830189 | 98 | 0.643907 | false | false | false | false |
wireapp/wire-ios-data-model | refs/heads/develop | Tests/Source/Model/Observer/StringKeyPathTests.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2016 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
class StringKeyPathTests: ZMBaseManagedObjectTest {
func testThatItCreatesASimpleKeyPath() {
let sut = StringKeyPath.keyPathForString("name")
XCTAssertEqual(sut.rawValue, "name")
XCTAssertEqual(sut.count, 1)
XCTAssertFalse(sut.isPath)
}
func testThatItCreatesKeyPathThatIsAPath() {
let sut = StringKeyPath.keyPathForString("foo.name")
XCTAssertEqual(sut.rawValue, "foo.name")
XCTAssertEqual(sut.count, 2)
XCTAssertTrue(sut.isPath)
}
func testThatItDecomposesSimpleKeys() {
let sut = StringKeyPath.keyPathForString("name")
if let (a, b) = sut.decompose {
XCTAssertEqual(a, StringKeyPath.keyPathForString("name"))
XCTAssertEqual(b, nil)
} else {
XCTFail("Did not decompose")
}
}
func testThatItDecomposesKeyPaths() {
let sut = StringKeyPath.keyPathForString("foo.name")
if let (a, b) = sut.decompose {
XCTAssertEqual(a, StringKeyPath.keyPathForString("foo"))
XCTAssertEqual(b, StringKeyPath.keyPathForString("name"))
} else {
XCTFail("Did not decompose")
}
}
}
| 0900306c2960deae31e0fa9ae745da93 | 33.232143 | 71 | 0.669797 | false | true | false | false |
soso1617/iCalendar | refs/heads/master | Calendar/DataModel/ModelManager/WeekManager.swift | mit | 1 | //
// WeekManager.swift
// Calendar
//
// Created by Zhang, Eric X. on 5/1/17.
// Copyright © 2017 ShangHe. All rights reserved.
//
import Foundation
/*********************************************************************
*
* class WeekManager -- Singleton
* This class is responsible for controlling the core data model: Week
*
*********************************************************************/
class WeekManager {
// MARK: Singleton init
//
// singleton instance
//
static let sharedManager = WeekManager()
//
// prevent be init from others
//
private init() {
}
/**
Create Week by Week data dict, will check core data if this object already exsit
- Parameter dict: Week data, must contain primary key value
- Returns: Week obj
*/
func createWeekBy(dict: [String : Any]) -> Week? {
var retWeek: Week? = nil
//
// make sure the primary key exists
//
if let primaryValue = dict[WeekProperties.primaryKey] as? Int32
{
//
// try to fetch the week obj if exist
//
if let week = self.fetchWeekByKeyValue(primaryValue)
{
retWeek = week
//
// set properties value if it's contained in dict
//
if let value = dict[WeekProperties.value] as? Int16
{
retWeek?.valueInYear = value
}
}
else
{
retWeek = CalendarModelManager.sharedManager.createObj(entityName: EntityName.week) as? Week
//
// set properties value if it's contained in dict
//
retWeek?.id = Int32(primaryValue)
if let value = dict[WeekProperties.value] as? Int16
{
retWeek?.valueInYear = value
}
}
}
return retWeek
}
/**
Fetch Week by Week id
- Parameter value: Week id
- Returns: Specified Week obj
*/
func fetchWeekByKeyValue(_ value: Int32) -> Week? {
var retWeek: Week? = nil
let predicate = NSPredicate.init(format: "%K = %ld", WeekProperties.primaryKey, value)
if let fetchedResult = CalendarModelManager.sharedManager.fetchObj(entityName: EntityName.week, predicate: predicate) as? Array<Week>, fetchedResult.count > 0
{
retWeek = fetchedResult.last
}
return retWeek
}
/**
Fetch this week obj
- Returns: This Week obj
*/
func thisWeek() -> Week? {
let calendar = Calendar.init(identifier: .gregorian)
let dateComponents = calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date())
return self.fetchWeekByKeyValue(weekId(year: dateComponents.yearForWeekOfYear!, weekInYear: dateComponents.weekOfYear!))
}
}
| eacfb898261846562235d9bdd547be9f | 25.073171 | 166 | 0.492049 | false | false | false | false |
konoma/matisse | refs/heads/master | Sources/MatisseErrors.swift | mit | 1 | //
// MatisseErrors.swift
// Matisse
//
// Created by Markus Gasser on 29.11.15.
// Copyright © 2015 konoma GmbH. All rights reserved.
//
import Foundation
/// Matisse error codes
///
public enum MatisseErrorCode: Int {
/// An unknown error happened.
case unknown = 0
/// An error downloading the image happened.
case downloadError = 1
/// An error creating or resizing the image happened.
case creationError = 2
}
public extension NSError {
// MARK: - Constants
/// The `NSError` error domain for Matisse errors.
///
public static var MatisseErrorDomain: String { return "MatisseErrorDomain" }
// MARK: - Error Information
/// Tests wether this error is a Matisse error or not.
///
/// Determined by checking the domain for `MatisseErrorDomain`.
///
public var isMatisseError: Bool {
return domain == NSError.MatisseErrorDomain
}
/// The matisse error code for this error.
///
/// If the receiver is not a matisse error, returns `MatisseErrorCode.Unknown`.
///
public var matisseErrorCode: MatisseErrorCode {
return isMatisseError ? (MatisseErrorCode(rawValue: code) ?? .unknown) : .unknown
}
// MARK: - Creating Matisse Errors
/// Create a new matisse error with code `MatisseErrorCode.Unknown`.
///
/// - Parameters:
/// - message: The message for this error. Optional.
///
/// - Returns:
/// A new `NSError` instance with the Matisse error domain and the unknown error code.
///
public class func matisseUnknownError(_ message: String? = nil) -> NSError {
return matisseErrorWithCode(.unknown, message: message)
}
/// Create a new matisse error with code `MatisseErrorCode.DownloadError`.
///
/// - Parameters:
/// - message: The message for this error. Optional.
///
/// - Returns:
/// A new `NSError` instance with the Matisse error domain and the download error code.
///
public class func matisseDownloadError(_ message: String? = nil) -> NSError {
return matisseErrorWithCode(.downloadError, message: message)
}
/// Create a new matisse error with code `MatisseErrorCode.CreationError`.
///
/// - Parameters:
/// - message: The message for this error. Optional.
///
/// - Returns:
/// A new `NSError` instance with the Matisse error domain and the creation error code.
///
public class func matisseCreationError(_ message: String? = nil) -> NSError {
return matisseErrorWithCode(.creationError, message: message)
}
/// Create a new matisse error with the given code.
///
/// - Parameters:
/// - code: The matisse error code.
/// - message: The message for this error. Optional.
///
/// - Returns:
/// A new `NSError` instance with the Matisse error domain and the specified error code.
///
public class func matisseErrorWithCode(_ code: MatisseErrorCode, message: String? = nil) -> NSError {
let userInfo: [String: AnyObject]
if let message = message {
userInfo = [ NSLocalizedDescriptionKey: message as AnyObject ]
} else {
userInfo = [:]
}
return NSError(domain: MatisseErrorDomain, code: code.rawValue, userInfo: userInfo)
}
}
| 1239d4e7efaa09b92dd8103245cdc324 | 28.646018 | 105 | 0.634925 | false | false | false | false |
hadibadjian/GAlileo | refs/heads/master | storyboards/Storyboards/Source/InitialViewController.swift | mit | 1 | // Copyright © 2016 HB. All rights reserved.
class InitialViewController: UIViewController {
@IBOutlet weak var purchaseCountLabel: UILabel!
let winningNumber = 5
let wonLotterySegueIdentifier = "wonLotterySegue"
var numberOfPurchases = 0
override func viewDidLoad() {
super.viewDidLoad()
title = "Storyboards"
}
@IBAction func purchaseTicketButtonPressed(sender: AnyObject) {
numberOfPurchases += 1
purchaseCountLabel.text = "You have purchased \(numberOfPurchases) items"
if numberOfPurchases == 5 {
self.performSegueWithIdentifier(wonLotterySegueIdentifier, sender: nil)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == wonLotterySegueIdentifier {
if let winnerVC = segue.destinationViewController as? WinnerViewController {
winnerVC.congratsText = "Congratulations Hadi!"
}
}
}
}
import UIKit
| 575b5e62cb09ac8a794ef81430cb829d | 25.885714 | 82 | 0.730074 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.