repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
luckymore0520/leetcode
SubstringWithConcatenationOfAllWords.playground/Contents.swift
1
2312
//: Playground - noun: a place where people can play import UIKit //You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters. // //For example, given: //s: "barfoothefoobarman" //words: ["foo", "bar"] // //You should return the indices: [0,9]. //(order does not matter). extension String { func intIndex(_ index:Index?) -> Int? { guard let index = index else { return nil } return distance(from: startIndex, to: index) } } class Solution { func findSubstring(_ s: String, _ words: [String]) -> [Int] { var ans:[Int] = [] let length = s.characters.count let wordCount = words.count if (length < 1 && wordCount < 1) { return ans } let wordLength = words[0].characters.count if (length < wordCount * wordLength) { return ans } var map:[String:Int] = [:] for word in words { if let count = map[word] { map[word] = count + 1 } else { map[word] = 1 } } for i in 0...length - wordLength * wordCount { var from = i var copyedMap = map let startIndex = s.index(s.startIndex, offsetBy: from) let endIndex = s.index(s.startIndex, offsetBy: from + wordLength) var str = s[startIndex..<endIndex] var count = 0 while copyedMap[str] != nil && copyedMap[str]! > 0 { let strCount = copyedMap[str]! copyedMap[str] = strCount - 1 count += 1 from += wordLength if (from + wordLength > length) { break } let startIndex = s.index(s.startIndex, offsetBy: from) let endIndex = s.index(s.startIndex, offsetBy: from + wordLength) str = s[startIndex..<endIndex] } if (count == wordCount) { ans.append(i) } } return ans } } let solution = Solution() solution.findSubstring("a", ["a","a"])
mit
f041b3eebc85b9cea8a7c6df36fd2ab3
29.421053
235
0.519464
4.321495
false
false
false
false
groschovskiy/firebase-for-banking-app
Barclays/Barclays/BMTransactionInfo.swift
1
1789
// // BMTransactionInfo.swift // Barclays // // Created by Dmitriy Groschovskiy on 22/03/2017. // Copyright © 2017 Accenture, PLC. All rights reserved. // import UIKit import Firebase class BMTransactionInfo: UIViewController { var paymentIdent : String! @IBOutlet weak var backgroundViewLayout: UIView! @IBOutlet weak var paidReferenceLabel: UILabel! @IBOutlet weak var paidToAccountLabel: UILabel! @IBOutlet weak var paidFromAccountLabel: UILabel! @IBOutlet weak var paymentAmountLabel: UILabel! @IBOutlet weak var paymentDateLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.backgroundViewLayout.layer.cornerRadius = 10 self.backgroundViewLayout.layer.masksToBounds = true let userRef = FIRAuth.auth()?.currentUser?.uid let purchaseRef = FIRDatabase.database().reference(withPath: "History/\(userRef!)/\(paymentIdent!)") purchaseRef.queryOrdered(byChild: "purchaseValue").observe(.value, with: { snapshot in let dataSnapshot = snapshot.value as! [String: AnyObject] self.paidReferenceLabel.text = "Reference #\(dataSnapshot["purchaseReference"] as! Int)" self.paidFromAccountLabel.text = dataSnapshot["purchaseCard"] as? String self.paidToAccountLabel.text = dataSnapshot["purchaseStore"] as? String self.paymentAmountLabel.text = String(format: "%.2f", dataSnapshot["purchaseAmount"] as! Double) self.paymentDateLabel.text = dataSnapshot["purchaseDate"] as? String }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func closeController(sender: UIBarButtonItem) { self.dismiss(animated: true, completion: nil) } }
apache-2.0
a06daa049f893155786109c829351d54
36.25
108
0.700783
4.632124
false
false
false
false
sisomollov/ReSwiftDataSource
Example/ReSwiftDataSource/Collection/CollectSection.swift
1
527
import Foundation import ReSwiftDataSource struct CollectSection: ItemSection { var items: [Item] = [] var headerTitle: String? var footerTitle: String? var headerItem: Item? var footerItem: Item? init(title: String? = nil, headerItem: CollectHeaderItem) { headerTitle = title self.headerItem = headerItem } } extension CollectSection: Equatable { static func ==(lhs: CollectSection, rhs: CollectSection) -> Bool { return lhs.headerTitle == rhs.headerTitle } }
mit
9393903014a9854680d31b06ae7b37db
20.958333
70
0.673624
4.428571
false
false
false
false
mathiasquintero/RandomStuff
Swift/PrimePalindrome.swift
1
782
import Foundation extension String { var isPalindrome: Bool { if characters.count < 2 { return true } if characters.first != characters.last { return false } let range = index(after: startIndex)..<index(before: endIndex) return substring(with: range).isPalindrome } } extension Int { var isPrime: Bool { let bound = Int(sqrt(Double(self))) + 1 return (2...bound) .filter { self % $0 == 0 } .isEmpty } var isPalindrome: Bool { return description.isPalindrome } } // Task: Find the biggest number that's a prime and a palindrome under 1000 let last = (2...1000) .filter { $0.isPalindrome && $0.isPrime } .last print(last)
mit
fe4bfb8ff1c61a0638e0fd8921f7cb65
19.051282
75
0.567775
4.181818
false
false
false
false
researchpanelasia/sop-ios-sdk
SurveyonPartners/models/SurveyListTableViewCell.swift
1
1476
// // SurveyListTableViewCell.swift // SurveyonPartners // // Copyright © 2017年 d8aspring. All rights reserved. // import UIKit class SurveyListTableViewCell: UITableViewCell { @IBOutlet weak var surveyNo: UILabel! @IBOutlet weak var titleName: UILabel! @IBOutlet weak var loi: UILabel! @IBOutlet weak var pointLabel: UILabel! @IBOutlet weak var pointImage: UIImageView! @IBOutlet weak var frameView: UIView! override func awakeFromNib() { super.awakeFromNib() self.surveyNo.textColor = UIColor(red: 200/255, green: 199/255, blue: 204/255, alpha: 1.0) self.titleName.textColor = UIColor(red: 66/255, green: 66/255, blue: 66/255, alpha: 1.0) self.pointLabel.textColor = UIColor(red: 57/255, green: 152/255, blue: 71/255, alpha: 1.0) self.pointImage.image = SurveyonPartners.getImage(name: "icon-point.png") self.loi.textColor = UIColor(red: 130/255, green: 130/255, blue: 130/255, alpha: 1.0) self.frameView.layer.cornerRadius = 2.0 self.frameView.layer.shadowOffset = CGSize(width: 0, height: 1) self.frameView.layer.shadowRadius = 2.0 self.frameView.layer.shadowOpacity = 0.5 } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func setCell(surveyListItem: SurveyListItem) { self.surveyNo!.text = surveyListItem.surveyIdLabel self.titleName!.text = surveyListItem.title self.loi!.text = surveyListItem.loi } }
mit
4c9a7a057e6e715fa16e520816e84766
34.071429
94
0.715547
3.583942
false
false
false
false
yanagiba/swift-ast
Tests/LexerTests/LexerIdentifierTests.swift
2
3199
/* Copyright 2015-2018 Ryuichi Intellectual Property and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest @testable import Lexer @testable import Source class LexerIdentifierTests: XCTestCase { let identifiers = ["foo", "_bar", "_1", "R2D2", "😃", "abc_"] func testIdentifiers() { identifiers.forEach { i in lexAndTest(i) { t in XCTAssertEqual(t, .identifier(i, false)) } } } func testBacktickIdentifiers() { let backtickIdentifiers = identifiers + ["public", "true", "class"] backtickIdentifiers.forEach { i in let backtickIdentifier = "`\(i)`" lexAndTest(backtickIdentifier) { t in XCTAssertEqual(t, .identifier(i, true)) } } } func testBacktickIdentifierMissingClosingBacktick() { lexAndTest("`class") { t in XCTAssertEqual(t, .invalid(.closingBacktickExpected)) } } func testImplicitParameterName() { let decimalDigits = [0, 1, 12, 123] decimalDigits.forEach { d in let implicitParameterName = "$\(d)" lexAndTest(implicitParameterName) { t in XCTAssertEqual(t, .implicitParameterName(d)) } } } func testBindingReferences() { identifiers.forEach { i in lexAndTest("$\(i)") { t in XCTAssertEqual(t, .bindingReference(i)) } } } func testDollarSignCanBeUsedAsIdentifierBody() { lexAndTest("foo$") { t in XCTAssertEqual(t, .identifier("foo$", false)) } lexAndTest("foo_$_bar") { t in XCTAssertEqual(t, .identifier("foo_$_bar", false)) } } func testStructName() { lexAndTest("foo") { t in guard case .name(let name)? = t.structName, name == "foo" else { XCTFail("Failed in lexing `foo`."); return } } lexAndTest("Type") { t in guard case .name(let name)? = t.structName, name == "Type" else { XCTFail("Failed in lexing `Type`."); return } } lexAndTest("Protocol") { t in guard case .name(let name)? = t.structName, name == "Protocol" else { XCTFail("Failed in lexing `Protocol`."); return } } lexAndTest("class") { t in XCTAssertNil(t.structName) } } static var allTests = [ ("testIdentifiers", testIdentifiers), ("testBacktickIdentifiers", testBacktickIdentifiers), ("testBacktickIdentifierMissingClosingBacktick", testBacktickIdentifierMissingClosingBacktick), ("testImplicitParameterName", testImplicitParameterName), ("testBindingReferences", testBindingReferences), ("testDollarSignCanBeUsedAsIdentifierBody", testDollarSignCanBeUsedAsIdentifierBody), ("testStructName", testStructName), ] }
apache-2.0
8f7007171151a4552065d1829f904b88
29.150943
99
0.663329
4.396149
false
true
false
false
xocialize/Kiosk
kiosk/Reachability.swift
3
13386
/* Copyright (c) 2014, Ashley Mills All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 SystemConfiguration import Foundation public let ReachabilityChangedNotification = "ReachabilityChangedNotification" public class Reachability: NSObject, Printable { public typealias NetworkReachable = (Reachability) -> () public typealias NetworkUneachable = (Reachability) -> () public enum NetworkStatus: Printable { case NotReachable, ReachableViaWiFi, ReachableViaWWAN public var description: String { switch self { case .ReachableViaWWAN: return "Cellular" case .ReachableViaWiFi: return "WiFi" case .NotReachable: return "No Connection" } } } // MARK: - *** Public properties *** public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUneachable? public var reachableOnWWAN: Bool public var currentReachabilityStatus: NetworkStatus { if isReachable() { if isReachableViaWiFi() { return .ReachableViaWiFi } if isRunningOnDevice { return .ReachableViaWWAN } } return .NotReachable } public var currentReachabilityString: String { return "\(currentReachabilityStatus)" } // MARK: - *** Initialisation methods *** public convenience init(hostname: String) { let ref = SCNetworkReachabilityCreateWithName(nil, (hostname as NSString).UTF8String).takeRetainedValue() self.init(reachabilityRef: ref) } public class func reachabilityForInternetConnection() -> Reachability { var zeroAddress = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let ref = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0)).takeRetainedValue() } return Reachability(reachabilityRef: ref) } public class func reachabilityForLocalWiFi() -> Reachability { var localWifiAddress: sockaddr_in = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) localWifiAddress.sin_len = UInt8(sizeofValue(localWifiAddress)) localWifiAddress.sin_family = sa_family_t(AF_INET) // IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0 let address: Int64 = 0xA9FE0000 localWifiAddress.sin_addr.s_addr = in_addr_t(address.bigEndian) let ref = withUnsafePointer(&localWifiAddress) { SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0)).takeRetainedValue() } return Reachability(reachabilityRef: ref) } // MARK: - *** Notifier methods *** public func startNotifier() -> Bool { reachabilityObject = self let reachability = self.reachabilityRef! previousReachabilityFlags = reachabilityFlags if let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timer_queue) { dispatch_source_set_timer(timer, dispatch_walltime(nil, 0), 500 * NSEC_PER_MSEC, 100 * NSEC_PER_MSEC) dispatch_source_set_event_handler(timer, { [unowned self] in self.timerFired() }) dispatch_timer = timer dispatch_resume(timer) return true } else { return false } } public func stopNotifier() { reachabilityObject = nil if let timer = dispatch_timer { dispatch_source_cancel(timer) dispatch_timer = nil } } // MARK: - *** Connection test methods *** public func isReachable() -> Bool { return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in return self.isReachableWithFlags(flags) }) } public func isReachableViaWWAN() -> Bool { if isRunningOnDevice { return isReachableWithTest() { flags -> Bool in // Check we're REACHABLE if self.isReachable(flags) { // Now, check we're on WWAN if self.isOnWWAN(flags) { return true } } return false } } return false } public func isReachableViaWiFi() -> Bool { return isReachableWithTest() { flags -> Bool in // Check we're reachable if self.isReachable(flags) { if self.isRunningOnDevice { // Check we're NOT on WWAN if self.isOnWWAN(flags) { return false } } return true } return false } } // MARK: - *** Private methods *** private var isRunningOnDevice: Bool = { #if (arch(i386) || arch(x86_64)) && os(iOS) return false #else return true #endif }() private var reachabilityRef: SCNetworkReachability? private var reachabilityObject: AnyObject? private var dispatch_timer: dispatch_source_t? private lazy var timer_queue: dispatch_queue_t = { return dispatch_queue_create("uk.co.joylordsystems.reachability_timer_queue", nil) }() private var previousReachabilityFlags: SCNetworkReachabilityFlags? private init(reachabilityRef: SCNetworkReachability) { reachableOnWWAN = true self.reachabilityRef = reachabilityRef } func timerFired() { let currentReachabilityFlags = reachabilityFlags if let _previousReachabilityFlags = previousReachabilityFlags { if currentReachabilityFlags != previousReachabilityFlags { dispatch_async(dispatch_get_main_queue(), { [unowned self] in self.reachabilityChanged(currentReachabilityFlags) self.previousReachabilityFlags = currentReachabilityFlags }) } } } private func reachabilityChanged(flags: SCNetworkReachabilityFlags) { if isReachableWithFlags(flags) { if let block = whenReachable { block(self) } } else { if let block = whenUnreachable { block(self) } } NSNotificationCenter.defaultCenter().postNotificationName(ReachabilityChangedNotification, object:self) } private func isReachableWithFlags(flags: SCNetworkReachabilityFlags) -> Bool { let reachable = isReachable(flags) if !reachable { return false } if isConnectionRequiredOrTransient(flags) { return false } if isRunningOnDevice { if isOnWWAN(flags) && !reachableOnWWAN { // We don't want to connect when on 3G. return false } } return true } private func isReachableWithTest(test: (SCNetworkReachabilityFlags) -> (Bool)) -> Bool { var flags: SCNetworkReachabilityFlags = 0 let gotFlags = SCNetworkReachabilityGetFlags(reachabilityRef, &flags) != 0 if gotFlags { return test(flags) } return false } // WWAN may be available, but not active until a connection has been established. // WiFi may require a connection for VPN on Demand. private func isConnectionRequired() -> Bool { return connectionRequired() } private func connectionRequired() -> Bool { return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in return self.isConnectionRequired(flags) }) } // Dynamic, on demand connection? private func isConnectionOnDemand() -> Bool { return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in return self.isConnectionRequired(flags) && self.isConnectionOnTrafficOrDemand(flags) }) } // Is user intervention required? private func isInterventionRequired() -> Bool { return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in return self.isConnectionRequired(flags) && self.isInterventionRequired(flags) }) } private func isOnWWAN(flags: SCNetworkReachabilityFlags) -> Bool { #if os(iOS) return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsWWAN) != 0 #else return false #endif } private func isReachable(flags: SCNetworkReachabilityFlags) -> Bool { return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable) != 0 } private func isConnectionRequired(flags: SCNetworkReachabilityFlags) -> Bool { return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionRequired) != 0 } private func isInterventionRequired(flags: SCNetworkReachabilityFlags) -> Bool { return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsInterventionRequired) != 0 } private func isConnectionOnTraffic(flags: SCNetworkReachabilityFlags) -> Bool { return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0 } private func isConnectionOnDemand(flags: SCNetworkReachabilityFlags) -> Bool { return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 } func isConnectionOnTrafficOrDemand(flags: SCNetworkReachabilityFlags) -> Bool { return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnTraffic | kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 } private func isTransientConnection(flags: SCNetworkReachabilityFlags) -> Bool { return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsTransientConnection) != 0 } private func isLocalAddress(flags: SCNetworkReachabilityFlags) -> Bool { return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsLocalAddress) != 0 } private func isDirect(flags: SCNetworkReachabilityFlags) -> Bool { return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsDirect) != 0 } private func isConnectionRequiredOrTransient(flags: SCNetworkReachabilityFlags) -> Bool { let testcase = SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionRequired | kSCNetworkReachabilityFlagsTransientConnection) return flags & testcase == testcase } private var reachabilityFlags: SCNetworkReachabilityFlags { var flags: SCNetworkReachabilityFlags = 0 let gotFlags = SCNetworkReachabilityGetFlags(reachabilityRef, &flags) != 0 if gotFlags { return flags } return 0 } override public var description: String { var W: String if isRunningOnDevice { W = isOnWWAN(reachabilityFlags) ? "W" : "-" } else { W = "X" } let R = isReachable(reachabilityFlags) ? "R" : "-" let c = isConnectionRequired(reachabilityFlags) ? "c" : "-" let t = isTransientConnection(reachabilityFlags) ? "t" : "-" let i = isInterventionRequired(reachabilityFlags) ? "i" : "-" let C = isConnectionOnTraffic(reachabilityFlags) ? "C" : "-" let D = isConnectionOnDemand(reachabilityFlags) ? "D" : "-" let l = isLocalAddress(reachabilityFlags) ? "l" : "-" let d = isDirect(reachabilityFlags) ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } deinit { stopNotifier() reachabilityRef = nil whenReachable = nil whenUnreachable = nil } }
mit
66434af2eefe400bb3193ef4a17ab7c5
35.080863
196
0.645973
5.497331
false
false
false
false
ephread/Instructions
Examples/Example/Unit Tests/Protocols/Internal/DataSource/DataSourceCoachMarkAtTest.swift
1
4451
// Copyright (c) 2016-present Frédéric Maquin <[email protected]> and contributors. // Licensed under the terms of the MIT License. import XCTest @testable import Instructions class DataSourceCoachMarkAtTest: DataSourceBaseTest, CoachMarksControllerDataSource, CoachMarksControllerDelegate { var delegateEndExpectation: XCTestExpectation? var numberOfTimesCoachMarkAtWasCalled = 0 var numberOfTimesCoachMarkViewsAtWasCalled = 0 var numberOfTimesConstraintsForSkipViewWasCalled = 0 override func setUp() { super.setUp() coachMarksController.dataSource = self coachMarksController.delegate = self } override func tearDown() { super.tearDown() delegateEndExpectation = nil } func testThatCoachMarkAtIsCalledAtLeastTheNumberOfExpectedTimes() { delegateEndExpectation = self.expectation(description: "CoachMarkAt") coachMarksController.start(in: .window(over: parentController)) waitForExpectations(timeout: 10) { error in if let error = error { print("Error: \(error.localizedDescription)") } } } func testThatCoachMarkViewsAtIsCalledAtLeastTheNumberOfExpectedTimes() { delegateEndExpectation = self.expectation(description: "CoachMarkViewsAt") coachMarksController.start(in: .window(over: parentController)) waitForExpectations(timeout: 10) { error in if let error = error { print("Error: \(error.localizedDescription)") } } } func testThatConstraintsForSkipViewIsCalledAtLeastTheNumberOfExpectedTimes() { delegateEndExpectation = self.expectation(description: "ConstraintsForSkipView") coachMarksController.start(in: .window(over: parentController)) waitForExpectations(timeout: 10) { error in if let error = error { print("Error: \(error.localizedDescription)") } } } func numberOfCoachMarks(for coachMarksController: CoachMarksController) -> Int { return 4 } func coachMarksController(_ coachMarksController: CoachMarksController, coachMarkAt index: Int) -> CoachMark { numberOfTimesCoachMarkAtWasCalled += 1 return CoachMark() } func coachMarksController( _ coachMarksController: CoachMarksController, coachMarkViewsAt index: Int, madeFrom coachMark: CoachMark ) -> (bodyView: (UIView & CoachMarkBodyView), arrowView: (UIView & CoachMarkArrowView)?) { numberOfTimesCoachMarkViewsAtWasCalled += 1 return (bodyView: CoachMarkBodyDefaultView(), arrowView: nil) } func coachMarksController(_ coachMarksController: CoachMarksController, constraintsForSkipView skipView: UIView, inParent parentView: UIView) -> [NSLayoutConstraint]? { numberOfTimesConstraintsForSkipViewWasCalled += 1 return nil } func coachMarksController(_ coachMarksController: CoachMarksController, didShow coachMark: CoachMark, afterChanging change: ConfigurationChange, at index: Int) { if change == .nothing { coachMarksController.flow.showNext() } } func coachMarksController(_ coachMarksController: CoachMarksController, didEndShowingBySkipping skipped: Bool) { guard let delegateEndExpectation = self.delegateEndExpectation else { XCTFail("Undefined expectation") return } if delegateEndExpectation.description == "CoachMarkAt" { if numberOfTimesCoachMarkAtWasCalled >= 4 { delegateEndExpectation.fulfill() return } } else if delegateEndExpectation.description == "CoachMarkViewsAt" { if numberOfTimesCoachMarkViewsAtWasCalled >= 4 { delegateEndExpectation.fulfill() return } } else if delegateEndExpectation.description == "ConstraintsForSkipView" { if numberOfTimesCoachMarkViewsAtWasCalled >= 1 { delegateEndExpectation.fulfill() return } } XCTFail("Unfulfilled expectation") } }
mit
471034bc1bec056c0ccbe2ee19839dd1
35.467213
116
0.63857
6.640299
false
true
false
false
wesj/firefox-ios-1
Storage/SQL/SchemaTable.swift
1
3365
/* 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 // A protocol for informationa about a particular table. This is used as a type to be stored by TableTable. protocol TableInfo { var name: String { get } var version: Int { get } } // A wrapper class for table info coming from the TableTable. This should ever only be used internally. class TableInfoWrapper: TableInfo { let name: String let version: Int init(name: String, version: Int) { self.name = name self.version = version } } /* A table in our database. Note this doesn't have to be a real table. It might be backed by a join * or something else interesting. */ protocol Table : TableInfo { typealias Type func create(db: SQLiteDBConnection, version: Int) -> Bool func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool func exists(db: SQLiteDBConnection) -> Bool func drop(db: SQLiteDBConnection) -> Bool func insert(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int func update(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int func delete(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int func query(db: SQLiteDBConnection, options: QueryOptions?) -> Cursor } // A table for holding info about other tables (also holds info about itself :)). This is used // to let us handle table upgrades when the table is first accessed, rather than when the database // itself is created. class SchemaTable<T>: GenericTable<TableInfo> { override var name: String { return "tableList" } override var version: Int { return 1 } override var rows: String { return "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL UNIQUE, " + "version INTEGER NOT NULL" } override func getInsertAndArgs(inout item: TableInfo) -> (String, [AnyObject?])? { var args = [AnyObject?]() args.append(item.name) args.append(item.version) return ("INSERT INTO \(name) (name, version) VALUES (?,?)", args) } override func getUpdateAndArgs(inout item: TableInfo) -> (String, [AnyObject?])? { var args = [AnyObject?]() args.append(item.version) args.append(item.name) return ("UPDATE \(name) SET version = ? WHERE name = ?", args) } override func getDeleteAndArgs(inout item: TableInfo?) -> (String, [AnyObject?])? { var args = [AnyObject?]() var sql = "DELETE FROM \(name)" if let table = item { args.append(table.name) sql += " WHERE name = ?" } return (sql, args) } override var factory: ((row: SDRow) -> TableInfo)? { return { row -> TableInfo in return TableInfoWrapper(name: row["name"] as String, version: row["version"] as Int) } } override func getQueryAndArgs(options: QueryOptions?) -> (String, [AnyObject?])? { var args = [AnyObject?]() if let filter: AnyObject = options?.filter { args.append(filter) return ("SELECT name, version FROM \(name) WHERE name = ?", args) } return ("SELECT name, version FROM \(name)", args) } }
mpl-2.0
8f33cc30ba631f459fc49de4ded4ca99
37.678161
107
0.641605
4.248737
false
false
false
false
KrishMunot/swift
test/Parse/matching_patterns.swift
4
7919
// RUN: %target-parse-verify-swift -enable-experimental-patterns -I %S/Inputs -enable-source-import import imported_enums // TODO: Implement tuple equality in the library. // BLOCKED: <rdar://problem/13822406> func ~= (x: (Int,Int,Int), y: (Int,Int,Int)) -> Bool { return true } var x:Int func square(_ x: Int) -> Int { return x*x } struct A<B> { struct C<D> { } // expected-error{{generic type 'C' nested in type}} } switch x { // Expressions as patterns. case 0: () case 1 + 2: () case square(9): () // 'var' and 'let' patterns. case var a: a = 1 case let a: a = 1 // expected-error {{cannot assign}} case var var a: // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}} a += 1 case var let a: // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}} print(a, terminator: "") case var (var b): // expected-error {{'var' cannot appear nested inside another 'var'}} b += 1 // 'Any' pattern. case _: () // patterns are resolved in expression-only positions are errors. case 1 + (_): // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} () } switch (x,x) { case (var a, var a): // expected-error {{definition conflicts with previous value}} expected-note {{previous definition of 'a' is here}} fallthrough case _: () } var e : protocol<> = 0 switch e { // 'is' pattern. case is Int, is A<Int>, is A<Int>.C<Int>, is (Int, Int), is (a: Int, b: Int): () } // Enum patterns. enum Foo { case A, B, C } func == <T>(_: Voluntary<T>, _: Voluntary<T>) -> Bool { return true } enum Voluntary<T> : Equatable { case Naught case Mere(T) case Twain(T, T) func enumMethod(_ other: Voluntary<T>, foo: Foo) { switch self { case other: () case Naught, Naught(), Naught(_, _): // expected-error{{tuple pattern has the wrong length for tuple type '()'}} () case Mere, Mere(), // expected-error{{tuple pattern cannot match values of the non-tuple type 'T'}} Mere(_), Mere(_, _): // expected-error{{tuple pattern cannot match values of the non-tuple type 'T'}} () case Twain(), // expected-error{{tuple pattern has the wrong length for tuple type '(T, T)'}} Twain(_), Twain(_, _), Twain(_, _, _): // expected-error{{tuple pattern has the wrong length for tuple type '(T, T)'}} () } switch foo { case Naught: // expected-error{{enum case 'Naught' is not a member of type 'Foo'}} () case .A, .B, .C: () } } } var n : Voluntary<Int> = .Naught switch n { case Foo.A: // expected-error{{enum case 'A' is not a member of type 'Voluntary<Int>'}} () case Voluntary<Int>.Naught, Voluntary<Int>.Naught(), Voluntary<Int>.Naught(_, _), // expected-error{{tuple pattern has the wrong length for tuple type '()'}} Voluntary.Naught, .Naught: () case Voluntary<Int>.Mere, Voluntary<Int>.Mere(_), Voluntary<Int>.Mere(_, _), // expected-error{{tuple pattern cannot match values of the non-tuple type 'Int'}} Voluntary.Mere, Voluntary.Mere(_), .Mere, .Mere(_): () case .Twain, .Twain(_), .Twain(_, _), .Twain(_, _, _): // expected-error{{tuple pattern has the wrong length for tuple type '(Int, Int)'}} () } var notAnEnum = 0 switch notAnEnum { case .Foo: // expected-error{{enum case 'Foo' not found in type 'Int'}} () } struct ContainsEnum { enum Possible<T> { // expected-error{{generic type 'Possible' nested in type}} case Naught case Mere(T) case Twain(T, T) } func member(_ n: Possible<Int>) { switch n { case ContainsEnum.Possible<Int>.Naught, ContainsEnum.Possible.Naught, Possible<Int>.Naught, Possible.Naught, .Naught: () } } } func nonmemberAccessesMemberType(_ n: ContainsEnum.Possible<Int>) { switch n { case ContainsEnum.Possible<Int>.Naught, .Naught: () } } var m : ImportedEnum = .Simple switch m { case imported_enums.ImportedEnum.Simple, ImportedEnum.Simple, .Simple: () case imported_enums.ImportedEnum.Compound, imported_enums.ImportedEnum.Compound(_), ImportedEnum.Compound, ImportedEnum.Compound(_), .Compound, .Compound(_): () } // Check that single-element tuple payloads work sensibly in patterns. enum LabeledScalarPayload { case Payload(name: Int) } var lsp: LabeledScalarPayload = .Payload(name: 0) func acceptInt(_: Int) {} func acceptString(_: String) {} switch lsp { case .Payload(0): () case .Payload(name: 0): () case let .Payload(x): acceptInt(x) acceptString("\(x)") case let .Payload(name: x): acceptInt(x) acceptString("\(x)") case let .Payload((name: x)): acceptInt(x) acceptString("\(x)") case .Payload(let (name: x)): acceptInt(x) acceptString("\(x)") case .Payload(let (name: x)): acceptInt(x) acceptString("\(x)") case .Payload(let x): acceptInt(x) acceptString("\(x)") case .Payload((let x)): acceptInt(x) acceptString("\(x)") } // Property patterns. struct S { static var stat: Int = 0 var x, y : Int var comp : Int { return x + y } func nonProperty() {} } struct T {} var s: S switch s { case S(): () case S(stat: _): // expected-error{{cannot match type property 'stat' of type 'S' in a 'case' pattern}} () case S(x: 0, y: 0, comp: 0): () case S(w: 0): // expected-error{{property 'w' not found in type 'S'}} () case S(nonProperty: 0): // expected-error{{member 'nonProperty' of type 'S' is not a property}} () case S(0): // expected-error{{subpattern of a struct or class pattern must have a keyword name}} () case S(x: 0, 0): // expected-error{{subpattern of a struct or class pattern must have a keyword name}} () case T(): // expected-error{{type 'T' of pattern does not match deduced type 'S'}} () } struct SG<A> { var x: A } var sgs: SG<S> switch sgs { case SG(x: S()): () case SG<S>(x: S()): () case SG<T>(x: T()): // expected-error{{type 'SG<T>' of pattern does not match deduced type 'SG<S>'}} () } func sg_generic<B : Equatable>(_ sgb: SG<B>, b: B) { switch sgb { case SG(x: b): () } } typealias NonNominal = (foo: Int, bar: UnicodeScalar) var nn = NonNominal.self switch nn { case NonNominal(): // expected-error{{non-nominal type 'NonNominal' (aka '(foo: Int, bar: UnicodeScalar)') cannot be used with property pattern syntax}} () } // Tuple patterns. var t = (1, 2, 3) prefix operator +++ {} infix operator +++ {} prefix func +++(x: (Int,Int,Int)) -> (Int,Int,Int) { return x } func +++(x: (Int,Int,Int), y: (Int,Int,Int)) -> (Int,Int,Int) { return (x.0+y.0, x.1+y.1, x.2+y.2) } switch t { case (_, var a, 3): a += 1 case var (_, b, 3): b += 1 case var (_, var c, 3): // expected-error{{'var' cannot appear nested inside another 'var'}} c += 1 case (1, 2, 3): () // patterns in expression-only positions are errors. case +++(_, var d, 3): // expected-error{{invalid pattern}} () case (_, var e, 3) +++ (1, 2, 3): // expected-error{{invalid pattern}} () } // FIXME: We don't currently allow subpatterns for "isa" patterns that // require interesting conditional downcasts. class Base { } class Derived : Base { } switch [Derived(), Derived(), Base()] { case let ds as [Derived]: // expected-error{{downcast pattern value of type '[Derived]' cannot be used}} () default: () } // Optional patterns. let op1 : Int? = nil let op2 : Int?? = nil switch op1 { case nil: break case 1?: break case _?: break } switch op2 { case nil: break case _?: break case (1?)?: break case (_?)?: break } // <rdar://problem/20365753> Bogus diagnostic "refutable pattern match can fail" let (responseObject: Int?) = op1 // expected-error @-1 2 {{expected ',' separator}} {{25-25=,}} {{25-25=,}} // expected-error @-2 {{expected pattern}}
apache-2.0
799c17655b0b3bee9de94bcc29af15e4
21.182073
152
0.609168
3.314776
false
false
false
false
ruslanskorb/CoreStore
Sources/CSWhere.swift
1
5184
// // CSWhere.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData // MARK: - CSWhere /** The `CSWhere` serves as the Objective-C bridging type for `Where`. - SeeAlso: `Where` */ @objc public final class CSWhere: NSObject, CSFetchClause, CSQueryClause, CSDeleteClause { /** The internal `NSPredicate` instance for the `Where` clause */ @objc public var predicate: NSPredicate { return self.bridgeToSwift.predicate } /** Initializes a `CSWhere` clause with a predicate that always evaluates to the specified boolean value ``` MyPersonEntity *people = [transaction fetchAllFrom:CSFromClass([MyPersonEntity class]) fetchClauses:@[CSWhereValue(YES)]]]; ``` - parameter value: the boolean value for the predicate */ @objc public convenience init(value: Bool) { self.init(Where(value)) } /** Initializes a `CSWhere` clause with a predicate using the specified string format and arguments ``` NSPredicate *predicate = // ... MyPersonEntity *people = [transaction fetchAllFrom:CSFromClass([MyPersonEntity class]) fetchClauses:@[CSWherePredicate(predicate)]]; ``` - parameter format: the format string for the predicate - parameter argumentArray: the arguments for `format` */ @objc public convenience init(format: String, argumentArray: [NSObject]?) { self.init(Where(format, argumentArray: argumentArray)) } /** Initializes a `CSWhere` clause that compares equality - parameter keyPath: the keyPath to compare with - parameter value: the arguments for the `==` operator */ @objc public convenience init(keyPath: KeyPathString, isEqualTo value: CoreDataNativeType?) { self.init(value == nil || value is NSNull ? Where("\(keyPath) == nil") : Where("\(keyPath) == %@", value!)) } /** Initializes a `CSWhere` clause that compares membership - parameter keyPath: the keyPath to compare with - parameter list: the array to check membership of */ @objc public convenience init(keyPath: KeyPathString, isMemberOf list: [CoreDataNativeType]) { self.init(Where("\(keyPath) IN %@", list as NSArray)) } /** Initializes a `CSWhere` clause with an `NSPredicate` - parameter predicate: the `NSPredicate` for the fetch or query */ @objc public convenience init(predicate: NSPredicate) { self.init(Where(predicate)) } // MARK: NSObject public override var hash: Int { return self.bridgeToSwift.hashValue } public override func isEqual(_ object: Any?) -> Bool { guard let object = object as? CSWhere else { return false } return self.bridgeToSwift == object.bridgeToSwift } public override var description: String { return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)" } // MARK: CSFetchClause, CSQueryClause, CSDeleteClause @objc public func applyToFetchRequest(_ fetchRequest: NSFetchRequest<NSFetchRequestResult>) { self.bridgeToSwift.applyToFetchRequest(fetchRequest) } // MARK: CoreStoreObjectiveCType public let bridgeToSwift: Where<NSManagedObject> public init<O: NSManagedObject>(_ swiftValue: Where<O>) { self.bridgeToSwift = swiftValue.downcast() super.init() } } // MARK: - Where extension Where where O: NSManagedObject { // MARK: CoreStoreSwiftType public var bridgeToObjectiveC: CSWhere { return CSWhere(self) } // MARK: FilePrivate fileprivate func downcast() -> Where<NSManagedObject> { return Where<NSManagedObject>(self.predicate) } }
mit
94dbc94c4225ea8ad3fb4cfcfa4acca1
27.794444
105
0.644607
5.027158
false
false
false
false
hamchapman/SwiftGQL
SwiftGQL/SchemaParser.swift
1
7597
//// **Parser** // //func parseSchemaIntoAST(source: Source, options: ParseOptions?) -> SchemaDocument { // let parser = makeParser(source, options: options) // return parseSchemaDocument(parser) //} // //func parseSchemaIntoAST(source: String, options: ParseOptions?) -> SchemaDocument { // let sourceObj = Source(body: source, name: nil) // let parser = makeParser(sourceObj, options: options) // return parseSchemaDocument(parser) //} // ///** //* SchemaDocument : SchemaDefinition+ //*/ //func parseSchemaDocument(parser: Parser) -> SchemaDocument { // let start = parser.token.start // var definitions: [SchemaDefinition] = [] // repeat { // definitions.append(parseSchemaDefinition(parser)) // } while !skip(parser, kind: getTokenKindDesc(TokenKind.EOF.rawValue)) // // return SchemaDocument(loc: loc(parser, start: start), definitions: definitions) //} // ///** //* SchemaDefinition : //* - TypeDefinition //* - InterfaceDefinition //* - UnionDefinition //* - ScalarDefinition //* - EnumDefinition //* - InputObjectDefinition //*/ //func parseSchemaDefinition(parser: Parser) -> SchemaDefinition { // if !peek(parser, kind: getTokenKindDesc(TokenKind.NAME.rawValue)) { // // throw unexpected(parser) // } // switch parser.token.value! { // case "type": // return parseTypeDefinition(parser) // case "interface": // return parseInterfaceDefinition(parser) // case "union": // return parseUnionDefinition(parser) // case "scalar": // return parseScalarDefinition(parser) // case "enum": // return parseEnumDefinition(parser) // case "input": // return parseInputObjectDefinition(parser) // default: // throw unexpected(parser) // } //} // ///** //* TypeDefinition : TypeName ImplementsInterfaces? { FieldDefinition+ } //* //* TypeName : Name //*/ //func parseTypeDefinition(parser: Parser) -> SchemaDefinition { // let start = parser.token.start // expectKeyword(parser, value: "type") // let name = parseName(parser) // let interfaces = parseImplementsInterfaces(parser) // let fields = any(parser, openKind: TokenKind.BRACE_L.rawValue, parseFn: parseFieldDefinition, closeKind: TokenKind.BRACE_R.rawValue) // return SchemaDefinition.TypeDef(definition: TypeDefinition(loc: loc(parser, start: start), name: name, interfaces: interfaces, fields: fields)) //} // ///** //* ImplementsInterfaces : `implements` NamedType+ //*/ //func parseImplementsInterfaces(parser: Parser) -> [NamedType] { // var types: [NamedType] = [] // if parser.token.value == "implements" { // advance(parser) // repeat { // types.append(parseNamedType(parser)) // } while !peek(parser, kind: getTokenKindDesc(TokenKind.BRACE_L.rawValue)) // } // return types //} // ///** //* FieldDefinition : FieldName ArgumentsDefinition? : Type //* //* FieldName : Name //*/ //func parseFieldDefinition(parser: Parser) -> FieldDefinition { // let start = parser.token.start // let name = parseName(parser) // let args = parseArgumentDefs(parser) // expect(parser, kind: getTokenKindDesc(TokenKind.COLON.rawValue)) // let type = parseType(parser) // return FieldDefinition(loc: loc(parser, start: start), name: name, arguments: args, type: type) //} // ///** //* ArgumentsDefinition : ( InputValueDefinition+ ) //*/ //func parseArgumentDefs(parser: Parser) -> [InputValueDefinition] { // if !peek(parser, kind: getTokenKindDesc(TokenKind.PAREN_L.rawValue)) { // return [] // } // return many(parser, openKind: TokenKind.PAREN_L.rawValue, parseFn: parseInputValueDef, closeKind: TokenKind.PAREN_R.rawValue) //} // ///** //* InputValueDefinition : Name : Value[Const] DefaultValue? //* //* DefaultValue : = Value[Const] //*/ //func parseInputValueDef(parser: Parser) -> InputValueDefinition { // let start = parser.token.start // let name = parseName(parser) // expect(parser, kind: getTokenKindDesc(TokenKind.COLON.rawValue)) // // TODO: Why is there an extra false in call here? // // var type = parseType(parser, false) // let type = parseType(parser) // var defaultValue: Value? = nil // if skip(parser, kind: getTokenKindDesc(TokenKind.EQUALS.rawValue)) { // defaultValue = parseConstValue(parser) // } // return InputValueDefinition(loc: loc(parser, start: start), name: name, type: type, defaultValue: defaultValue) //} // ///** //* InterfaceDefinition : `interface` TypeName { Fields+ } //*/ //func parseInterfaceDefinition(parser: Parser) -> SchemaDefinition { // let start = parser.token.start // expectKeyword(parser, value: "interface") // let name = parseName(parser) // let fields = any(parser, openKind: TokenKind.BRACE_L.rawValue, parseFn: parseFieldDefinition, closeKind: TokenKind.BRACE_R.rawValue) // return SchemaDefinition.InterfaceDef(definition: InterfaceDefinition(loc: loc(parser, start: start), name: name, fields: fields)) //} // ///** //* UnionDefinition : `union` TypeName = UnionMembers //*/ //func parseUnionDefinition(parser: Parser) -> SchemaDefinition { // let start = parser.token.start // expectKeyword(parser, value: "union") // let name = parseName(parser) // expect(parser, kind: getTokenKindDesc(TokenKind.EQUALS.rawValue)) // let types = parseUnionMembers(parser) // return SchemaDefinition.UnionDef(definition: UnionDefinition(loc: loc(parser, start: start), name: name, types: types)) //} // ///** //* UnionMembers : //* - NamedType //* - UnionMembers | NamedType //*/ //func parseUnionMembers(parser: Parser) -> [NamedType] { // var members: [NamedType] = [] // repeat { // members.append(parseNamedType(parser)) // } while skip(parser, kind: getTokenKindDesc(TokenKind.PIPE.rawValue)) // return members //} // ///** //* ScalarDefinition : `scalar` TypeName //*/ //func parseScalarDefinition(parser: Parser) -> SchemaDefinition { // let start = parser.token.start // expectKeyword(parser, value: "scalar") // let name = parseName(parser) // return SchemaDefinition.ScalarDef(definition: ScalarDefinition(loc: loc(parser, start: start), name: name)) //} // ///** //* EnumDefinition : `enum` TypeName { EnumValueDefinition+ } //*/ //func parseEnumDefinition(parser: Parser) -> SchemaDefinition { // let start = parser.token.start // expectKeyword(parser, value: "enum") // let name = parseName(parser) // let values = many(parser, openKind: TokenKind.BRACE_L.rawValue, parseFn: parseEnumValueDefinition, closeKind: TokenKind.BRACE_R.rawValue) // return SchemaDefinition.EnumDef(definition: EnumDefinition(loc: loc(parser, start: start), name: name, values: values)) //} // ///** //* EnumValueDefinition : EnumValue //* //* EnumValue : Name //*/ //func parseEnumValueDefinition(parser: Parser) -> EnumValueDefinition { // let start = parser.token.start // let name = parseName(parser) // return EnumValueDefinition(loc: loc(parser, start: start), name: name) //} // ///** //* InputObjectDefinition : `input` TypeName { InputValueDefinition+ } //*/ //func parseInputObjectDefinition(parser: Parser) -> SchemaDefinition { // let start = parser.token.start // expectKeyword(parser, value: "input") // let name = parseName(parser) // let fields = any(parser, openKind: TokenKind.BRACE_L.rawValue, parseFn: parseInputValueDef, closeKind: TokenKind.BRACE_R.rawValue) // return SchemaDefinition.InputObjectDef(definition: InputObjectDefinition(loc: loc(parser, start: start), name: name, fields: fields)) //}
mit
8ba2347e0c61cbecf11c7e2b2693934e
35.878641
149
0.678952
3.891906
false
false
false
false
DrabWeb/Booru-chan
Booru-chan/Booru-chan/InfoBarController.swift
1
1223
// // InfoBarController.swift // Booru-chan // // Created by Ushio on 2017-12-05. // import Cocoa class InfoBarController: NSViewController { @IBOutlet private weak var label: NSTextField! var imageSize: NSSize! { didSet { updateLabel(); } } var rating: Rating! { didSet { updateLabel(); } } var loadingProgress: Double! { didSet { updateLabel(); } } private func updateLabel() { if imageSize == nil && self.rating == nil && loadingProgress == nil { label.stringValue = ""; return; } let size = imageSize == nil ? "?x?" : "\(Int(imageSize.width))x\(Int(imageSize.height))"; let rating = self.rating == nil ? "?" : "\(String(String(describing: self.rating!).first!).uppercased())"; let progress = loadingProgress == nil ? "0" : "\(Int((loadingProgress * 100).rounded()))"; label.stringValue = "\(size) [\(rating)] \(progress)%"; } override func awakeFromNib() { super.awakeFromNib(); // hide the label initially imageSize = nil; rating = nil; loadingProgress = nil; } }
gpl-3.0
8a66333e15bbe743e7b9efd83f76063d
22.075472
114
0.537204
4.512915
false
false
false
false
aschwaighofer/swift
test/IRGen/struct_resilience.swift
2
19447
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift // RUN: %target-swift-frontend -module-name struct_resilience -I %t -emit-ir -enable-library-evolution %s | %FileCheck %s // RUN: %target-swift-frontend -module-name struct_resilience -I %t -emit-ir -enable-library-evolution -O %s import resilient_struct import resilient_enum // CHECK: %TSi = type <{ [[INT:i32|i64]] }> // CHECK-LABEL: @"$s17struct_resilience26StructWithResilientStorageVMf" = internal global // Resilient structs from outside our resilience domain are manipulated via // value witnesses // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience30functionWithResilientTypesSize_1f010resilient_A00G0VAFn_A2FnXEtF"(%swift.opaque* noalias nocapture sret %0, %swift.opaque* noalias nocapture %1, i8* %2, %swift.opaque* %3) public func functionWithResilientTypesSize(_ s: __owned Size, f: (__owned Size) -> Size) -> Size { // CHECK: entry: // CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 0) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable* // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8 // CHECK: [[WITNESS_FOR_SIZE:%.*]] = load [[INT]], [[INT]]* [[WITNESS_ADDR]] // CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16 // CHECK: [[STRUCT_ADDR:%.*]] = bitcast i8* [[ALLOCA]] to %swift.opaque* // CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]] // CHECK: [[initializeWithCopy:%.*]] = bitcast i8* [[WITNESS]] // CHECK: [[STRUCT_LOC:%.*]] = call %swift.opaque* [[initializeWithCopy]](%swift.opaque* noalias [[STRUCT_ADDR]], %swift.opaque* noalias %1, %swift.type* [[METADATA]]) // CHECK: [[FN:%.*]] = bitcast i8* %2 to void (%swift.opaque*, %swift.opaque*, %swift.refcounted*)* // CHECK: [[SELF:%.*]] = bitcast %swift.opaque* %3 to %swift.refcounted* // CHECK: call swiftcc void [[FN]](%swift.opaque* noalias nocapture sret %0, %swift.opaque* noalias nocapture [[STRUCT_ADDR]], %swift.refcounted* swiftself [[SELF]]) // CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 1 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]] // CHECK: [[destroy:%.*]] = bitcast i8* [[WITNESS]] to void (%swift.opaque*, %swift.type*)* // CHECK: call void [[destroy]](%swift.opaque* noalias %1, %swift.type* [[METADATA]]) // CHECK-NEXT: bitcast // CHECK-NEXT: call // CHECK-NEXT: ret void return f(s) } // CHECK-LABEL: declare{{( dllimport)?}} swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa" // CHECK-SAME: ([[INT]]) // Rectangle has fixed layout inside its resilience domain, and dynamic // layout on the outside. // // Make sure we use a type metadata accessor function, and load indirect // field offsets from it. // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience35functionWithResilientTypesRectangleyy010resilient_A00G0VF"(%T16resilient_struct9RectangleV* noalias nocapture %0) public func functionWithResilientTypesRectangle(_ r: Rectangle) { // CHECK: entry: // CHECK-NEXT: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct9RectangleVMa"([[INT]] 0) // CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i32* // CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds i32, i32* [[METADATA_ADDR]], [[INT]] [[IDX:2|4|6]] // CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load i32, i32* [[FIELD_OFFSET_PTR]] // CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %T16resilient_struct9RectangleV* %0 to i8* // CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], i32 [[FIELD_OFFSET]] // CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %TSi* // CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]] _ = r.color // CHECK-NEXT: ret void } // Resilient structs from inside our resilience domain are manipulated // directly. public struct MySize { public let w: Int public let h: Int } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience32functionWithMyResilientTypesSize_1fAA0eH0VAEn_A2EnXEtF"(%T17struct_resilience6MySizeV* noalias nocapture sret %0, %T17struct_resilience6MySizeV* noalias nocapture dereferenceable({{8|(16)}}) %1, i8* %2, %swift.opaque* %3) public func functionWithMyResilientTypesSize(_ s: __owned MySize, f: (__owned MySize) -> MySize) -> MySize { // There's an alloca for debug info? // CHECK: {{%.*}} = alloca %T17struct_resilience6MySizeV // CHECK: [[DST:%.*]] = alloca %T17struct_resilience6MySizeV // CHECK: [[W_ADDR:%.*]] = getelementptr inbounds %T17struct_resilience6MySizeV, %T17struct_resilience6MySizeV* %1, i32 0, i32 0 // CHECK: [[W_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[W_ADDR]], i32 0, i32 0 // CHECK: [[W:%.*]] = load [[INT]], [[INT]]* [[W_PTR]] // CHECK: [[H_ADDR:%.*]] = getelementptr inbounds %T17struct_resilience6MySizeV, %T17struct_resilience6MySizeV* %1, i32 0, i32 1 // CHECK: [[H_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[H_ADDR]], i32 0, i32 0 // CHECK: [[H:%.*]] = load [[INT]], [[INT]]* [[H_PTR]] // CHECK: [[DST_ADDR:%.*]] = bitcast %T17struct_resilience6MySizeV* [[DST]] to i8* // CHECK: call void @llvm.lifetime.start.p0i8({{i32|i64}} {{8|16}}, i8* [[DST_ADDR]]) // CHECK: [[W_ADDR:%.*]] = getelementptr inbounds %T17struct_resilience6MySizeV, %T17struct_resilience6MySizeV* [[DST]], i32 0, i32 0 // CHECK: [[W_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[W_ADDR]], i32 0, i32 0 // CHECK: store [[INT]] [[W]], [[INT]]* [[W_PTR]] // CHECK: [[H_ADDR:%.*]] = getelementptr inbounds %T17struct_resilience6MySizeV, %T17struct_resilience6MySizeV* [[DST]], i32 0, i32 1 // CHECK: [[H_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[H_ADDR]], i32 0, i32 0 // CHECK: store [[INT]] [[H]], [[INT]]* [[H_PTR]] // CHECK: [[FN:%.*]] = bitcast i8* %2 to void (%T17struct_resilience6MySizeV*, %T17struct_resilience6MySizeV*, %swift.refcounted*)* // CHECK: [[CONTEXT:%.*]] = bitcast %swift.opaque* %3 to %swift.refcounted* // CHECK: call swiftcc void [[FN]](%T17struct_resilience6MySizeV* noalias nocapture sret %0, %T17struct_resilience6MySizeV* noalias nocapture dereferenceable({{8|16}}) [[DST]], %swift.refcounted* swiftself [[CONTEXT]]) // CHECK: [[DST_ADDR:%.*]] = bitcast %T17struct_resilience6MySizeV* [[DST]] to i8* // CHECK: call void @llvm.lifetime.end.p0i8({{i32|i64}} {{8|16}}, i8* [[DST_ADDR]]) // CHECK: ret void return f(s) } // Structs with resilient storage from a different resilience domain require // runtime metadata instantiation, just like generics. public struct StructWithResilientStorage { public let s: Size public let ss: (Size, Size) public let n: Int public let i: ResilientInt } // Make sure we call a function to access metadata of structs with // resilient layout, and go through the field offset vector in the // metadata when accessing stored properties. // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc {{i32|i64}} @"$s17struct_resilience26StructWithResilientStorageV1nSivg"(%T17struct_resilience26StructWithResilientStorageV* {{.*}}) // CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s17struct_resilience26StructWithResilientStorageVMa"([[INT]] 0) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i32* // CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds i32, i32* [[METADATA_ADDR]], [[INT]] [[IDX:2|4|6]] // CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load i32, i32* [[FIELD_OFFSET_PTR]] // CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %T17struct_resilience26StructWithResilientStorageV* %0 to i8* // CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], i32 [[FIELD_OFFSET]] // CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %TSi* // CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]] // CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]] // Indirect enums with resilient payloads are still fixed-size. public struct StructWithIndirectResilientEnum { public let s: FunnyShape public let n: Int } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc {{i32|i64}} @"$s17struct_resilience31StructWithIndirectResilientEnumV1nSivg"(%T17struct_resilience31StructWithIndirectResilientEnumV* {{.*}}) // CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %T17struct_resilience31StructWithIndirectResilientEnumV, %T17struct_resilience31StructWithIndirectResilientEnumV* %0, i32 0, i32 1 // CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]] // CHECK: ret [[INT]] [[FIELD_PAYLOAD]] // Partial application of methods on resilient value types public struct ResilientStructWithMethod { public func method() {} } // Corner case -- type is address-only in SIL, but empty in IRGen // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience29partialApplyOfResilientMethod1ryAA0f10StructWithG0V_tF"(%T17struct_resilience25ResilientStructWithMethodV* noalias nocapture %0) public func partialApplyOfResilientMethod(r: ResilientStructWithMethod) { _ = r.method } // Type is address-only in SIL, and resilient in IRGen // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience29partialApplyOfResilientMethod1sy010resilient_A04SizeV_tF"(%swift.opaque* noalias nocapture %0) public func partialApplyOfResilientMethod(s: Size) { _ = s.method } public func wantsAny(_ any: Any) {} public func resilientAny(s : ResilientWeakRef) { wantsAny(s) } // CHECK-LABEL: define{{.*}} swiftcc void @"$s17struct_resilience12resilientAny1sy0c1_A016ResilientWeakRefV_tF"(%swift.opaque* noalias nocapture %0) // CHECK: entry: // CHECK: [[ANY:%.*]] = alloca %Any // CHECK: [[META:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct16ResilientWeakRefVMa"([[INT]] 0) // CHECK: [[META2:%.*]] = extractvalue %swift.metadata_response %3, 0 // CHECK: [[TYADDR:%.*]] = getelementptr inbounds %Any, %Any* [[ANY]], i32 0, i32 1 // CHECK: store %swift.type* [[META2]], %swift.type** [[TYADDR]] // CHECK: [[BITCAST:%.*]] = bitcast %Any* [[ANY]] to %__opaque_existential_type_0* // CHECK: call %swift.opaque* @__swift_allocate_boxed_opaque_existential_0(%__opaque_existential_type_0* [[BITCAST]]) // CHECK: call swiftcc void @"$s17struct_resilience8wantsAnyyyypF"(%Any* noalias nocapture dereferenceable({{(32|16)}}) [[ANY]]) // CHECK: [[BITCAST:%.*]] = bitcast %Any* [[ANY]] to %__opaque_existential_type_0* // CHECK: call void @__swift_destroy_boxed_opaque_existential_0(%__opaque_existential_type_0* [[BITCAST]]) // CHECK: ret void // Make sure that MemoryLayout properties access resilient types' metadata // instead of hardcoding sizes based on compile-time layouts. // CHECK-LABEL: define{{.*}} swiftcc {{i32|i64}} @"$s17struct_resilience38memoryLayoutDotSizeWithResilientStructSiyF"() public func memoryLayoutDotSizeWithResilientStruct() -> Int { // CHECK: entry: // CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 0) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable* // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8 // CHECK: [[WITNESS_FOR_SIZE:%.*]] = load [[INT]], [[INT]]* [[WITNESS_ADDR]] // CHECK: ret [[INT]] [[WITNESS_FOR_SIZE]] return MemoryLayout<Size>.size } // CHECK-LABEL: define{{.*}} swiftcc {{i32|i64}} @"$s17struct_resilience40memoryLayoutDotStrideWithResilientStructSiyF"() public func memoryLayoutDotStrideWithResilientStruct() -> Int { // CHECK: entry: // CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 0) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable* // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 9 // CHECK: [[WITNESS_FOR_STRIDE:%.*]] = load [[INT]], [[INT]]* [[WITNESS_ADDR]] // CHECK: ret [[INT]] [[WITNESS_FOR_STRIDE]] return MemoryLayout<Size>.stride } // CHECK-LABEL: define{{.*}} swiftcc {{i32|i64}} @"$s17struct_resilience43memoryLayoutDotAlignmentWithResilientStructSiyF"() public func memoryLayoutDotAlignmentWithResilientStruct() -> Int { // CHECK: entry: // CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 0) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable* // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 10 // CHECK: [[WITNESS_FOR_FLAGS:%.*]] = load i32, i32* [[WITNESS_ADDR]] // Not checked because it only exists on 64-bit: [[EXTENDED_FLAGS:%.*]] = zext i32 [[WITNESS_FOR_FLAGS]] to [[INT]] // CHECK: [[ALIGNMENT_MASK:%.*]] = and [[INT]] {{%.*}}, 255 // CHECK: [[ALIGNMENT:%.*]] = add [[INT]] [[ALIGNMENT_MASK]], 1 // CHECK: ret [[INT]] [[ALIGNMENT]] return MemoryLayout<Size>.alignment } // Make sure that MemoryLayout.offset(of:) on a resilient type uses the accessor // in the key path instead of hardcoding offsets based on compile-time layouts. // CHECK-LABEL: define{{.*}} swiftcc { {{i32|i64}}, i8 } @"$s17struct_resilience42memoryLayoutDotOffsetOfWithResilientStructSiSgyF"() public func memoryLayoutDotOffsetOfWithResilientStruct() -> Int? { // CHECK-NEXT: entry: // CHECK: [[RAW_KEY_PATH:%.*]] = call %swift.refcounted* @swift_getKeyPath // CHECK: [[WRITABLE_KEY_PATH:%.*]] = bitcast %swift.refcounted* [[RAW_KEY_PATH]] to %Ts15WritableKeyPathCy16resilient_struct4SizeVSiG* // CHECK: [[PARTIAL_KEY_PATH:%.*]] = bitcast %Ts15WritableKeyPathCy16resilient_struct4SizeVSiG* [[WRITABLE_KEY_PATH]] to %Ts14PartialKeyPathCy16resilient_struct4SizeVG* // CHECK: [[ANY_KEY_PATH:%.*]] = bitcast %Ts14PartialKeyPathCy16resilient_struct4SizeVG* [[PARTIAL_KEY_PATH]] to %Ts10AnyKeyPathC* // CHECK: [[STORED_INLINE_OFFSET:%.*]] = call swiftcc { [[INT]], i8 } @"$ss10AnyKeyPathC19_storedInlineOffsetSiSgvgTj"(%Ts10AnyKeyPathC* swiftself [[ANY_KEY_PATH]]) // CHECK: [[VALUE:%.*]] = extractvalue { [[INT]], i8 } [[STORED_INLINE_OFFSET]], 0 // CHECK: [[RET_PARTIAL:%.*]] = insertvalue { [[INT]], i8 } undef, [[INT]] [[VALUE]], 0 // CHECK: [[RET:%.*]] = insertvalue { [[INT]], i8 } [[RET_PARTIAL]] // CHECK: ret { [[INT]], i8 } [[RET]] return MemoryLayout<Size>.offset(of: \Size.w) } // Public metadata accessor for our resilient struct // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.metadata_response @"$s17struct_resilience6MySizeVMa" // CHECK-SAME: ([[INT]] %0) // CHECK: ret %swift.metadata_response { %swift.type* bitcast ([[INT]]* getelementptr inbounds {{.*}} @"$s17struct_resilience6MySizeVMf", i32 0, i32 1) to %swift.type*), [[INT]] 0 } // CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s17struct_resilience26StructWithResilientStorageVMr"(%swift.type* %0, i8* %1, i8** %2) // CHECK: [[FIELDS:%.*]] = alloca [4 x i8**] // CHECK: [[TUPLE_LAYOUT:%.*]] = alloca %swift.full_type_layout, // CHECK: [[FIELDS_ADDR:%.*]] = getelementptr inbounds [4 x i8**], [4 x i8**]* [[FIELDS]], i32 0, i32 0 // public let s: Size // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 319) // CHECK: [[SIZE_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK: [[T0:%.*]] = bitcast %swift.type* [[SIZE_METADATA]] to i8*** // CHECK: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], [[INT]] -1 // CHECK: [[SIZE_VWT:%.*]] = load i8**, i8*** [[T1]], // CHECK: [[SIZE_LAYOUT_1:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8 // CHECK: [[FIELD_1:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 0 // CHECK: store i8** [[SIZE_LAYOUT_1:%.*]], i8*** [[FIELD_1]] // public let ss: (Size, Size) // CHECK: [[SIZE_LAYOUT_2:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8 // CHECK: [[SIZE_LAYOUT_3:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8 // CHECK: call swiftcc [[INT]] @swift_getTupleTypeLayout2(%swift.full_type_layout* [[TUPLE_LAYOUT]], i8** [[SIZE_LAYOUT_2]], i8** [[SIZE_LAYOUT_3]]) // CHECK: [[T0:%.*]] = bitcast %swift.full_type_layout* [[TUPLE_LAYOUT]] to i8** // CHECK: [[FIELD_2:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 1 // CHECK: store i8** [[T0]], i8*** [[FIELD_2]] // Fixed-layout aggregate -- we can reference a static value witness table // public let n: Int // CHECK: [[FIELD_3:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 2 // CHECK: store i8** getelementptr inbounds (i8*, i8** @"$sBi{{32|64}}_WV", i32 {{.*}}), i8*** [[FIELD_3]] // Resilient aggregate with one field -- make sure we don't look inside it // public let i: ResilientInt // CHECK: call swiftcc %swift.metadata_response @"$s16resilient_struct12ResilientIntVMa"([[INT]] 319) // CHECK: [[FIELD_4:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 3 // CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_4]] // CHECK: call void @swift_initStructMetadata(%swift.type* {{.*}}, [[INT]] 256, [[INT]] 4, i8*** [[FIELDS_ADDR]], i32* {{.*}})
apache-2.0
fdde100ee594a7fbcd49dda5742fbbf9
56.029326
316
0.661747
3.503964
false
false
false
false
nagahar/Tetriswift
Tetriswift/Tetrimino.swift
2
5538
// // Tetrimino.swift // Tetriswift // // Created by nagahara on 2015/08/15. // Copyright (c) 2015年 ___Takanori Nagahara___. All rights reserved. // import UIKit class Tetrimino: UIView { var dest: CGPoint = CGPointZero var type: TetriminoType = .None var game: Game! var blocks: [Block] = [] static let p_00: CGPoint = CGPointMake(0, 0) static let p_01: CGPoint = CGPointMake(0, Game.funit) static let p_10: CGPoint = CGPointMake(Game.funit, 0) static let p_11: CGPoint = CGPointMake(Game.funit, Game.funit) init () { super.init(frame: CGRectZero) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } init(type: TetriminoType = .None, game: Game) { self.type = type self.game = game super.init(frame: Tetrimino.getSize(type)) self.blocks = Tetrimino.create(self) for b in self.blocks { self.addSubview(b) } self.addDoubleTap("doubleTapped:") self.backgroundColor = UIColor.yellowColor() } deinit { dispose() } private static func getSize(type: TetriminoType) -> CGRect { switch type { case .O: return CGRectMake(0, 0, Game.funit * 2, Game.funit * 2) case .I: return CGRectZero case .S: return CGRectZero case .Z: return CGRectZero case .J: return CGRectZero case .L: return CGRectZero case .T: return CGRectZero case .None: return CGRectZero } } static func create(tetrimino: Tetrimino) -> [Block] { switch tetrimino.type { case .O: return createO(tetrimino) case .I: return ([]) case .S: return ([]) case .Z: return ([]) case .J: return ([]) case .L: return ([]) case .T: return ([]) case .None: return ([]) } } func dispose() { self.removeFromSuperview() for b in self.blocks { b.removeFromSuperview() } self.blocks = [] } func replace(parent: UIView, w: World) { self.removeFromSuperview() Tetrimino.reset(self, p: parent, w: w) } func moveTo(w: World) -> Bool { if (Game.hasUpdated(self.dest, v: self)) { let result = isOccupiedAndGrounded(w) if (!result.isOccupied) { print("move from \(self.frame.origin)") print("dest: \(dest)") Game.translate(dest - self.frame.origin, v: self) return result.isGrounded } } return false } func convert(b: Block) -> (Int, Int) { return Game.convert(b.locationInView(self) + self.dest - self.frame.origin) } func updateFromDiff(diff: CGPoint) { self.dest = Game.normalize(diff, v: self) } func isOccupiedAndGrounded(w: World) -> (isOccupied: Bool, isGrounded: Bool) { var isOccupied: Bool = false var isGrounded: Bool = false for b in self.blocks { let t = self.convert(b) let res = w.isOccupiedAndGrounded(t.0, col: t.1) isOccupied = isOccupied || res.isOccupied isGrounded = isGrounded || res.isGrounded } return (isOccupied, isGrounded) } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { self.update(touches, withEvent: event) } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { self.update(touches, withEvent: event) } func update(touches: Set<UITouch>, withEvent event: UIEvent?) { if let touch = touches.first { self.updateFromDiff(touch.locationInView(self.superview) - self.frame.origin) } } static func createO(tetrimino: Tetrimino) -> [Block] { var block: [Block] = [] //let c = UIColor.yellowColor() let c = UIColor.blueColor() block.append(Block(o: p_00, c: c, t: tetrimino)) block.append(Block(o: p_01, c: c, t: tetrimino)) block.append(Block(o: p_10, c: c, t: tetrimino)) block.append(Block(o: p_11, c: c, t: tetrimino)) return block } static func reset(t: Tetrimino, p: UIView, w: World) { for b in t.blocks { b.frame.origin = b.locationInView(t) b.removeFromSuperview() p.addSubview(b) w.putBlock(b) print("@@@@@@@\(b.frame.origin)") } } func doubleTapped(sender: UITapGestureRecognizer) { print("DDDDDDDDDDDDDDDD") let lowest = CGFloat(Game.getLowest(self.frame.origin.x)) print("CCCCCCCCCC tapped \(lowest)") if (0 < lowest) { self.updateFromDiff(CGPointMake(0, lowest - self.frame.height - self.frame.origin.y)) } } func addDoubleTap(selector: Selector) { let doubleTap = UITapGestureRecognizer(target: self, action: selector) doubleTap.numberOfTapsRequired = 2 self.addGestureRecognizer(doubleTap) } func rightRotate() { } func leftRotate() { } }
mit
fca5b27149a364ad5642096937e9535a
26.819095
97
0.540282
4.21309
false
false
false
false
stuffmc/RealmCloudKit
Pod/Classes/RealmCloudKit.swift
1
6968
import MultiRealm import RealmSwift import CloudKit import SwiftFileManager import Backgroundable import KeychainAccess import Security import Internet import ReachabilitySwift internal let domain = "com.bellapplab.RealmCloudKit" internal let bundle = NSBundle(identifier: "org.cocoapods.RealmCloudKit")! public final class RealmCloudKit { deinit { Internet.removeChangeBlock(self.internetChange) Internet.pause() } private var backgroundRealm: MultiRealm private var cloudKitRealm: MultiRealm private var internetChange: Internet.Change! private func setupInternetChange() { self.internetChange = Internet.addChangeBlock { [unowned self] (status: Reachability.NetworkStatus) -> Void in self.suspended = status == .NotReachable } } private let options: Options private var suspendedCount = 0 private var isSuspended: Bool { return suspendedCount > 0 } private func suspend() { } private func resume() { } private init(pathToRealmToBeSynced: String, encryptionKey: NSData?, pathToCloudKitRealm: String, options: Options) { // self.backgroundRealm = MultiRealm(path: pathToRealmToBeSynced, readOnly: false, encryptionKey: encryptionKey, queueType: .Background) self.backgroundRealm = MultiRealm(.Background, {}) self.backgroundRealm.set(try! Realm(path: pathToRealmToBeSynced)) self.options = options self.path = pathToCloudKitRealm self.suspendedCount++ if !Internet.areYouThere() { suspendedCount++ } let keychain = Keychain(service: domain).accessibility(.WhenUnlockedThisDeviceOnly) var password = try! keychain.getData("RealmCloudKit") if password == nil { // Generate a random encryption key let key = NSMutableData(length: 64)! SecRandomCopyBytes(kSecRandomDefault, key.length, UnsafeMutablePointer<UInt8>(key.mutableBytes)) try! keychain.set(key, key: "RealmCloudKit") password = key } // self.cloudKitRealm = MultiRealm(path: self.path, readOnly: false, encryptionKey: password!, queueType: .Background) self.cloudKitRealm = MultiRealm(.Background, {}) self.cloudKitRealm.set(try! Realm(path: self.path)) self.setupInternetChange() } public class func start(realmToBeSynced realm: Realm, block: (resultRealm: RealmCloudKit?, error: NSError?) -> Void) { self.start(pathToRealmToBeSynced: realm.path, block: block) } public class func start(pathToRealmToBeSynced path: String?, block: (resultRealm: RealmCloudKit?, error: NSError?) -> Void) { self.start(pathToRealmToBeSynced: path, encryptionKey: nil, options: nil, block: block) } public class func start(pathToRealmToBeSynced path: String?, encryptionKey: NSData?, var options: Options?, block: (resultRealm: RealmCloudKit?, error: NSError?) -> Void) { if options == nil { options = Options.forPublicContainer() } if path == nil || path!.isEmpty { print("Realm.defaultPath?") // path = Realm.defaultPath } let errorBlock: (NSError)->() = { (anError: NSError) -> () in toMainThread { block(resultRealm: nil, error: anError) } } //Getting the Cloud Kit Realm's URL NSFileManager.URLForFile(.Database, withName: NSURL(fileURLWithPath: path!).lastPathComponent!) { (urlSuccess, cloudKitRealmURL) -> Void in if !urlSuccess { errorBlock(RealmCloudKitError.Denied.produceError()) } else { let deleteBlock: ((()->())?)->() = { (deleteReturnBlock: (()->())?) in NSFileManager.deleteFile(cloudKitRealmURL!, withBlock: { (success, finalURL) -> Void in deleteReturnBlock?() }) } let startBlock: ()->() = { toBackground { let result = RealmCloudKit(pathToRealmToBeSynced: path!, encryptionKey: encryptionKey, pathToCloudKitRealm: cloudKitRealmURL!.path!, options: options!) toMainThread { block(resultRealm: result, error: nil) } } } if !options!.needCloudKitPermissions() {//It doesn't matter if the user doesn't have an iCloud account set up startBlock() } else {//We need an iCloud account getCloudAccount(options!, deleteBlock: deleteBlock, resultBlock: { (success: Bool, error: NSError?) -> Void in if !success { errorBlock(error!) } else { startBlock() } }) } } } } public let path: String public var suspended: Bool { get { return self.isSuspended } set { if newValue { if !self.isSuspended { self.suspend() } suspendedCount++ } else { if suspendedCount == 1 { self.resume() } suspendedCount-- if suspendedCount < 0 { suspendedCount == 0 } } } } } //MARK: - Errors public enum RealmCloudKitError: Int { case Denied = 1 //User chose not to use iCloud case PasswordMiss = 2 //User hasn't set up an iCloud account and doesn't want to set it case TurnedOff = 3 //IPromiseTheUserWantsToUseiCloud option in NSUserDefaults is set to false case Restricted = 4 //iCloud access is restricted on the device public var description: String { switch self { case .Denied: return NSLocalizedString("Denied", tableName: "RealmCloudKit", bundle: bundle, comment: "Error code's description") case .PasswordMiss: return NSLocalizedString("PasswordMiss", tableName: "RealmCloudKit", bundle: bundle, comment: "Error code's description") case .TurnedOff: return NSLocalizedString("TurnedOff", tableName: "RealmCloudKit", bundle: bundle, comment: "Error code's description") case .Restricted: return NSLocalizedString("Restricted", tableName: "RealmCloudKit", bundle: bundle, comment: "Error code's description") } } internal func produceError() -> NSError { return NSError(domain: domain, code: self.rawValue, userInfo: [NSLocalizedDescriptionKey: self.description]) } }
mit
cb414315c4f2d662508a90cb58443a7c
36.664865
176
0.583812
5.4395
false
false
false
false
gyzerocc/zh_daily
ZhiHuDailyProject/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift
15
13663
// // ImageView+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif // MARK: - Extension methods. /** * Set image to use from web. */ extension Kingfisher where Base: ImageView { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. If `resource` is `nil`, the `placeholder` image will be set and `completionHandler` will be called with both `error` and `image` being `nil`. */ @discardableResult public func setImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { guard let resource = resource else { base.image = placeholder setWebURL(nil) completionHandler?(nil, nil, .none, nil) return .empty } var options = KingfisherManager.shared.defaultOptions + (options ?? KingfisherEmptyOptionsInfo) if !options.keepCurrentImageWhileLoading { base.image = placeholder } let maybeIndicator = indicator maybeIndicator?.startAnimatingView() setWebURL(resource.downloadURL) if base.shouldPreloadAllAnimation() { options.append(.preloadAllAnimationData) } let task = KingfisherManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in guard resource.downloadURL == self.webURL else { return } if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: {[weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { guard let strongBase = base, imageURL == self.webURL else { completionHandler?(image, error, cacheType, imageURL) return } self.setImageTask(nil) guard let image = image else { maybeIndicator?.stopAnimatingView() completionHandler?(nil, error, cacheType, imageURL) return } guard let transitionItem = options.lastMatchIgnoringAssociatedValue(.transition(.none)), case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else { maybeIndicator?.stopAnimatingView() strongBase.image = image completionHandler?(image, error, cacheType, imageURL) return } #if !os(macOS) UIView.transition(with: strongBase, duration: 0.0, options: [], animations: { maybeIndicator?.stopAnimatingView() }, completion: { _ in UIView.transition(with: strongBase, duration: transition.duration, options: [transition.animationOptions, .allowUserInteraction], animations: { // Set image property in the animation. transition.animations?(strongBase, image) }, completion: { finished in transition.completion?(finished) completionHandler?(image, error, cacheType, imageURL) }) }) #endif } }) setImageTask(task) return task } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func cancelDownloadTask() { imageTask?.cancel() } } // MARK: - Associated Object private var lastURLKey: Void? private var indicatorKey: Void? private var indicatorTypeKey: Void? private var imageTaskKey: Void? extension Kingfisher where Base: ImageView { /// Get the image URL binded to this image view. public var webURL: URL? { return objc_getAssociatedObject(base, &lastURLKey) as? URL } fileprivate func setWebURL(_ url: URL?) { objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } /// Holds which indicator type is going to be used. /// Default is .none, means no indicator will be shown. public var indicatorType: IndicatorType { get { let indicator = (objc_getAssociatedObject(base, &indicatorTypeKey) as? Box<IndicatorType?>)?.value return indicator ?? .none } set { switch newValue { case .none: indicator = nil case .activity: indicator = ActivityIndicator() case .image(let data): indicator = ImageIndicator(imageData: data) case .custom(let anIndicator): indicator = anIndicator } objc_setAssociatedObject(base, &indicatorTypeKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Holds any type that conforms to the protocol `Indicator`. /// The protocol `Indicator` has a `view` property that will be shown when loading an image. /// It will be `nil` if `indicatorType` is `.none`. public fileprivate(set) var indicator: Indicator? { get { return (objc_getAssociatedObject(base, &indicatorKey) as? Box<Indicator?>)?.value } set { // Remove previous if let previousIndicator = indicator { previousIndicator.view.removeFromSuperview() } // Add new if var newIndicator = newValue { newIndicator.view.frame = base.frame newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY) newIndicator.view.isHidden = true base.addSubview(newIndicator.view) } // Save in associated object objc_setAssociatedObject(base, &indicatorKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate var imageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask } fileprivate func setImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Deprecated. Only for back compatibility. /** * Set image to use from web. Deprecated. Use `kf` namespacing instead. */ extension ImageView { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.setImage` instead.", renamed: "kf.setImage") @discardableResult public func kf_setImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.cancelDownloadTask` instead.", renamed: "kf.cancelDownloadTask") public func kf_cancelDownloadTask() { kf.cancelDownloadTask() } /// Get the image URL binded to this image view. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.webURL` instead.", renamed: "kf.webURL") public var kf_webURL: URL? { return kf.webURL } /// Holds which indicator type is going to be used. /// Default is .none, means no indicator will be shown. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicatorType` instead.", renamed: "kf.indicatorType") public var kf_indicatorType: IndicatorType { get { return kf.indicatorType } set { kf.indicatorType = newValue } } @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicator` instead.", renamed: "kf.indicator") /// Holds any type that conforms to the protocol `Indicator`. /// The protocol `Indicator` has a `view` property that will be shown when loading an image. /// It will be `nil` if `kf_indicatorType` is `.none`. public private(set) var kf_indicator: Indicator? { get { return kf.indicator } set { kf.indicator = newValue } } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.imageTask") fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setImageTask") fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setWebURL") fileprivate func kf_setWebURL(_ url: URL) { kf.setWebURL(url) } func shouldPreloadAllAnimation() -> Bool { return true } @available(*, deprecated, renamed: "shouldPreloadAllAnimation") func shouldPreloadAllGIF() -> Bool { return true } }
mit
a1f42f58fa9b2c8fd02a81cacc637dc5
44.848993
173
0.602796
5.59959
false
false
false
false
jcmendez/JCMTimeSlider
TimeSliderTests/JCMTimeSliderUtilsTests.swift
1
14588
// // JCMTimeSliderUtilsTests.swift // TimeSlider // // Created by Larry Pepchuk on 5/11/15. // // The MIT License (MIT) // // Copyright (c) 2015 Accenture. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import XCTest import TimeSlider // // Contains Unit Tests for JCMTimeSliderUtils.findNearestDate() method // class JCMTimeSliderUtilsTests: XCTestCase { let tsu = JCMTimeSliderUtils() // Create an empty data source var testDataSource = TimeSliderTestDataSource(data: [JCMTimeSliderControlDataPoint]()) override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // // Tests for 'findNearestDate' method with small data source that has 0,1,2, or 3 records // // NOTE: 'findNearestDate' is always expected to find the closest date in the past // func testFindNearestDate() { // // Empty data source (0 records) // NSLog("Empty data source (0 records)") XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: NSDate()), 0, "Should return zero for an empty data source") // // Single data source record (current date) // NSLog("Single data source record (current date)") let currentDate = NSDate(timeIntervalSinceNow: 0) let oneDayInThePast = currentDate.dateByAddingTimeInterval(-60*60*24) let oneDayInThePastM10sec = currentDate.dateByAddingTimeInterval(-60*60*24 - 10) let oneDayInThePastP10sec = currentDate.dateByAddingTimeInterval(-60*60*24 + 10) let currentDateM10sec = currentDate.dateByAddingTimeInterval(0 - 10) let currentDateP10sec = currentDate.dateByAddingTimeInterval(0 + 10) let oneDayInTheFuture = currentDate.dateByAddingTimeInterval(60*60*24) let oneDayInTheFutureM10sec = currentDate.dateByAddingTimeInterval(60*60*24 - 10) let oneDayInTheFutureP10sec = currentDate.dateByAddingTimeInterval(60*60*24 + 10) let currentDateDataPoint = JCMTimeSliderControlDataPoint(date: currentDate, hasIcon: false) self.testDataSource = TimeSliderTestDataSource(data:[currentDateDataPoint]) // ...same target date XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: currentDate), 0, "Should match 1st element (zero)") // ...target date is in the past (exact match) XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: oneDayInThePast), 0, "Should match 1st element (zero)") // ...target date is in the future XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: oneDayInTheFuture), 0, "Should match 1st element (zero)") // ---- Target date is close but is not an exact match ---- NSLog("...target date is close but is not an exact match...") // ...target date is current date (10 sec in the past) XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: currentDateM10sec), 0, "Should match 2nd element (one)") // ...target date is current date (10 sec in the future) XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: currentDateP10sec), 0, "Should match 2nd element (one)") // // Two data source records (past, current date) // NSLog("Two data source records (past, current date)") let oneDayInThePastDataPoint = JCMTimeSliderControlDataPoint(date: oneDayInThePast, hasIcon: false) self.testDataSource = TimeSliderTestDataSource(data:[oneDayInThePastDataPoint, currentDateDataPoint]) // ...target date is in the past (exact match) XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: oneDayInThePast), 0, "Should match 1st element (zero)") // ...target date is current date (exact match) XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: currentDate), 1, "Should match 2nd element (one)") // ---- Target date is close but is not an exact match ---- NSLog("...target date is close but is not an exact match...") // ...target date is in the past (shifted 10 sec in the past) XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: oneDayInThePastM10sec), 0, "Should match 1st element (zero)") // ...target date is in the past (shifted 10 sec in the future) XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: oneDayInThePastP10sec), 0, "Should match 1st element (zero)") // ...target date is current date (shifted 10 sec in the past) // // NOTE: This is supposed to snap to the previous (older) date even // though the closest date is in the future // XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: currentDateM10sec), 0, "Should match 1st element (zero)") // ...target date is current date (shifted 10 sec in the future) XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: currentDateP10sec), 1, "Should match 2nd element (one)") // // 3 data source records (past, current date, future date) // let oneDayInTheFutureDataPoint = JCMTimeSliderControlDataPoint(date: oneDayInTheFuture, hasIcon: false) self.testDataSource = TimeSliderTestDataSource(data:[ oneDayInThePastDataPoint, currentDateDataPoint, oneDayInTheFutureDataPoint]) // ...target date is in the past (exact match) XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: oneDayInThePast), 0, "Should match 1st element (zero)") // ...target date is current date (exact match) XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: NSDate(timeIntervalSinceNow: 0)), 1, "Should match 2nd element (one)") // ...target date is in the future (exact match) XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: oneDayInTheFuture), 2, "Should match 3rd element (two)") // ---- Target date is close but is not an exact match ---- NSLog("...target date is close but is not an exact match...") // ...target date is in the past (shifted 10 sec in the past) XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: oneDayInThePastM10sec), 0, "Should match 1st element (zero)") // ...target date is in the past (shifted 10 sec in the future) XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: oneDayInThePastP10sec), 0, "Should match 1st element (zero)") // ...target date is current date (shifted 10 sec in the past) // // NOTE: This is supposed to snap to the previous (older) date even // though the closest date is in the future // XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: currentDateM10sec), 0, "Should match 1st element (zero)") // ...target date is current date (shifted 10 sec in the future) XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: currentDateP10sec), 1, "Should match 2nd element (one)") // ...target date is in the future (shifted 10 sec in the past) // // NOTE: This is supposed to snap to the previous (older) date even // though the closest date is in the future // XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: oneDayInTheFutureM10sec), 1, "Should match 2nd element (one)") // ...target date is in the future (shifted 10 sec in the future) XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: oneDayInTheFutureP10sec), 2, "Should match 2nd element (one)") } // // Tests for 'findNearestDate' method with data source that has: // - 50 records // // NOTE: 'findNearestDate' is always expected to find the closest date in the past // func testFindNearestDateLargeRecordCount() { var recordCount = 5 performTestFindNearestDate(recordCount) recordCount = 50 performTestFindNearestDate(recordCount) recordCount = 1000 performTestFindNearestDate(recordCount) // Exceed max allowed number of records // // NOTE: There is currently no easy way to catch an exception/assert during unit testing in Swift. // In objective-C we could use XCTAssertThrows(...) but it does not exists in Swift. // // So... // a) if we uncomment the code below, it will crash the app (thus Unit Tests cannot continue) // b) if we keep it commented out, we certanly cannot check for the test condition // // recordCount = 1001 // createTestDataSource(recordCount) // let targetDate = NSDate(timeIntervalSinceNow: 0) // // // This should throw an assert thus crashing the app (Unit Tests will stop executing) // self.tsu.findNearestDate(self.testDataSource, searchItem: targetDate) } // // Creates test data source with a given number of records // func createTestDataSource(recordCount: Int) { // // Prepare data source records (~1/2 in the past, current date, ~1/2 in the future) // NSLog("data source record count=\(recordCount)") // // Init data source with the given number of records // // NOTE: We create records that are one day apart; // half in the past, and half in the future // let recordCountConverted = NSTimeInterval(recordCount) var testDataSourceArray:[JCMTimeSliderControlDataPoint] = [] let startIndex: NSTimeInterval = -((recordCountConverted / 2) - 1) let endIndex: NSTimeInterval = startIndex + recordCountConverted let currentDate = NSDate(timeIntervalSinceNow: 0) for var i: NSTimeInterval = startIndex; i < endIndex; i++ { let dataPoint = JCMTimeSliderControlDataPoint(date: currentDate.dateByAddingTimeInterval(60*60*24*i), hasIcon: false) testDataSourceArray.append(dataPoint) } self.testDataSource = TimeSliderTestDataSource(data: testDataSourceArray) XCTAssertEqual(self.testDataSource.numberOfDates(), recordCount, "Data source record count '\(self.testDataSource.numberOfDates())' should match desired record count '\(recordCount)'") } // // Tests for 'findNearestDate' method with data source that has a given number of records // // NOTE: 'findNearestDate' is always expected to find the closest date in the past // func performTestFindNearestDate(recordCount: Int) { createTestDataSource(recordCount) let recordCountConverted = NSTimeInterval(recordCount) var testDataSourceArray = NSMutableArray() let startIndex: NSTimeInterval = -((recordCountConverted / 2) - 1) let endIndex: NSTimeInterval = startIndex + recordCountConverted let currentDate = NSDate(timeIntervalSinceNow: 0) // // Test exact and close matches // var j = 0 var targetDate: NSDate for var i: NSTimeInterval = startIndex; i < endIndex; i++ { // Target date is exact match targetDate = currentDate.dateByAddingTimeInterval(60*60*24*i); XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: targetDate), j, "Should match current index \(j)") // Target date is a close match: shifted 10 sec in the past targetDate = currentDate.dateByAddingTimeInterval(60*60*24*i - 10); XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: targetDate), j - 1 < 0 ? 0 : j - 1, "Should match previous index \(j)") // Target date is a close match: shifted 10 sec in the future targetDate = currentDate.dateByAddingTimeInterval(60*60*24*i + 10); XCTAssertEqual(self.tsu.findNearestDate(self.testDataSource, searchItem: targetDate), j, "Should match current index \(j)") // Move target index to the next record j++ } } }
mit
19287269667814003fc14cdd3e2a93a1
40.443182
192
0.635934
5.116801
false
true
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Post/PostEditor+MoreOptions.swift
1
5658
import Foundation import WordPressFlux extension PostEditor { func displayPostSettings() { let settingsViewController: PostSettingsViewController if post is Page { settingsViewController = PageSettingsViewController(post: post) } else { settingsViewController = PostSettingsViewController(post: post) } settingsViewController.featuredImageDelegate = self as? FeaturedImageDelegate settingsViewController.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(settingsViewController, animated: true) } private func createPostRevisionBeforePreview(completion: @escaping (() -> Void)) { let context = ContextManager.sharedInstance().mainContext context.performAndWait { post = self.post.createRevision() ContextManager.sharedInstance().save(context) completion() } } private func savePostBeforePreview(completion: @escaping ((String?, Error?) -> Void)) { let context = ContextManager.sharedInstance().mainContext let postService = PostService(managedObjectContext: context) if !post.hasUnsavedChanges() { completion(nil, nil) return } navigationBarManager.reloadTitleView(navigationBarManager.generatingPreviewTitleView) postService.autoSave(post, success: { [weak self] savedPost, previewURL in guard let self = self else { return } self.post = savedPost if self.post.isRevision() { ContextManager.sharedInstance().save(context) completion(previewURL, nil) } else { self.createPostRevisionBeforePreview() { completion(previewURL, nil) } } }) { error in //When failing to save a published post will result in "preview not available" DDLogError("Error while trying to save post before preview: \(String(describing: error))") completion(nil, error) } } private func displayPreviewNotAvailable(title: String, subtitle: String? = nil) { let noResultsController = NoResultsViewController.controllerWith(title: title, subtitle: subtitle) noResultsController.hidesBottomBarWhenPushed = true navigationController?.pushViewController(noResultsController, animated: true) } func displayPreview() { guard !isUploadingMedia else { displayMediaIsUploadingAlert() return } guard post.remoteStatus != .pushing else { displayPostIsUploadingAlert() return } savePostBeforePreview() { [weak self] previewURLString, error in guard let self = self else { return } let navigationBarManager = self.navigationBarManager navigationBarManager.reloadTitleView(navigationBarManager.blogTitleViewLabel) if error != nil { let title = NSLocalizedString("Preview Unavailable", comment: "Title on display preview error" ) self.displayPreviewNotAvailable(title: title) return } let previewController: PreviewWebKitViewController if let previewURLString = previewURLString, let previewURL = URL(string: previewURLString) { previewController = PreviewWebKitViewController(post: self.post, previewURL: previewURL, source: "edit_post_more_preview") } else { if self.post.permaLink == nil { DDLogError("displayPreview: Post permalink is unexpectedly nil") self.displayPreviewNotAvailable(title: NSLocalizedString("Preview Unavailable", comment: "Title on display preview error" )) return } previewController = PreviewWebKitViewController(post: self.post, source: "edit_post_more_preview") } previewController.trackOpenEvent() let navWrapper = LightNavigationController(rootViewController: previewController) if self.navigationController?.traitCollection.userInterfaceIdiom == .pad { navWrapper.modalPresentationStyle = .fullScreen } self.navigationController?.present(navWrapper, animated: true) } } func displayHistory() { let revisionsViewController = RevisionsTableViewController(post: post) { [weak self] revision in guard let post = self?.post.update(from: revision) else { return } // show the notice with undo button let notice = Notice(title: "Revision loaded", message: nil, feedbackType: .success, notificationInfo: nil, actionTitle: "Undo", cancelTitle: nil) { (happened) in guard happened else { return } DispatchQueue.main.async { guard let original = self?.post.original, let clone = self?.post.clone(from: original) else { return } self?.post = clone WPAnalytics.track(.postRevisionsLoadUndone) } } ActionDispatcher.dispatch(NoticeAction.post(notice)) DispatchQueue.main.async { self?.post = post } } navigationController?.pushViewController(revisionsViewController, animated: true) } }
gpl-2.0
8732586aa1863b68298d7f2b01f30204
38.84507
173
0.612761
5.881497
false
false
false
false
narner/AudioKit
AudioKit/Common/Nodes/Playback/Player/ClipPlayer/AKClipRecorder.swift
1
11016
// // AKClipRecorder.swift // AudioKit // // Created by David O'Neill on 5/8/17. // Copyright © 2017 Audive Inc. All rights reserved. // /// A closure that will be called when the clip is finished recording. If /// successful URL will be non-nil. If recording failed, Error will be non nil. The actual /// start time is included and should be checked in case it was adjusted. public typealias AKRecordingResult = (URL?, Double, Error?) -> Void open class AKClipRecorder { open var node: AKOutput private let timing: AKNodeTiming fileprivate var clips = [AKClipRecording]() /// Initialize a recorder with a node. /// /// - Parameter node: The node that audio will be recorded from /// @objc public init(node: AKOutput) { self.node = node timing = AKNodeTiming(node: node) node.outputNode.installTap(onBus: 0, bufferSize: 256, format: nil, block: self.audioTap) } deinit { node.outputNode.removeTap(onBus: 0) } /// Starts the internal timeline. open func play() { play(at: nil) } /// Starts the internal timeline from audioTime. /// /// - Parameter audioTime: An time in the audio render context. /// open func play(at audioTime: AVAudioTime?) { if isPlaying { return } for clip in clips where clip.endTime <= timing.currentTime { finalize(clip: clip, error: ClipRecordingError.timingError) } timing.play(at: audioTime) } /// The current time of the internal timeline. Setting will call stop(). open var currentTime: Double { get { return timing.currentTime } set { timing.currentTime = newValue } } /// Stops internal timeline and finalizes any clips that are recording. /// /// Will stop immediately, clips may finish recording after stop returns. /// /// - Parameter completion: a closure that will be called after all clips have benn finalized. /// open func stop(_ completion: (() -> Void)? = nil) { if !isPlaying { return } timing.stop() for clip in clips { finalize(clip: clip, error: nil, completion: completion) } } /// Sets recording end time for any recording clips. /// /// Playback continues. If clips have an endTime less than endTime, they will be unaffected. /// /// - Parameters /// - endTime: A time in the timeline that recording clips should end. /// - completion: A closure that will be called after all clips' endTime /// has been reached and they have benn finalized. /// open func stopRecording(endTime: Double? = nil, _ completion: (() -> Void)? = nil) { let clipEndTime = endTime ?? currentTime guard let completion = completion else { for clip in clips { clip.endTime = clipEndTime } return } if clips.isEmpty { completion() return } let group = DispatchGroup() for clip in clips { group.enter() clip.endTime = clipEndTime clip.completion = doAfter(result: clip.completion, action: { group.leave() }) } group.notify(queue: DispatchQueue.main, execute: completion) } private func doAfter(result: @escaping AKRecordingResult, action: @escaping () -> Void) -> AKRecordingResult { return { (url, time, error) in result(url, time, error) action() } } /// Is inner timeline playing. open var isPlaying: Bool { return timing.isPlaying } /// True if there are any clips recording. open var isRecording: Bool { return !clips.isEmpty } /// Schedule an audio clip to record. /// /// Clips are recorded to an audio file in the tmp directory, they are accessed when the /// completeion block is called, if no error. /// /// - Parameters /// - time: A time in the timeline that a clip should start recording, if timeline has /// surpassed the clip's start time, the start time will be adjusted. /// - duration: The duration in seconds of the clip to record, will be adjusted if start time /// was adjusted. /// - tap: An optional tap to access audio as it's being recorded. /// - completion: A closure that will be called when the clip is finished recording. If /// successful URL will be non-nil. If recording failed, Error will be non nil. The actual /// start time is included and should be checked in case it was adjusted. /// public func recordClip(time: Double = 0, duration: Double = Double.greatestFiniteMagnitude, tap: AVAudioNodeTapBlock? = nil, completion: @escaping AKRecordingResult) throws { guard time >= 0, duration > 0, time + duration > timing.currentTime else { throw ClipRecordingError.invalidParameters } let clipRecording = AKClipRecording(start: time, end: time + duration, audioFile: nil, completion: completion) clipRecording.tap = tap clips.append(clipRecording) } private func finalize(clip: AKClipRecording, error: Error? = nil, completion: (() -> Void)? = nil) { if let index = clips.index(of: clip) { clips.remove(at: index) } guard let audioFile = clip.audioFile, audioFile.length > 0 else { clip.completion(nil, 0, error ?? ClipRecordingError.clipIsEmpty) completion?() return } let url = audioFile.url if clip.audioTimeStart != nil, let audioFile = clip.audioFile, audioFile.length > 0 { clip.audioFile = nil clip.completion(url, clip.startTime, error) completion?() } else { clip.completion(nil, 0, error ?? ClipRecordingError.timingError) completion?() } if FileManager.default.fileExists(atPath: url.path) { do { try FileManager.default.removeItem(atPath: url.path) } catch let error { print(error) } } } // Audio tap that is set on node. private func audioTap(buffer: AVAudioPCMBuffer, audioTime: AVAudioTime) { if !timing.isPlaying { return } let timeIn = timing.time(atAudioTime: audioTime) let timeOut = timeIn + Double(buffer.frameLength) / buffer.format.sampleRate for clip in clips { if clip.startTime < timeOut && clip.endTime > timeIn { var adjustedBuffer = buffer var adjustedAudioTme = audioTime if clip.audioTimeStart == nil { clip.startTime = max(clip.startTime, timeIn) guard let audioTimeStart = timing.audioTime(atTime: clip.startTime) else { finalize(clip: clip, error: ClipRecordingError.timingError) continue } clip.audioTimeStart = audioTimeStart let timeOffset = clip.startTime - timeIn let sampleOffset = AVAudioFrameCount(timeOffset * buffer.format.sampleRate) if let partial = buffer.copyFrom(startSample: sampleOffset) { adjustedBuffer = partial } adjustedAudioTme = audioTimeStart } let lastBuffer = timeOut > clip.endTime if lastBuffer { let timeLeft = clip.endTime - timeIn let samplesLeft = AVAudioFrameCount(timeLeft * buffer.format.sampleRate) if let partial = buffer.copyTo(endSample: samplesLeft) { adjustedBuffer = partial } } do { try clip.record(buffer: adjustedBuffer, audioTime: adjustedAudioTme) } catch let error { finalize(clip: clip, error: error) } if lastBuffer { finalize(clip: clip, error: nil) } } } } } public enum ClipRecordingError: Error, LocalizedError { case timingError case invalidParameters case clipIsEmpty case formatError public var errorDescription: String? { switch self { case .timingError: return "Timing Error" case .invalidParameters: return "Invalid Parameters" case .clipIsEmpty: return "Clip is empty" case .formatError: return "Invalid format" } } } private class AKClipRecording: Equatable { var startTime: Double var endTime: Double var audioTimeStart: AVAudioTime? var audioFile: AKAudioFile? var completion: AKRecordingResult var tap: AVAudioNodeTapBlock? init(start: Double = 0, end: Double = Double.greatestFiniteMagnitude, audioFile: AKAudioFile? = nil, completion: @escaping AKRecordingResult) { startTime = start endTime = end var called = false self.completion = { (url: URL?, actualStart: Double, error: Error?) in if called { return } called = true completion(url, actualStart, error) } self.audioFile = audioFile } func record(buffer: AVAudioPCMBuffer, audioTime: AVAudioTime) throws { if audioFile == nil { let tmp = URL(fileURLWithPath: NSTemporaryDirectory()) let url = tmp.appendingPathComponent(UUID().uuidString).appendingPathExtension("caf").standardizedFileURL guard let fileFormat = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: AudioKit.format.sampleRate, channels: buffer.format.channelCount, interleaved: true) else { throw ClipRecordingError.formatError } audioFile = try AKAudioFile(forWriting: url, settings: fileFormat.settings, commonFormat: buffer.format.commonFormat, interleaved: buffer.format.isInterleaved) } try audioFile?.write(from: buffer) if let tap = self.tap { tap(buffer, audioTime) } } static public func == (a: AKClipRecording, b: AKClipRecording) -> Bool { return a === b } }
mit
bcbe0f0d4d9d4e3cf2ec6689631006ee
35.47351
117
0.563595
5.164088
false
false
false
false
lenssss/whereAmI
Whereami/Controller/Personal/PersonalEditAvatorViewController.swift
1
3931
// // PersonalEditAvatorViewController.swift // Whereami // // Created by A on 16/5/23. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit import DKImagePickerController public var KNotificationChangeAvatar: String { get{ return "KNotificationChangeAvatar"} } class PersonalEditAvatorViewController: UIViewController { var backImageView:UIImageView? = nil var imageString:String? = nil var asset:DKAsset? = nil override func viewDidLoad() { super.viewDidLoad() self.setConfig() self.title = NSLocalizedString("Avatar",tableName:"Localizable", comment: "") self.setUI() LNotificationCenter().rac_addObserverForName("KNotificationChangeAvatar", object: nil).subscribeNext { (notification) in let image = notification.object as! UIImage self.backImageView?.image = image } } func setUI(){ self.view.backgroundColor = UIColor.blackColor() let backBtn = TheBackBarButton.initWithAction({ self.pushBack() }) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("next",tableName:"Localizable", comment: ""), style: .Done, target: self, action: #selector(self.presentImagePicker)) self.backImageView = UIImageView() self.backImageView?.kf_setImageWithURL(NSURL(string:self.imageString!)!, placeholderImage: UIImage(named: "avator.png"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) self.view.addSubview(self.backImageView!) self.backImageView?.autoCenterInSuperview() self.backImageView?.autoSetDimensionsToSize(CGSize(width: LScreenW,height: LScreenW)) } func presentImagePicker(){ let pickerController = DKImagePickerController() pickerController.navigationBar.setBackgroundImage(UIImage.imageWithColor(UIColor.getNavigationBarColor()), forBarMetrics: UIBarMetrics.Default) UINavigationBar.appearance().titleTextAttributes = [ NSForegroundColorAttributeName : UIColor.whiteColor() ] pickerController.singleSelect = true pickerController.maxSelectableCount = 1 pickerController.assetType = .AllPhotos pickerController.didSelectAssets = { [unowned self] (assets: [DKAsset]) in print("didSelectAssets") self.asset = assets[0] } pickerController.didCancel = { () in if self.asset != nil { self.asset!.fetchFullScreenImageWithCompleteBlock({ (image, info) in self.runInMainQueue({ self.asset = nil self.performSelector(#selector(self.present2CropperViewController(_:)), withObject: image,afterDelay: 0.1) }) }) } } self.presentViewController(pickerController, animated: true, completion: nil) } func pushBack(){ let viewControllers = self.navigationController?.viewControllers let index = (viewControllers?.count)! - 2 let viewController = viewControllers![index] self.navigationController?.popToViewController(viewController, animated: false) } func present2CropperViewController(image:UIImage){ let viewController = PublishCropperViewController() viewController.photoImage = image viewController.type = editType.avator let nav = PhotoMainNavigationViewController(rootViewController: viewController) self.presentViewController(nav, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
13aaa7f45b87c38381d658efab4b152e
39.081633
208
0.664206
5.692754
false
false
false
false
castial/Quick-Start-iOS
Quick-Start-iOS/Vendors/HYRefresh/HYNormalRefresh.swift
1
1951
// // HYNormalRefresh.swift // Quick-Start-iOS // // Created by work on 2016/11/30. // Copyright © 2016年 hyyy. All rights reserved. // import UIKit public class HYNormalRefresh: UIView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ // 上次刷新时间缓存关键字 public var lastRefreshTimeKey: String? = "NormalRefreshKey" // 刷新完成之后是否自动隐藏, 默认为false public var isAutomaticlyHidden: Bool? = false // 上次刷新时间 public var lastRefreshTime: NSDate? = NSDate () override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.black } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension HYNormalRefresh: HYRefreshControl { public func refreshViewDidPrepare(refreshView: HYRefreshView, refreshType: HYRefreshType) { if refreshType == .header { print("下拉刷新准备开始") }else { print("上拉刷新准备开始") } } public func refreshDidBegin(refreshView: HYRefreshView, refreshType: HYRefreshType) { print("刷新开始") } public func refreshDidEnd(refreshView: HYRefreshView, refreshType: HYRefreshType) { print("下拉刷新结束") } public func refreshProgressDidChanged(refreshView: HYRefreshView, progress: CGFloat, refreshType: HYRefreshType) { print("刷新进度改为\(progress)") } public func refreshStateDidChanged(refreshView: HYRefreshView, fromState: HYRefreshStatus, toState: HYRefreshStatus, refreshType: HYRefreshType) { print("刷新从\(fromState)状态改变成\(toState)") } }
mit
9d67991d1f7545633cdf2cc768a39eae
27.634921
150
0.659091
4.432432
false
false
false
false
derekli66/Learning-Core-Audio-Swift-SampleCode
CH06_ExtAudioFileConverter-Swift/CH06_ExtAudioFileConverter-Swift/main.swift
1
4899
// // main.swift // CH06_ExtAudioFileConverter-Swift // // Created by LEE CHIEN-MING on 14/06/2017. // Copyright © 2017 derekli66. All rights reserved. // import Foundation import AudioToolbox private let kInputFileLocation = "/Users/derekli/bitbucket/shape_of_you.mp3" struct MyAudioConverterSettings { var outputFormat: AudioStreamBasicDescription = AudioStreamBasicDescription() var inputFile: ExtAudioFileRef? var outputFile: AudioFileID? } // MARK: - Audio Converter func Convert(_ mySettings: inout MyAudioConverterSettings) { let outputBufferSize: UInt32 = 32 * 1024 let sizePerPacket: UInt32 = mySettings.outputFormat.mBytesPerPacket let packetsPerBuffer: UInt32 = outputBufferSize / sizePerPacket // allocate destination buffer let outputBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(outputBufferSize)) outputBuffer.initialize(repeating: 0, count: Int(outputBufferSize)) var outputFilePacketPosition: UInt32 = 0 // in bytes while (true) { // wrap the destination buffer in an AudioBufferList let convertedData: UnsafeMutableAudioBufferListPointer = AudioBufferList.allocate(maximumBuffers: 1) convertedData[0].mNumberChannels = mySettings.outputFormat.mChannelsPerFrame convertedData[0].mDataByteSize = outputBufferSize convertedData[0].mData = UnsafeMutableRawPointer(outputBuffer) var frameCount = packetsPerBuffer guard let inputFile = mySettings.inputFile else { debugPrint("No input source provided. Please specify one before converting audio file") break } // Read from the extaudio file CheckError(ExtAudioFileRead(inputFile, &frameCount, convertedData.unsafeMutablePointer), "Couldn't read from input file") if (0 == frameCount) { debugPrint("done reading from file") return } guard let outputFile = mySettings.outputFile else { debugPrint("There is no outputFile before converting audio file") return; } // write the converted data to the output file CheckError(AudioFileWritePackets(outputFile, false, frameCount * mySettings.outputFormat.mBytesPerPacket, // Weird part nil, Int64(outputFilePacketPosition / mySettings.outputFormat.mBytesPerPacket), &frameCount, convertedData[0].mData!), "Couldn't write packets to file") // advance the output file write location outputFilePacketPosition += (frameCount * mySettings.outputFormat.mBytesPerPacket) // free memory of AudioBufferList pointer free(convertedData.unsafeMutablePointer) } outputBuffer.deinitialize(count: Int(packetsPerBuffer)) outputBuffer.deallocate() } var audioConverterSettings = MyAudioConverterSettings() // open the input with ExtAudioFile let inputFileURLRef = URL(fileURLWithPath: kInputFileLocation) as CFURL CheckError(ExtAudioFileOpenURL(inputFileURLRef, &audioConverterSettings.inputFile), "ExtAudioFileOpenURL failed") // define the output format. AudioConverter requires that one of the data formats be LPCM audioConverterSettings.outputFormat.mSampleRate = 44100.0 audioConverterSettings.outputFormat.mFormatID = kAudioFormatLinearPCM audioConverterSettings.outputFormat.mFormatFlags = kAudioFormatFlagIsBigEndian | kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked audioConverterSettings.outputFormat.mBytesPerPacket = 4 audioConverterSettings.outputFormat.mFramesPerPacket = 1 audioConverterSettings.outputFormat.mBytesPerFrame = 4 audioConverterSettings.outputFormat.mChannelsPerFrame = 2 audioConverterSettings.outputFormat.mBitsPerChannel = 16 // create output file let outputFileURLRef = URL(fileURLWithPath: "output.aif") as CFURL CheckError(AudioFileCreateWithURL(outputFileURLRef, kAudioFileAIFFType, &audioConverterSettings.outputFormat, AudioFileFlags.eraseFile, &audioConverterSettings.outputFile), "AudioFileCreateWithURL failed") CheckError(ExtAudioFileSetProperty(audioConverterSettings.inputFile!, kExtAudioFileProperty_ClientDataFormat, UInt32(Int(MemoryLayout<AudioStreamBasicDescription>.size)), &audioConverterSettings.outputFormat), "Couldn't set client data format on input ext file") debugPrint("Converting...") Convert(&audioConverterSettings) ExtAudioFileDispose(audioConverterSettings.inputFile!) AudioFileClose(audioConverterSettings.outputFile!)
mit
b71a008dd94a71084a0e2e64cf300b10
39.816667
139
0.699673
5.908323
false
false
false
false
vishw3/IOSChart-IOS-7.0-Support
VisChart/Classes/Data/ChartData.swift
3
21804
// // ChartData.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartData: NSObject { internal var _yMax = Float(0.0) internal var _yMin = Float(0.0) internal var _leftAxisMax = Float(0.0) internal var _leftAxisMin = Float(0.0) internal var _rightAxisMax = Float(0.0) internal var _rightAxisMin = Float(0.0) private var _yValueSum = Float(0.0) private var _yValCount = Int(0) /// the average length (in characters) across all x-value strings private var _xValAverageLength = Float(0.0) internal var _xVals: [String]! internal var _dataSets: [ChartDataSet]! public override init() { super.init(); _xVals = [String](); _dataSets = [ChartDataSet](); } public init(xVals: [String]?) { super.init(); _xVals = xVals == nil ? [String]() : xVals; _dataSets = [ChartDataSet](); self.initialize(_dataSets); } public convenience init(xVals: [String]?, dataSet: ChartDataSet?) { self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]); } public init(xVals: [String]?, dataSets: [ChartDataSet]?) { super.init() _xVals = xVals == nil ? [String]() : xVals; _dataSets = dataSets == nil ? [ChartDataSet]() : dataSets; self.initialize(_dataSets) } internal func initialize(dataSets: [ChartDataSet]) { checkIsLegal(dataSets); calcMinMax(); calcYValueSum(); calcYValueCount(); calcXValAverageLength() } // calculates the average length (in characters) across all x-value strings internal func calcXValAverageLength() { if (_xVals.count == 0) { _xValAverageLength = 1; return; } var sum = 1; for (var i = 0; i < _xVals.count; i++) { sum += _xVals[i].lengthOfBytesUsingEncoding(NSUTF16StringEncoding); } _xValAverageLength = Float(sum) / Float(_xVals.count); } // Checks if the combination of x-values array and DataSet array is legal or not. // :param: dataSets internal func checkIsLegal(dataSets: [ChartDataSet]!) { if (dataSets == nil) { return; } for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].yVals.count > _xVals.count) { println("One or more of the DataSet Entry arrays are longer than the x-values array of this Data object."); return; } } } public func notifyDataChanged() { initialize(_dataSets); } /// calc minimum and maximum y value over all datasets internal func calcMinMax() { if (_dataSets == nil || _dataSets.count < 1) { _yMax = 0.0; _yMin = 0.0; } else { // calculate absolute min and max _yMin = _dataSets[0].yMin; _yMax = _dataSets[0].yMax; for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i].yMin < _yMin) { _yMin = _dataSets[i].yMin; } if (_dataSets[i].yMax > _yMax) { _yMax = _dataSets[i].yMax; } } // left axis var firstLeft = getFirstLeft(); if (firstLeft !== nil) { _leftAxisMax = firstLeft!.yMax; _leftAxisMin = firstLeft!.yMin; for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { if (dataSet.yMin < _leftAxisMin) { _leftAxisMin = dataSet.yMin; } if (dataSet.yMax > _leftAxisMax) { _leftAxisMax = dataSet.yMax; } } } } // right axis var firstRight = getFirstRight(); if (firstRight !== nil) { _rightAxisMax = firstRight!.yMax; _rightAxisMin = firstRight!.yMin; for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { if (dataSet.yMin < _rightAxisMin) { _rightAxisMin = dataSet.yMin; } if (dataSet.yMax > _rightAxisMax) { _rightAxisMax = dataSet.yMax; } } } } // in case there is only one axis, adjust the second axis handleEmptyAxis(firstLeft, firstRight: firstRight); } } /// calculates the sum of all y-values in all datasets internal func calcYValueSum() { _yValueSum = 0; if (_dataSets == nil) { return; } for (var i = 0; i < _dataSets.count; i++) { _yValueSum += fabsf(_dataSets[i].yValueSum); } } /// Calculates the total number of y-values across all ChartDataSets the ChartData represents. internal func calcYValueCount() { _yValCount = 0; if (_dataSets == nil) { return; } var count = 0; for (var i = 0; i < _dataSets.count; i++) { count += _dataSets[i].entryCount; } _yValCount = count; } /// returns the number of LineDataSets this object contains public var dataSetCount: Int { if (_dataSets == nil) { return 0; } return _dataSets.count; } /// returns the smallest y-value the data object contains. public var yMin: Float { return _yMin; } public func getYMin() -> Float { return _yMin; } public func getYMin(axis: ChartYAxis.AxisDependency) -> Float { if (axis == .Left) { return _leftAxisMin; } else { return _rightAxisMin; } } /// returns the greatest y-value the data object contains. public var yMax: Float { return _yMax; } public func getYMax() -> Float { return _yMax; } public func getYMax(axis: ChartYAxis.AxisDependency) -> Float { if (axis == .Left) { return _leftAxisMax; } else { return _rightAxisMax; } } /// returns the average length (in characters) across all values in the x-vals array public var xValAverageLength: Float { return _xValAverageLength; } /// returns the total y-value sum across all DataSet objects the this object represents. public var yValueSum: Float { return _yValueSum; } /// Returns the total number of y-values across all DataSet objects the this object represents. public var yValCount: Int { return _yValCount; } /// returns the x-values the chart represents public var xVals: [String] { return _xVals; } ///Adds a new x-value to the chart data. public func addXValue(xVal: String) { _xVals.append(xVal); } /// Removes the x-value at the specified index. public func removeXValue(index: Int) { _xVals.removeAtIndex(index); } /// Returns the array of ChartDataSets this object holds. public var dataSets: [ChartDataSet] { get { return _dataSets; } set { _dataSets = newValue; } } /// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not. /// IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations. /// /// :param: dataSets the DataSet array to search /// :param: type /// :param: ignorecase if true, the search is not case-sensitive /// :returns: internal func getDataSetIndexByLabel(label: String, ignorecase: Bool) -> Int { if (ignorecase) { for (var i = 0; i < dataSets.count; i++) { if (label.caseInsensitiveCompare(dataSets[i].label) == NSComparisonResult.OrderedSame) { return i; } } } else { for (var i = 0; i < dataSets.count; i++) { if (label == dataSets[i].label) { return i; } } } return -1; } /// returns the total number of x-values this ChartData object represents (the size of the x-values array) public var xValCount: Int { return _xVals.count; } /// Returns the labels of all DataSets as a string array. internal func dataSetLabels() -> [String] { var types = [String](); for (var i = 0; i < _dataSets.count; i++) { types[i] = _dataSets[i].label; } return types; } /// Get the Entry for a corresponding highlight object /// /// :param: highlight /// :returns: the entry that is highlighted public func getEntryForHighlight(highlight: ChartHighlight) -> ChartDataEntry { return _dataSets[highlight.dataSetIndex].entryForXIndex(highlight.xIndex); } /// Returns the DataSet object with the given label. /// sensitive or not. /// IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations. /// /// :param: label /// :param: ignorecase public func getDataSetByLabel(label: String, ignorecase: Bool) -> ChartDataSet? { var index = getDataSetIndexByLabel(label, ignorecase: ignorecase); if (index < 0 || index >= _dataSets.count) { return nil; } else { return _dataSets[index]; } } public func getDataSetByIndex(index: Int) -> ChartDataSet! { if (_dataSets == nil || index < 0 || index >= _dataSets.count) { return nil; } return _dataSets[index]; } public func addDataSet(d: ChartDataSet!) { if (_dataSets == nil) { return; } _yValCount += d.entryCount; _yValueSum += d.yValueSum; if (_dataSets.count == 0) { _yMax = d.yMax; _yMin = d.yMin; if (d.axisDependency == .Left) { _leftAxisMax = d.yMax; _leftAxisMin = d.yMin; } else { _rightAxisMax = d.yMax; _rightAxisMin = d.yMin; } } else { if (_yMax < d.yMax) { _yMax = d.yMax; } if (_yMin > d.yMin) { _yMin = d.yMin; } if (d.axisDependency == .Left) { if (_leftAxisMax < d.yMax) { _leftAxisMax = d.yMax; } if (_leftAxisMin > d.yMin) { _leftAxisMin = d.yMin; } } else { if (_rightAxisMax < d.yMax) { _rightAxisMax = d.yMax; } if (_rightAxisMin > d.yMin) { _rightAxisMin = d.yMin; } } } _dataSets.append(d); handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()); } public func handleEmptyAxis(firstLeft: ChartDataSet?, firstRight: ChartDataSet?) { // in case there is only one axis, adjust the second axis if (firstLeft === nil) { _leftAxisMax = _rightAxisMax; _leftAxisMin = _rightAxisMin; } else if (firstRight === nil) { _rightAxisMax = _leftAxisMax; _rightAxisMin = _leftAxisMin; } } /// Removes the given DataSet from this data object. /// Also recalculates all minimum and maximum values. /// /// :returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSet(dataSet: ChartDataSet!) -> Bool { if (_dataSets == nil || dataSet === nil) { return false; } var removed = false; for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return removeDataSetByIndex(i); } } return false; } /// Removes the DataSet at the given index in the DataSet array from the data object. /// Also recalculates all minimum and maximum values. /// /// :returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSetByIndex(index: Int) -> Bool { if (_dataSets == nil || index >= _dataSets.count || index < 0) { return false; } var d = _dataSets.removeAtIndex(index); _yValCount -= d.entryCount; _yValueSum -= d.yValueSum; calcMinMax(); return true; } /// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list. public func addEntry(e: ChartDataEntry, dataSetIndex: Int) { if (_dataSets != nil && _dataSets.count > dataSetIndex && dataSetIndex >= 0) { var val = e.value; _yValCount += 1; _yValueSum += val; if (_yMax < val) { _yMax = val; } if (_yMin > val) { _yMin = val; } var set = _dataSets[dataSetIndex]; if (set.axisDependency == .Left) { if (_leftAxisMax < e.value) { _leftAxisMax = e.value; } if (_leftAxisMin > e.value) { _leftAxisMin = e.value; } } else { if (_rightAxisMax < e.value) { _rightAxisMax = e.value; } if (_rightAxisMin > e.value) { _rightAxisMin = e.value; } } handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()); set.addEntry(e); } else { println("ChartData.addEntry() - dataSetIndex our of range."); } } /// Removes the given Entry object from the DataSet at the specified index. public func removeEntry(entry: ChartDataEntry!, dataSetIndex: Int) -> Bool { // entry null, outofbounds if (entry === nil || dataSetIndex >= _dataSets.count) { return false; } // remove the entry from the dataset var removed = _dataSets[dataSetIndex].removeEntry(xIndex: entry.xIndex); if (removed) { var val = entry.value; _yValCount -= 1; _yValueSum -= val; calcMinMax(); } return removed; } /// Removes the Entry object at the given xIndex from the ChartDataSet at the /// specified index. Returns true if an entry was removed, false if no Entry /// was found that meets the specified requirements. public func removeEntryByXIndex(xIndex: Int, dataSetIndex: Int) -> Bool { if (dataSetIndex >= _dataSets.count) { return false; } var entry = _dataSets[dataSetIndex].entryForXIndex(xIndex); return removeEntry(entry, dataSetIndex: dataSetIndex); } /// Returns the DataSet that contains the provided Entry, or null, if no DataSet contains this entry. public func getDataSetForEntry(e: ChartDataEntry!) -> ChartDataSet? { if (e == nil) { return nil; } for (var i = 0; i < _dataSets.count; i++) { var set = _dataSets[i]; for (var j = 0; j < set.entryCount; j++) { if (e === set.entryForXIndex(e.xIndex)) { return set; } } } return nil; } /// Returns the index of the provided DataSet inside the DataSets array of /// this data object. Returns -1 if the DataSet was not found. public func indexOfDataSet(dataSet: ChartDataSet) -> Int { for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return i; } } return -1; } public func getFirstLeft() -> ChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { return dataSet; } } return nil; } public func getFirstRight() -> ChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { return dataSet; } } return nil; } /// Returns all colors used across all DataSet objects this object represents. public func getColors() -> [UIColor]? { if (_dataSets == nil) { return nil; } var clrcnt = 0; for (var i = 0; i < _dataSets.count; i++) { clrcnt += _dataSets[i].colors.count; } var colors = [UIColor](); for (var i = 0; i < _dataSets.count; i++) { var clrs = _dataSets[i].colors; for clr in clrs { colors.append(clr); } } return colors; } /// Generates an x-values array filled with numbers in range specified by the parameters. Can be used for convenience. public func generateXVals(from: Int, to: Int) -> [String] { var xvals = [String](); for (var i = from; i < to; i++) { xvals.append(String(i)); } return xvals; } /// Sets a custom ValueFormatter for all DataSets this data object contains. public func setValueFormatter(formatter: NSNumberFormatter!) { for set in dataSets { set.valueFormatter = formatter; } } /// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains. public func setValueTextColor(color: UIColor!) { for set in dataSets { set.valueTextColor = color ?? set.valueTextColor; } } /// Sets the font for all value-labels for all DataSets this data object contains. public func setValueFont(font: UIFont!) { for set in dataSets { set.valueFont = font ?? set.valueFont; } } /// Enables / disables drawing values (value-text) for all DataSets this data object contains. public func setDrawValues(enabled: Bool) { for set in dataSets { set.drawValuesEnabled = enabled; } } /// Clears this data object from all DataSets and removes all Entries. public func clearValues() { dataSets.removeAll(keepCapacity: false); notifyDataChanged(); } /// Checks if this data object contains the specified Entry. Returns true if so, false if not. public func contains(#entry: ChartDataEntry) -> Bool { for set in dataSets { if (set.contains(entry)) { return true; } } return false; } /// Checks if this data object contains the specified DataSet. Returns true if so, false if not. public func contains(#dataSet: ChartDataSet) -> Bool { for set in dataSets { if (set.isEqual(dataSet)) { return true; } } return false; } }
mit
70ea8e97168c6702688f56417d64bedc
25.238267
128
0.475509
5.064808
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/ApplePlatform/ImageIO/CGImageSource.swift
1
10633
// // CGImageSource.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. // #if canImport(CoreGraphics) && canImport(ImageIO) struct _CGImageSourceImageRepBase: CGImageRepBase { let source: CGImageSource let index: Int let numberOfPages: Int init(source: CGImageSource, index: Int, numberOfPages: Int) { self.source = source self.index = index self.numberOfPages = numberOfPages } init?(source: CGImageSource) { self.source = source self.index = 0 self.numberOfPages = CGImageSourceGetCount(source) guard numberOfPages > 0 else { return nil } } var general_properties: [CFString: Any] { return CGImageSourceCopyProperties(source, nil) as? [CFString: Any] ?? [:] } var properties: [CFString: Any] { return CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? [CFString: Any] ?? [:] } var orientation: Int { let orientation = properties[kCGImagePropertyOrientation] as? NSNumber return orientation?.intValue ?? 1 } var _width: Int { let width = properties[kCGImagePropertyPixelWidth] as? NSNumber return width?.intValue ?? 0 } var _height: Int { let height = properties[kCGImagePropertyPixelHeight] as? NSNumber return height?.intValue ?? 0 } var width: Int { return 1...4 ~= orientation ? _width : _height } var height: Int { return 1...4 ~= orientation ? _height : _width } var _resolution: Resolution { let properties = self.properties if let resolutionX = properties[kCGImagePropertyDPIWidth] as? NSNumber, let resolutionY = properties[kCGImagePropertyDPIHeight] as? NSNumber { return Resolution(horizontal: resolutionX.doubleValue, vertical: resolutionY.doubleValue, unit: .inch) } if let properties = properties[kCGImagePropertyTIFFDictionary] as? [CFString: Any] { guard let resolutionUnit = (properties[kCGImagePropertyTIFFResolutionUnit] as? NSNumber)?.intValue else { return .default } let resolutionX = properties[kCGImagePropertyTIFFXResolution] as? NSNumber let resolutionY = properties[kCGImagePropertyTIFFYResolution] as? NSNumber switch resolutionUnit { case 1: return Resolution(horizontal: resolutionX?.doubleValue ?? 0, vertical: resolutionY?.doubleValue ?? 0, unit: .point) case 2: return Resolution(horizontal: resolutionX?.doubleValue ?? 0, vertical: resolutionY?.doubleValue ?? 0, unit: .inch) case 3: return Resolution(horizontal: resolutionX?.doubleValue ?? 0, vertical: resolutionY?.doubleValue ?? 0, unit: .centimeter) default: return .default } } if let properties = properties[kCGImagePropertyJFIFDictionary] as? [CFString: Any] { guard let resolutionUnit = (properties[kCGImagePropertyJFIFDensityUnit] as? NSNumber)?.intValue else { return .default } let resolutionX = properties[kCGImagePropertyJFIFXDensity] as? NSNumber let resolutionY = properties[kCGImagePropertyJFIFYDensity] as? NSNumber switch resolutionUnit { case 1: return Resolution(horizontal: resolutionX?.doubleValue ?? 0, vertical: resolutionY?.doubleValue ?? 0, unit: .point) case 2: return Resolution(horizontal: resolutionX?.doubleValue ?? 0, vertical: resolutionY?.doubleValue ?? 0, unit: .inch) case 3: return Resolution(horizontal: resolutionX?.doubleValue ?? 0, vertical: resolutionY?.doubleValue ?? 0, unit: .centimeter) default: return .default } } if let properties = properties[kCGImagePropertyPNGDictionary] as? [CFString: Any] { let resolutionX = properties[kCGImagePropertyPNGXPixelsPerMeter] as? NSNumber let resolutionY = properties[kCGImagePropertyPNGYPixelsPerMeter] as? NSNumber return Resolution(horizontal: resolutionX?.doubleValue ?? 0, vertical: resolutionY?.doubleValue ?? 0, unit: .meter) } return .default } var resolution: Resolution { let resolution = self._resolution return 1...4 ~= orientation ? resolution : Resolution(horizontal: resolution.vertical, vertical: resolution.horizontal, unit: resolution.unit) } var mediaType: MediaType? { return CGImageSourceGetType(source).map { MediaType(rawValue: $0 as String) } } func page(_ index: Int) -> CGImageRepBase { return _CGImageSourceImageRepBase(source: source, index: index, numberOfPages: 1) } var cgImage: CGImage? { return CGImageSourceCreateImageAtIndex(source, index, nil) } func auxiliaryDataInfo(_ type: String) -> [String: AnyObject]? { return CGImageSourceCopyAuxiliaryDataInfoAtIndex(source, index, type as CFString) as? [String: AnyObject] } func copy(to destination: CGImageDestination, properties: [CFString: Any]) { CGImageDestinationAddImageFromSource(destination, source, index, properties as CFDictionary) } var isAnimated: Bool { return _repeats != nil } var _repeats: Int? { let general_properties = self.general_properties if let properties = general_properties[kCGImagePropertyGIFDictionary] as? [CFString: Any] { return (properties[kCGImagePropertyGIFLoopCount] as? NSNumber)?.intValue } if let properties = general_properties[kCGImagePropertyPNGDictionary] as? [CFString: Any] { return (properties[kCGImagePropertyAPNGLoopCount] as? NSNumber)?.intValue } if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { if let properties = general_properties[kCGImagePropertyHEICSDictionary] as? [CFString: Any] { return (properties[kCGImagePropertyHEICSLoopCount] as? NSNumber)?.intValue } } return nil } var repeats: Int { return _repeats ?? 0 } var duration: Double { let general_properties = self.general_properties let properties = self.properties if let properties = properties[kCGImagePropertyGIFDictionary] as? [CFString: Any], let duration = (properties[kCGImagePropertyGIFDelayTime] as? NSNumber)?.doubleValue { return duration } if let properties = general_properties[kCGImagePropertyGIFDictionary] as? [CFString: Any], let duration = (properties[kCGImagePropertyGIFDelayTime] as? NSNumber)?.doubleValue { return duration } if let properties = properties[kCGImagePropertyPNGDictionary] as? [CFString: Any], let duration = (properties[kCGImagePropertyAPNGDelayTime] as? NSNumber)?.doubleValue { return duration } if let properties = general_properties[kCGImagePropertyPNGDictionary] as? [CFString: Any], let duration = (properties[kCGImagePropertyAPNGDelayTime] as? NSNumber)?.doubleValue { return duration } if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { if let properties = properties[kCGImagePropertyHEICSDictionary] as? [CFString: Any], let duration = (properties[kCGImagePropertyHEICSDelayTime] as? NSNumber)?.doubleValue { return duration } if let properties = general_properties[kCGImagePropertyHEICSDictionary] as? [CFString: Any], let duration = (properties[kCGImagePropertyHEICSDelayTime] as? NSNumber)?.doubleValue { return duration } } return 0 } } struct _CGImageRepBase: CGImageRepBase { let image: CGImage let resolution: Resolution var width: Int { return image.width } var height: Int { return image.height } var mediaType: MediaType? { return nil } var numberOfPages: Int { return 1 } var general_properties: [CFString: Any] { return [:] } var properties: [CFString: Any] { return [:] } func page(_ index: Int) -> CGImageRepBase { precondition(index == 0, "Index out of range.") return self } var cgImage: CGImage? { return image } func auxiliaryDataInfo(_ type: String) -> [String: AnyObject]? { return nil } func copy(to destination: CGImageDestination, properties: [CFString: Any]) { var properties = properties let resolution = self.resolution.convert(to: .inch) properties[kCGImagePropertyDPIWidth] = resolution.horizontal properties[kCGImagePropertyDPIHeight] = resolution.vertical CGImageDestinationAddImage(destination, image, properties as CFDictionary) } var isAnimated: Bool { return false } var repeats: Int { return 0 } var duration: Double { return 0 } } #endif
mit
69e7719ccd72d3fc0fd08c4a58ec42a4
35.539519
150
0.632465
5.240513
false
false
false
false
mikaelm1/Teach-Me-Fast
Teach Me Fast/SweetAlert.swift
1
24714
// // SweetAlert.swift // SweetAlert // // Created by Codester on 11/3/14. // Copyright (c) 2014 Codester. All rights reserved. // import Foundation import UIKit import QuartzCore public enum AlertStyle { case success,error,warning,none case customImag(imageFile:String) } public class SweetAlert: UIViewController { let kBakcgroundTansperancy: CGFloat = 0.7 let kHeightMargin: CGFloat = 10.0 let KTopMargin: CGFloat = 20.0 let kWidthMargin: CGFloat = 10.0 let kAnimatedViewHeight: CGFloat = 70.0 let kMaxHeight: CGFloat = 300.0 var kContentWidth: CGFloat = 300.0 let kButtonHeight: CGFloat = 35.0 var textViewHeight: CGFloat = 90.0 let kTitleHeight:CGFloat = 30.0 var strongSelf:SweetAlert? var contentView = UIView() var titleLabel: UILabel = UILabel() var buttons: [UIButton] = [] var animatedView: AnimatableView? var imageView:UIImageView? var subTitleTextView = UITextView() var userAction:((isOtherButton: Bool) -> Void)? = nil let kFont = "Helvetica" init() { super.init(nibName: nil, bundle: nil) self.view.frame = UIScreen.main().bounds self.view.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth] self.view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:kBakcgroundTansperancy) self.view.addSubview(contentView) //Retaining itself strongly so can exist without strong refrence strongSelf = self } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupContentView() { contentView.backgroundColor = UIColor(white: 1.0, alpha: 1.0) contentView.layer.cornerRadius = 5.0 contentView.layer.masksToBounds = true contentView.layer.borderWidth = 0.5 contentView.addSubview(titleLabel) contentView.addSubview(subTitleTextView) contentView.backgroundColor = UIColor.colorFromRGB(0xFFFFFF) // TODO: Change colors here //contentView.backgroundColor = UIColor.redColor() contentView.layer.borderColor = UIColor.colorFromRGB(0xCCCCCC).cgColor view.addSubview(contentView) } private func setupTitleLabel() { titleLabel.text = "" titleLabel.numberOfLines = 1 titleLabel.textAlignment = .center titleLabel.font = UIFont(name: kFont, size:25) titleLabel.textColor = UIColor.colorFromRGB(0x575757) } private func setupSubtitleTextView() { subTitleTextView.text = "" subTitleTextView.textAlignment = .center subTitleTextView.font = UIFont(name: kFont, size:16) subTitleTextView.textColor = UIColor.colorFromRGB(0x797979) subTitleTextView.isEditable = false } private func resizeAndRelayout() { let mainScreenBounds = UIScreen.main().bounds self.view.frame.size = mainScreenBounds.size let x: CGFloat = kWidthMargin var y: CGFloat = KTopMargin let width: CGFloat = kContentWidth - (kWidthMargin*2) if animatedView != nil { animatedView!.frame = CGRect(x: (kContentWidth - kAnimatedViewHeight) / 2.0, y: y, width: kAnimatedViewHeight, height: kAnimatedViewHeight) contentView.addSubview(animatedView!) y += kAnimatedViewHeight + kHeightMargin } if imageView != nil { imageView!.frame = CGRect(x: (kContentWidth - kAnimatedViewHeight) / 2.0, y: y, width: kAnimatedViewHeight, height: kAnimatedViewHeight) contentView.addSubview(imageView!) y += imageView!.frame.size.height + kHeightMargin } // Title if self.titleLabel.text != nil { titleLabel.frame = CGRect(x: x, y: y, width: width, height: kTitleHeight) contentView.addSubview(titleLabel) y += kTitleHeight + kHeightMargin } // Subtitle if self.subTitleTextView.text.isEmpty == false { let subtitleString = subTitleTextView.text! as NSString let rect = subtitleString.boundingRect(with: CGSize(width: width, height: 0.0), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:subTitleTextView.font!], context: nil) textViewHeight = ceil(rect.size.height) + 10.0 subTitleTextView.frame = CGRect(x: x, y: y, width: width, height: textViewHeight) contentView.addSubview(subTitleTextView) y += textViewHeight + kHeightMargin } var buttonRect:[CGRect] = [] for button in buttons { let string = button.title(for: UIControlState())! as NSString buttonRect.append(string.boundingRect(with: CGSize(width: width, height:0.0), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:[NSFontAttributeName:button.titleLabel!.font], context:nil)) } var totalWidth: CGFloat = 0.0 if buttons.count == 2 { totalWidth = buttonRect[0].size.width + buttonRect[1].size.width + kWidthMargin + 40.0 } else{ totalWidth = buttonRect[0].size.width + 20.0 } y += kHeightMargin var buttonX = (kContentWidth - totalWidth ) / 2.0 for i in 0 ..< buttons.count { buttons[i].frame = CGRect(x: buttonX, y: y, width: buttonRect[i].size.width + 20.0, height: buttonRect[i].size.height + 10.0) buttonX = buttons[i].frame.origin.x + kWidthMargin + buttonRect[i].size.width + 20.0 buttons[i].layer.cornerRadius = 5.0 self.contentView.addSubview(buttons[i]) buttons[i].addTarget(self, action: "pressed:", for: UIControlEvents.touchUpInside) } y += kHeightMargin + buttonRect[0].size.height + 10.0 if y > kMaxHeight { let diff = y - kMaxHeight let sFrame = subTitleTextView.frame subTitleTextView.frame = CGRect(x: sFrame.origin.x, y: sFrame.origin.y, width: sFrame.width, height: sFrame.height - diff) for button in buttons { let bFrame = button.frame button.frame = CGRect(x: bFrame.origin.x, y: bFrame.origin.y - diff, width: bFrame.width, height: bFrame.height) } y = kMaxHeight } contentView.frame = CGRect(x: (mainScreenBounds.size.width - kContentWidth) / 2.0, y: (mainScreenBounds.size.height - y) / 2.0, width: kContentWidth, height: y) contentView.clipsToBounds = true } public func pressed(_ sender: UIButton!) { self.closeAlert(sender.tag) } public override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() var sz = UIScreen.main().bounds.size let sver = UIDevice.current().systemVersion as NSString let ver = sver.floatValue if ver < 8.0 { // iOS versions before 7.0 did not switch the width and height on device roration if UIInterfaceOrientationIsLandscape(UIApplication.shared().statusBarOrientation) { let ssz = sz sz = CGSize(width:ssz.height, height:ssz.width) } } self.resizeAndRelayout() } func closeAlert(_ buttonIndex:Int){ if userAction != nil { let isOtherButton = buttonIndex == 0 ? true: false SweetAlertContext.shouldNotAnimate = true userAction!(isOtherButton: isOtherButton) SweetAlertContext.shouldNotAnimate = false } UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in self.view.alpha = 0.0 }) { (Bool) -> Void in self.view.removeFromSuperview() self.cleanUpAlert() //Releasing strong refrence of itself. self.strongSelf = nil } } func cleanUpAlert() { if self.animatedView != nil { self.animatedView!.removeFromSuperview() self.animatedView = nil } self.contentView.removeFromSuperview() self.contentView = UIView() } public func showAlert(_ title: String) -> SweetAlert { _ = self.showAlert(title, subTitle: nil, style: .none) return self } public func showAlert(_ title: String, subTitle: String?, style: AlertStyle) -> SweetAlert { _ = self.showAlert(title, subTitle: subTitle, style: style, buttonTitle: "OK") return self } public func showAlert(_ title: String, subTitle: String?, style: AlertStyle,buttonTitle: String, action: ((isOtherButton: Bool) -> Void)? = nil) -> SweetAlert { _ = self.showAlert(title, subTitle: subTitle, style: style, buttonTitle: buttonTitle,buttonColor: UIColor.colorFromRGB(0xAEDEF4)) userAction = action return self } public func showAlert(_ title: String, subTitle: String?, style: AlertStyle,buttonTitle: String,buttonColor: UIColor,action: ((isOtherButton: Bool) -> Void)? = nil) -> SweetAlert { _ = self.showAlert(title, subTitle: subTitle, style: style, buttonTitle: buttonTitle,buttonColor: buttonColor,otherButtonTitle: nil) userAction = action return self } public func showAlert(_ title: String, subTitle: String?, style: AlertStyle,buttonTitle: String,buttonColor: UIColor,otherButtonTitle: String?, action: ((isOtherButton: Bool) -> Void)? = nil) -> SweetAlert { self.showAlert(title, subTitle: subTitle, style: style, buttonTitle: buttonTitle,buttonColor: buttonColor,otherButtonTitle: otherButtonTitle,otherButtonColor: UIColor.red()) userAction = action return self } public func showAlert(_ title: String, subTitle: String?, style: AlertStyle,buttonTitle: String,buttonColor: UIColor,otherButtonTitle: String?, otherButtonColor: UIColor?,action: ((isOtherButton: Bool) -> Void)? = nil) { userAction = action let window: UIWindow = UIApplication.shared().keyWindow! window.addSubview(view) window.bringSubview(toFront: view) view.frame = window.bounds self.setupContentView() self.setupTitleLabel() self.setupSubtitleTextView() switch style { case .success: self.animatedView = SuccessAnimatedView() case .error: self.animatedView = CancelAnimatedView() case .warning: self.animatedView = InfoAnimatedView() case let .customImag(imageFile): if let image = UIImage(named: imageFile) { self.imageView = UIImageView(image: image) } case .none: self.animatedView = nil } self.titleLabel.text = title if subTitle != nil { self.subTitleTextView.text = subTitle } buttons = [] if buttonTitle.isEmpty == false { let button: UIButton = UIButton(type: UIButtonType.custom) button.setTitle(buttonTitle, for: UIControlState()) button.backgroundColor = buttonColor button.isUserInteractionEnabled = true button.tag = 0 buttons.append(button) } if otherButtonTitle != nil && otherButtonTitle!.isEmpty == false { let button: UIButton = UIButton(type: UIButtonType.custom) button.setTitle(otherButtonTitle, for: UIControlState()) button.backgroundColor = otherButtonColor button.addTarget(self, action: "pressed:", for: UIControlEvents.touchUpInside) button.tag = 1 buttons.append(button) } resizeAndRelayout() if SweetAlertContext.shouldNotAnimate == true { //Do not animate Alert if self.animatedView != nil { self.animatedView!.animate() } } else { animateAlert() } } func animateAlert() { view.alpha = 0; UIView.animate(withDuration: 0.1, animations: { () -> Void in self.view.alpha = 1.0; }) let previousTransform = self.contentView.transform self.contentView.layer.transform = CATransform3DMakeScale(0.9, 0.9, 0.0); UIView.animate(withDuration: 0.2, animations: { () -> Void in self.contentView.layer.transform = CATransform3DMakeScale(1.1, 1.1, 0.0); }) { (Bool) -> Void in UIView.animate(withDuration: 0.1, animations: { () -> Void in self.contentView.layer.transform = CATransform3DMakeScale(0.9, 0.9, 0.0); }) { (Bool) -> Void in UIView.animate(withDuration: 0.1, animations: { () -> Void in self.contentView.layer.transform = CATransform3DMakeScale(1.0, 1.0, 0.0); if self.animatedView != nil { self.animatedView!.animate() } }) { (Bool) -> Void in self.contentView.transform = previousTransform } } } } private struct SweetAlertContext { static var shouldNotAnimate = false } } // MARK: - // MARK: Animatable Views class AnimatableView: UIView { func animate(){ print("Should overide by subclasss", terminator: "") } } class CancelAnimatedView: AnimatableView { var circleLayer = CAShapeLayer() var crossPathLayer = CAShapeLayer() override required init(frame: CGRect) { super.init(frame: frame) setupLayers() var t = CATransform3DIdentity; t.m34 = 1.0 / -500.0; t = CATransform3DRotate(t, CGFloat(90.0 * M_PI / 180.0), 1, 0, 0); circleLayer.transform = t crossPathLayer.opacity = 0.0 } override func layoutSubviews() { setupLayers() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var outlineCircle: CGPath { let path = UIBezierPath() let startAngle: CGFloat = CGFloat((0) / 180.0 * M_PI) //0 let endAngle: CGFloat = CGFloat((360) / 180.0 * M_PI) //360 path.addArc(withCenter: CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.width/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false) return path.cgPath } private var crossPath: CGPath { let path = UIBezierPath() let factor:CGFloat = self.frame.size.width / 5.0 path.move(to: CGPoint(x: self.frame.size.height/2.0-factor,y: self.frame.size.height/2.0-factor)) path.addLine(to: CGPoint(x: self.frame.size.height/2.0+factor,y: self.frame.size.height/2.0+factor)) path.move(to: CGPoint(x: self.frame.size.height/2.0+factor,y: self.frame.size.height/2.0-factor)) path.addLine(to: CGPoint(x: self.frame.size.height/2.0-factor,y: self.frame.size.height/2.0+factor)) return path.cgPath } private func setupLayers() { circleLayer.path = outlineCircle circleLayer.fillColor = UIColor.clear().cgColor; circleLayer.strokeColor = UIColor.colorFromRGB(0xF27474).cgColor; circleLayer.lineCap = kCALineCapRound circleLayer.lineWidth = 4; circleLayer.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height) circleLayer.position = CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0) self.layer.addSublayer(circleLayer) crossPathLayer.path = crossPath crossPathLayer.fillColor = UIColor.clear().cgColor; crossPathLayer.strokeColor = UIColor.colorFromRGB(0xF27474).cgColor; crossPathLayer.lineCap = kCALineCapRound crossPathLayer.lineWidth = 4; crossPathLayer.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height) crossPathLayer.position = CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0) self.layer.addSublayer(crossPathLayer) } override func animate() { var t = CATransform3DIdentity; t.m34 = 1.0 / -500.0; t = CATransform3DRotate(t, CGFloat(90.0 * M_PI / 180.0), 1, 0, 0); var t2 = CATransform3DIdentity; t2.m34 = 1.0 / -500.0; t2 = CATransform3DRotate(t2, CGFloat(-M_PI), 1, 0, 0); let animation = CABasicAnimation(keyPath: "transform") let time = 0.3 animation.duration = time; animation.fromValue = NSValue(caTransform3D: t) animation.toValue = NSValue(caTransform3D:t2) animation.isRemovedOnCompletion = false animation.fillMode = kCAFillModeForwards self.circleLayer.add(animation, forKey: "transform") var scale = CATransform3DIdentity; scale = CATransform3DScale(scale, 0.3, 0.3, 0) let crossAnimation = CABasicAnimation(keyPath: "transform") crossAnimation.duration = 0.3; crossAnimation.beginTime = CACurrentMediaTime() + time crossAnimation.fromValue = NSValue(caTransform3D: scale) crossAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 0.25, 0.8, 0.7, 2.0) crossAnimation.toValue = NSValue(caTransform3D:CATransform3DIdentity) self.crossPathLayer.add(crossAnimation, forKey: "scale") let fadeInAnimation = CABasicAnimation(keyPath: "opacity") fadeInAnimation.duration = 0.3; fadeInAnimation.beginTime = CACurrentMediaTime() + time fadeInAnimation.fromValue = 0.3 fadeInAnimation.toValue = 1.0 fadeInAnimation.isRemovedOnCompletion = false fadeInAnimation.fillMode = kCAFillModeForwards self.crossPathLayer.add(fadeInAnimation, forKey: "opacity") } } class InfoAnimatedView: AnimatableView { var circleLayer = CAShapeLayer() var crossPathLayer = CAShapeLayer() override init(frame: CGRect) { super.init(frame: frame) setupLayers() } override func layoutSubviews() { setupLayers() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var outlineCircle: CGPath { let path = UIBezierPath() let startAngle: CGFloat = CGFloat((0) / 180.0 * M_PI) //0 let endAngle: CGFloat = CGFloat((360) / 180.0 * M_PI) //360 path.addArc(withCenter: CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.width/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false) let factor:CGFloat = self.frame.size.width / 1.5 path.move(to: CGPoint(x: self.frame.size.width/2.0 , y: 15.0)) path.addLine(to: CGPoint(x: self.frame.size.width/2.0,y: factor)) path.move(to: CGPoint(x: self.frame.size.width/2.0,y: factor + 10.0)) path.addArc(withCenter: CGPoint(x: self.frame.size.width/2.0,y: factor + 10.0), radius: 1.0, startAngle: startAngle, endAngle: endAngle, clockwise: true) return path.cgPath } func setupLayers() { circleLayer.path = outlineCircle circleLayer.fillColor = UIColor.clear().cgColor; circleLayer.strokeColor = UIColor.colorFromRGB(0xF8D486).cgColor; circleLayer.lineCap = kCALineCapRound circleLayer.lineWidth = 4; circleLayer.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height) circleLayer.position = CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0) self.layer.addSublayer(circleLayer) } override func animate() { let colorAnimation = CABasicAnimation(keyPath:"strokeColor") colorAnimation.duration = 1.0; colorAnimation.repeatCount = HUGE colorAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) colorAnimation.autoreverses = true colorAnimation.fromValue = UIColor.colorFromRGB(0xF7D58B).cgColor colorAnimation.toValue = UIColor.colorFromRGB(0xF2A665).cgColor circleLayer.add(colorAnimation, forKey: "strokeColor") } } class SuccessAnimatedView: AnimatableView { var circleLayer = CAShapeLayer() var outlineLayer = CAShapeLayer() override init(frame: CGRect) { super.init(frame: frame) setupLayers() circleLayer.strokeStart = 0.0 circleLayer.strokeEnd = 0.0 } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { setupLayers() } var outlineCircle: CGPath { let path = UIBezierPath() let startAngle: CGFloat = CGFloat((0) / 180.0 * M_PI) //0 let endAngle: CGFloat = CGFloat((360) / 180.0 * M_PI) //360 path.addArc(withCenter: CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false) return path.cgPath } var path: CGPath { let path = UIBezierPath() let startAngle:CGFloat = CGFloat((60) / 180.0 * M_PI) //60 let endAngle:CGFloat = CGFloat((200) / 180.0 * M_PI) //190 path.addArc(withCenter: CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false) path.addLine(to: CGPoint(x: 36.0 - 10.0 ,y: 60.0 - 10.0)) path.addLine(to: CGPoint(x: 85.0 - 20.0, y: 30.0 - 20.0)) return path.cgPath } func setupLayers() { outlineLayer.position = CGPoint(x: 0, y: 0); outlineLayer.path = outlineCircle outlineLayer.fillColor = UIColor.clear().cgColor; outlineLayer.strokeColor = UIColor(red: 150.0/255.0, green: 216.0/255.0, blue: 115.0/255.0, alpha: 1.0).cgColor; outlineLayer.lineCap = kCALineCapRound outlineLayer.lineWidth = 4; outlineLayer.opacity = 0.1 self.layer.addSublayer(outlineLayer) circleLayer.position = CGPoint(x: 0, y: 0); circleLayer.path = path circleLayer.fillColor = UIColor.clear().cgColor; circleLayer.strokeColor = UIColor(red: 150.0/255.0, green: 216.0/255.0, blue: 115.0/255.0, alpha: 1.0).cgColor; circleLayer.lineCap = kCALineCapRound circleLayer.lineWidth = 4; circleLayer.actions = [ "strokeStart": NSNull(), "strokeEnd": NSNull(), "transform": NSNull() ] self.layer.addSublayer(circleLayer) } override func animate() { let strokeStart = CABasicAnimation(keyPath: "strokeStart") let strokeEnd = CABasicAnimation(keyPath: "strokeEnd") let factor = 0.045 strokeEnd.fromValue = 0.00 strokeEnd.toValue = 0.93 strokeEnd.duration = 10.0*factor let timing = CAMediaTimingFunction(controlPoints: 0.3, 0.6, 0.8, 1.2) strokeEnd.timingFunction = timing strokeStart.fromValue = 0.0 strokeStart.toValue = 0.68 strokeStart.duration = 7.0*factor strokeStart.beginTime = CACurrentMediaTime() + 3.0*factor strokeStart.fillMode = kCAFillModeBackwards strokeStart.timingFunction = timing circleLayer.strokeStart = 0.68 circleLayer.strokeEnd = 0.93 self.circleLayer.add(strokeEnd, forKey: "strokeEnd") self.circleLayer.add(strokeStart, forKey: "strokeStart") } } extension UIColor { class func colorFromRGB(_ rgbValue: UInt) -> UIColor { return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } }
mit
f24d7a2952df1c261d275e82808e5163
39.12013
219
0.615967
4.507386
false
false
false
false
BlurredSoftware/BSWFoundation
Sources/BSWFoundation/Extensions/Throttler.swift
1
634
// // Throttler.swift // Created by Pierluigi Cifani on 29/01/2020. // import Foundation public class Throttler { private let queue: DispatchQueue private var job = DispatchWorkItem(block: {}) private let maxInterval: Double public init(seconds: Double, queue: DispatchQueue = .global(qos: .default)) { self.maxInterval = seconds self.queue = queue } public func throttle(block: @escaping () -> ()) { job.cancel() job = DispatchWorkItem() { block() } queue.asyncAfter(deadline: .now() + Double(maxInterval), execute: job) } }
mit
51a10fd3b88d0c5429c372fefa82726d
23.384615
81
0.604101
4.372414
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/Views/PaddedLabel.swift
1
1020
// // PaddedView.swift // Habitica // // Created by Phillip Thelen on 27/02/2017. // Copyright © 2017 HabitRPG Inc. All rights reserved. // import UIKit class PaddedLabel: UILabel { @objc public var horizontalPadding: CGFloat = 8.0 @objc public var verticalPadding: CGFloat = 4.0 override var intrinsicContentSize: CGSize { let size = super.intrinsicContentSize return CGSize(width: size.width+horizontalPadding*2, height: size.height+verticalPadding*2) } override func sizeThatFits(_ size: CGSize) -> CGSize { let fittingSize = super.sizeThatFits(size) return CGSize(width: fittingSize.width+horizontalPadding*2, height: fittingSize.height+verticalPadding*2) } override func sizeToFit() { super.sizeToFit() let paddedSize = CGSize(width: frame.size.width+horizontalPadding*2, height: frame.size.height+verticalPadding*2) frame = CGRect(x: 0, y: 0, width: paddedSize.width, height: paddedSize.height) } }
gpl-3.0
e521a731928c673590836d31a2b354b6
31.870968
121
0.687929
4.228216
false
false
false
false
almapp/uc-access-ios
uc-access/src/Requests.swift
1
1336
// // Requests.swift // uc-access // // Created by Patricio Lopez on 09-01-16. // Copyright © 2016 Almapp. All rights reserved. // import Foundation import Alamofire import PromiseKit public typealias HTTPResponse = (NSHTTPURLResponse, NSData) public class Request { public static func POST(url: String, parameters: [String: AnyObject]? = nil, headers: [String : String]? = nil) -> Promise<HTTPResponse> { return self.perform(Alamofire.Method.POST, url: url, parameters: parameters, headers: headers) } public static func GET(url: String, parameters: [String: AnyObject]? = nil, headers: [String : String]? = nil) -> Promise<HTTPResponse> { return self.perform(Alamofire.Method.GET, url: url, parameters: parameters, headers: headers) } public static func perform(method: Alamofire.Method, url: String, parameters: [String: AnyObject]? = nil, headers: [String : String]? = nil) -> Promise<HTTPResponse> { return Promise { fulfill, reject in Alamofire.request(method, url, parameters: parameters, encoding: .URL, headers: headers).response { (_, response, data, error) in if let err = error{ reject(err) } else { fulfill((response!, data!)) } } } } }
gpl-3.0
cb10852a7796e5baadd8b99dcb6dbc2e
37.142857
171
0.629213
4.251592
false
false
false
false
blstream/TOZ_iOS
TOZ_iOS/SignUpResponseMapper.swift
1
1566
// // SignUpResponseMapper.swift // TOZ_iOS // // Created by patronage on 28.04.2017. // Copyright © 2017 intive. All rights reserved. // import Foundation final class SignUpResponseMapper: ResponseMapper<SignUpItem>, ResponseMapperProtocol { // swiftlint:disable cyclomatic_complexity static func process(_ obj: AnyObject?) throws -> SignUpItem { return try process(obj, parse: { json in guard let userID = json["id"] as? String else { return nil } guard let password = json["password"] as? String else { return nil } guard let roles = json["roles"] as? [String]? else { return nil } guard let name = json["name"] as? String else { return nil } guard let surname = json["surname"] as? String else { return nil } guard let phoneNumber = json["phoneNumber"] as? String else { return nil } guard let email = json["email"] as? String else { return nil } guard let passwordChangeDate = json["passwordChangeDate"] as? Int? else { return nil } var role: [Role] = [] if let roles = roles { for r in roles { guard let singleRole = Role(rawValue: r) else { continue } role.append(singleRole) } } return SignUpItem(userID: userID, password: password, roles: role, name: name, surname: surname, phoneNumber: phoneNumber, email: email, passwordChangeDate: passwordChangeDate) }) } }
apache-2.0
8176063e37954f719b73a4297a8421e4
43.714286
188
0.591693
4.602941
false
false
false
false
JockerLUO/ShiftLibra
ShiftLibra/ShiftLibra/Class/View/Home/View/SLHomeCell.swift
1
6294
// // SLHomeCell.swift // ShiftLibra // // Created by LUO on 2017/7/23. // Copyright © 2017年 JockerLuo. All rights reserved. // import UIKit import FoldingCell import SnapKit class SLHomeCell: FoldingCell { var closure : (()->())? var gestureClosure : (()->())? static let detailID = "detailID" var fromMoneyDetailList : [String]? { didSet { detailView.fromMoneyDetailList = fromMoneyDetailList } } var toMoneyDetailList : [String]? { didSet { detailView.toMoneyDetailList = toMoneyDetailList } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) itemCount = 1 setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { contentView.addSubview(fgView) foregroundView = fgView foregroundView.snp.makeConstraints { (make) in make.left.equalTo(0) make.right.equalTo(0) make.height.equalTo(homeTableViewCellHight) } foregroundViewTop = NSLayoutConstraint(item: foregroundView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0) addConstraint(foregroundViewTop) contentView.addSubview(ctView) containerView = ctView containerView.snp.makeConstraints { (make) in make.left.right.equalTo(foregroundView.snp.left) make.height.equalTo(homeDetailTableViewCellHight * 9) } containerViewTop = NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: (homeTableViewCellHight)) addConstraint(containerViewTop) contentView.addSubview(detailView) detailView.snp.makeConstraints { (make) in make.top.equalTo(homeTableViewCellHight) make.left.right.equalTo(contentView) make.bottom.equalTo(contentView) } foregroundView.addSubview(labLeft) labLeft.snp.makeConstraints { (make) in make.centerY.equalTo(foregroundView) make.right.equalTo(foregroundView.snp.centerX).offset(-labSpace) } foregroundView.addSubview(labRight) labRight.snp.makeConstraints { (make) in make.centerY.equalTo(foregroundView) make.left.equalTo(foregroundView.snp.centerX).offset(labSpace) } foregroundView.addSubview(line) line.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(foregroundView) make.height.equalTo(lineHight) } detailView.closure = { [weak self] in self?.closure?() } NotificationCenter.default.addObserver(self, selector: #selector(swipeAnimation(noti:)), name: homeTableViewSwipeGestureNotification, object: nil) } @objc func swipeAnimation(noti : Notification) -> () { guard let direction = noti.object as? UISwipeGestureRecognizerDirection else { return } let i : Int = direction == .left ? -1 : 1 labLeft.snp.updateConstraints { (make) in make.right.equalTo(foregroundView.snp.centerX).offset(-labSpace + i * labSpace) } labRight.snp.updateConstraints { (make) in make.left.equalTo(foregroundView.snp.centerX).offset(labSpace + i * labSpace) } self.layoutIfNeeded() UIView.animate(withDuration: swipeAnimationDuration) { self.labLeft.snp.updateConstraints { (make) in make.right.equalTo(self.foregroundView.snp.centerX).offset(-labSpace) } self.labRight.snp.updateConstraints { (make) in make.left.equalTo(self.foregroundView.snp.centerX).offset(labSpace) } self.layoutIfNeeded() UIView.animate(withDuration: swipeAnimationDuration, animations: { }) } let time : TimeInterval = swipeAnimationDuration DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) { self.gestureClosure?() } } override func animationDuration(_ itemIndex:NSInteger, type:AnimationType)-> TimeInterval { return 0.01 } fileprivate lazy var fgView: SLHomeTableBackgroundView! = { let view = SLHomeTableBackgroundView() return view }() fileprivate lazy var ctView: UIView = { let view = UIView() view.isHidden = true return view }() lazy var labLeft: UILabel = { let lab = UILabel() lab.text = "456" lab.font = UIFont.systemFont(ofSize: bottomFontSize) lab.textColor = bottom_left_textColor lab.sizeToFit() return lab }() lazy var labRight: UILabel = { let lab = UILabel() lab.text = "654" lab.font = UIFont.systemFont(ofSize: bottomFontSize) lab.textColor = bottom_right_textColor lab.sizeToFit() return lab }() fileprivate lazy var detailView: SLHomeDetailView = SLHomeDetailView() fileprivate lazy var line : SLHomeTableLineView = SLHomeTableLineView() }
mit
e8d70572e02749d94d79c77607bfa539
26.116379
241
0.55492
5.627013
false
false
false
false
rayho/CodePathRottenTomatoes
CodePathRottenTomatoes/ListController.swift
1
6130
// // ListController.swift // Rotten Tomatoes // // Created by Ray Ho on 9/10/14. // Copyright (c) 2014 Prime Rib Software. All rights reserved. // import UIKit class ListController: UIViewController, UITableViewDataSource, UITableViewDelegate { // Rotten Tomatoes API key let RT_API_KEY = "xznfv6xvh3bn9cvm99c7nvst" // Network error UI states let NETWORK_ERR_STATE_HIDDEN = 0 let NETWORK_ERR_STATE_SHOWN = 1 @IBOutlet weak var moviesTableView: UITableView! @IBOutlet weak var networkErrorLabel: UILabel! // Backing movie data to be displayed in table view var movies: NSArray = NSArray() // The currently selected/tapped movie var movieSelected: NSDictionary? // Pull-to-refresh var refreshControl: UIRefreshControl! // The current network error UI state var networkErrorAnimationState: Int! override func viewDidLoad() { super.viewDidLoad() // Initialize table view var nib = UINib(nibName: "MovieCell", bundle: nil) moviesTableView.registerNib(nib, forCellReuseIdentifier: "MovieCell") moviesTableView.dataSource = self moviesTableView.delegate = self // Initialize pull-to-refresh behavior refreshControl = UIRefreshControl(); refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControl.addTarget(self, action: "pullToRefresh", forControlEvents: UIControlEvents.ValueChanged) networkErrorAnimationState = NETWORK_ERR_STATE_HIDDEN moviesTableView.addSubview(refreshControl) moviesTableView.hidden = true getMovies(true) } override func viewDidDisappear(animated: Bool) { // Deselect cell upon leaving var indexPath: NSIndexPath? = moviesTableView.indexPathForSelectedRow() if (indexPath != nil) { moviesTableView.deselectRowAtIndexPath(indexPath!, animated: false) } } func pullToRefresh() { getMovies(false) } func getMovies(showHUD: Bool) { if (showHUD) { MBProgressHUD.showHUDAddedTo(self.view, animated: true) } hideNetworkError() let request = NSMutableURLRequest(URL: NSURL.URLWithString("http://api.rottentomatoes.com/api/public/v1.0/lists/dvds/top_rentals.json?apikey=\(RT_API_KEY)")) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: { (response, data, error) in // Hide progress views MBProgressHUD.hideHUDForView(self.view, animated: true) self.refreshControl.endRefreshing() self.moviesTableView.hidden = false // Did network request go through? var isSuccessful: Bool = (error == nil) if (!isSuccessful) { self.showNetworkError() return } // Parse response var errorValue: NSError? = nil let parsedResult: AnyObject? = (data != nil) ? NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &errorValue) : nil if (parsedResult != nil) { let dictionary: NSDictionary = parsedResult! as NSDictionary var movies: AnyObject? = dictionary.objectForKey("movies") if (movies != nil) { self.movies = movies as NSArray isSuccessful = true } } // Update UI if (isSuccessful) { self.moviesTableView.reloadData() } else { self.showNetworkError() return } }) } func showNetworkError() { if (networkErrorAnimationState == NETWORK_ERR_STATE_SHOWN) { return } networkErrorAnimationState = NETWORK_ERR_STATE_SHOWN UIView.animateWithDuration(0.5, animations: { self.networkErrorLabel.frame = CGRectMake(0, 64, self.networkErrorLabel.frame.size.width, self.networkErrorLabel.frame.size.height) }) } func hideNetworkError() { if (networkErrorAnimationState == NETWORK_ERR_STATE_HIDDEN) { return } networkErrorAnimationState = NETWORK_ERR_STATE_HIDDEN UIView.animateWithDuration(0.5, animations: { self.networkErrorLabel.frame = CGRectMake(0, (64 - self.networkErrorLabel.frame.size.height), self.networkErrorLabel.frame.size.width, self.networkErrorLabel.frame.size.height) }) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return movies.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: MovieCell = moviesTableView.dequeueReusableCellWithIdentifier("MovieCell") as MovieCell let movie: NSDictionary = movies.objectAtIndex(indexPath.row) as NSDictionary let title: NSString = movie.objectForKey("title") as NSString let posters: NSDictionary = movie.objectForKey("posters") as NSDictionary let posterThumbnailUrl: NSString = posters.objectForKey("thumbnail") as NSString let synopsis: NSString = movie.objectForKey("synopsis") as NSString cell.populate(title, withImageUrlString: posterThumbnailUrl, withSynopsis: synopsis) return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 88 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { movieSelected = movies[indexPath.row] as NSDictionary performSegueWithIdentifier("toDetailSegue", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Pass movie details to the next view controller if (segue.identifier == "toDetailSegue") { var detailController: DetailController = segue.destinationViewController as DetailController detailController.movie = movieSelected } } }
mit
77d7ba7a99c77f0b6448404bc3718097
38.044586
188
0.660033
5.217021
false
false
false
false
Acidburn0zzz/firefox-ios
fastlane/SnapshotHelper.swift
1
11354
// // SnapshotHelper.swift // Example // // Created by Felix Krause on 10/8/15. // // ----------------------------------------------------- // IMPORTANT: When modifying this file, make sure to // increment the version number at the very // bottom of the file to notify users about // the new SnapshotHelper.swift // ----------------------------------------------------- import Foundation import XCTest var deviceLanguage = "" var locale = "" func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) { Snapshot.setupSnapshot(app, waitForAnimations: waitForAnimations) } func snapshot(_ name: String, waitForLoadingIndicator: Bool) { if waitForLoadingIndicator { Snapshot.snapshot(name) } else { Snapshot.snapshot(name, timeWaitingForIdle: 0) } } /// - Parameters: /// - name: The name of the snapshot /// - timeout: Amount of seconds to wait until the network loading indicator disappears. Pass `0` if you don't want to wait. func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { Snapshot.snapshot(name, timeWaitingForIdle: timeout) } enum SnapshotError: Error, CustomDebugStringConvertible { case cannotFindSimulatorHomeDirectory case cannotRunOnPhysicalDevice var debugDescription: String { switch self { case .cannotFindSimulatorHomeDirectory: return "Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable." case .cannotRunOnPhysicalDevice: return "Can't use Snapshot on a physical device." } } } @objcMembers open class Snapshot: NSObject { static var app: XCUIApplication? static var waitForAnimations = true static var cacheDirectory: URL? static var screenshotsDirectory: URL? { return cacheDirectory?.appendingPathComponent("screenshots", isDirectory: true) } open class func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) { Snapshot.app = app Snapshot.waitForAnimations = waitForAnimations do { let cacheDir = try getCacheDirectory() Snapshot.cacheDirectory = cacheDir setLanguage(app) setLocale(app) setLaunchArguments(app) } catch let error { NSLog(error.localizedDescription) } } class func setLanguage(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { NSLog("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("language.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"] } catch { NSLog("Couldn't detect/set language...") } } class func setLocale(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { NSLog("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("locale.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) } catch { NSLog("Couldn't detect/set locale...") } if locale.isEmpty && !deviceLanguage.isEmpty { locale = Locale(identifier: deviceLanguage).identifier } if !locale.isEmpty { app.launchArguments += ["-AppleLocale", "\"\(locale)\""] } } class func setLaunchArguments(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { NSLog("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("snapshot-launch_arguments.txt") app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"] do { let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8) let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: []) let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location: 0, length: launchArguments.count)) let results = matches.map { result -> String in (launchArguments as NSString).substring(with: result.range) } app.launchArguments += results } catch { NSLog("Couldn't detect/set launch_arguments...") } } open class func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { if timeout > 0 { waitForLoadingIndicatorToDisappear(within: timeout) } NSLog("snapshot: \(name)") // more information about this, check out https://docs.fastlane.tools/actions/snapshot/#how-does-it-work if Snapshot.waitForAnimations { sleep(1) // Waiting for the animation to be finished (kind of) } #if os(OSX) guard let app = self.app else { NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } app.typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: []) #else guard self.app != nil else { NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } let screenshot = XCUIScreen.main.screenshot() #if os(iOS) let image = XCUIDevice.shared.orientation.isLandscape ? fixLandscapeOrientation(image: screenshot.image) : screenshot.image #else let image = screenshot.image #endif guard var simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"], let screenshotsDir = screenshotsDirectory else { return } do { // The simulator name contains "Clone X of " inside the screenshot file when running parallelized UI Tests on concurrent devices let regex = try NSRegularExpression(pattern: "Clone [0-9]+ of ") let range = NSRange(location: 0, length: simulator.count) simulator = regex.stringByReplacingMatches(in: simulator, range: range, withTemplate: "") let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png") try image.pngData()?.write(to: path, options: .atomic) } catch let error { NSLog("Problem writing screenshot: \(name) to \(screenshotsDir)/\(simulator)-\(name).png") NSLog(error.localizedDescription) } #endif } class func fixLandscapeOrientation(image: UIImage) -> UIImage { if #available(iOS 10.0, *) { let format = UIGraphicsImageRendererFormat() format.scale = image.scale let renderer = UIGraphicsImageRenderer(size: image.size, format: format) return renderer.image { context in image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)) } } else { return image } } class func waitForLoadingIndicatorToDisappear(within timeout: TimeInterval) { #if os(tvOS) return #endif guard let app = self.app else { NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } let networkLoadingIndicator = app.otherElements.deviceStatusBars.networkLoadingIndicators.element let networkLoadingIndicatorDisappeared = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: networkLoadingIndicator) _ = XCTWaiter.wait(for: [networkLoadingIndicatorDisappeared], timeout: timeout) } class func getCacheDirectory() throws -> URL { let cachePath = "Library/Caches/tools.fastlane" // on OSX config is stored in /Users/<username>/Library // and on iOS/tvOS/WatchOS it's in simulator's home dir #if os(OSX) let homeDir = URL(fileURLWithPath: NSHomeDirectory()) return homeDir.appendingPathComponent(cachePath) #elseif arch(i386) || arch(x86_64) guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else { throw SnapshotError.cannotFindSimulatorHomeDirectory } let homeDir = URL(fileURLWithPath: simulatorHostHome) return homeDir.appendingPathComponent(cachePath) #else throw SnapshotError.cannotRunOnPhysicalDevice #endif } } private extension XCUIElementAttributes { var isNetworkLoadingIndicator: Bool { if hasAllowListedIdentifier { return false } let hasOldLoadingIndicatorSize = frame.size == CGSize(width: 10, height: 20) let hasNewLoadingIndicatorSize = frame.size.width.isBetween(46, and: 47) && frame.size.height.isBetween(2, and: 3) return hasOldLoadingIndicatorSize || hasNewLoadingIndicatorSize } var hasAllowListedIdentifier: Bool { let allowListedIdentifiers = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"] return allowListedIdentifiers.contains(identifier) } func isStatusBar(_ deviceWidth: CGFloat) -> Bool { if elementType == .statusBar { return true } guard frame.origin == .zero else { return false } let oldStatusBarSize = CGSize(width: deviceWidth, height: 20) let newStatusBarSize = CGSize(width: deviceWidth, height: 44) return [oldStatusBarSize, newStatusBarSize].contains(frame.size) } } private extension XCUIElementQuery { var networkLoadingIndicators: XCUIElementQuery { let isNetworkLoadingIndicator = NSPredicate { (evaluatedObject, _) in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isNetworkLoadingIndicator } return self.containing(isNetworkLoadingIndicator) } var deviceStatusBars: XCUIElementQuery { guard let app = Snapshot.app else { fatalError("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") } let deviceWidth = app.windows.firstMatch.frame.width let isStatusBar = NSPredicate { (evaluatedObject, _) in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isStatusBar(deviceWidth) } return self.containing(isStatusBar) } } private extension CGFloat { func isBetween(_ numberA: CGFloat, and numberB: CGFloat) -> Bool { return numberA...numberB ~= self } } // Please don't remove the lines below // They are used to detect outdated configuration files // SnapshotHelperVersion [1.24]
mpl-2.0
408ffbfb2cee647ade3097b634cce6da
36.72093
158
0.637661
5.396388
false
false
false
false
practicalswift/swift
test/IRGen/witness_table_objc_associated_type.swift
7
2166
// RUN: %target-swift-frontend -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s -DINT=i%target-ptrsize protocol A {} protocol B { associatedtype AA: A func foo() } @objc protocol O {} protocol C { associatedtype OO: O func foo() } struct SA: A {} struct SB: B { typealias AA = SA func foo() {} } // CHECK-LABEL: @"$s34witness_table_objc_associated_type2SBVAA1BAAWP" = hidden global [4 x i8*] [ // CHECK: @"associated conformance 34witness_table_objc_associated_type2SBVAA1BAA2AAAaDP_AA1A" // CHECK: @"symbolic 34witness_table_objc_associated_type2SAV" // CHECK: i8* bitcast {{.*}} @"$s34witness_table_objc_associated_type2SBVAA1BA2aDP3fooyyFTW" // CHECK: ] class CO: O {} struct SO: C { typealias OO = CO func foo() {} } // CHECK-LABEL: @"$s34witness_table_objc_associated_type2SOVAA1CAAWP" = hidden global [3 x i8*] [ // CHECK: @"symbolic 34witness_table_objc_associated_type2COC" // CHECK: i8* bitcast {{.*}} @"$s34witness_table_objc_associated_type2SOVAA1CA2aDP3fooyyFTW" // CHECK: ] // CHECK-LABEL: define hidden swiftcc void @"$s34witness_table_objc_associated_type0A25OffsetAfterAssociatedTypeyyxAA1BRzlF"(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.B) func witnessOffsetAfterAssociatedType<T: B>(_ x: T) { // CHECK: [[FOO_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.B, i32 3 // CHECK: [[FOO_OPAQUE:%.*]] = load {{.*}} [[FOO_ADDR]] // CHECK: [[FOO:%.*]] = bitcast {{.*}} [[FOO_OPAQUE]] // CHECK: call swiftcc void [[FOO]] x.foo() } // CHECK-LABEL: define hidden swiftcc void @"$s34witness_table_objc_associated_type0A29OffsetAfterAssociatedTypeObjCyyxAA1CRzlF"(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.C) {{.*}} { func witnessOffsetAfterAssociatedTypeObjC<T: C>(_ x: T) { // CHECK: [[FOO_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.C, i32 2 // CHECK: [[FOO_OPAQUE:%.*]] = load {{.*}} [[FOO_ADDR]] // CHECK: [[FOO:%.*]] = bitcast {{.*}} [[FOO_OPAQUE]] // CHECK: call swiftcc void [[FOO]] x.foo() }
apache-2.0
63765fe4a6dd1c94e922250524888325
39.111111
199
0.634349
3.223214
false
false
false
false
huonw/swift
test/decl/var/variables.swift
14
3795
// RUN: %target-typecheck-verify-swift var t1 : Int var t2 = 10 var t3 = 10, t4 = 20.0 var (t5, t6) = (10, 20.0) var t7, t8 : Int var t9, t10 = 20 // expected-error {{type annotation missing in pattern}} var t11, t12 : Int = 20 // expected-error {{type annotation missing in pattern}} var t13 = 2.0, t14 : Int var (x = 123, // expected-error {{expected ',' separator}} {{7-7=,}} expected-error {{expected pattern}} y = 456) : (Int,Int) var bfx : Int, bfy : Int _ = 10 var self1 = self1 // expected-error {{variable used within its own initial value}} var self2 : Int = self2 // expected-error {{variable used within its own initial value}} var (self3) : Int = self3 // expected-error {{variable used within its own initial value}} var (self4) : Int = self4 // expected-error {{variable used within its own initial value}} var self5 = self5 + self5 // expected-error 2 {{variable used within its own initial value}} var self6 = !self6 // expected-error {{variable used within its own initial value}} var (self7a, self7b) = (self7b, self7a) // expected-error 2 {{variable used within its own initial value}} var self8 = 0 func testShadowing() { var self8 = self8 // expected-error {{variable used within its own initial value}} } var (paren) = 0 var paren2: Int = paren struct Broken { var b : Bool = True // expected-error{{use of unresolved identifier 'True'}} } // rdar://16252090 - Warning when inferring empty tuple type for declarations var emptyTuple = testShadowing() // expected-warning {{variable 'emptyTuple' inferred to have type '()'}} \ // expected-note {{add an explicit type annotation to silence this warning}} // rdar://15263687 - Diagnose variables inferenced to 'AnyObject' var ao1 : AnyObject var ao2 = ao1 var aot1 : AnyObject.Type var aot2 = aot1 // expected-warning {{variable 'aot2' inferred to have type 'AnyObject.Type', which may be unexpected}} \ // expected-note {{add an explicit type annotation to silence this warning}} for item in [AnyObject]() { // No warning in for-each loop. _ = item } // <rdar://problem/16574105> Type inference of _Nil very coherent but kind of useless var ptr = nil // expected-error {{'nil' requires a contextual type}} func testAnyObjectOptional() -> AnyObject? { let x = testAnyObjectOptional() return x } class SomeClass {} // <rdar://problem/16877304> weak let's should be rejected weak let V = SomeClass() // expected-error {{'weak' must be a mutable variable, because it may change at runtime}} let a = b ; let b = a // expected-note@-1 {{'a' declared here}} // expected-error@-2 {{ambiguous use of 'a'}} // <rdar://problem/17501765> Swift should warn about immutable default initialized values let uselessValue : String? func tuplePatternDestructuring(_ x : Int, y : Int) { let (b: _, a: h) = (b: x, a: y) _ = h // <rdar://problem/20392122> Destructuring tuple with labels doesn't work let (i, j) = (b: x, a: y) _ = i+j // <rdar://problem/20395243> QoI: type variable reconstruction failing for tuple types let (x: g1, a: h1) = (b: x, a: y) // expected-error {{tuple type '(b: Int, a: Int)' is not convertible to tuple '(x: Int, a: Int)'}} } // <rdar://problem/21057425> Crash while compiling attached test-app. func test21057425() -> (Int, Int) { let x: Int = "not an int!", y = 0 // expected-error{{cannot convert value of type 'String' to specified type 'Int'}} return (x, y) } // rdar://problem/21081340 func test21081340() { let (x: a, y: b): () = foo() // expected-error{{tuple pattern has the wrong length for tuple type '()'}} } // <rdar://problem/22322266> Swift let late initialization in top level control flow statements if true { let s : Int s = 42 // should be valid. _ = s }
apache-2.0
3a9fed9d4b2c92b79990844536347314
34.801887
135
0.665086
3.4375
false
true
false
false
PekanMmd/Pokemon-XD-Code
enums/XGEggGroups.swift
1
1264
// // XGEggGroups.swift // GoD Tool // // Created by Stars Momodu on 28/03/2021. // import Foundation enum XGEggGroups: Int, CaseIterable { case None = 0 case Monster = 1 case Water = 2 case Bug = 3 case Flying = 4 case Field = 5 case Fairy = 6 case Grass = 7 case Humanoid = 8 case Water3 = 9 case Mineral = 10 case Amorphous = 11 case Water2 = 12 case Ditto = 13 case Dragon = 14 case Undiscovered = 15 var name: String { switch self { case .None: return "None" case .Monster: return "Monster" case .Water: return "Water" case .Bug: return "Bug" case .Flying: return "Flying" case .Field: return "Field" case .Fairy: return "Fairy" case .Grass: return "Grass" case .Humanoid: return "Human-Like" case .Water3: return "Water 3" case .Mineral: return "Mineral" case .Amorphous: return "Amorphous" case .Water2: return "Water 2" case .Ditto: return "Ditto" case .Dragon: return "Dragon" case .Undiscovered: return "Undiscovered" } } } extension XGEggGroups: XGEnumerable { var enumerableName: String { return name } var enumerableValue: String? { return rawValue.string } static var className: String { return "Egg Groups" } static var allValues: [XGEggGroups] { return allCases } }
gpl-2.0
72c8d277f55477450b426a2a67493d2e
17.588235
43
0.678006
2.872727
false
false
false
false
SwiftGen/SwiftGenKit
Sources/Parsers/ColorsFileParsers/ColorsXMLFileParser.swift
1
1159
// // SwiftGenKit // Copyright (c) 2017 SwiftGen // MIT Licence // import Foundation import Kanna import PathKit final class ColorsXMLFileParser: ColorsFileTypeParser { static let extensions = ["xml"] private enum XML { static let colorXPath = "/resources/color" static let nameAttribute = "name" } func parseFile(at path: Path) throws -> Palette { guard let document = Kanna.XML(xml: try path.read(), encoding: .utf8) else { throw ColorsParserError.invalidFile(path: path, reason: "Unknown XML parser error.") } var colors = [String: UInt32]() for color in document.xpath(XML.colorXPath) { guard let value = color.text else { throw ColorsParserError.invalidFile(path: path, reason: "Invalid structure, color must have a value.") } guard let name = color["name"], !name.isEmpty else { throw ColorsParserError.invalidFile(path: path, reason: "Invalid structure, color \(value) must have a name.") } colors[name] = try parse(hex: value, key: name, path: path) } let name = path.lastComponentWithoutExtension return Palette(name: name, colors: colors) } }
mit
f82ec51126e0dd9f078ec1d62f11f42f
27.975
118
0.678171
4.080986
false
false
false
false
vector-im/riot-ios
Riot/Modules/Secrets/Setup/RecoveryPassphrase/SecretsSetupRecoveryPassphraseCoordinator.swift
1
3075
// File created from ScreenTemplate // $ createScreen.sh Test SecretsSetupRecoveryPassphrase /* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit final class SecretsSetupRecoveryPassphraseCoordinator: SecretsSetupRecoveryPassphraseCoordinatorType { // MARK: - Properties // MARK: Private private var secretsSetupRecoveryPassphraseViewModel: SecretsSetupRecoveryPassphraseViewModelType private let secretsSetupRecoveryPassphraseViewController: SecretsSetupRecoveryPassphraseViewController // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] weak var delegate: SecretsSetupRecoveryPassphraseCoordinatorDelegate? // MARK: - Setup init(passphraseInput: SecretsSetupRecoveryPassphraseInput) { let secretsSetupRecoveryPassphraseViewModel = SecretsSetupRecoveryPassphraseViewModel(passphraseInput: passphraseInput) let secretsSetupRecoveryPassphraseViewController = SecretsSetupRecoveryPassphraseViewController.instantiate(with: secretsSetupRecoveryPassphraseViewModel) self.secretsSetupRecoveryPassphraseViewModel = secretsSetupRecoveryPassphraseViewModel self.secretsSetupRecoveryPassphraseViewController = secretsSetupRecoveryPassphraseViewController } // MARK: - Public methods func start() { self.secretsSetupRecoveryPassphraseViewModel.coordinatorDelegate = self } func toPresentable() -> UIViewController { return self.secretsSetupRecoveryPassphraseViewController } } // MARK: - SecretsSetupRecoveryPassphraseViewModelCoordinatorDelegate extension SecretsSetupRecoveryPassphraseCoordinator: SecretsSetupRecoveryPassphraseViewModelCoordinatorDelegate { func secretsSetupRecoveryPassphraseViewModel(_ viewModel: SecretsSetupRecoveryPassphraseViewModelType, didEnterNewPassphrase passphrase: String) { self.delegate?.secretsSetupRecoveryPassphraseCoordinator(self, didEnterNewPassphrase: passphrase) } func secretsSetupRecoveryPassphraseViewModel(_ viewModel: SecretsSetupRecoveryPassphraseViewModelType, didConfirmPassphrase passphrase: String) { self.delegate?.secretsSetupRecoveryPassphraseCoordinator(self, didConfirmPassphrase: passphrase) } func secretsSetupRecoveryPassphraseViewModelDidCancel(_ viewModel: SecretsSetupRecoveryPassphraseViewModelType) { self.delegate?.secretsSetupRecoveryPassphraseCoordinatorDidCancel(self) } }
apache-2.0
0a76bcc30012edadc28bd08ea6ec1995
41.123288
162
0.79187
7.391827
false
false
false
false
tensorflow/examples
lite/examples/bert_qa/ios/ViewInSwiftUI/SceneDelegate.swift
1
1407
// Copyright 2020 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import SwiftUI import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene( _ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions ) { // Use a UIHostingController as window root view controller if let windowScene = scene as? UIWindowScene { let bertQA: BertQAHandler do { bertQA = try BertQAHandler() } catch let error { fatalError(error.localizedDescription) } let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController( rootView: DatasetListView(datasets: Dataset.load(), bertQA: bertQA)) self.window = window window.makeKeyAndVisible() } } }
apache-2.0
0ca247ef4e6aac38cb8177c963b5ead1
32.5
76
0.720682
4.674419
false
false
false
false
Andgfaria/MiniGitClient-iOS
MiniGitClient/MiniGitClient/Scenes/Detail/Cell/PullRequestTableViewCell.swift
1
4914
/* Copyright 2017 - André Gimenez Faria 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 PullRequestTableViewCell: UITableViewCell { fileprivate let wrapperView = UIView(frame: CGRect.zero) let titleLabel = UILabel(frame: CGRect.zero) let bodyTextView = UITextView(frame: CGRect.zero) let avatarImageView = UIImageView(frame: CGRect.zero) let authorLabel = UILabel(frame: CGRect.zero) override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup(withViews: [wrapperView]) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup(withViews: [wrapperView]) } } extension PullRequestTableViewCell : ViewCodable { func setupConstraints() { wrapperView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true wrapperView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true wrapperView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true wrapperView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -12).isActive = true let heightConstraint = wrapperView.heightAnchor.constraint(greaterThanOrEqualToConstant: 72) heightConstraint.priority = 500 heightConstraint.isActive = true let subviews = [titleLabel,bodyTextView,avatarImageView,authorLabel] for view in subviews { wrapperView.addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false } titleLabel.topAnchor.constraint(equalTo: wrapperView.topAnchor, constant: 6).isActive = true titleLabel.leadingAnchor.constraint(equalTo: wrapperView.leadingAnchor, constant: 16).isActive = true titleLabel.trailingAnchor.constraint(equalTo: avatarImageView.leadingAnchor, constant: -16).isActive = true bodyTextView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 6).isActive = true bodyTextView.leadingAnchor.constraint(equalTo: wrapperView.leadingAnchor, constant: 11).isActive = true bodyTextView.trailingAnchor.constraint(equalTo: titleLabel.trailingAnchor).isActive = true bodyTextView.bottomAnchor.constraint(equalTo: wrapperView.bottomAnchor).isActive = true avatarImageView.topAnchor.constraint(equalTo: wrapperView.topAnchor, constant: 6).isActive = true avatarImageView.trailingAnchor.constraint(equalTo: wrapperView.trailingAnchor, constant: -18).isActive = true avatarImageView.widthAnchor.constraint(equalToConstant: 44).isActive = true avatarImageView.heightAnchor.constraint(equalToConstant: 44).isActive = true authorLabel.topAnchor.constraint(equalTo: avatarImageView.bottomAnchor, constant: 3).isActive = true authorLabel.widthAnchor.constraint(equalTo: avatarImageView.widthAnchor).isActive = true authorLabel.centerXAnchor.constraint(equalTo: avatarImageView.centerXAnchor).isActive = true authorLabel.heightAnchor.constraint(equalToConstant: 18).isActive = true } func setupStyles() { titleLabel.font = UIFont.boldSystemFont(ofSize: 16) titleLabel.numberOfLines = 0 bodyTextView.font = UIFont.systemFont(ofSize: 14) bodyTextView.isUserInteractionEnabled = false bodyTextView.isScrollEnabled = false bodyTextView.textContainerInset = UIEdgeInsets.zero avatarImageView.layer.cornerRadius = 22 avatarImageView.layer.masksToBounds = true authorLabel.textAlignment = .center authorLabel.font = UIFont.systemFont(ofSize: 7) authorLabel.textColor = .lightGray authorLabel.numberOfLines = 0 } }
mit
70e1562eac5f231d83acce73dab565cf
50.177083
461
0.734175
5.608447
false
false
false
false
chrisjmendez/swift-exercises
GUI/Timeline/Timeline/ViewController.swift
1
4302
// // ViewController.swift // Timeline // // Created by Chris on 2/1/16. // Copyright © 2016 Chris Mendez. All rights reserved. // import Alamofire import SwiftyJSON import UIKit class ViewController: UIViewController { var scrollView: UIScrollView! var timeline: TimelineView! let REDDIT = "https://www.reddit.com/new.json?limit=100" let HACKER_NEWS = "https://hacker-news.firebaseio.com/v0/topstories.json" var events:[TimeFrame] = [ TimeFrame(text: "New Year's Day", date: "January 1", image: UIImage(named: "fireworks.jpeg")), TimeFrame(text: "The month of love!", date: "February 14", image: UIImage(named: "heart.png")), TimeFrame(text: "Comes like a lion, leaves like a lamb", date: "March", image: nil), TimeFrame(text: "Dumb stupid pranks.", date: "April 1", image: UIImage(named: "april.jpeg")), TimeFrame(text: "That's right. No image is necessary!", date: "No image?", image: nil), TimeFrame(text: "This control can stretch. It doesn't matter how long or short the text is, or how many times you wiggle your nose and make a wish. The control always fits the content, and even extends a while at the end so the scroll view it is put into, even when pulled pretty far down, does not show the end of the scroll view.", date: "Long text", image: nil), TimeFrame(text: "Hope this helps someone!", date: "That's it!", image: nil) ] func getJSON(url:String){ Alamofire.request(.GET, REDDIT, parameters: nil).validate().responseJSON { response in switch response.result { case .Success: let data = response.result.value as? NSDictionary let json = JSON(data!) self.parseJSON(json) case .Failure(let error): print(error) } } } func parseJSON(json:JSON){ print("JSON: \(json["data"]["children"][0]["data"]["title"])") initScrollView(events) } func onLoad(){ getJSON(REDDIT) } func initScrollView(timeFrames:[TimeFrame]){ scrollView = UIScrollView(frame: view.bounds) scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) view.addConstraints([ NSLayoutConstraint(item: scrollView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: scrollView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1.0, constant: 29), NSLayoutConstraint(item: scrollView, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: scrollView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1.0, constant: 0) ]) timeline = TimelineView(bulletType: .Circle, timeFrames: timeFrames ) scrollView.addSubview(timeline) scrollView.addConstraints([ NSLayoutConstraint(item: timeline, attribute: .Left, relatedBy: .Equal, toItem: scrollView, attribute: .Left, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: timeline, attribute: .Bottom, relatedBy: .LessThanOrEqual, toItem: scrollView, attribute: .Bottom, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: timeline, attribute: .Top, relatedBy: .Equal, toItem: scrollView, attribute: .Top, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: timeline, attribute: .Right, relatedBy: .Equal, toItem: scrollView, attribute: .Right, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: timeline, attribute: .Width, relatedBy: .Equal, toItem: scrollView, attribute: .Width, multiplier: 1.0, constant: 0) ]) view.sendSubviewToBack(scrollView) } override func viewDidLoad() { super.viewDidLoad() onLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prefersStatusBarHidden() -> Bool { return true } }
mit
873455ed7defde8e50be0eabdd8dca00
43.802083
373
0.643339
4.434021
false
false
false
false
haveahennessy/Patrician
Patrician/Node.swift
1
2284
// // Node.swift // Patrician // // Created by Matt Isaacs. // Copyright (c) 2015 Matt Isaacs. All rights reserved. // class Node<T> { var edges: ContiguousArray<Edge<T>> = [] var prefix: String var terminal: Terminal<T>? = nil init(edges: ContiguousArray<Edge<T>>, prefix: String, terminal: Terminal<T>?) { self.edges = edges self.prefix = prefix self.terminal = terminal } convenience init(edges: ContiguousArray<Edge<T>>, prefix: Array<Character>, terminal: Terminal<T>?) { self.init(edges: edges, prefix: String(prefix), terminal: terminal) } func search(idx: Int, col: ArraySlice<Edge<T>>, label: Character) -> Int? { let count = col.count if count == 1 { return label == col[0].label ? idx : nil } if count > 1 { let mid = count / 2 let left = col[0..<mid] let right = col[mid..<count] let midEdge = col[mid] if label == midEdge.label { return mid + idx } if label < midEdge.label { return search(0, col: left, label: label) } else { return search(mid + idx, col: right, label: label) } } return nil } func edgeForLabel(char: Character) -> Edge<T>? { if let idx = search(0, col: self.edges.slice, label: char) { return self.edges[idx] } return nil } func addEdge(edge: Edge<T>) { self.edges.append(edge) self.edges.sort { return $0.label < $1.label } } func replaceEdge(edge: Edge<T>) { if let idx = search(0, col: self.edges.slice, label: edge.label) { self.edges[idx] = edge } else { self.edges.append(edge) } } func removeEdge(label: Character) { if let idx = search(0, col: self.edges.slice, label: label) { self.edges.removeAtIndex(idx) } } func setTerminal(terminal: Terminal<T>) { self.terminal = terminal } func setPrefix(prefix: String) { self.prefix = prefix } func setPrefix(prefix: Array<Character>) { self.prefix = String(prefix) } }
mit
39177ec0b6f9a302d46e03b198ae2ae0
24.662921
105
0.531524
3.851602
false
false
false
false
yume190/JSONDecodeKit
Sources/JSONDecodeKit/JSONSerializable.swift
1
1324
import Foundation // Title: An easy way to convert Swift structs to JSON // source: http://codelle.com/blog/2016/5/an-easy-way-to-convert-swift-structs-to-json/ public protocol JSONRepresentable { var JSONRepresentation: Any { get } } public protocol JSONSerializable: JSONRepresentable {} extension JSONSerializable { public var JSONRepresentation: Any { var representation = [String: Any]() for case let (label?, value) in Mirror(reflecting: self).children { switch value { case let value as JSONRepresentable: representation[label] = value.JSONRepresentation default: // Ignore any unserializable properties representation[label] = value break } } return representation } } extension JSONSerializable { public func toJSON() -> String { let representation = JSONRepresentation guard JSONSerialization.isValidJSONObject(representation) else { return "" } do { let data = try JSONSerialization.data(withJSONObject:representation, options: []) return String(data: data, encoding: .utf8) ?? "" } catch { return "" } } }
mit
d1be7f8cafddefb02f9b80d5afef7e03
27.170213
93
0.594411
5.360324
false
false
false
false
arietis/codility-swift
99.4.swift
1
1487
public func solution(inout A : [Point2D]) -> Int { // write your code in Swift 2.2 (Linux) func isClockwise(a: Point2D, b: Point2D, c: Point2D) -> Int { let result = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) if result > 0 { return 1 } else if result < 0 { return -1 } else { return 0 } } var lowestY = A[0].y var lowestYIndex: [Int] = [] for i in 0..<A.count { if A[i].y < lowestY { lowestY = A[i].y lowestYIndex = [i] } else if A[i].y == lowestY { lowestYIndex.append(i) } else { continue } } var startPoint = lowestYIndex[0] var lowestYArray = Array(count: A.count, repeatedValue: false) for i in lowestYIndex { lowestYArray[i] = true } while lowestYArray[startPoint] == true { startPoint = (startPoint + 1) % A.count } startPoint = (startPoint - 1 + A.count) % A.count let rotatedA = Array(A[startPoint..<A.count] + A[0..<startPoint]) let direction = isClockwise(rotatedA[rotatedA.count - 1], b: rotatedA[0], c: rotatedA[1]) let extendedA = rotatedA + Array(rotatedA[0..<2]) for i in 0..<A.count { let temp = isClockwise(extendedA[i], b: extendedA[i + 1], c: extendedA[i + 2]) if temp * direction < 0 { return (i + 1 + startPoint) % A.count } } return -1 }
mit
b17817badf7d30dedfcbafff2cdde167
24.20339
93
0.510424
3.394977
false
false
false
false
zzgo/v2ex
v2ex/Pods/RAMAnimatedTabBarController/RAMAnimatedTabBarController/RAMItemAnimationProtocol.swift
7
3429
// RAMItemAnimationProtocol.swift // // Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit public protocol RAMItemAnimationProtocol { func playAnimation(_ icon : UIImageView, textLabel : UILabel) func deselectAnimation(_ icon : UIImageView, textLabel : UILabel, defaultTextColor : UIColor, defaultIconColor : UIColor) func selectedState(_ icon : UIImageView, textLabel : UILabel) } /// Base class for UITabBarItems animation open class RAMItemAnimation: NSObject, RAMItemAnimationProtocol { // MARK: constants struct Constants { struct AnimationKeys { static let Scale = "transform.scale" static let Rotation = "transform.rotation" static let KeyFrame = "contents" static let PositionY = "position.y" static let Opacity = "opacity" } } // MARK: properties /// The duration of the animation @IBInspectable open var duration : CGFloat = 0.5 /// The text color in selected state. @IBInspectable open var textSelectedColor: UIColor = UIColor.init(red: 0, green: 0.478431, blue: 1, alpha: 1) /// The icon color in selected state. @IBInspectable open var iconSelectedColor: UIColor! /** Start animation, method call when UITabBarItem is selected - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel */ open func playAnimation(_ icon : UIImageView, textLabel : UILabel) { fatalError("override method in subclass") } /** Start animation, method call when UITabBarItem is unselected - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel - parameter defaultTextColor: default UITabBarItem text color - parameter defaultIconColor: default UITabBarItem icon color */ open func deselectAnimation(_ icon : UIImageView, textLabel : UILabel, defaultTextColor : UIColor, defaultIconColor : UIColor) { fatalError("override method in subclass") } /** Method call when TabBarController did load - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel */ open func selectedState(_ icon: UIImageView, textLabel : UILabel) { fatalError("override method in subclass") } }
mit
4ffe09f94e5fdb1dc8aef8671c9ac6c7
35.870968
130
0.728492
5.020498
false
false
false
false
r-mckay/montreal-iqa
montrealIqaCore/Carthage/Checkouts/realm-cocoa/RealmSwift/Tests/ObjectiveCSupportTests.swift
5
4395
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import RealmSwift import XCTest class ObjectiveCSupportTests: TestCase { func testSupport() { let realm = try! Realm() try! realm.write { realm.add(SwiftObject()) return } let results = realm.objects(SwiftObject.self) let rlmResults = ObjectiveCSupport.convert(object: results) XCTAssert(rlmResults.isKind(of: RLMResults.self)) XCTAssertEqual(rlmResults.count, 1) XCTAssertEqual(unsafeBitCast(rlmResults.firstObject(), to: SwiftObject.self).intCol, 123) let list = List<SwiftObject>() list.append(SwiftObject()) let rlmArray = ObjectiveCSupport.convert(object: list) XCTAssert(rlmArray.isKind(of: RLMArray.self)) XCTAssertEqual(unsafeBitCast(rlmArray.firstObject(), to: SwiftObject.self).floatCol, 1.23) XCTAssertEqual(rlmArray.count, 1) let rlmRealm = ObjectiveCSupport.convert(object: realm) XCTAssert(rlmRealm.isKind(of: RLMRealm.self)) XCTAssertEqual(rlmRealm.allObjects("SwiftObject").count, 1) let sortDescriptor: RealmSwift.SortDescriptor = "property" XCTAssertEqual(sortDescriptor.keyPath, ObjectiveCSupport.convert(object: sortDescriptor).keyPath, "SortDescriptor.keyPath must be equal to RLMSortDescriptor.keyPath") XCTAssertEqual(sortDescriptor.ascending, ObjectiveCSupport.convert(object: sortDescriptor).ascending, "SortDescriptor.ascending must be equal to RLMSortDescriptor.ascending") } func testConfigurationSupport() { let realm = try! Realm() try! realm.write { realm.add(SwiftObject()) return } XCTAssertEqual(realm.configuration.fileURL, ObjectiveCSupport.convert(object: realm.configuration).fileURL, "Configuration.fileURL must be equal to RLMConfiguration.fileURL") XCTAssertEqual(realm.configuration.inMemoryIdentifier, ObjectiveCSupport.convert(object: realm.configuration).inMemoryIdentifier, "Configuration.inMemoryIdentifier must be equal to RLMConfiguration.inMemoryIdentifier") XCTAssertEqual(realm.configuration.syncConfiguration?.realmURL, ObjectiveCSupport.convert(object: realm.configuration).syncConfiguration?.realmURL, "Configuration.syncConfiguration must be equal to RLMConfiguration.syncConfiguration") XCTAssertEqual(realm.configuration.encryptionKey, ObjectiveCSupport.convert(object: realm.configuration).encryptionKey, "Configuration.encryptionKey must be equal to RLMConfiguration.encryptionKey") XCTAssertEqual(realm.configuration.readOnly, ObjectiveCSupport.convert(object: realm.configuration).readOnly, "Configuration.readOnly must be equal to RLMConfiguration.readOnly") XCTAssertEqual(realm.configuration.schemaVersion, ObjectiveCSupport.convert(object: realm.configuration).schemaVersion, "Configuration.schemaVersion must be equal to RLMConfiguration.schemaVersion") XCTAssertEqual(realm.configuration.deleteRealmIfMigrationNeeded, ObjectiveCSupport.convert(object: realm.configuration).deleteRealmIfMigrationNeeded, "Configuration.deleteRealmIfMigrationNeeded must be equal to RLMConfiguration.deleteRealmIfMigrationNeeded") } }
mit
bee40576b7bcd71370108a5f8fd4ed3b
43.846939
131
0.659841
5.979592
false
true
false
false
PodRepo/firefox-ios
Utils/DeferredUtils.swift
3
5038
/* 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/. */ // Haskell, baby. // Monadic bind/flatMap operator for Deferred. infix operator >>== { associativity left precedence 160 } public func >>== <T, U>(x: Deferred<Maybe<T>>, f: T -> Deferred<Maybe<U>>) -> Deferred<Maybe<U>> { return chainDeferred(x, f: f) } // A termination case. public func >>== <T>(x: Deferred<Maybe<T>>, f: T -> ()) { return x.upon { result in if let v = result.successValue { f(v) } } } // Monadic `do` for Deferred. infix operator >>> { associativity left precedence 150 } public func >>> <T, U>(x: Deferred<Maybe<T>>, f: () -> Deferred<Maybe<U>>) -> Deferred<Maybe<U>> { return x.bind { res in if res.isSuccess { return f(); } return deferMaybe(res.failureValue!) } } /** * Returns a thunk that return a Deferred that resolves to the provided value. */ public func always<T>(t: T) -> () -> Deferred<Maybe<T>> { return { deferMaybe(t) } } public func deferMaybe<T>(s: T) -> Deferred<Maybe<T>> { return Deferred(value: Maybe(success: s)) } public func deferMaybe<T>(e: MaybeErrorType) -> Deferred<Maybe<T>> { return Deferred(value: Maybe(failure: e)) } public typealias Success = Deferred<Maybe<()>> public func succeed() -> Success { return deferMaybe(()) } /** * Return a single Deferred that represents the sequential chaining * of f over the provided items. */ public func walk<T>(items: [T], f: T -> Success) -> Success { return items.reduce(succeed()) { success, item -> Success in success >>> { f(item) } } } /** * Like `all`, but thanks to its taking thunks as input, each result is * generated in strict sequence. Fails immediately if any result is failure. */ public func accumulate<T>(thunks: [() -> Deferred<Maybe<T>>]) -> Deferred<Maybe<[T]>> { if thunks.isEmpty { return deferMaybe([]) } let combined = Deferred<Maybe<[T]>>() var results: [T] = [] results.reserveCapacity(thunks.count) var onValue: (T -> ())! var onResult: (Maybe<T> -> ())! onValue = { t in results.append(t) if results.count == thunks.count { combined.fill(Maybe(success: results)) } else { thunks[results.count]().upon(onResult) } } onResult = { r in if r.isFailure { combined.fill(Maybe(failure: r.failureValue!)) return } onValue(r.successValue!) } thunks[0]().upon(onResult) return combined } /** * Take a function and turn it into a side-effect that can appear * in a chain of async operations without producing its own value. */ public func effect<T, U>(f: T -> U) -> T -> Deferred<Maybe<T>> { return { t in f(t) return deferMaybe(t) } } /** * Return a single Deferred that represents the sequential chaining of * f over the provided items, with the return value chained through. */ public func walk<T, U>(items: [T], start: Deferred<Maybe<U>>, f: (T, U) -> Deferred<Maybe<U>>) -> Deferred<Maybe<U>> { let fs = items.map { item in return { val in f(item, val) } } return fs.reduce(start, combine: >>==) } /** * Like `all`, but doesn't accrue individual values. */ public func allSucceed(deferreds: Success...) -> Success { return all(deferreds).bind { (results) -> Success in if let failure = find(results, f: { $0.isFailure }) { return deferMaybe(failure.failureValue!) } return succeed() } } public func allSucceed(deferreds: [Success]) -> Success { return all(deferreds).bind { (results) -> Success in if let failure = find(results, f: { $0.isFailure }) { return deferMaybe(failure.failureValue!) } return succeed() } } public func chainDeferred<T, U>(a: Deferred<Maybe<T>>, f: T -> Deferred<Maybe<U>>) -> Deferred<Maybe<U>> { return a.bind { res in if let v = res.successValue { return f(v) } return Deferred(value: Maybe<U>(failure: res.failureValue!)) } } public func chainResult<T, U>(a: Deferred<Maybe<T>>, f: T -> Maybe<U>) -> Deferred<Maybe<U>> { return a.map { res in if let v = res.successValue { return f(v) } return Maybe<U>(failure: res.failureValue!) } } public func chain<T, U>(a: Deferred<Maybe<T>>, f: T -> U) -> Deferred<Maybe<U>> { return chainResult(a, f: { Maybe<U>(success: f($0)) }) } /// Defer-ifies a block to an async dispatch queue. public func deferDispatchAsync<T>(queue: dispatch_queue_t, f: () -> Deferred<Maybe<T>>) -> Deferred<Maybe<T>> { let deferred = Deferred<Maybe<T>>() dispatch_async(queue, { f().upon { result in deferred.fill(result) } }) return deferred }
mpl-2.0
fd3f8bf6c35cf61b9535047f466c421d
26.530055
118
0.594085
3.666667
false
false
false
false
CatchChat/Yep
Yep/Views/Mention/MentionView.swift
1
7110
// // MentionView.swift // Yep // // Created by nixzhu on 16/1/11. // Copyright © 2016年 Catch Inc. All rights reserved. // import UIKit import YepKit import Navi private class MentionUserCell: UITableViewCell { lazy var avatarImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .ScaleAspectFit return imageView }() lazy var nicknameLabel: UILabel = { let label = UILabel() label.textColor = UIColor.blackColor() label.font = UIFont.systemFontOfSize(14) return label }() lazy var mentionUsernameLabel: UILabel = { let label = UILabel() label.textColor = UIColor.yepTintColor() label.font = UIFont.systemFontOfSize(14) return label }() private override func prepareForReuse() { super.prepareForReuse() avatarImageView.image = nil } override func didMoveToSuperview() { super.didMoveToSuperview() makeUI() } func makeUI() { backgroundColor = UIColor.clearColor() contentView.addSubview(avatarImageView) contentView.addSubview(nicknameLabel) contentView.addSubview(mentionUsernameLabel) avatarImageView.translatesAutoresizingMaskIntoConstraints = false nicknameLabel.translatesAutoresizingMaskIntoConstraints = false mentionUsernameLabel.translatesAutoresizingMaskIntoConstraints = false let views: [String: AnyObject] = [ "avatarImageView": avatarImageView, "nicknameLabel": nicknameLabel, "mentionUsernameLabel": mentionUsernameLabel, ] let constraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[avatarImageView(30)]-15-[nicknameLabel]-[mentionUsernameLabel]-15-|", options: [.AlignAllCenterY], metrics: nil, views: views) mentionUsernameLabel.setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Horizontal) let avatarImageViewCenterY = NSLayoutConstraint(item: avatarImageView, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0) let avatarImageViewHeight = NSLayoutConstraint(item: avatarImageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 30) NSLayoutConstraint.activateConstraints(constraintsH) NSLayoutConstraint.activateConstraints([avatarImageViewCenterY, avatarImageViewHeight]) } func configureWithUsernamePrefixMatchedUser(user: UsernamePrefixMatchedUser) { if let avatarURLString = user.avatarURLString { let plainAvatar = PlainAvatar(avatarURLString: avatarURLString, avatarStyle: picoAvatarStyle) avatarImageView.navi_setAvatar(plainAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration) } else { avatarImageView.image = UIImage.yep_defaultAvatar30 } nicknameLabel.text = user.nickname mentionUsernameLabel.text = user.mentionUsername } } final class MentionView: UIView { static let height: CGFloat = 125 var users: [UsernamePrefixMatchedUser] = [] { didSet { tableView.reloadData() } } var pickUserAction: ((username: String) -> Void)? lazy var horizontalLineView: HorizontalLineView = { let view = HorizontalLineView() view.backgroundColor = UIColor.clearColor() view.lineColor = UIColor.lightGrayColor() return view }() static let tableViewRowHeight: CGFloat = 50 lazy var tableView: UITableView = { let tableView = UITableView() tableView.backgroundColor = UIColor.clearColor() tableView.separatorInset = UIEdgeInsets(top: 0, left: 60, bottom: 0, right: 0) let effect = UIBlurEffect(style: .ExtraLight) let blurView = UIVisualEffectView(effect: effect) tableView.backgroundView = blurView tableView.separatorEffect = UIVibrancyEffect(forBlurEffect: effect) tableView.registerClassOf(MentionUserCell) tableView.rowHeight = MentionView.tableViewRowHeight tableView.dataSource = self tableView.delegate = self return tableView }() override func didMoveToSuperview() { super.didMoveToSuperview() makeUI() } func makeUI() { addSubview(horizontalLineView) addSubview(tableView) horizontalLineView.translatesAutoresizingMaskIntoConstraints = false tableView.translatesAutoresizingMaskIntoConstraints = false let views: [String: AnyObject] = [ "horizontalLineView": horizontalLineView, "tableView": tableView, ] let constraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[tableView]|", options: [], metrics: nil, views: views) let constraintsV = NSLayoutConstraint.constraintsWithVisualFormat("V:|[horizontalLineView(1)][tableView]|", options: [.AlignAllLeading, .AlignAllTrailing], metrics: nil, views: views) NSLayoutConstraint.activateConstraints(constraintsH) NSLayoutConstraint.activateConstraints(constraintsV) } weak var heightConstraint: NSLayoutConstraint? weak var bottomConstraint: NSLayoutConstraint? func show() { let usersCount = users.count let height = usersCount >= 3 ? MentionView.height : CGFloat(usersCount) * MentionView.tableViewRowHeight UIView.animateWithDuration(0.25, delay: 0.0, options: .CurveEaseInOut, animations: { [weak self] in self?.bottomConstraint?.constant = 0 self?.heightConstraint?.constant = height self?.superview?.layoutIfNeeded() }, completion: { _ in }) if !users.isEmpty { tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: .Top, animated: false) } } func hide() { UIView.animateWithDuration(0.25, delay: 0.0, options: .CurveEaseInOut, animations: { [weak self] in self?.bottomConstraint?.constant = MentionView.height self?.superview?.layoutIfNeeded() }, completion: { _ in }) } } extension MentionView: UITableViewDataSource, UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return users.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: MentionUserCell = tableView.dequeueReusableCell() let user = users[indexPath.row] cell.configureWithUsernamePrefixMatchedUser(user) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { defer { tableView.deselectRowAtIndexPath(indexPath, animated: true) } let username = users[indexPath.row].username pickUserAction?(username: username) } }
mit
3abf72936e0002faaf1b667627dfd5a2
32.21028
209
0.686506
5.596063
false
false
false
false
SwifterSwift/SwifterSwift
Sources/SwifterSwift/SwiftStdlib/DictionaryExtensions.swift
1
11221
// DictionaryExtensions.swift - Copyright 2020 SwifterSwift #if canImport(Foundation) import Foundation #endif // MARK: - Methods public extension Dictionary { /// SwifterSwift: Creates a Dictionary from a given sequence grouped by a given key path. /// /// - Parameters: /// - sequence: Sequence being grouped. /// - keypath: The key path to group by. init<S: Sequence>(grouping sequence: S, by keyPath: KeyPath<S.Element, Key>) where Value == [S.Element] { self.init(grouping: sequence, by: { $0[keyPath: keyPath] }) } /// SwifterSwift: Check if key exists in dictionary. /// /// let dict: [String: Any] = ["testKey": "testValue", "testArrayKey": [1, 2, 3, 4, 5]] /// dict.has(key: "testKey") -> true /// dict.has(key: "anotherKey") -> false /// /// - Parameter key: key to search for. /// - Returns: true if key exists in dictionary. func has(key: Key) -> Bool { return index(forKey: key) != nil } /// SwifterSwift: Remove all keys contained in the keys parameter from the dictionary. /// /// var dict : [String: String] = ["key1" : "value1", "key2" : "value2", "key3" : "value3"] /// dict.removeAll(keys: ["key1", "key2"]) /// dict.keys.contains("key3") -> true /// dict.keys.contains("key1") -> false /// dict.keys.contains("key2") -> false /// /// - Parameter keys: keys to be removed. mutating func removeAll<S: Sequence>(keys: S) where S.Element == Key { keys.forEach { removeValue(forKey: $0) } } /// SwifterSwift: Remove a value for a random key from the dictionary. @discardableResult mutating func removeValueForRandomKey() -> Value? { guard let randomKey = keys.randomElement() else { return nil } return removeValue(forKey: randomKey) } #if canImport(Foundation) /// SwifterSwift: JSON Data from dictionary. /// /// - Parameter prettify: set true to prettify data (default is false). /// - Returns: optional JSON Data (if applicable). func jsonData(prettify: Bool = false) -> Data? { guard JSONSerialization.isValidJSONObject(self) else { return nil } let options = (prettify == true) ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization .WritingOptions() return try? JSONSerialization.data(withJSONObject: self, options: options) } #endif #if canImport(Foundation) /// SwifterSwift: JSON String from dictionary. /// /// dict.jsonString() -> "{"testKey":"testValue","testArrayKey":[1,2,3,4,5]}" /// /// dict.jsonString(prettify: true) /// /* /// returns the following string: /// /// "{ /// "testKey" : "testValue", /// "testArrayKey" : [ /// 1, /// 2, /// 3, /// 4, /// 5 /// ] /// }" /// /// */ /// /// - Parameter prettify: set true to prettify string (default is false). /// - Returns: optional JSON String (if applicable). func jsonString(prettify: Bool = false) -> String? { guard JSONSerialization.isValidJSONObject(self) else { return nil } let options = (prettify == true) ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization .WritingOptions() guard let jsonData = try? JSONSerialization.data(withJSONObject: self, options: options) else { return nil } return String(data: jsonData, encoding: .utf8) } #endif /// SwifterSwift: Returns a dictionary containing the results of mapping the given closure over the sequence’s elements. /// - Parameter transform: A mapping closure. `transform` accepts an element of this sequence as its parameter and returns a transformed value of the same or of a different type. /// - Returns: A dictionary containing the transformed elements of this sequence. func mapKeysAndValues<K, V>(_ transform: ((key: Key, value: Value)) throws -> (K, V)) rethrows -> [K: V] { return [K: V](uniqueKeysWithValues: try map(transform)) } /// SwifterSwift: Returns a dictionary containing the non-`nil` results of calling the given transformation with each element of this sequence. /// - Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value. /// - Returns: A dictionary of the non-`nil` results of calling `transform` with each element of the sequence. /// - Complexity: *O(m + n)*, where _m_ is the length of this sequence and _n_ is the length of the result. func compactMapKeysAndValues<K, V>(_ transform: ((key: Key, value: Value)) throws -> (K, V)?) rethrows -> [K: V] { return [K: V](uniqueKeysWithValues: try compactMap(transform)) } /// SwifterSwift: Creates a new dictionary using specified keys. /// /// var dict = ["key1": 1, "key2": 2, "key3": 3, "key4": 4] /// dict.pick(keys: ["key1", "key3", "key4"]) -> ["key1": 1, "key3": 3, "key4": 4] /// dict.pick(keys: ["key2"]) -> ["key2": 2] /// /// - Complexity: O(K), where _K_ is the length of the keys array. /// /// - Parameter keys: An array of keys that will be the entries in the resulting dictionary. /// /// - Returns: A new dictionary that contains the specified keys only. If none of the keys exist, an empty dictionary will be returned. func pick(keys: [Key]) -> [Key: Value] { keys.reduce(into: [Key: Value]()) { result, item in result[item] = self[item] } } } // MARK: - Methods (Value: Equatable) public extension Dictionary where Value: Equatable { /// SwifterSwift: Returns an array of all keys that have the given value in dictionary. /// /// let dict = ["key1": "value1", "key2": "value1", "key3": "value2"] /// dict.keys(forValue: "value1") -> ["key1", "key2"] /// dict.keys(forValue: "value2") -> ["key3"] /// dict.keys(forValue: "value3") -> [] /// /// - Parameter value: Value for which keys are to be fetched. /// - Returns: An array containing keys that have the given value. func keys(forValue value: Value) -> [Key] { return keys.filter { self[$0] == value } } } // MARK: - Methods (ExpressibleByStringLiteral) public extension Dictionary where Key: StringProtocol { /// SwifterSwift: Lowercase all keys in dictionary. /// /// var dict = ["tEstKeY": "value"] /// dict.lowercaseAllKeys() /// print(dict) // prints "["testkey": "value"]" /// mutating func lowercaseAllKeys() { // http://stackoverflow.com/questions/33180028/extend-dictionary-where-key-is-of-type-string for key in keys { if let lowercaseKey = String(describing: key).lowercased() as? Key { self[lowercaseKey] = removeValue(forKey: key) } } } } // MARK: - Subscripts public extension Dictionary { /// SwifterSwift: Deep fetch or set a value from nested dictionaries. /// /// var dict = ["key": ["key1": ["key2": "value"]]] /// dict[path: ["key", "key1", "key2"]] = "newValue" /// dict[path: ["key", "key1", "key2"]] -> "newValue" /// /// - Note: Value fetching is iterative, while setting is recursive. /// /// - Complexity: O(N), _N_ being the length of the path passed in. /// /// - Parameter path: An array of keys to the desired value. /// /// - Returns: The value for the key-path passed in. `nil` if no value is found. subscript(path path: [Key]) -> Any? { get { guard !path.isEmpty else { return nil } var result: Any? = self for key in path { if let element = (result as? [Key: Any])?[key] { result = element } else { return nil } } return result } set { if let first = path.first { if path.count == 1, let new = newValue as? Value { return self[first] = new } if var nested = self[first] as? [Key: Any] { nested[path: Array(path.dropFirst())] = newValue return self[first] = nested as? Value } } } } } // MARK: - Operators public extension Dictionary { /// SwifterSwift: Merge the keys/values of two dictionaries. /// /// let dict: [String: String] = ["key1": "value1"] /// let dict2: [String: String] = ["key2": "value2"] /// let result = dict + dict2 /// result["key1"] -> "value1" /// result["key2"] -> "value2" /// /// - Parameters: /// - lhs: dictionary. /// - rhs: dictionary. /// - Returns: An dictionary with keys and values from both. static func + (lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] { var result = lhs rhs.forEach { result[$0] = $1 } return result } // MARK: - Operators /// SwifterSwift: Append the keys and values from the second dictionary into the first one. /// /// var dict: [String: String] = ["key1": "value1"] /// let dict2: [String: String] = ["key2": "value2"] /// dict += dict2 /// dict["key1"] -> "value1" /// dict["key2"] -> "value2" /// /// - Parameters: /// - lhs: dictionary. /// - rhs: dictionary. static func += (lhs: inout [Key: Value], rhs: [Key: Value]) { rhs.forEach { lhs[$0] = $1 } } /// SwifterSwift: Remove keys contained in the sequence from the dictionary. /// /// let dict: [String: String] = ["key1": "value1", "key2": "value2", "key3": "value3"] /// let result = dict-["key1", "key2"] /// result.keys.contains("key3") -> true /// result.keys.contains("key1") -> false /// result.keys.contains("key2") -> false /// /// - Parameters: /// - lhs: dictionary. /// - keys: array with the keys to be removed. /// - Returns: a new dictionary with keys removed. static func - <S: Sequence>(lhs: [Key: Value], keys: S) -> [Key: Value] where S.Element == Key { var result = lhs result.removeAll(keys: keys) return result } /// SwifterSwift: Remove keys contained in the sequence from the dictionary. /// /// var dict: [String: String] = ["key1": "value1", "key2": "value2", "key3": "value3"] /// dict-=["key1", "key2"] /// dict.keys.contains("key3") -> true /// dict.keys.contains("key1") -> false /// dict.keys.contains("key2") -> false /// /// - Parameters: /// - lhs: dictionary. /// - keys: array with the keys to be removed. static func -= <S: Sequence>(lhs: inout [Key: Value], keys: S) where S.Element == Key { lhs.removeAll(keys: keys) } }
mit
94b1d96993a8397283933fec7c4f28c8
38.925267
182
0.559319
4.031261
false
false
false
false
nfls/nflsers
app/v2/Model/Practice/Course.swift
1
774
// // Course.swift // NFLSers-iOS // // Created by Qingyang Hu on 2018/8/11. // Copyright © 2018 胡清阳. All rights reserved. // import Foundation import ObjectMapper class Course: Model { required init(map: Map) throws { self.id = UUID(uuidString: try map.value("id"))! self.name = try map.value("name") self.remark = try map.value("remark") self.type = CourseType(rawValue: try map.value("type"))! } let id: UUID let name: String let remark: String let type: CourseType var fullname: String { get { return self.name + " (" + self.remark + ")" } } enum CourseType: Int, Codable { case igcse = 1 case alevel = 2 case ibdp = 3 } }
apache-2.0
1a0098729bcc2b1b2fd716cd36532ae9
20.914286
64
0.563233
3.723301
false
false
false
false
yangchenghu/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Discover/DiscoverViewController.swift
5
3401
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class DiscoverViewController: AATableViewController { var tableData: UAGrouppedTableData! var groups: JavaUtilList! init() { super.init(style: UITableViewStyle.Plain) var title = ""; if (MainAppTheme.tab.showText) { title = NSLocalizedString("TabDiscover", comment: "Discover Title") } tabBarItem = UITabBarItem(title: title, image: MainAppTheme.tab.createUnselectedIcon("ic_discover_outlined"), selectedImage: MainAppTheme.tab.createSelectedIcon("ic_discover")) if (!MainAppTheme.tab.showText) { tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0); } navigationItem.title = NSLocalizedString("TabDiscover", comment: "Discover Title") extendedLayoutIncludesOpaqueBars = true } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.backgroundColor = MainAppTheme.list.backyardColor tableView.hidden = true // tableData = UAGrouppedTableData(tableView: tableView) view.backgroundColor = UIColor.whiteColor() execute(Actor.listPublicGroups(), successBlock: { (val) -> Void in self.groups = val as! JavaUtilList self.tableView.hidden = false self.tableView.reloadData() }) { (val) -> Void in } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 104 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.groups == nil { return 0 } return Int(self.groups.size()) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let g = groups.getWithInt(jint(indexPath.row)) as! ACPublicGroup let res = PublicCell() res.bind(g, isLast: (indexPath.row == self.groups.size() - 1)) return res } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let g = groups.getWithInt(jint(indexPath.row)) as! ACPublicGroup confirmAlertUser("JoinAlertMessage", action: "AlertYes", tapYes: { () -> () in let gid = g.getId() self.execute(Actor.joinPublicGroupCommandWithGig(g.getId(), withAccessHash: g.getAccessHash()), successBlock: { (val) -> Void in self.navigateNext(ConversationViewController(peer: ACPeer.groupWithInt(gid)), removeCurrent: false) }, failureBlock: { (val) -> Void in // Try to open chat, why not? // TODO: Better logic self.navigateNext(ConversationViewController(peer: ACPeer.groupWithInt(gid)), removeCurrent: false) }) }) } }
mit
528532deac8c60b246a0e35ee3319068
34.061856
140
0.620994
5.137462
false
false
false
false
exponent/exponent
ios/vendored/sdk44/@stripe/stripe-react-native/ios/CardFieldView.swift
2
6537
import Foundation import UIKit import Stripe class CardFieldView: UIView, STPPaymentCardTextFieldDelegate { @objc var onCardChange: ABI44_0_0RCTDirectEventBlock? @objc var onFocusChange: ABI44_0_0RCTDirectEventBlock? @objc var dangerouslyGetFullCardDetails: Bool = false private var cardField = STPPaymentCardTextField() public var cardParams: STPPaymentMethodCardParams? = nil public var cardPostalCode: String? = nil @objc var postalCodeEnabled: Bool = true { didSet { cardField.postalCodeEntryEnabled = postalCodeEnabled } } @objc var placeholder: NSDictionary = NSDictionary() { didSet { if let numberPlaceholder = placeholder["number"] as? String { cardField.numberPlaceholder = numberPlaceholder } else { cardField.numberPlaceholder = "1234123412341234" } if let expirationPlaceholder = placeholder["expiration"] as? String { cardField.expirationPlaceholder = expirationPlaceholder } if let cvcPlaceholder = placeholder["cvc"] as? String { cardField.cvcPlaceholder = cvcPlaceholder } if let postalCodePlaceholder = placeholder["postalCode"] as? String { cardField.postalCodePlaceholder = postalCodePlaceholder } } } @objc var autofocus: Bool = false { didSet { if autofocus == true { cardField.abi44_0_0ReactFocus() } } } @objc var cardStyle: NSDictionary = NSDictionary() { didSet { if let borderWidth = cardStyle["borderWidth"] as? Int { cardField.borderWidth = CGFloat(borderWidth) } else { cardField.borderWidth = CGFloat(0) } if let backgroundColor = cardStyle["backgroundColor"] as? String { cardField.backgroundColor = UIColor(hexString: backgroundColor) } if let borderColor = cardStyle["borderColor"] as? String { cardField.borderColor = UIColor(hexString: borderColor) } if let borderRadius = cardStyle["borderRadius"] as? Int { cardField.cornerRadius = CGFloat(borderRadius) } if let cursorColor = cardStyle["cursorColor"] as? String { cardField.cursorColor = UIColor(hexString: cursorColor) } if let textColor = cardStyle["textColor"] as? String { cardField.textColor = UIColor(hexString: textColor) } if let textErrorColor = cardStyle["textErrorColor"] as? String { cardField.textErrorColor = UIColor(hexString: textErrorColor) } let fontSize = cardStyle["fontSize"] as? Int ?? 14 if let fontFamily = cardStyle["fontFamily"] as? String { cardField.font = UIFont(name: fontFamily, size: CGFloat(fontSize)) ?? UIFont.systemFont(ofSize: CGFloat(fontSize)) } else { if let fontSize = cardStyle["fontSize"] as? Int { cardField.font = UIFont.systemFont(ofSize: CGFloat(fontSize)) } } if let placeholderColor = cardStyle["placeholderColor"] as? String { cardField.placeholderColor = UIColor(hexString: placeholderColor) } } } override init(frame: CGRect) { super.init(frame: frame) cardField.delegate = self self.addSubview(cardField) } func focus() { cardField.becomeFirstResponder() } func blur() { cardField.resignFirstResponder() } func clear() { cardField.clear() } func paymentCardTextFieldDidEndEditing(_ textField: STPPaymentCardTextField) { onFocusChange?(["focusedField": NSNull()]) } func paymentCardTextFieldDidBeginEditingNumber(_ textField: STPPaymentCardTextField) { onFocusChange?(["focusedField": "CardNumber"]) } func paymentCardTextFieldDidBeginEditingCVC(_ textField: STPPaymentCardTextField) { onFocusChange?(["focusedField": "Cvc"]) } func paymentCardTextFieldDidBeginEditingExpiration(_ textField: STPPaymentCardTextField) { onFocusChange?(["focusedField": "ExpiryDate"]) } func paymentCardTextFieldDidBeginEditingPostalCode(_ textField: STPPaymentCardTextField) { onFocusChange?(["focusedField": "PostalCode"]) } func paymentCardTextFieldDidChange(_ textField: STPPaymentCardTextField) { if onCardChange != nil { let brand = STPCardValidator.brand(forNumber: textField.cardParams.number ?? "") var cardData: [String: Any?] = [ "expiryMonth": textField.cardParams.expMonth ?? NSNull(), "expiryYear": textField.cardParams.expYear ?? NSNull(), "complete": textField.isValid, "brand": Mappers.mapCardBrand(brand) ?? NSNull(), "last4": textField.cardParams.last4 ?? "" ] if (cardField.postalCodeEntryEnabled) { cardData["postalCode"] = textField.postalCode ?? "" } if (dangerouslyGetFullCardDetails) { cardData["number"] = textField.cardParams.number ?? "" } onCardChange!(cardData as [AnyHashable : Any]) } if (textField.isValid) { self.cardParams = textField.cardParams self.cardPostalCode = textField.postalCode } else { self.cardParams = nil self.cardPostalCode = nil } } override func layoutSubviews() { cardField.frame = self.bounds } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func paymentContext(_ paymentContext: STPPaymentContext, didFailToLoadWithError error: Error) { // } func paymentContextDidChange(_ paymentContext: STPPaymentContext) { // } func paymentContext(_ paymentContext: STPPaymentContext, didCreatePaymentResult paymentResult: STPPaymentResult, completion: @escaping STPPaymentStatusBlock) { // } func paymentContext(_ paymentContext: STPPaymentContext, didFinishWith status: STPPaymentStatus, error: Error?) { // } }
bsd-3-clause
6d90d92c00092e041ec187aadbdf747e
35.724719
163
0.600581
5.729185
false
false
false
false
0x0c/RDImageViewerController
RDImageViewerController/Classes/View/PageHud.swift
1
1959
// // PageHud.swift // Pods-RDImageViewerController_Example // // Created by Akira Matsuda on 2020/01/13. // import UIKit open class PageHud: UIView { public let label: UILabel override public init(frame: CGRect) { label = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) super.init(frame: frame) widthAnchor.constraint(equalToConstant: frame.width).isActive = true heightAnchor.constraint(equalToConstant: frame.height).isActive = true configureViews() } @available(*, unavailable) public required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } func configureViews() { clipsToBounds = true let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .dark)) blurView.translatesAutoresizingMaskIntoConstraints = false addSubview(blurView) blurView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true blurView.heightAnchor.constraint(equalTo: heightAnchor).isActive = true blurView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true blurView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = UIColor.clear layer.cornerRadius = 15 layer.borderWidth = 1 layer.borderColor = UIColor.white.cgColor label.textColor = UIColor.white label.textAlignment = .center label.font = UIFont.systemFont(ofSize: RDImageViewerController.pageHudLabelFontSize) label.widthAnchor.constraint(equalTo: widthAnchor).isActive = true label.heightAnchor.constraint(equalTo: heightAnchor).isActive = true label.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true label.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true } }
mit
1b409a6f09006c47603c42acee3bb962
36.673077
92
0.70291
5.048969
false
false
false
false
1457792186/JWSwift
熊猫TV2/XMTV/Classes/Main/View/CollectionSearchCell.swift
2
1402
// // CollectionSearchCell.swift // XMTV // // Created by Mac on 2017/1/17. // Copyright © 2017年 Mac. All rights reserved. // import UIKit class CollectionSearchCell: UICollectionViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var onlineBtn: UIButton! @IBOutlet weak var nickNameLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! var anchor : SearchListModel? { didSet { guard let anchor = anchor else { return } var onlineStr : String = "" if anchor.person_num >= 10000 { onlineStr = String(format:"%.1f万",Float(anchor.person_num) / 10000) } else { onlineStr = "\(anchor.person_num)" } onlineBtn.setTitle(onlineStr, for: UIControlState()) nickNameLabel.text = anchor.name nameLabel.text = anchor.nickname if let picture = anchor.pictures { guard let iconURL = URL(string: picture["img"] as! String) else { return } iconImageView.kf.setImage(with: iconURL, placeholder: UIImage(named: "homepage_refresh_tv"), options: [.forceRefresh], progressBlock: nil, completionHandler: nil) } } } override func awakeFromNib() { super.awakeFromNib() iconImageView.contentMode = .scaleAspectFit } }
apache-2.0
e1067c9c602979473542e20e64ebc9fe
31.488372
178
0.599141
4.784247
false
false
false
false
fgulan/letter-ml
project/LetterML/Frameworks/framework/Source/OpenGLContext_Shared.swift
3
4352
#if os(Linux) #if GLES import COpenGLES.gles2 #else import COpenGL #endif #else #if GLES import OpenGLES #else import OpenGL.GL3 #endif #endif import Foundation public let sharedImageProcessingContext = OpenGLContext() extension OpenGLContext { public func programForVertexShader(_ vertexShader:String, fragmentShader:String) throws -> ShaderProgram { let lookupKeyForShaderProgram = "V: \(vertexShader) - F: \(fragmentShader)" if let shaderFromCache = shaderCache[lookupKeyForShaderProgram] { return shaderFromCache } else { return try sharedImageProcessingContext.runOperationSynchronously{ let program = try ShaderProgram(vertexShader:vertexShader, fragmentShader:fragmentShader) self.shaderCache[lookupKeyForShaderProgram] = program return program } } } public func programForVertexShader(_ vertexShader:String, fragmentShader:URL) throws -> ShaderProgram { return try programForVertexShader(vertexShader, fragmentShader:try shaderFromFile(fragmentShader)) } public func programForVertexShader(_ vertexShader:URL, fragmentShader:URL) throws -> ShaderProgram { return try programForVertexShader(try shaderFromFile(vertexShader), fragmentShader:try shaderFromFile(fragmentShader)) } public func openGLDeviceSettingForOption(_ option:Int32) -> GLint { return self.runOperationSynchronously{() -> GLint in self.makeCurrentContext() var openGLValue:GLint = 0 glGetIntegerv(GLenum(option), &openGLValue) return openGLValue } } public func deviceSupportsExtension(_ openGLExtension:String) -> Bool { #if os(Linux) return false #else return self.extensionString.contains(openGLExtension) #endif } // http://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_rg.txt public func deviceSupportsRedTextures() -> Bool { return deviceSupportsExtension("GL_EXT_texture_rg") } public func deviceSupportsFramebufferReads() -> Bool { return deviceSupportsExtension("GL_EXT_shader_framebuffer_fetch") } public func sizeThatFitsWithinATextureForSize(_ size:Size) -> Size { let maxTextureSize = Float(self.maximumTextureSizeForThisDevice) if ( (size.width < maxTextureSize) && (size.height < maxTextureSize) ) { return size } let adjustedSize:Size if (size.width > size.height) { adjustedSize = Size(width:maxTextureSize, height:(maxTextureSize / size.width) * size.height) } else { adjustedSize = Size(width:(maxTextureSize / size.height) * size.width, height:maxTextureSize) } return adjustedSize } func generateTextureVBOs() { textureVBOs[.noRotation] = generateVBO(for:Rotation.noRotation.textureCoordinates()) textureVBOs[.rotateCounterclockwise] = generateVBO(for:Rotation.rotateCounterclockwise.textureCoordinates()) textureVBOs[.rotateClockwise] = generateVBO(for:Rotation.rotateClockwise.textureCoordinates()) textureVBOs[.rotate180] = generateVBO(for:Rotation.rotate180.textureCoordinates()) textureVBOs[.flipHorizontally] = generateVBO(for:Rotation.flipHorizontally.textureCoordinates()) textureVBOs[.flipVertically] = generateVBO(for:Rotation.flipVertically.textureCoordinates()) textureVBOs[.rotateClockwiseAndFlipVertically] = generateVBO(for:Rotation.rotateClockwiseAndFlipVertically.textureCoordinates()) textureVBOs[.rotateClockwiseAndFlipHorizontally] = generateVBO(for:Rotation.rotateClockwiseAndFlipHorizontally.textureCoordinates()) } public func textureVBO(for rotation:Rotation) -> GLuint { guard let textureVBO = textureVBOs[rotation] else {fatalError("GPUImage doesn't have a texture VBO set for the rotation \(rotation)") } return textureVBO } } @_semantics("sil.optimize.never") public func debugPrint(_ stringToPrint:String, file: StaticString = #file, line: UInt = #line, function: StaticString = #function) { #if DEBUG print("\(stringToPrint) --> \((String(describing:file) as NSString).lastPathComponent): \(function): \(line)") #endif }
mit
0d85ac526c0c91ebcff80a9f30f5df2f
40.056604
166
0.699908
5.07818
false
false
false
false
jianwoo/ios-charts
Charts/Classes/Renderers/ChartRendererBase.swift
1
1777
// // ChartRendererBase.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation public class ChartRendererBase: NSObject { /// the component that handles the drawing area of the chart and it's offsets public var viewPortHandler: ChartViewPortHandler!; internal var _minX: Int = 0; internal var _maxX: Int = 0; public override init() { super.init(); } public init(viewPortHandler: ChartViewPortHandler) { super.init(); self.viewPortHandler = viewPortHandler; } /// Returns true if the specified value fits in between the provided min and max bounds, false if not. internal func fitsBounds(val: Float, min: Float, max: Float) -> Bool { if (val < min || val > max) { return false; } else { return true; } } /// Calculates the minimum and maximum x-value the chart can currently display (with the given zoom level). internal func calcXBounds(trans: ChartTransformer!) { var minx = trans.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: 0.0)).x; var maxx = trans.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentRight, y: 0.0)).x; if (isnan(minx)) { minx = 0; } if (isnan(maxx)) { maxx = 0; } if (!isinf(minx)) { _minX = Int(minx); } if (!isinf(maxx)) { _maxX = Int(ceil(maxx)); } } }
apache-2.0
33de5e14ea19fd14a25ad9f0669f6353
24.042254
111
0.57175
4.387654
false
false
false
false
abelsanchezali/ViewBuilder
ViewBuilderDemo/ViewBuilderDemoTests/DictionaryTextDeserializerServiceProtocolDelegate.swift
1
1045
// // DictionaryTextDeserializerServiceProtocolDelegate.swift // ViewBuilder // // Created by Abel Ernesto Sanchez Ali on 1/18/17. // Copyright © 2017 Abel Sanchez. All rights reserved. // @testable import ViewBuilder class DictionaryTextDeserializerServiceProtocolDelegate: TextDeserializerServiceProtocolDelegate { init() { } init(values: [String: Any], domains: [String: String] = [:]) { self.values = values self.domains = domains } var values = [String: Any]() var domains = [String: String]() // MARK: KeyValueResolverProtocol func resolveValue(for key: String) -> Any? { if key.hasPrefix(DocumentFactory.DomainsValuesPrefix) { return resolveDomain(for: key.substring(from: key.characters.index(key.startIndex, offsetBy: DocumentFactory.DomainsValuesPrefixLength))) } return values[key] } // MARK: TextDeserializerServiceProtocolDelegate func resolveDomain(for prefix: String) -> String? { return domains[prefix] } }
mit
ae14a7000cfdd9348c359a64fa2e2a49
26.473684
149
0.685824
4.405063
false
false
false
false
shuuchen/SwiftTips
protocols_3.swift
1
5280
// protocol inheritance // syntax is like class inheritance, but can inherit several protocols protocol InheritingProtocol: SomeProtocol, AnotherProtocol { // protocol definition goes here } protocol PrettyTextRepresentable: TextRepresentable { var prettyTextualDescription: String { get } } extension SnakesAndLadders: PrettyTextRepresentable { var prettyTextualDescription: String { var output = textualDescription + ":\n" for index in 1...finalSquare { switch board[index] { case let ladder where ladder > 0: output += "▲ " case let snake where snake < 0: output += "▼ " default: output += "○ " } } return output } } print(game.prettyTextualDescription) // A game of Snakes and Ladders with 25 squares: // ○ ○ ▲ ○ ○ ▲ ○ ○ ▲ ▲ ○ ○ ○ ▼ ○ ○ ○ ○ ▼ ○ ○ ▼ ○ ▼ ○ // Class-Only Protocols // limit protocol adoption to class types // used when conforming type is required to have reference semantics protocol SomeClassOnlyProtocol: class, SomeInheritedProtocol { // class-only protocol definition goes here } // protocol composition // combine multiple protocols into a single requirement // form: "protocol<p1, p2>" protocol Named { var name: String { get } } protocol Aged { var age: Int { get } } struct Person: Named, Aged { var name: String var age: Int } func wishHappyBirthday(celebrator: protocol<Named, Aged>) { print("Happy birthday \(celebrator.name) - you're \(celebrator.age)!") } let birthdayPerson = Person(name: "Malcolm", age: 21) wishHappyBirthday(birthdayPerson) // prints "Happy birthday Malcolm - you're 21!" // checking for protocol conformance // use "is" to check, use "as" to downcast protocol HasArea { var area: Double { get } } class Circle: HasArea { let pi = 3.1415927 var radius: Double var area: Double { return pi * radius * radius } init(radius: Double) { self.radius = radius } } class Country: HasArea { var area: Double init(area: Double) { self.area = area } } class Animal { var legs: Int init(legs: Int) { self.legs = legs } } let objects: [AnyObject] = [ Circle(radius: 2.0), Country(area: 243_610), Animal(legs: 4) ] for object in objects { if let objectWithArea = object as? HasArea { print("Area is \(objectWithArea.area)") } else { print("Something that doesn't have an area") } } // optional protocol requirements // using "optional" modifier, the specified type is wrapped to optional // only for protocols marked with "@objc" attribute // can only be adopted by "@objc" classes // cannot be adopted by structures & enumetations // called with optional chaining @objc protocol CounterDataSource { optional func incrementForCount(count: Int) -> Int optional var fixedIncrement: Int { get } } class Counter { var count = 0 var dataSource: CounterDataSource? func increment() { if let amount = dataSource?.incrementForCount?(count) { count += amount } else if let amount = dataSource?.fixedIncrement { count += amount } } } class ThreeSource: NSObject, CounterDataSource { let fixedIncrement = 3 } var counter = Counter() counter.dataSource = ThreeSource() for _ in 1...4 { counter.increment() print(counter.count) } @objc class TowardsZeroSource: NSObject, CounterDataSource { func incrementForCount(count: Int) -> Int { if count == 0 { return 0 } else if count < 0 { return 1 } else { return -1 } } } counter.count = -4 counter.dataSource = TowardsZeroSource() for _ in 1...5 { counter.increment() print(counter.count) } // protocol extensions // protocols can be extended to provide behaviors themselves // all conforming types automatically gain this method implementation extension RandomNumberGenerator { func randomBool() -> Bool { return random() > 0.5 } } let generator = LinearCongruentialGenerator() print("Here's a random number: \(generator.random())") // prints "Here's a random number: 0.37464991998171" print("And here's a random Boolean: \(generator.randomBool())") // prints "And here's a random Boolean: true" // providing default implementations // use protocol extension to provide default implementation extension PrettyTextRepresentable { var prettyTextualDescription: String { return textualDescription } } // adding constraints to protocol extensions // specify constraints that conforming types must satisfy // before the extension is available // using "where" clause extension CollectionType where Generator.Element: TextRepresentable { var textualDescription: String { let itemsAsText = self.map { $0.textualDescription } return "[" + itemsAsText.joinWithSeparator(", ") + "]" } } let murrayTheHamster = Hamster(name: "Murray") let morganTheHamster = Hamster(name: "Morgan") let mauriceTheHamster = Hamster(name: "Maurice") let hamsters = [murrayTheHamster, morganTheHamster, mauriceTheHamster]
mit
de9857c21b3964d6e0eb2b49e123ef50
20.322449
74
0.661371
4.274959
false
false
false
false
mirego/PinLayout
Sources/Pin.swift
1
3310
// Copyright (c) 2017 Luc Dion // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation @objc public class Pin: NSObject { @objc public static var layoutDirection = LayoutDirection.ltr #if os(iOS) || os(tvOS) /// Controls how PinLayout will calls `UIView.safeAreaInsetsDidChange` when the `UIView.pin.safeArea` change. @objc public static var safeAreaInsetsDidChangeMode: PinSafeAreaInsetsDidChangeMode = .optIn { didSet { PinSafeArea.safeAreaInsetsDidChangeMode = safeAreaInsetsDidChangeMode } } #endif static private var isInitialized = false @objc public static func initPinLayout() { #if os(iOS) || os(tvOS) guard !Pin.isInitialized else { return } PinSafeArea.initSafeAreaSupport() Pin.isInitialized = true #endif } @objc public static func layoutDirection(_ direction: LayoutDirection) { self.layoutDirection = direction } internal static var autoSizingInProgress: Bool = false // // Warnings // #if DEBUG @objc public static var logWarnings = true #else @objc public static var logWarnings = false #endif @objc public static var activeWarnings = ActiveWarnings() /** If your codes need to work in Xcode playgrounds, you may set to `true` the property `Pin.logMissingLayoutCalls`, this way any missing call to `layout()` will generate a warning in the Xcode console.. */ @objc public static var logMissingLayoutCalls = false // Contains PinLayout last warning's text. Used by PinLayout's Unit Tests. @objc public static var lastWarningText: String? public static func resetWarnings() { #if DEBUG logWarnings = true #endif activeWarnings = ActiveWarnings() } } @objc public class ActiveWarnings: NSObject { /// When set to true, a warning is displayed if there is no space available between views /// specified in a call to `horizontallyBetween(...)` or `verticallyBetween(...)`. public var noSpaceAvailableBetweenViews = true /// When set to true, a warning is displayed if 'aspectRatio()' is called on a UIImageView without a valid UIImage. public var aspectRatioImageNotSet = true }
mit
707fa9964ca33d0260e298406b3db6fd
37.488372
119
0.708459
4.688385
false
false
false
false
reza-ryte-club/firefox-ios
Storage/SQL/SQLiteHistory.swift
1
42111
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger private let log = Logger.syncLogger class NoSuchRecordError: MaybeErrorType { let guid: GUID init(guid: GUID) { self.guid = guid } var description: String { return "No such record: \(guid)." } } func failOrSucceed<T>(err: NSError?, op: String, val: T) -> Deferred<Maybe<T>> { if let err = err { log.debug("\(op) failed: \(err.localizedDescription)") return deferMaybe(DatabaseError(err: err)) } return deferMaybe(val) } func failOrSucceed(err: NSError?, op: String) -> Success { return failOrSucceed(err, op: op, val: ()) } private var ignoredSchemes = ["about"] public func isIgnoredURL(url: NSURL) -> Bool { let scheme = url.scheme if let _ = ignoredSchemes.indexOf(scheme) { return true } if url.host == "localhost" { return true } return false } public func isIgnoredURL(url: String) -> Bool { if let url = NSURL(string: url) { return isIgnoredURL(url) } return false } /* // Here's the Swift equivalent of the below. func simulatedFrecency(now: MicrosecondTimestamp, then: MicrosecondTimestamp, visitCount: Int) -> Double { let ageMicroseconds = (now - then) let ageDays = Double(ageMicroseconds) / 86400000000.0 // In SQL the .0 does the coercion. let f = 100 * 225 / ((ageSeconds * ageSeconds) + 225) return Double(visitCount) * max(1.0, f) } */ // The constants in these functions were arrived at by utterly unscientific experimentation. func getRemoteFrecencySQL() -> String { let visitCountExpression = "remoteVisitCount" let now = NSDate.nowMicroseconds() let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24 let ageDays = "((\(now) - remoteVisitDate) / \(microsecondsPerDay))" return "\(visitCountExpression) * max(1, 100 * 110 / (\(ageDays) * \(ageDays) + 110))" } func getLocalFrecencySQL() -> String { let visitCountExpression = "((2 + localVisitCount) * (2 + localVisitCount))" let now = NSDate.nowMicroseconds() let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24 let ageDays = "((\(now) - localVisitDate) / \(microsecondsPerDay))" return "\(visitCountExpression) * max(2, 100 * 225 / (\(ageDays) * \(ageDays) + 225))" } extension SDRow { func getTimestamp(column: String) -> Timestamp? { return (self[column] as? NSNumber)?.unsignedLongLongValue } func getBoolean(column: String) -> Bool { if let val = self[column] as? Int { return val != 0 } return false } } /** * The sqlite-backed implementation of the history protocol. */ public class SQLiteHistory { let db: BrowserDB let favicons: FaviconsTable<Favicon> let prefs: Prefs required public init?(db: BrowserDB, prefs: Prefs, version: Int? = nil) { self.db = db self.favicons = FaviconsTable<Favicon>() self.prefs = prefs // Always start by needing invalidation. self.setTopSitesNeedsInvalidation() // BrowserTable exists only to perform create/update etc. operations -- it's not // a queryable thing that needs to stick around. if !db.createOrUpdate(BrowserTable(version: version ?? BrowserTable.DefaultVersion)) { return nil } } } extension SQLiteHistory: BrowserHistory { public func removeSiteFromTopSites(site: Site) -> Success { if let host = site.url.asURL?.normalizedHost() { return db.run([("UPDATE \(TableDomains) set showOnTopSites = 0 WHERE domain = ?", [host])]) } return deferMaybe(DatabaseError(description: "Invalid url for site \(site.url)")) } public func removeHistoryForURL(url: String) -> Success { let visitArgs: Args = [url] let deleteVisits = "DELETE FROM \(TableVisits) WHERE siteID = (SELECT id FROM \(TableHistory) WHERE url = ?)" let markArgs: Args = [NSDate.nowNumber(), url] let markDeleted = "UPDATE \(TableHistory) SET url = NULL, is_deleted = 1, should_upload = 1, local_modified = ? WHERE url = ?" return db.run([(deleteVisits, visitArgs), (markDeleted, markArgs), favicons.getCleanupCommands()]) } // Note: clearing history isn't really a sane concept in the presence of Sync. // This method should be split to do something else. // Bug 1162778. public func clearHistory() -> Success { return self.db.run([ ("DELETE FROM \(TableVisits)", nil), ("DELETE FROM \(TableHistory)", nil), ("DELETE FROM \(TableDomains)", nil), self.favicons.getCleanupCommands(), ]) // We've probably deleted a lot of stuff. Vacuum now to recover the space. >>> effect(self.db.vacuum) } func recordVisitedSite(site: Site) -> Success { var error: NSError? = nil // Don't store visits to sites with about: protocols if isIgnoredURL(site.url) { return deferMaybe(IgnoredSiteError()) } db.withWritableConnection(&error) { (conn, inout err: NSError?) -> Int in let now = NSDate.nowNumber() let i = self.updateSite(site, atTime: now, withConnection: conn) if i > 0 { return i } // Insert instead. return self.insertSite(site, atTime: now, withConnection: conn) } return failOrSucceed(error, op: "Record site") } func updateSite(site: Site, atTime time: NSNumber, withConnection conn: SQLiteDBConnection) -> Int { // We know we're adding a new visit, so we'll need to upload this record. // If we ever switch to per-visit change flags, this should turn into a CASE statement like // CASE WHEN title IS ? THEN max(should_upload, 1) ELSE should_upload END // so that we don't flag this as changed unless the title changed. // // Note that we will never match against a deleted item, because deleted items have no URL, // so we don't need to unset is_deleted here. if let host = site.url.asURL?.normalizedHost() { let update = "UPDATE \(TableHistory) SET title = ?, local_modified = ?, should_upload = 1, domain_id = (SELECT id FROM \(TableDomains) where domain = ?) WHERE url = ?" let updateArgs: Args? = [site.title, time, host, site.url] if Logger.logPII { log.debug("Setting title to \(site.title) for URL \(site.url)") } let error = conn.executeChange(update, withArgs: updateArgs) if error != nil { log.warning("Update failed with \(error?.localizedDescription)") return 0 } return conn.numberOfRowsModified } return 0 } private func insertSite(site: Site, atTime time: NSNumber, withConnection conn: SQLiteDBConnection) -> Int { if let host = site.url.asURL?.normalizedHost() { if let error = conn.executeChange("INSERT OR IGNORE INTO \(TableDomains) (domain) VALUES (?)", withArgs: [host]) { log.warning("Domain insertion failed with \(error.localizedDescription)") return 0 } let insert = "INSERT INTO \(TableHistory) " + "(guid, url, title, local_modified, is_deleted, should_upload, domain_id) " + "SELECT ?, ?, ?, ?, 0, 1, id FROM \(TableDomains) WHERE domain = ?" let insertArgs: Args? = [site.guid ?? Bytes.generateGUID(), site.url, site.title, time, host] if let error = conn.executeChange(insert, withArgs: insertArgs) { log.warning("Site insertion failed with \(error.localizedDescription)") return 0 } return 1 } if Logger.logPII { log.warning("Invalid URL \(site.url). Not stored in history.") } return 0 } // TODO: thread siteID into this to avoid the need to do the lookup. func addLocalVisitForExistingSite(visit: SiteVisit) -> Success { var error: NSError? = nil db.withWritableConnection(&error) { (conn, inout err: NSError?) -> Int in // INSERT OR IGNORE because we *might* have a clock error that causes a timestamp // collision with an existing visit, and it would really suck to error out for that reason. let insert = "INSERT OR IGNORE INTO \(TableVisits) (siteID, date, type, is_local) VALUES (" + "(SELECT id FROM \(TableHistory) WHERE url = ?), ?, ?, 1)" let realDate = NSNumber(unsignedLongLong: visit.date) let insertArgs: Args? = [visit.site.url, realDate, visit.type.rawValue] error = conn.executeChange(insert, withArgs: insertArgs) if error != nil { log.warning("Visit insertion failed with \(err?.localizedDescription)") return 0 } return 1 } return failOrSucceed(error, op: "Record visit") } public func addLocalVisit(visit: SiteVisit) -> Success { return recordVisitedSite(visit.site) >>> { self.addLocalVisitForExistingSite(visit) } } public func getSitesByFrecencyWithLimit(limit: Int) -> Deferred<Maybe<Cursor<Site>>> { return self.getSitesByFrecencyWithLimit(limit, includeIcon: true) } public func getSitesByFrecencyWithLimit(limit: Int, includeIcon: Bool) -> Deferred<Maybe<Cursor<Site>>> { // Exclude redirect domains. Bug 1194852. let (whereData, groupBy) = self.topSiteClauses() return self.getFilteredSitesByFrecencyWithLimit(limit, groupClause: groupBy, whereData: whereData, includeIcon: includeIcon) } public func getTopSitesWithLimit(limit: Int) -> Deferred<Maybe<Cursor<Site>>> { let topSitesQuery = "SELECT * FROM \(TableCachedTopSites) ORDER BY frecencies DESC LIMIT (?)" let factory = SQLiteHistory.iconHistoryColumnFactory return self.db.runQuery(topSitesQuery, args: [limit], factory: factory) } public func setTopSitesNeedsInvalidation() { prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid) } public func invalidateTopSitesIfNeeded() -> Deferred<Maybe<Bool>> { if prefs.boolForKey(PrefsKeys.KeyTopSitesCacheIsValid) ?? false { return deferMaybe(false) } let cacheSize = Int(prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? 0) return clearTopSitesCache() >>> { self.updateTopSitesCacheWithLimit(cacheSize) } >>> always(true) } public func setTopSitesCacheSize(size: Int32) { let oldValue = prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? 0 if oldValue != size { prefs.setInt(size, forKey: PrefsKeys.KeyTopSitesCacheSize) setTopSitesNeedsInvalidation() } } private func updateTopSitesCacheWithLimit(limit : Int) -> Success { let (whereData, groupBy) = self.topSiteClauses() let (query, args) = self.filteredSitesByFrecencyQueryWithLimit(limit, groupClause: groupBy, whereData: whereData) let insertQuery = "INSERT INTO \(TableCachedTopSites) \(query)" return self.clearTopSitesCache() >>> { self.db.run(insertQuery, withArgs: args) >>> { self.prefs.setBool(true, forKey: PrefsKeys.KeyTopSitesCacheIsValid) return succeed() } } } public func clearTopSitesCache() -> Success { let deleteQuery = "DELETE FROM \(TableCachedTopSites)" return self.db.run(deleteQuery, withArgs: nil) >>> { self.prefs.removeObjectForKey(PrefsKeys.KeyTopSitesCacheIsValid) return succeed() } } public func getSitesByFrecencyWithLimit(limit: Int, whereURLContains filter: String) -> Deferred<Maybe<Cursor<Site>>> { return self.getFilteredSitesByFrecencyWithLimit(limit, whereURLContains: filter) } public func getSitesByLastVisit(limit: Int) -> Deferred<Maybe<Cursor<Site>>> { return self.getFilteredSitesByVisitDateWithLimit(limit, whereURLContains: nil, includeIcon: true) } private class func basicHistoryColumnFactory(row: SDRow) -> Site { let id = row["historyID"] as! Int let url = row["url"] as! String let title = row["title"] as! String let guid = row["guid"] as! String let site = Site(url: url, title: title) site.guid = guid site.id = id // Find the most recent visit, regardless of which column it might be in. let local = row.getTimestamp("localVisitDate") ?? 0 let remote = row.getTimestamp("remoteVisitDate") ?? 0 let either = row.getTimestamp("visitDate") ?? 0 let latest = max(local, remote, either) if latest > 0 { site.latestVisit = Visit(date: latest, type: VisitType.Unknown) } return site } private class func iconColumnFactory(row: SDRow) -> Favicon? { if let iconType = row["iconType"] as? Int, let iconURL = row["iconURL"] as? String, let iconDate = row["iconDate"] as? Double, let _ = row["iconID"] as? Int { let date = NSDate(timeIntervalSince1970: iconDate) return Favicon(url: iconURL, date: date, type: IconType(rawValue: iconType)!) } return nil } private class func iconHistoryColumnFactory(row: SDRow) -> Site { let site = basicHistoryColumnFactory(row) site.icon = iconColumnFactory(row) return site } private func topSiteClauses() -> (String, String) { let whereData = "(\(TableDomains).showOnTopSites IS 1) AND (\(TableDomains).domain NOT LIKE 'r.%') " let groupBy = "GROUP BY domain_id " return (whereData, groupBy) } private func getFilteredSitesByVisitDateWithLimit(limit: Int, whereURLContains filter: String? = nil, includeIcon: Bool = true) -> Deferred<Maybe<Cursor<Site>>> { let args: Args? let whereClause: String if let filter = filter { args = ["%\(filter)%", "%\(filter)%"] // No deleted item has a URL, so there is no need to explicitly add that here. whereClause = "WHERE ((\(TableHistory).url LIKE ?) OR (\(TableHistory).title LIKE ?)) " + "AND (\(TableHistory).is_deleted = 0)" } else { args = [] whereClause = "WHERE (\(TableHistory).is_deleted = 0)" } let ungroupedSQL = "SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, title, guid, domain_id, domain, " + "COALESCE(max(case \(TableVisits).is_local when 1 then \(TableVisits).date else 0 end), 0) AS localVisitDate, " + "COALESCE(max(case \(TableVisits).is_local when 0 then \(TableVisits).date else 0 end), 0) AS remoteVisitDate, " + "COALESCE(count(\(TableVisits).is_local), 0) AS visitCount " + "FROM \(TableHistory) " + "INNER JOIN \(TableDomains) ON \(TableDomains).id = \(TableHistory).domain_id " + "INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id " + whereClause + " GROUP BY historyID" let historySQL = "SELECT historyID, url, title, guid, domain_id, domain, visitCount, " + "max(localVisitDate) AS localVisitDate, " + "max(remoteVisitDate) AS remoteVisitDate " + "FROM (" + ungroupedSQL + ") " + "WHERE (visitCount > 0) " + // Eliminate dead rows from coalescing. "GROUP BY historyID " + "ORDER BY max(localVisitDate, remoteVisitDate) DESC " + "LIMIT \(limit) " if includeIcon { // We select the history items then immediately join to get the largest icon. // We do this so that we limit and filter *before* joining against icons. let sql = "SELECT " + "historyID, url, title, guid, domain_id, domain, " + "localVisitDate, remoteVisitDate, visitCount, " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM (\(historySQL)) LEFT OUTER JOIN " + "view_history_id_favicon ON historyID = view_history_id_favicon.id" let factory = SQLiteHistory.iconHistoryColumnFactory return db.runQuery(sql, args: args, factory: factory) } let factory = SQLiteHistory.basicHistoryColumnFactory return db.runQuery(historySQL, args: args, factory: factory) } private func getFilteredSitesByFrecencyWithLimit(limit: Int, whereURLContains filter: String? = nil, groupClause: String = "GROUP BY historyID ", whereData: String? = nil, includeIcon: Bool = true) -> Deferred<Maybe<Cursor<Site>>> { let factory: (SDRow) -> Site if includeIcon { factory = SQLiteHistory.iconHistoryColumnFactory } else { factory = SQLiteHistory.basicHistoryColumnFactory } let (query, args) = filteredSitesByFrecencyQueryWithLimit(limit, whereURLContains: filter, groupClause: groupClause, whereData: whereData, includeIcon: includeIcon ) return db.runQuery(query, args: args, factory: factory) } private func filteredSitesByFrecencyQueryWithLimit(limit: Int, whereURLContains filter: String? = nil, groupClause: String = "GROUP BY historyID ", whereData: String? = nil, includeIcon: Bool = true) -> (String, Args?) { let localFrecencySQL = getLocalFrecencySQL() let remoteFrecencySQL = getRemoteFrecencySQL() let sixMonthsInMicroseconds: UInt64 = 15_724_800_000_000 // 182 * 1000 * 1000 * 60 * 60 * 24 let sixMonthsAgo = NSDate.nowMicroseconds() - sixMonthsInMicroseconds let args: Args? let whereClause: String let whereFragment = (whereData == nil) ? "" : " AND (\(whereData!))" if let filter = filter { args = ["%\(filter)%", "%\(filter)%"] // No deleted item has a URL, so there is no need to explicitly add that here. whereClause = " WHERE ((\(TableHistory).url LIKE ?) OR (\(TableHistory).title LIKE ?)) \(whereFragment)" } else { args = [] whereClause = " WHERE (\(TableHistory).is_deleted = 0) \(whereFragment)" } // Innermost: grab history items and basic visit/domain metadata. let ungroupedSQL = "SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, title, guid, domain_id, domain" + ", COALESCE(max(case \(TableVisits).is_local when 1 then \(TableVisits).date else 0 end), 0) AS localVisitDate" + ", COALESCE(max(case \(TableVisits).is_local when 0 then \(TableVisits).date else 0 end), 0) AS remoteVisitDate" + ", COALESCE(sum(\(TableVisits).is_local), 0) AS localVisitCount" + ", COALESCE(sum(case \(TableVisits).is_local when 1 then 0 else 1 end), 0) AS remoteVisitCount" + " FROM \(TableHistory) " + "INNER JOIN \(TableDomains) ON \(TableDomains).id = \(TableHistory).domain_id " + "INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id " + whereClause + " GROUP BY historyID" // Next: limit to only those that have been visited at all within the last six months. // (Don't do that in the innermost: we want to get the full count, even if some visits are older.) // Discard all but the 1000 most frecent. // Compute and return the frecency for all 1000 URLs. let frecenciedSQL = "SELECT *, (\(localFrecencySQL) + \(remoteFrecencySQL)) AS frecency" + " FROM (" + ungroupedSQL + ")" + " WHERE (" + "((localVisitCount > 0) OR (remoteVisitCount > 0)) AND " + // Eliminate dead rows from coalescing. "((localVisitDate > \(sixMonthsAgo)) OR (remoteVisitDate > \(sixMonthsAgo)))" + // Exclude really old items. ") ORDER BY frecency DESC" + " LIMIT 1000" // Don't even look at a huge set. This avoids work. // Next: merge by domain and sum frecency, ordering by that sum and reducing to a (typically much lower) limit. let historySQL = "SELECT historyID, url, title, guid, domain_id, domain" + ", max(localVisitDate) AS localVisitDate" + ", max(remoteVisitDate) AS remoteVisitDate" + ", sum(localVisitCount) AS localVisitCount" + ", sum(remoteVisitCount) AS remoteVisitCount" + ", sum(frecency) AS frecencies" + " FROM (" + frecenciedSQL + ") " + groupClause + " " + "ORDER BY frecencies DESC " + "LIMIT \(limit) " // Finally: join this small list to the favicon data. if includeIcon { // We select the history items then immediately join to get the largest icon. // We do this so that we limit and filter *before* joining against icons. let sql = "SELECT" + " historyID, url, title, guid, domain_id, domain" + ", localVisitDate, remoteVisitDate, localVisitCount, remoteVisitCount" + ", iconID, iconURL, iconDate, iconType, iconWidth, frecencies" + " FROM (\(historySQL)) LEFT OUTER JOIN " + "view_history_id_favicon ON historyID = view_history_id_favicon.id" return (sql, args) } return (historySQL, args) } } extension SQLiteHistory: Favicons { // These two getter functions are only exposed for testing purposes (and aren't part of the public interface). func getFaviconsForURL(url: String) -> Deferred<Maybe<Cursor<Favicon?>>> { let sql = "SELECT iconID AS id, iconURL AS url, iconDate AS date, iconType AS type, iconWidth AS width FROM " + "\(ViewWidestFaviconsForSites), \(TableHistory) WHERE " + "\(TableHistory).id = siteID AND \(TableHistory).url = ?" let args: Args = [url] return db.runQuery(sql, args: args, factory: SQLiteHistory.iconColumnFactory) } func getFaviconsForBookmarkedURL(url: String) -> Deferred<Maybe<Cursor<Favicon?>>> { let sql = "SELECT \(TableFavicons).id AS id, \(TableFavicons).url AS url, \(TableFavicons).date AS date, \(TableFavicons).type AS type, \(TableFavicons).width AS width FROM \(TableFavicons), \(TableBookmarks) WHERE \(TableBookmarks).faviconID = \(TableFavicons).id AND \(TableBookmarks).url IS ?" let args: Args = [url] return db.runQuery(sql, args: args, factory: SQLiteHistory.iconColumnFactory) } public func clearAllFavicons() -> Success { var err: NSError? = nil db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in err = conn.executeChange("DELETE FROM \(TableFaviconSites)", withArgs: nil) if err == nil { err = conn.executeChange("DELETE FROM \(TableFavicons)", withArgs: nil) } return 1 } return failOrSucceed(err, op: "Clear favicons") } public func addFavicon(icon: Favicon) -> Deferred<Maybe<Int>> { var err: NSError? let res = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in // Blind! We don't see failure here. let id = self.favicons.insertOrUpdate(conn, obj: icon) return id ?? 0 } if err == nil { return deferMaybe(res) } return deferMaybe(DatabaseError(err: err)) } /** * This method assumes that the site has already been recorded * in the history table. */ public func addFavicon(icon: Favicon, forSite site: Site) -> Deferred<Maybe<Int>> { if Logger.logPII { log.verbose("Adding favicon \(icon.url) for site \(site.url).") } func doChange(query: String, args: Args?) -> Deferred<Maybe<Int>> { var err: NSError? let res = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in // Blind! We don't see failure here. let id = self.favicons.insertOrUpdate(conn, obj: icon) // Now set up the mapping. err = conn.executeChange(query, withArgs: args) if let err = err { log.error("Got error adding icon: \(err).") return 0 } // Try to update the favicon ID column in the bookmarks table as well for this favicon // if this site has been bookmarked if let id = id { conn.executeChange("UPDATE \(TableBookmarks) SET faviconID = ? WHERE url = ?", withArgs: [id, site.url]) } return id ?? 0 } if res == 0 { return deferMaybe(DatabaseError(err: err)) } return deferMaybe(icon.id!) } let siteSubselect = "(SELECT id FROM \(TableHistory) WHERE url = ?)" let iconSubselect = "(SELECT id FROM \(TableFavicons) WHERE url = ?)" let insertOrIgnore = "INSERT OR IGNORE INTO \(TableFaviconSites)(siteID, faviconID) VALUES " if let iconID = icon.id { // Easy! if let siteID = site.id { // So easy! let args: Args? = [siteID, iconID] return doChange("\(insertOrIgnore) (?, ?)", args: args) } // Nearly easy. let args: Args? = [site.url, iconID] return doChange("\(insertOrIgnore) (\(siteSubselect), ?)", args: args) } // Sigh. if let siteID = site.id { let args: Args? = [siteID, icon.url] return doChange("\(insertOrIgnore) (?, \(iconSubselect))", args: args) } // The worst. let args: Args? = [site.url, icon.url] return doChange("\(insertOrIgnore) (\(siteSubselect), \(iconSubselect))", args: args) } } extension SQLiteHistory: SyncableHistory { /** * TODO: * When we replace an existing row, we want to create a deleted row with the old * GUID and switch the new one in -- if the old record has escaped to a Sync server, * we want to delete it so that we don't have two records with the same URL on the server. * We will know if it's been uploaded because it'll have a server_modified time. */ public func ensurePlaceWithURL(url: String, hasGUID guid: GUID) -> Success { let args: Args = [guid, url, guid] // The additional IS NOT is to ensure that we don't do a write for no reason. return db.run("UPDATE \(TableHistory) SET guid = ? WHERE url = ? AND guid IS NOT ?", withArgs: args) } public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success { let args: Args = [guid] // This relies on ON DELETE CASCADE to remove visits. return db.run("DELETE FROM \(TableHistory) WHERE guid = ?", withArgs: args) } // Fails on non-existence. private func getSiteIDForGUID(guid: GUID) -> Deferred<Maybe<Int>> { let args: Args = [guid] let query = "SELECT id FROM history WHERE guid = ?" let factory: SDRow -> Int = { return $0["id"] as! Int } return db.runQuery(query, args: args, factory: factory) >>== { cursor in if cursor.count == 0 { return deferMaybe(NoSuchRecordError(guid: guid)) } return deferMaybe(cursor[0]!) } } public func storeRemoteVisits(visits: [Visit], forGUID guid: GUID) -> Success { return self.getSiteIDForGUID(guid) >>== { (siteID: Int) -> Success in let visitArgs = visits.map { (visit: Visit) -> Args in let realDate = NSNumber(unsignedLongLong: visit.date) let isLocal = 0 let args: Args = [siteID, realDate, visit.type.rawValue, isLocal] return args } // Magic happens here. The INSERT OR IGNORE relies on the multi-column uniqueness // constraint on `visits`: we allow only one row for (siteID, date, type), so if a // local visit already exists, this silently keeps it. End result? Any new remote // visits are added with only one query, keeping any existing rows. return self.db.bulkInsert(TableVisits, op: .InsertOrIgnore, columns: ["siteID", "date", "type", "is_local"], values: visitArgs) } } private struct HistoryMetadata { let id: Int let serverModified: Timestamp? let localModified: Timestamp? let isDeleted: Bool let shouldUpload: Bool let title: String } private func metadataForGUID(guid: GUID) -> Deferred<Maybe<HistoryMetadata?>> { let select = "SELECT id, server_modified, local_modified, is_deleted, should_upload, title FROM \(TableHistory) WHERE guid = ?" let args: Args = [guid] let factory = { (row: SDRow) -> HistoryMetadata in return HistoryMetadata( id: row["id"] as! Int, serverModified: row.getTimestamp("server_modified"), localModified: row.getTimestamp("local_modified"), isDeleted: row.getBoolean("is_deleted"), shouldUpload: row.getBoolean("should_upload"), title: row["title"] as! String ) } return db.runQuery(select, args: args, factory: factory) >>== { cursor in return deferMaybe(cursor[0]) } } public func insertOrUpdatePlace(place: Place, modified: Timestamp) -> Deferred<Maybe<GUID>> { // One of these things will be true here. // 0. The item is new. // (a) We have a local place with the same URL but a different GUID. // (b) We have never visited this place locally. // In either case, reconcile and proceed. // 1. The remote place is not modified when compared to our mirror of it. This // can occur when we redownload after a partial failure. // (a) And it's not modified locally, either. Nothing to do. Ideally we // will short-circuit so we don't need to update visits. (TODO) // (b) It's modified locally. Don't overwrite anything; let the upload happen. // 2. The remote place is modified (either title or visits). // (a) And it's not locally modified. Update the local entry. // (b) And it's locally modified. Preserve the title of whichever was modified last. // N.B., this is the only instance where we compare two timestamps to see // which one wins. // We use this throughout. let serverModified = NSNumber(unsignedLongLong: modified) // Check to see if our modified time is unchanged, if the record exists locally, etc. let insertWithMetadata = { (metadata: HistoryMetadata?) -> Deferred<Maybe<GUID>> in if let metadata = metadata { // The item exists locally (perhaps originally with a different GUID). if metadata.serverModified == modified { log.verbose("History item \(place.guid) is unchanged; skipping insert-or-update.") return deferMaybe(place.guid) } // Otherwise, the server record must have changed since we last saw it. if metadata.shouldUpload { // Uh oh, it changed locally. // This might well just be a visit change, but we can't tell. Usually this conflict is harmless. log.debug("Warning: history item \(place.guid) changed both locally and remotely. Comparing timestamps from different clocks!") if metadata.localModified > modified { log.debug("Local changes overriding remote.") // Update server modified time only. (Though it'll be overwritten again after a successful upload.) let update = "UPDATE \(TableHistory) SET server_modified = ? WHERE id = ?" let args: Args = [serverModified, metadata.id] return self.db.run(update, withArgs: args) >>> always(place.guid) } log.verbose("Remote changes overriding local.") // Fall through. } // The record didn't change locally. Update it. log.verbose("Updating local history item for guid \(place.guid).") let update = "UPDATE \(TableHistory) SET title = ?, server_modified = ?, is_deleted = 0 WHERE id = ?" let args: Args = [place.title, serverModified, metadata.id] return self.db.run(update, withArgs: args) >>> always(place.guid) } // The record doesn't exist locally. Insert it. log.verbose("Inserting remote history item for guid \(place.guid).") if let host = place.url.asURL?.normalizedHost() { if Logger.logPII { log.debug("Inserting: \(place.url).") } let insertDomain = "INSERT OR IGNORE INTO \(TableDomains) (domain) VALUES (?)" let insertHistory = "INSERT INTO \(TableHistory) (guid, url, title, server_modified, is_deleted, should_upload, domain_id) " + "SELECT ?, ?, ?, ?, 0, 0, id FROM \(TableDomains) where domain = ?" return self.db.run([ (insertDomain, [host]), (insertHistory, [place.guid, place.url, place.title, serverModified, host]) ]) >>> always(place.guid) } else { // This is a URL with no domain. Insert it directly. if Logger.logPII { log.debug("Inserting: \(place.url) with no domain.") } let insertHistory = "INSERT INTO \(TableHistory) (guid, url, title, server_modified, is_deleted, should_upload, domain_id) " + "VALUES (?, ?, ?, ?, 0, 0, NULL)" return self.db.run([ (insertHistory, [place.guid, place.url, place.title, serverModified]) ]) >>> always(place.guid) } } // Make sure that we only need to compare GUIDs by pre-merging on URL. return self.ensurePlaceWithURL(place.url, hasGUID: place.guid) >>> { self.metadataForGUID(place.guid) >>== insertWithMetadata } } public func getDeletedHistoryToUpload() -> Deferred<Maybe<[GUID]>> { // Use the partial index on should_upload to make this nice and quick. let sql = "SELECT guid FROM \(TableHistory) WHERE \(TableHistory).should_upload = 1 AND \(TableHistory).is_deleted = 1" let f: SDRow -> String = { $0["guid"] as! String } return self.db.runQuery(sql, args: nil, factory: f) >>== { deferMaybe($0.asArray()) } } public func getModifiedHistoryToUpload() -> Deferred<Maybe<[(Place, [Visit])]>> { // What we want to do: find all items flagged for update, selecting some number of their // visits alongside. // // A difficulty here: we don't want to fetch *all* visits, only some number of the most recent. // (It's not enough to only get new ones, because the server record should contain more.) // // That's the greatest-N-per-group problem in SQL. Please read and understand the solution // to this (particularly how the LEFT OUTER JOIN/HAVING clause works) before changing this query! // // We can do this in a single query, rather than the N+1 that desktop takes. // We then need to flatten the cursor. We do that by collecting // places as a side-effect of the factory, producing visits as a result, and merging in memory. let args: Args = [ 20, // Maximum number of visits to retrieve. ] // Exclude 'unknown' visits, because they're not syncable. let filter = "history.should_upload = 1 AND v1.type IS NOT 0" let sql = "SELECT " + "history.id AS siteID, history.guid AS guid, history.url AS url, history.title AS title, " + "v1.siteID AS siteID, v1.date AS visitDate, v1.type AS visitType " + "FROM " + "visits AS v1 " + "JOIN history ON history.id = v1.siteID AND \(filter) " + "LEFT OUTER JOIN " + "visits AS v2 " + "ON v1.siteID = v2.siteID AND v1.date < v2.date " + "GROUP BY v1.date " + "HAVING COUNT(*) < ? " + "ORDER BY v1.siteID, v1.date DESC" var places = [Int: Place]() var visits = [Int: [Visit]]() // Add a place to the accumulator, prepare to accumulate visits, return the ID. let ensurePlace: SDRow -> Int = { row in let id = row["siteID"] as! Int if places[id] == nil { let guid = row["guid"] as! String let url = row["url"] as! String let title = row["title"] as! String places[id] = Place(guid: guid, url: url, title: title) visits[id] = Array() } return id } // Store the place and the visit. let factory: SDRow -> Int = { row in let date = row.getTimestamp("visitDate")! let type = VisitType(rawValue: row["visitType"] as! Int)! let visit = Visit(date: date, type: type) let id = ensurePlace(row) visits[id]?.append(visit) return id } return db.runQuery(sql, args: args, factory: factory) >>== { c in // Consume every row, with the side effect of populating the places // and visit accumulators. var ids = Set<Int>() for row in c { // Collect every ID first, so that we're guaranteed to have // fully populated the visit lists, and we don't have to // worry about only collecting each place once. ids.insert(row!) } // Now we're done with the cursor. Close it. c.close() // Now collect the return value. return deferMaybe(ids.map { return (places[$0]!, visits[$0]!) } ) } } public func markAsDeleted(guids: [GUID]) -> Success { // TODO: support longer GUID lists. assert(guids.count < BrowserDB.MaxVariableNumber) if guids.isEmpty { return succeed() } log.debug("Wiping \(guids.count) deleted GUIDs.") // We deliberately don't limit this to records marked as should_upload, just // in case a coding error leaves records with is_deleted=1 but not flagged for // upload -- this will catch those and throw them away. let inClause = BrowserDB.varlist(guids.count) let sql = "DELETE FROM \(TableHistory) WHERE " + "is_deleted = 1 AND guid IN \(inClause)" let args: Args = guids.map { $0 as AnyObject } return self.db.run(sql, withArgs: args) } public func markAsSynchronized(guids: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> { // TODO: support longer GUID lists. assert(guids.count < 99) if guids.isEmpty { return deferMaybe(modified) } log.debug("Marking \(guids.count) GUIDs as synchronized. Returning timestamp \(modified).") let inClause = BrowserDB.varlist(guids.count) let sql = "UPDATE \(TableHistory) SET " + "should_upload = 0, server_modified = \(modified) " + "WHERE guid IN \(inClause)" let args: Args = guids.map { $0 as AnyObject } return self.db.run(sql, withArgs: args) >>> always(modified) } public func doneApplyingRecordsAfterDownload() -> Success { self.db.checkpoint() return succeed() } public func doneUpdatingMetadataAfterUpload() -> Success { self.db.checkpoint() return succeed() } } extension SQLiteHistory: ResettableSyncStorage { // We don't drop deletions when we reset -- we might need to upload a deleted item // that never made it to the server. public func resetClient() -> Success { let flag = "UPDATE \(TableHistory) SET should_upload = 1, server_modified = NULL" return self.db.run(flag) } } extension SQLiteHistory: AccountRemovalDelegate { public func onRemovedAccount() -> Success { log.info("Clearing history metadata and deleted items after account removal.") let discard = "DELETE FROM \(TableHistory) WHERE is_deleted = 1" return self.db.run(discard) >>> self.resetClient } }
mpl-2.0
11735736960113c4257dd9aeaf3b0367
42.957203
304
0.587044
4.704088
false
false
false
false
xuech/OMS-WH
OMS-WH/Classes/Base/Controller/GuideViewController.swift
1
3203
// // GuideViewController.swift // OMSOwner // // Created by gwy on 2017/4/25. // Copyright © 2017年 medlog. All rights reserved. // import UIKit class GuideViewController: UICollectionViewController { private let imageCount = 3 private let layout = CustomFlowLayout() private let reuseIdentifier = "Cell" // fileprivate var pageControl:UIPageControl? fileprivate lazy var pageControl: XCHPageControlView = { let pageControl = XCHPageControlView() pageControl.pageStyle = .flatBar return pageControl }() init(){ super.init(collectionViewLayout: layout) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setup() setupPageControlFrame() } fileprivate func setupPageControlFrame() { let pageW = view.bounds.width let pageH:CGFloat = 20 let pageX = view.bounds.origin.x let pageY = view.bounds.height - pageH pageControl.frame = CGRect(x:pageX, y:pageY, width:pageW, height:pageH) view.addSubview(pageControl) pageControl.setPageview(3, current: 0, tintColor: kAppearanceColor) } fileprivate func setup() { collectionView?.register(NewFetureCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) } // MARK: UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imageCount } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! NewFetureCollectionViewCell cell.imageIndex = indexPath.item cell.parentViewController = self return cell } override func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { let path = collectionView.indexPathsForVisibleItems.last if path?.item == (imageCount - 1) { let cell = collectionView.cellForItem(at: path!) as! NewFetureCollectionViewCell cell.startBtnAmiatino() } } override func scrollViewDidScroll(_ scrollView: UIScrollView){ pageControl.scroll_did(scrollView) // pageControl.currentPage = Int(collectionView!.contentOffset.x / layout.itemSize.width) } } //MARK:-自定义FlowLayout private class CustomFlowLayout: UICollectionViewFlowLayout{ /// 准备布局属性 override func prepare() { itemSize = (collectionView?.bounds.size)! minimumInteritemSpacing = 0 minimumLineSpacing = 0 scrollDirection = UICollectionViewScrollDirection.horizontal collectionView?.isPagingEnabled = true collectionView?.bounces = false collectionView?.showsHorizontalScrollIndicator = false } }
mit
7dd5bbcd2a6cff4fa6e49259df163818
31.141414
152
0.677561
5.39322
false
false
false
false
kouky/PrimaryFlightDisplay
Sources/TapeIndicator.swift
1
2311
// // TapeIndicator.swift // PrimaryFlightDisplay // // Created by Michael Koukoullis on 18/01/2016. // Copyright © 2016 Michael Koukoullis. All rights reserved. // import SpriteKit class TapeIndicator: SKNode { let style: TapeIndicatorStyleType let pointer: TapePointer let cellContainer: TapeCellContainer let cropNode = SKCropNode() var value: Double = 0 { didSet { cellContainer.run(cellContainer.actionForValue(value: value)) pointer.value = Int(value) } } init(style: TapeIndicatorStyleType) { switch style.markerJustification { case .bottom, .top: if style.type == .compass && (style.size.width / CGFloat(style.pointsPerUnitValue) > CGFloat(style.optimalCellMagnitude)) { fatalError("Invalid Compass style: Decrease width and / or increase pointsPerUnitValue") } case .left, .right: if style.type == .compass && (style.size.height / CGFloat(style.pointsPerUnitValue) > CGFloat(style.optimalCellMagnitude)) { fatalError("Invalid Compass style: Decrease height and / or increase pointsPerUnitValue") } } self.style = style let seedModel = style.seedModel do { cellContainer = try TapeCellContainer(seedModel: seedModel, style: style) } catch { fatalError("Seed model lower value must be zero") } pointer = TapePointer(initialValue: style.seedModel.lowerValue, style: style) super.init() let backgroundShape = SKShapeNode(rectOf: style.size, cornerRadius: 2) backgroundShape.fillColor = style.backgroundColor backgroundShape.strokeColor = SKColor.clear backgroundShape.zPosition = 0 cellContainer.zPosition = 1 pointer.zPosition = 2 cropNode.addChild(backgroundShape) cropNode.addChild(cellContainer) cropNode.addChild(pointer) cropNode.maskNode = SKSpriteNode(color: SKColor.black, size: style.size) addChild(cropNode) } func recycleCells() { cellContainer.recycleCells() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
4eb4ef2cd1a7190056a2c2a11ae6b707
32
136
0.638961
4.666667
false
false
false
false
fernandomarins/food-drivr-pt
hackathon-for-hunger/Modules/Donor/AddDonation/DonationPresenter.swift
1
1411
// // DashboardPresenter.swift // hackathon-for-hunger // // Created by Ian Gristock on 5/6/16. // Copyright © 2016 Hacksmiths. All rights reserved. // import Foundation import RealmSwift protocol DonationView: NSObjectProtocol { func startLoading() func finishLoading() func donations(sender: DonationPresenter, didSucceed donation: Donation) func donations(sender: DonationPresenter, didFail error: NSError) } class DonationPresenter { private let donationService: DonationService private var donationView : DonationView? var realm = try! Realm() init(donationService: DonationService){ self.donationService = donationService } func attachView(view: DonationView){ donationView = view } func detachView() { donationView = nil } func createDonation(items: [String]?) { guard let items = items where items.count > 0 else { self.donationView?.donations(self, didFail: NSError(domain: "No Donation Items Found", code: 422, userInfo: nil)) return } self.donationService.createDonation(items).then() { donation -> Void in self.donationView?.donations(self, didSucceed: donation) }.error { error in self.donationView?.donations(self, didFail: error as NSError) } } }
mit
83c36b53a1a4cdb5a74b71690bdf20e7
26.666667
125
0.641844
4.638158
false
false
false
false
dvxiaofan/Pro-Swift-Learning
Part-01/01-PatternMatching/09-Where.playground/Contents.swift
1
329
//: Playground - noun: a place where people can play import UIKit let numbers = [1, 2, 3, 4, 5] for num in numbers where num % 2 == 0 { print(num) } let names: [String?] = ["xiaofan", nil, "xiaoming", nil, "hahha"] for name in names where name != nil { print(name) } for case let name? in names { print(name) }
mit
33789e5107b31a99b0d304724cb71c8b
16.315789
65
0.613982
2.911504
false
false
false
false
benlangmuir/swift
stdlib/public/Concurrency/TaskGroup.swift
2
32977
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift @_implementationOnly import _SwiftConcurrencyShims // ==== TaskGroup -------------------------------------------------------------- /// Starts a new scope that can contain a dynamic number of child tasks. /// /// A group waits for all of its child tasks /// to complete or be canceled before it returns. /// After this function returns, the task group is always empty. /// /// To collect the results of the group's child tasks, /// you can use a `for`-`await`-`in` loop: /// /// var sum = 0 /// for await result in group { /// sum += result /// } /// /// If you need more control or only a few results, /// you can call `next()` directly: /// /// guard let first = await group.next() else { /// group.cancelAll() /// return 0 /// } /// let second = await group.next() ?? 0 /// group.cancelAll() /// return first + second /// /// Task Group Cancellation /// ======================= /// /// You can cancel a task group and all of its child tasks /// by calling the `cancelAll()` method on the task group, /// or by canceling the task in which the group is running. /// /// If you call `async(priority:operation:)` to create a new task in a canceled group, /// that task is immediately canceled after creation. /// Alternatively, you can call `asyncUnlessCancelled(priority:operation:)`, /// which doesn't create the task if the group has already been canceled /// Choosing between these two functions /// lets you control how to react to cancellation within a group: /// some child tasks need to run regardless of cancellation, /// but other tasks are better not even being created /// when you know they can't produce useful results. /// /// Because the tasks you add to a group with this method are nonthrowing, /// those tasks can't respond to cancellation by throwing `CancellationError`. /// The tasks must handle cancellation in some other way, /// such as returning the work completed so far, returning an empty result, or returning `nil`. /// For tasks that need to handle cancellation by throwing an error, /// use the `withThrowingTaskGroup(of:returning:body:)` method instead. @available(SwiftStdlib 5.1, *) @_silgen_name("$ss13withTaskGroup2of9returning4bodyq_xm_q_mq_ScGyxGzYaXEtYar0_lF") @_unsafeInheritExecutor @inlinable public func withTaskGroup<ChildTaskResult, GroupResult>( of childTaskResultType: ChildTaskResult.Type, returning returnType: GroupResult.Type = GroupResult.self, body: (inout TaskGroup<ChildTaskResult>) async -> GroupResult ) async -> GroupResult { #if compiler(>=5.5) && $BuiltinTaskGroupWithArgument let _group = Builtin.createTaskGroup(ChildTaskResult.self) var group = TaskGroup<ChildTaskResult>(group: _group) // Run the withTaskGroup body. let result = await body(&group) await group.awaitAllRemainingTasks() Builtin.destroyTaskGroup(_group) return result #else fatalError("Swift compiler is incompatible with this SDK version") #endif } /// Starts a new scope that can contain a dynamic number of throwing child tasks. /// /// A group waits for all of its child tasks /// to complete, throw an error, or be canceled before it returns. /// After this function returns, the task group is always empty. /// /// To collect the results of the group's child tasks, /// you can use a `for`-`await`-`in` loop: /// /// var sum = 0 /// for try await result in group { /// sum += result /// } /// /// If you need more control or only a few results, /// you can call `next()` directly: /// /// guard let first = try await group.next() else { /// group.cancelAll() /// return 0 /// } /// let second = await group.next() ?? 0 /// group.cancelAll() /// return first + second /// /// Task Group Cancellation /// ======================= /// /// You can cancel a task group and all of its child tasks /// by calling the `cancelAll()` method on the task group, /// or by canceling the task in which the group is running. /// /// If you call `async(priority:operation:)` to create a new task in a canceled group, /// that task is immediately canceled after creation. /// Alternatively, you can call `asyncUnlessCancelled(priority:operation:)`, /// which doesn't create the task if the group has already been canceled /// Choosing between these two functions /// lets you control how to react to cancellation within a group: /// some child tasks need to run regardless of cancellation, /// but other tasks are better not even being created /// when you know they can't produce useful results. /// /// Throwing an error in one of the tasks of a task group /// doesn't immediately cancel the other tasks in that group. /// However, /// if you call `next()` in the task group and propagate its error, /// all other tasks are canceled. /// For example, in the code below, /// nothing is canceled and the group doesn't throw an error: /// /// withThrowingTaskGroup { group in /// group.addTask { throw SomeError() } /// } /// /// In contrast, this example throws `SomeError` /// and cancels all of the tasks in the group: /// /// withThrowingTaskGroup { group in /// group.addTask { throw SomeError() } /// try group.next() /// } /// /// An individual task throws its error /// in the corresponding call to `Group.next()`, /// which gives you a chance to handle the individual error /// or to let the group rethrow the error. @available(SwiftStdlib 5.1, *) @_silgen_name("$ss21withThrowingTaskGroup2of9returning4bodyq_xm_q_mq_Scgyxs5Error_pGzYaKXEtYaKr0_lF") @_unsafeInheritExecutor @inlinable public func withThrowingTaskGroup<ChildTaskResult, GroupResult>( of childTaskResultType: ChildTaskResult.Type, returning returnType: GroupResult.Type = GroupResult.self, body: (inout ThrowingTaskGroup<ChildTaskResult, Error>) async throws -> GroupResult ) async rethrows -> GroupResult { #if compiler(>=5.5) && $BuiltinTaskGroupWithArgument let _group = Builtin.createTaskGroup(ChildTaskResult.self) var group = ThrowingTaskGroup<ChildTaskResult, Error>(group: _group) do { // Run the withTaskGroup body. let result = try await body(&group) await group.awaitAllRemainingTasks() Builtin.destroyTaskGroup(_group) return result } catch { group.cancelAll() await group.awaitAllRemainingTasks() Builtin.destroyTaskGroup(_group) throw error } #else fatalError("Swift compiler is incompatible with this SDK version") #endif } /// A group that contains dynamically created child tasks. /// /// To create a task group, /// call the `withTaskGroup(of:returning:body:)` method. /// /// Don't use a task group from outside the task where you created it. /// In most cases, /// the Swift type system prevents a task group from escaping like that /// because adding a child task to a task group is a mutating operation, /// and mutation operations can't be performed /// from a concurrent execution context like a child task. /// /// For information about the language-level concurrency model that `TaskGroup` is part of, /// see [Concurrency][concurrency] in [The Swift Programming Language][tspl]. /// /// [concurrency]: https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html /// [tspl]: https://docs.swift.org/swift-book/ /// @available(SwiftStdlib 5.1, *) @frozen public struct TaskGroup<ChildTaskResult: Sendable> { /// Group task into which child tasks offer their results, /// and the `next()` function polls those results from. @usableFromInline internal let _group: Builtin.RawPointer // No public initializers @inlinable init(group: Builtin.RawPointer) { self._group = group } /// Adds a child task to the group. /// /// - Parameters: /// - overridingPriority: The priority of the operation task. /// Omit this parameter or pass `.unspecified` /// to set the child task's priority to the priority of the group. /// - operation: The operation to execute as part of the task group. @_alwaysEmitIntoClient public mutating func addTask( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async -> ChildTaskResult ) { #if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup #if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY let flags = taskCreateFlags( priority: priority, isChildTask: true, copyTaskLocals: false, inheritContext: false, enqueueJob: false, addPendingGroupTaskUnconditionally: true ) #else let flags = taskCreateFlags( priority: priority, isChildTask: true, copyTaskLocals: false, inheritContext: false, enqueueJob: true, addPendingGroupTaskUnconditionally: true ) #endif // Create the task in this group. _ = Builtin.createAsyncTaskInGroup(flags, _group, operation) #else fatalError("Unsupported Swift compiler") #endif } /// Adds a child task to the group, unless the group has been canceled. /// /// - Parameters: /// - overridingPriority: The priority of the operation task. /// Omit this parameter or pass `.unspecified` /// to set the child task's priority to the priority of the group. /// - operation: The operation to execute as part of the task group. /// - Returns: `true` if the child task was added to the group; /// otherwise `false`. @_alwaysEmitIntoClient public mutating func addTaskUnlessCancelled( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async -> ChildTaskResult ) -> Bool { #if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup let canAdd = _taskGroupAddPendingTask(group: _group, unconditionally: false) guard canAdd else { // the group is cancelled and is not accepting any new work return false } #if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY let flags = taskCreateFlags( priority: priority, isChildTask: true, copyTaskLocals: false, inheritContext: false, enqueueJob: false, addPendingGroupTaskUnconditionally: false ) #else let flags = taskCreateFlags( priority: priority, isChildTask: true, copyTaskLocals: false, inheritContext: false, enqueueJob: true, addPendingGroupTaskUnconditionally: false ) #endif // Create the task in this group. _ = Builtin.createAsyncTaskInGroup(flags, _group, operation) return true #else fatalError("Unsupported Swift compiler") #endif } /// Wait for the next child task to complete, /// and return the value it returned. /// /// The values returned by successive calls to this method /// appear in the order that the tasks *completed*, /// not in the order that those tasks were added to the task group. /// For example: /// /// group.addTask { 1 } /// group.addTask { 2 } /// /// print(await group.next()) /// // Prints either "2" or "1". /// /// If there aren't any pending tasks in the task group, /// this method returns `nil`, /// which lets you write the following /// to wait for a single task to complete: /// /// if let first = try await group.next() { /// return first /// } /// /// It also lets you write code like the following /// to wait for all the child tasks to complete, /// collecting the values they returned: /// /// while let first = try await group.next() { /// collected += value /// } /// return collected /// /// Awaiting on an empty group /// immediate returns `nil` without suspending. /// /// You can also use a `for`-`await`-`in` loop to collect results of a task group: /// /// for await try value in group { /// collected += value /// } /// /// Don't call this method from outside the task /// where you created this task group. /// In most cases, the Swift type system prevents this mistake. /// For example, because the `add(priority:operation:)` method is mutating, /// that method can't be called from a concurrent execution context like a child task. /// /// - Returns: The value returned by the next child task that completes. public mutating func next() async -> ChildTaskResult? { // try!-safe because this function only exists for Failure == Never, // and as such, it is impossible to spawn a throwing child task. return try! await _taskGroupWaitNext(group: _group) } /// Await all of the remaining tasks on this group. @usableFromInline internal mutating func awaitAllRemainingTasks() async { while let _ = await next() {} } /// Wait for all of the group's remaining tasks to complete. @_alwaysEmitIntoClient public mutating func waitForAll() async { await awaitAllRemainingTasks() } /// A Boolean value that indicates whether the group has any remaining tasks. /// /// At the start of the body of a `withTaskGroup(of:returning:body:)` call, /// the task group is always empty. /// It`s guaranteed to be empty when returning from that body /// because a task group waits for all child tasks to complete before returning. /// /// - Returns: `true` if the group has no pending tasks; otherwise `false`. public var isEmpty: Bool { _taskGroupIsEmpty(_group) } /// Cancel all of the remaining tasks in the group. /// /// After cancellation, /// any new results from the tasks in this group /// are silently discarded. /// /// If you add a task to a group after canceling the group, /// that task is canceled immediately after being added to the group. /// /// This method can only be called by the parent task that created the task /// group. /// /// - SeeAlso: `Task.isCancelled` /// - SeeAlso: `TaskGroup.isCancelled` public func cancelAll() { _taskGroupCancelAll(group: _group) } /// A Boolean value that indicates whether the group was canceled. /// /// To cancel a group, call the `TaskGroup.cancelAll()` method. /// /// If the task that's currently running this group is canceled, /// the group is also implicitly canceled, /// which is also reflected in this property's value. public var isCancelled: Bool { return _taskGroupIsCancelled(group: _group) } } @available(SwiftStdlib 5.1, *) @available(*, unavailable) extension TaskGroup: Sendable { } // Implementation note: // We are unable to just™ abstract over Failure == Error / Never because of the // complicated relationship between `group.spawn` which dictates if `group.next` // AND the AsyncSequence conformances would be throwing or not. // // We would be able to abstract over TaskGroup<..., Failure> equal to Never // or Error, and specifically only add the `spawn` and `next` functions for // those two cases. However, we are not able to conform to AsyncSequence "twice" // depending on if the Failure is Error or Never, as we'll hit: // conflicting conformance of 'TaskGroup<ChildTaskResult, Failure>' to protocol // 'AsyncSequence'; there cannot be more than one conformance, even with // different conditional bounds // So, sadly we're forced to duplicate the entire implementation of TaskGroup // to TaskGroup and ThrowingTaskGroup. // // The throwing task group is parameterized with failure only because of future // proofing, in case we'd ever have typed errors, however unlikely this may be. // Today the throwing task group failure is simply automatically bound to `Error`. /// A group that contains throwing, dynamically created child tasks. /// /// To create a throwing task group, /// call the `withThrowingTaskGroup(of:returning:body:)` method. /// /// Don't use a task group from outside the task where you created it. /// In most cases, /// the Swift type system prevents a task group from escaping like that /// because adding a child task to a task group is a mutating operation, /// and mutation operations can't be performed /// from concurrent execution contexts like a child task. /// /// For information about the language-level concurrency model that `ThrowingTaskGroup` is part of, /// see [Concurrency][concurrency] in [The Swift Programming Language][tspl]. /// /// [concurrency]: https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html /// [tspl]: https://docs.swift.org/swift-book/ /// @available(SwiftStdlib 5.1, *) @frozen public struct ThrowingTaskGroup<ChildTaskResult: Sendable, Failure: Error> { /// Group task into which child tasks offer their results, /// and the `next()` function polls those results from. @usableFromInline internal let _group: Builtin.RawPointer // No public initializers @inlinable init(group: Builtin.RawPointer) { self._group = group } /// Await all the remaining tasks on this group. @usableFromInline internal mutating func awaitAllRemainingTasks() async { while true { do { guard let _ = try await next() else { return } } catch {} } } @usableFromInline internal mutating func _waitForAll() async throws { while let _ = try await next() { } } /// Wait for all of the group's remaining tasks to complete. @_alwaysEmitIntoClient public mutating func waitForAll() async throws { while let _ = try await next() { } } /// Adds a child task to the group. /// /// This method doesn't throw an error, even if the child task does. /// Instead, the corresponding call to `ThrowingTaskGroup.next()` rethrows that error. /// /// - overridingPriority: The priority of the operation task. /// Omit this parameter or pass `.unspecified` /// to set the child task's priority to the priority of the group. /// - operation: The operation to execute as part of the task group. @_alwaysEmitIntoClient public mutating func addTask( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async throws -> ChildTaskResult ) { #if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup let flags = taskCreateFlags( priority: priority, isChildTask: true, copyTaskLocals: false, inheritContext: false, enqueueJob: true, addPendingGroupTaskUnconditionally: true ) // Create the task in this group. _ = Builtin.createAsyncTaskInGroup(flags, _group, operation) #else fatalError("Unsupported Swift compiler") #endif } /// Adds a child task to the group, unless the group has been canceled. /// /// This method doesn't throw an error, even if the child task does. /// Instead, the corresponding call to `ThrowingTaskGroup.next()` rethrows that error. /// /// - Parameters: /// - overridingPriority: The priority of the operation task. /// Omit this parameter or pass `.unspecified` /// to set the child task's priority to the priority of the group. /// - operation: The operation to execute as part of the task group. /// - Returns: `true` if the child task was added to the group; /// otherwise `false`. @_alwaysEmitIntoClient public mutating func addTaskUnlessCancelled( priority: TaskPriority? = nil, operation: __owned @Sendable @escaping () async throws -> ChildTaskResult ) -> Bool { #if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup let canAdd = _taskGroupAddPendingTask(group: _group, unconditionally: false) guard canAdd else { // the group is cancelled and is not accepting any new work return false } let flags = taskCreateFlags( priority: priority, isChildTask: true, copyTaskLocals: false, inheritContext: false, enqueueJob: true, addPendingGroupTaskUnconditionally: false ) // Create the task in this group. _ = Builtin.createAsyncTaskInGroup(flags, _group, operation) return true #else fatalError("Unsupported Swift compiler") #endif } /// Wait for the next child task to complete, /// and return the value it returned or rethrow the error it threw. /// /// The values returned by successive calls to this method /// appear in the order that the tasks *completed*, /// not in the order that those tasks were added to the task group. /// For example: /// /// group.addTask { 1 } /// group.addTask { 2 } /// /// print(await group.next()) /// // Prints either "2" or "1". /// /// If there aren't any pending tasks in the task group, /// this method returns `nil`, /// which lets you write the following /// to wait for a single task to complete: /// /// if let first = try await group.next() { /// return first /// } /// /// It also lets you write code like the following /// to wait for all the child tasks to complete, /// collecting the values they returned: /// /// while let first = try await group.next() { /// collected += value /// } /// return collected /// /// Awaiting on an empty group /// immediately returns `nil` without suspending. /// /// You can also use a `for`-`await`-`in` loop to collect results of a task group: /// /// for try await value in group { /// collected += value /// } /// /// If the next child task throws an error /// and you propagate that error from this method /// out of the body of a call to the /// `ThrowingTaskGroup.withThrowingTaskGroup(of:returning:body:)` method, /// then all remaining child tasks in that group are implicitly canceled. /// /// Don't call this method from outside the task /// where this task group was created. /// In most cases, the Swift type system prevents this mistake; /// for example, because the `add(priority:operation:)` method is mutating, /// that method can't be called from a concurrent execution context like a child task. /// /// - Returns: The value returned by the next child task that completes. /// /// - Throws: The error thrown by the next child task that completes. /// /// - SeeAlso: `nextResult()` public mutating func next() async throws -> ChildTaskResult? { return try await _taskGroupWaitNext(group: _group) } @_silgen_name("$sScg10nextResults0B0Oyxq_GSgyYaKF") @usableFromInline mutating func nextResultForABI() async throws -> Result<ChildTaskResult, Failure>? { do { guard let success: ChildTaskResult = try await _taskGroupWaitNext(group: _group) else { return nil } return .success(success) } catch { return .failure(error as! Failure) // as!-safe, because we are only allowed to throw Failure (Error) } } /// Wait for the next child task to complete, /// and return a result containing either /// the value that the child task returned or the error that it threw. /// /// The values returned by successive calls to this method /// appear in the order that the tasks *completed*, /// not in the order that those tasks were added to the task group. /// For example: /// /// group.addTask { 1 } /// group.addTask { 2 } /// /// guard let result = await group.nextResult() else { /// return // No task to wait on, which won't happen in this example. /// } /// /// switch result { /// case .success(let value): print(value) /// case .failure(let error): print("Failure: \(error)") /// } /// // Prints either "2" or "1". /// /// If the next child task throws an error /// and you propagate that error from this method /// out of the body of a call to the /// `ThrowingTaskGroup.withThrowingTaskGroup(of:returning:body:)` method, /// then all remaining child tasks in that group are implicitly canceled. /// /// - Returns: A `Result.success` value /// containing the value that the child task returned, /// or a `Result.failure` value /// containing the error that the child task threw. /// /// - SeeAlso: `next()` @_alwaysEmitIntoClient public mutating func nextResult() async -> Result<ChildTaskResult, Failure>? { return try! await nextResultForABI() } /// A Boolean value that indicates whether the group has any remaining tasks. /// /// At the start of the body of a `withThrowingTaskGroup(of:returning:body:)` call, /// the task group is always empty. /// It's guaranteed to be empty when returning from that body /// because a task group waits for all child tasks to complete before returning. /// /// - Returns: `true` if the group has no pending tasks; otherwise `false`. public var isEmpty: Bool { _taskGroupIsEmpty(_group) } /// Cancel all of the remaining tasks in the group. /// /// After cancellation, /// any new results or errors from the tasks in this group /// are silently discarded. /// /// If you add a task to a group after canceling the group, /// that task is canceled immediately after being added to the group. /// /// There are no restrictions on where you can call this method. /// Code inside a child task or even another task can cancel a group. /// /// - SeeAlso: `Task.isCancelled` /// - SeeAlso: `ThrowingTaskGroup.isCancelled` public func cancelAll() { _taskGroupCancelAll(group: _group) } /// A Boolean value that indicates whether the group was canceled. /// /// To cancel a group, call the `ThrowingTaskGroup.cancelAll()` method. /// /// If the task that's currently running this group is canceled, /// the group is also implicitly canceled, /// which is also reflected in this property's value. public var isCancelled: Bool { return _taskGroupIsCancelled(group: _group) } } @available(SwiftStdlib 5.1, *) @available(*, unavailable) extension ThrowingTaskGroup: Sendable { } /// ==== TaskGroup: AsyncSequence ---------------------------------------------- @available(SwiftStdlib 5.1, *) extension TaskGroup: AsyncSequence { public typealias AsyncIterator = Iterator public typealias Element = ChildTaskResult public func makeAsyncIterator() -> Iterator { return Iterator(group: self) } /// A type that provides an iteration interface /// over the results of tasks added to the group. /// /// The elements returned by this iterator /// appear in the order that the tasks *completed*, /// not in the order that those tasks were added to the task group. /// /// This iterator terminates after all tasks have completed. /// After iterating over the results of each task, /// it's valid to make a new iterator for the task group, /// which you can use to iterate over the results of new tasks you add to the group. /// For example: /// /// group.addTask { 1 } /// for await r in group { print(r) } /// /// // Add a new child task and iterate again. /// group.addTask { 2 } /// for await r in group { print(r) } /// /// - SeeAlso: `TaskGroup.next()` @available(SwiftStdlib 5.1, *) public struct Iterator: AsyncIteratorProtocol { public typealias Element = ChildTaskResult @usableFromInline var group: TaskGroup<ChildTaskResult> @usableFromInline var finished: Bool = false // no public constructors init(group: TaskGroup<ChildTaskResult>) { self.group = group } /// Advances to and returns the result of the next child task. /// /// The elements returned from this method /// appear in the order that the tasks *completed*, /// not in the order that those tasks were added to the task group. /// After this method returns `nil`, /// this iterator is guaranteed to never produce more values. /// /// For more information about the iteration order and semantics, /// see `TaskGroup.next()`. /// /// - Returns: The value returned by the next child task that completes, /// or `nil` if there are no remaining child tasks, public mutating func next() async -> Element? { guard !finished else { return nil } guard let element = await group.next() else { finished = true return nil } return element } public mutating func cancel() { finished = true group.cancelAll() } } } @available(SwiftStdlib 5.1, *) extension ThrowingTaskGroup: AsyncSequence { public typealias AsyncIterator = Iterator public typealias Element = ChildTaskResult public func makeAsyncIterator() -> Iterator { return Iterator(group: self) } /// A type that provides an iteration interface /// over the results of tasks added to the group. /// /// The elements returned by this iterator /// appear in the order that the tasks *completed*, /// not in the order that those tasks were added to the task group. /// /// This iterator terminates after all tasks have completed successfully, /// or after any task completes by throwing an error. /// If a task completes by throwing an error, /// it doesn't return any further task results. /// After iterating over the results of each task, /// it's valid to make a new iterator for the task group, /// which you can use to iterate over the results of new tasks you add to the group. /// You can also make a new iterator to resume iteration /// after a child task throws an error. /// For example: /// /// group.addTask { 1 } /// group.addTask { throw SomeError } /// group.addTask { 2 } /// /// do { /// // Assuming the child tasks complete in order, this prints "1" /// // and then throws an error. /// for try await r in group { print(r) } /// } catch { /// // Resolve the error. /// } /// /// // Assuming the child tasks complete in order, this prints "2". /// for try await r in group { print(r) } /// /// - SeeAlso: `ThrowingTaskGroup.next()` @available(SwiftStdlib 5.1, *) public struct Iterator: AsyncIteratorProtocol { public typealias Element = ChildTaskResult @usableFromInline var group: ThrowingTaskGroup<ChildTaskResult, Failure> @usableFromInline var finished: Bool = false // no public constructors init(group: ThrowingTaskGroup<ChildTaskResult, Failure>) { self.group = group } /// Advances to and returns the result of the next child task. /// /// The elements returned from this method /// appear in the order that the tasks *completed*, /// not in the order that those tasks were added to the task group. /// After this method returns `nil`, /// this iterator is guaranteed to never produce more values. /// /// For more information about the iteration order and semantics, /// see `ThrowingTaskGroup.next()` /// /// - Throws: The error thrown by the next child task that completes. /// /// - Returns: The value returned by the next child task that completes, /// or `nil` if there are no remaining child tasks, public mutating func next() async throws -> Element? { guard !finished else { return nil } do { guard let element = try await group.next() else { finished = true return nil } return element } catch { finished = true throw error } } public mutating func cancel() { finished = true group.cancelAll() } } } /// ==== ----------------------------------------------------------------------- @available(SwiftStdlib 5.1, *) @_silgen_name("swift_taskGroup_destroy") func _taskGroupDestroy(group: __owned Builtin.RawPointer) @available(SwiftStdlib 5.1, *) @_silgen_name("swift_taskGroup_addPending") @usableFromInline func _taskGroupAddPendingTask( group: Builtin.RawPointer, unconditionally: Bool ) -> Bool @available(SwiftStdlib 5.1, *) @_silgen_name("swift_taskGroup_cancelAll") func _taskGroupCancelAll(group: Builtin.RawPointer) /// Checks ONLY if the group was specifically canceled. /// The task itself being canceled must be checked separately. @available(SwiftStdlib 5.1, *) @_silgen_name("swift_taskGroup_isCancelled") func _taskGroupIsCancelled(group: Builtin.RawPointer) -> Bool @available(SwiftStdlib 5.1, *) @_silgen_name("swift_taskGroup_wait_next_throwing") func _taskGroupWaitNext<T>(group: Builtin.RawPointer) async throws -> T? @available(SwiftStdlib 5.1, *) @_silgen_name("swift_task_hasTaskGroupStatusRecord") func _taskHasTaskGroupStatusRecord() -> Bool @available(SwiftStdlib 5.1, *) enum PollStatus: Int { case empty = 0 case waiting = 1 case success = 2 case error = 3 } @available(SwiftStdlib 5.1, *) @_silgen_name("swift_taskGroup_isEmpty") func _taskGroupIsEmpty( _ group: Builtin.RawPointer ) -> Bool
apache-2.0
579138a12c6091016800362e388c83dc
34.229701
106
0.67069
4.434508
false
false
false
false
HeartRateLearning/HRLApp
HRLApp/Common/Model/WorkoutRecord.swift
1
901
// // WorkoutRecord.swift // HRLApp // // Created by Enrique de la Torre (dev) on 04/02/2017. // Copyright © 2017 Enrique de la Torre. All rights reserved. // import Foundation // MARK: - Main body struct WorkoutRecord { // MARK: - Public properties var date: Date { return heartRate.date } var bpm: Float { return heartRate.bpm } let workingOut: WorkingOut // MARK: - Private properties fileprivate let heartRate: HeartRateRecord // MARK: - Init methods init(heartRate: HeartRateRecord, workingOut: WorkingOut) { self.heartRate = heartRate self.workingOut = workingOut } } // MARK: - Equatable methods extension WorkoutRecord: Equatable {} // MARK: - Free functions func ==(lhs: WorkoutRecord, rhs: WorkoutRecord) -> Bool { return lhs.heartRate == rhs.heartRate && lhs.workingOut == rhs.workingOut }
mit
b74b627f937c386bf66ada543d2a39f5
18.148936
77
0.654444
4
false
false
false
false
varkor/firefox-ios
Client/Frontend/Browser/BackForwardListAnimator.swift
1
4061
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit class BackForwardListAnimator: NSObject, UIViewControllerAnimatedTransitioning { var presenting: Bool = false let animationDuration = 0.4 func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let screens = (from: transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!, to: transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!) guard let backForwardViewController = !self.presenting ? screens.from as? BackForwardListViewController : screens.to as? BackForwardListViewController else { return } var bottomViewController = !self.presenting ? screens.to as UIViewController : screens.from as UIViewController if let navController = bottomViewController as? UINavigationController { bottomViewController = navController.viewControllers.last ?? bottomViewController } if let browserViewController = bottomViewController as? BrowserViewController { animateWithBackForward(backForwardViewController, browserViewController: browserViewController, transitionContext: transitionContext) } } func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return animationDuration } } extension BackForwardListAnimator: UIViewControllerTransitioningDelegate { func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = true return self } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = false return self } } extension BackForwardListAnimator { private func animateWithBackForward(backForward: BackForwardListViewController, browserViewController bvc: BrowserViewController, transitionContext: UIViewControllerContextTransitioning) { guard let containerView = transitionContext.containerView() else { return } if presenting { backForward.view.frame = bvc.view.frame backForward.view.alpha = 0 containerView.addSubview(backForward.view) backForward.view.snp_updateConstraints { make in make.edges.equalTo(containerView) } backForward.view.layoutIfNeeded() UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.3, options: [], animations: { () -> Void in backForward.view.alpha = 1 backForward.tableView.snp_updateConstraints { make in make.height.equalTo(backForward.tableHeight) } backForward.view.layoutIfNeeded() }, completion: { (completed) -> Void in transitionContext.completeTransition(completed) }) } else { UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 1.2, initialSpringVelocity: 0.0, options: [], animations: { () -> Void in backForward.view.alpha = 0 backForward.tableView.snp_updateConstraints { make in make.height.equalTo(0) } backForward.view.layoutIfNeeded() }, completion: { (completed) -> Void in backForward.view.removeFromSuperview() transitionContext.completeTransition(completed) }) } } }
mpl-2.0
fcda6df08fadadfc806dc6f526fad760
46.776471
217
0.68259
6.70132
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/NaturalLanguageUnderstandingV1/Models/EntitiesResult.swift
1
1944
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** The important people, places, geopolitical entities and other types of entities in your content. */ public struct EntitiesResult: Decodable { /// Entity type. public var type: String? /// The name of the entity. public var text: String? /// Relevance score from 0 to 1. Higher values indicate greater relevance. public var relevance: Double? /// Entity mentions and locations. public var mentions: [EntityMention]? /// How many times the entity was mentioned in the text. public var count: Int? /// Emotion analysis results for the entity, enabled with the "emotion" option. public var emotion: EmotionScores? /// Sentiment analysis results for the entity, enabled with the "sentiment" option. public var sentiment: FeatureSentimentResults? /// Disambiguation information for the entity. public var disambiguation: DisambiguationResult? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case type = "type" case text = "text" case relevance = "relevance" case mentions = "mentions" case count = "count" case emotion = "emotion" case sentiment = "sentiment" case disambiguation = "disambiguation" } }
mit
de5a0ea1851263afb0c343fac259f884
32.517241
103
0.700617
4.584906
false
false
false
false
adrfer/swift
test/Interpreter/classes.swift
14
3733
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test class Interval { var lo, hi : Int init(_ lo:Int, _ hi:Int) { self.lo = lo self.hi = hi } func show() { print("[\(lo), \(hi)]") } class func like(lo: Int, _ hi: Int) -> Interval { return Interval(lo, hi) } } class OpenInterval : Interval { override init(_ lo:Int, _ hi:Int) { super.init(lo, hi) } override func show() { print("(\(lo), \(hi))") } override class func like(lo:Int, _ hi:Int) -> Interval { return OpenInterval(lo, hi) } } func +(a: Interval, b: Interval) -> Interval { return Interval(a.lo + b.lo, a.hi + b.hi) } func -(a: Interval, b: Interval) -> Interval { return Interval(a.lo - b.hi, a.hi - b.lo) } prefix func -(a: Interval) -> Interval { return a.dynamicType.like(-a.hi, -a.lo) } // CHECK: [-2, -1] (-Interval(1,2)).show() // CHECK: [4, 6] (Interval(1,2) + Interval(3,4)).show() // CHECK: [1, 3] (Interval(3,4) - Interval(1,2)).show() // CHECK: (-1, 1) (OpenInterval(-1,1)).show() // CHECK: (-3, 2) (-OpenInterval(-2,3)).show() // CHECK: false print(Interval(1,2) is OpenInterval) // CHECK: true var i12 : Interval = OpenInterval(1,2) print(i12 is OpenInterval) class RDar16563763_A {} class RDar16563763_B : RDar16563763_A {} print("self is Type = \(RDar16563763_A.self is RDar16563763_B.Type)") // CHECK: self is Type = false // // rdar://problem/19321484 // class Base { func makePossibleString() -> String? { return "Base" } } /* inherits from Base with method that returns a String instead of an Optional * String */ class CompilerCrasher : Base { override func makePossibleString() -> String { return "CompilerCrasher" } } class SonOfCompilerCrasher: CompilerCrasher {} class ReturnOfCompilerCrasher: CompilerCrasher { override func makePossibleString() -> String { return "ReturnOfCompilerCrasher" } } func testCrash(c: Base) -> String? { let s = c.makePossibleString() return s } public func driver() { var c = CompilerCrasher() var d = SonOfCompilerCrasher() var e = ReturnOfCompilerCrasher() var r = testCrash(c) print(r) r = testCrash(d) print(r) r = testCrash(e) print(r) } driver() // CHECK: Optional("CompilerCrasher") // CHECK-NEXT: Optional("CompilerCrasher") // CHECK-NEXT: Optional("ReturnOfCompilerCrasher") struct Account { var owner: String } class Bank { func transferMoney(from: Account?, to: Account!) -> Account! { return nil } func deposit(to: Account) -> Account? { return nil } } class DodgyBank : Bank { // Parameters: swap ? and ! // Result: less optional override func transferMoney(from: Account!, to: Account?) -> Account { if let fromAccount = from { return fromAccount } else { return Account(owner: "Bank fees") } } // Parameter: more optional // Result: swap ? and ! override func deposit(to: Account?) -> Account! { if let toAccount = to { if (toAccount.owner == "Cyberdyne Systems") { return nil } } return to } } // CHECK: Account(owner: "A") // CHECK: Account(owner: "Bank fees") // CHECK: nil // CHECK: Optional(main.Account(owner: "A")) let b = DodgyBank() #if false // FIXME: rdar://problem/21435542 print(b.transferMoney(Account(owner: "A"), to: Account(owner: "B"))) print(b.transferMoney(nil, to: nil)) print(b.deposit(Account(owner: "Cyberdyne Systems"))) print(b.deposit(Account(owner: "A"))) print(b.deposit(nil)) #endif print((b as Bank).transferMoney(Account(owner: "A"), to: Account(owner: "B"))) print((b as Bank).transferMoney(nil, to: nil)) print((b as Bank).deposit(Account(owner: "Cyberdyne Systems"))) print((b as Bank).deposit(Account(owner: "A")))
apache-2.0
f58e84003b7e6921d6ca2ea61c8de951
20.703488
78
0.638896
3.177021
false
false
false
false
audrl1010/EasyMakePhotoPicker
Example/EasyMakePhotoPicker/FacebookPhotosLayout.swift
1
1061
// // FacebookPhotosLayout.swift // EasyMakePhotoPicker // // Created by myung gi son on 2017. 7. 7.. // Copyright © 2017년 CocoaPods. All rights reserved. // import UIKit class FacebookPhotosLayout: UICollectionViewFlowLayout { // MARK: - Constant fileprivate struct Constant { static let padding = CGFloat(5) static let numberOfColumns = CGFloat(3) } override var itemSize: CGSize { set { } get { guard let collectionView = collectionView else { return .zero } let collectionViewWidth = (collectionView.bounds.width) let columnWidth = (collectionViewWidth - Constant.padding * (Constant.numberOfColumns - 1)) / Constant.numberOfColumns return CGSize(width: columnWidth, height: columnWidth) } } override init() { super.init() setupLayout() } required init?(coder aDecoder: NSCoder) { super.init() setupLayout() } func setupLayout() { minimumLineSpacing = Constant.padding minimumInteritemSpacing = Constant.padding } }
mit
ce9d52b9faf4950cd32bc87964dba5c9
19.745098
85
0.665406
4.681416
false
false
false
false
tenebreux/realm-cocoa
RealmSwift-swift1.2/Tests/KVOTests.swift
3
12853
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import RealmSwift var pkCounter = 0 func nextPrimaryKey() -> Int { return ++pkCounter } class KVOObject: Object { dynamic var pk = nextPrimaryKey() // primary key for equality dynamic var ignored: Int = 0 dynamic var boolCol: Bool = false dynamic var int8Col: Int8 = 1 dynamic var int16Col: Int16 = 2 dynamic var int32Col: Int32 = 3 dynamic var int64Col: Int64 = 4 dynamic var floatCol: Float = 5 dynamic var doubleCol: Double = 6 dynamic var stringCol: String = "" dynamic var binaryCol: NSData = NSData() dynamic var dateCol: NSDate = NSDate(timeIntervalSince1970: 0) dynamic var objectCol: KVOObject? dynamic var arrayCol = List<KVOObject>() let optIntCol = RealmOptional<Int>() let optFloatCol = RealmOptional<Float>() let optDoubleCol = RealmOptional<Double>() let optBoolCol = RealmOptional<Bool>() dynamic var optStringCol: String? dynamic var optBinaryCol: NSData? dynamic var optDateCol: NSDate? override class func primaryKey() -> String { return "pk" } override class func ignoredProperties() -> [String] { return ["ignored"] } } // Most of the testing of KVO functionality is done in the obj-c tests // These tests just verify that it also works on Swift types class KVOTests: TestCase { var realm: Realm! = nil override func setUp() { super.setUp() realm = Realm() realm.beginWrite() } override func tearDown() { realm.cancelWrite() realm = nil super.tearDown() } var changeDictionary: [NSObject: AnyObject]? override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { changeDictionary = change } func observeChange(obj: NSObject, _ key: String, _ old: AnyObject, _ new: AnyObject, fileName: String = __FILE__, lineNumber: UInt = __LINE__, _ block: () -> Void) { obj.addObserver(self, forKeyPath: key, options: .Old | .New, context: nil) block() obj.removeObserver(self, forKeyPath: key) XCTAssert(changeDictionary != nil, "Did not get a notification", file: fileName, line: lineNumber) if changeDictionary == nil { return } let actualOld: AnyObject = changeDictionary![NSKeyValueChangeOldKey]! let actualNew: AnyObject = changeDictionary![NSKeyValueChangeNewKey]! XCTAssert(actualOld.isEqual(old), "Old value: expected \(old), got \(actualOld)", file: fileName, line: lineNumber) XCTAssert(actualNew.isEqual(new), "New value: expected \(new), got \(actualNew)", file: fileName, line: lineNumber) changeDictionary = nil } func observeListChange(obj: NSObject, _ key: String, _ kind: NSKeyValueChange, _ indexes: NSIndexSet, fileName: String = __FILE__, lineNumber: UInt = __LINE__, _ block: () -> Void) { obj.addObserver(self, forKeyPath: key, options: .Old | .New, context: nil) block() obj.removeObserver(self, forKeyPath: key) XCTAssert(changeDictionary != nil, "Did not get a notification", file: fileName, line: lineNumber) if changeDictionary == nil { return } let actualKind = NSKeyValueChange(rawValue: (changeDictionary![NSKeyValueChangeKindKey] as! NSNumber).unsignedLongValue)! let actualIndexes = changeDictionary![NSKeyValueChangeIndexesKey]! as! NSIndexSet XCTAssert(actualKind == kind, "Change kind: expected \(kind), got \(actualKind)", file: fileName, line: lineNumber) XCTAssert(actualIndexes.isEqual(indexes), "Changed indexes: expected \(indexes), got \(actualIndexes)", file: fileName, line: lineNumber) changeDictionary = nil } // Actual tests follow func testAllPropertyTypesStandalone() { let obj = KVOObject() observeChange(obj, "boolCol", false, true) { obj.boolCol = true } observeChange(obj, "int8Col", 1, 10) { obj.int8Col = 10 } observeChange(obj, "int16Col", 2, 10) { obj.int16Col = 10 } observeChange(obj, "int32Col", 3, 10) { obj.int32Col = 10 } observeChange(obj, "int64Col", 4, 10) { obj.int64Col = 10 } observeChange(obj, "floatCol", 5, 10) { obj.floatCol = 10 } observeChange(obj, "doubleCol", 6, 10) { obj.doubleCol = 10 } observeChange(obj, "stringCol", "", "abc") { obj.stringCol = "abc" } observeChange(obj, "objectCol", NSNull(), obj) { obj.objectCol = obj } let data = "abc".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! observeChange(obj, "binaryCol", NSData(), data) { obj.binaryCol = data } let date = NSDate(timeIntervalSince1970: 1) observeChange(obj, "dateCol", NSDate(timeIntervalSince1970: 0), date) { obj.dateCol = date } observeListChange(obj, "arrayCol", .Insertion, NSIndexSet(index: 0)) { obj.arrayCol.append(obj) } observeListChange(obj, "arrayCol", .Removal, NSIndexSet(index: 0)) { obj.arrayCol.removeAll() } observeChange(obj, "optIntCol", NSNull(), 10) { obj.optIntCol.value = 10 } observeChange(obj, "optFloatCol", NSNull(), 10) { obj.optFloatCol.value = 10 } observeChange(obj, "optDoubleCol", NSNull(), 10) { obj.optDoubleCol.value = 10 } observeChange(obj, "optBoolCol", NSNull(), true) { obj.optBoolCol.value = true } observeChange(obj, "optStringCol", NSNull(), "abc") { obj.optStringCol = "abc" } observeChange(obj, "optBinaryCol", NSNull(), data) { obj.optBinaryCol = data } observeChange(obj, "optDateCol", NSNull(), date) { obj.optDateCol = date } observeChange(obj, "optIntCol", 10, NSNull()) { obj.optIntCol.value = nil } observeChange(obj, "optFloatCol", 10, NSNull()) { obj.optFloatCol.value = nil } observeChange(obj, "optDoubleCol", 10, NSNull()) { obj.optDoubleCol.value = nil } observeChange(obj, "optBoolCol", true, NSNull()) { obj.optBoolCol.value = nil } observeChange(obj, "optStringCol", "abc", NSNull()) { obj.optStringCol = nil } observeChange(obj, "optBinaryCol", data, NSNull()) { obj.optBinaryCol = nil } observeChange(obj, "optDateCol", date, NSNull()) { obj.optDateCol = nil } } func testAllPropertyTypesPersisted() { let obj = KVOObject() realm.add(obj) observeChange(obj, "boolCol", false, true) { obj.boolCol = true } observeChange(obj, "int8Col", 1, 10) { obj.int8Col = 10 } observeChange(obj, "int16Col", 2, 10) { obj.int16Col = 10 } observeChange(obj, "int32Col", 3, 10) { obj.int32Col = 10 } observeChange(obj, "int64Col", 4, 10) { obj.int64Col = 10 } observeChange(obj, "floatCol", 5, 10) { obj.floatCol = 10 } observeChange(obj, "doubleCol", 6, 10) { obj.doubleCol = 10 } observeChange(obj, "stringCol", "", "abc") { obj.stringCol = "abc" } observeChange(obj, "objectCol", NSNull(), obj) { obj.objectCol = obj } let data = "abc".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! observeChange(obj, "binaryCol", NSData(), data) { obj.binaryCol = data } let date = NSDate(timeIntervalSince1970: 1) observeChange(obj, "dateCol", NSDate(timeIntervalSince1970: 0), date) { obj.dateCol = date } observeListChange(obj, "arrayCol", .Insertion, NSIndexSet(index: 0)) { obj.arrayCol.append(obj) } observeListChange(obj, "arrayCol", .Removal, NSIndexSet(index: 0)) { obj.arrayCol.removeAll() } observeChange(obj, "optIntCol", NSNull(), 10) { obj.optIntCol.value = 10 } observeChange(obj, "optFloatCol", NSNull(), 10) { obj.optFloatCol.value = 10 } observeChange(obj, "optDoubleCol", NSNull(), 10) { obj.optDoubleCol.value = 10 } observeChange(obj, "optBoolCol", NSNull(), true) { obj.optBoolCol.value = true } observeChange(obj, "optStringCol", NSNull(), "abc") { obj.optStringCol = "abc" } observeChange(obj, "optBinaryCol", NSNull(), data) { obj.optBinaryCol = data } observeChange(obj, "optDateCol", NSNull(), date) { obj.optDateCol = date } observeChange(obj, "optIntCol", 10, NSNull()) { obj.optIntCol.value = nil } observeChange(obj, "optFloatCol", 10, NSNull()) { obj.optFloatCol.value = nil } observeChange(obj, "optDoubleCol", 10, NSNull()) { obj.optDoubleCol.value = nil } observeChange(obj, "optBoolCol", true, NSNull()) { obj.optBoolCol.value = nil } observeChange(obj, "optStringCol", "abc", NSNull()) { obj.optStringCol = nil } observeChange(obj, "optBinaryCol", data, NSNull()) { obj.optBinaryCol = nil } observeChange(obj, "optDateCol", date, NSNull()) { obj.optDateCol = nil } observeChange(obj, "invalidated", false, true) { self.realm.delete(obj) } let obj2 = KVOObject() realm.add(obj2) observeChange(obj2, "arrayCol.invalidated", false, true) { self.realm.delete(obj2) } } func testAllPropertyTypesMultipleAccessors() { let obj = KVOObject() realm.add(obj) let obs = realm.objectForPrimaryKey(KVOObject.self, key: obj.pk)! observeChange(obs, "boolCol", false, true) { obj.boolCol = true } observeChange(obs, "int8Col", 1, 10) { obj.int8Col = 10 } observeChange(obs, "int16Col", 2, 10) { obj.int16Col = 10 } observeChange(obs, "int32Col", 3, 10) { obj.int32Col = 10 } observeChange(obs, "int64Col", 4, 10) { obj.int64Col = 10 } observeChange(obs, "floatCol", 5, 10) { obj.floatCol = 10 } observeChange(obs, "doubleCol", 6, 10) { obj.doubleCol = 10 } observeChange(obs, "stringCol", "", "abc") { obj.stringCol = "abc" } observeChange(obs, "objectCol", NSNull(), obj) { obj.objectCol = obj } let data = "abc".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! observeChange(obs, "binaryCol", NSData(), data) { obj.binaryCol = data } let date = NSDate(timeIntervalSince1970: 1) observeChange(obs, "dateCol", NSDate(timeIntervalSince1970: 0), date) { obj.dateCol = date } observeListChange(obs, "arrayCol", .Insertion, NSIndexSet(index: 0)) { obj.arrayCol.append(obj) } observeListChange(obs, "arrayCol", .Removal, NSIndexSet(index: 0)) { obj.arrayCol.removeAll() } observeChange(obj, "optIntCol", NSNull(), 10) { obj.optIntCol.value = 10 } observeChange(obj, "optFloatCol", NSNull(), 10) { obj.optFloatCol.value = 10 } observeChange(obj, "optDoubleCol", NSNull(), 10) { obj.optDoubleCol.value = 10 } observeChange(obj, "optBoolCol", NSNull(), true) { obj.optBoolCol.value = true } observeChange(obj, "optStringCol", NSNull(), "abc") { obj.optStringCol = "abc" } observeChange(obj, "optBinaryCol", NSNull(), data) { obj.optBinaryCol = data } observeChange(obj, "optDateCol", NSNull(), date) { obj.optDateCol = date } observeChange(obj, "optIntCol", 10, NSNull()) { obj.optIntCol.value = nil } observeChange(obj, "optFloatCol", 10, NSNull()) { obj.optFloatCol.value = nil } observeChange(obj, "optDoubleCol", 10, NSNull()) { obj.optDoubleCol.value = nil } observeChange(obj, "optBoolCol", true, NSNull()) { obj.optBoolCol.value = nil } observeChange(obj, "optStringCol", "abc", NSNull()) { obj.optStringCol = nil } observeChange(obj, "optBinaryCol", data, NSNull()) { obj.optBinaryCol = nil } observeChange(obj, "optDateCol", date, NSNull()) { obj.optDateCol = nil } observeChange(obs, "invalidated", false, true) { self.realm.delete(obj) } let obj2 = KVOObject() realm.add(obj2) let obs2 = realm.objectForPrimaryKey(KVOObject.self, key: obj2.pk)! observeChange(obs2, "arrayCol.invalidated", false, true) { self.realm.delete(obj2) } } }
apache-2.0
b8f8eff2839125c0a387afc37df5f840
47.319549
186
0.63386
4.253144
false
false
false
false
WINKgroup/WinkKit
WinkKit/Core/Presentation/ViewControllers/WKTableViewController.swift
1
3168
// // WKTableViewController.swift // WinkKit // // Created by Rico Crescenzio on 04/05/17. // // import UIKit /// The base TableViewController that will be subclassed in your project instead of subclassing `UITableViewController`. /// This provides some useful methods like the static instantiation. open class WKTableViewController<P>: UITableViewController, WKBaseViewController where P: WKGenericViewControllerPresenter { /// The presenter that will handle all logic of this viewController. open var presenter: P! /// If your project has a storyboard that contains an instance of the subclass of this view controller, /// you can override this property to indicate the name of that storyboard to allow auto-instantiation feature open class var storyboardName: String? { return nil } /// The identifier that is set in Storybaord. Default value is `String(describing: self)`, which means that /// the identifier of the view controller is the view controller class name. open class var identifier: String? { return String(describing: self) } // - MARK: Initializers /// Initialize view controller and assign the presenter. override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) initPresenter() } /// Initialize view controller and assign the presenter. required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initPresenter() } // - MARK: View Controller life-cycle open override func viewDidLoad() { super.viewDidLoad() guard presenter != nil else { fatalError("presenter is nil. it could be possible that you created a custom init for this view controller and you didn't call `initPresenter()`.") } presenter.viewDidLoad() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) presenter.viewWillAppear() } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) presenter.viewDidAppear() } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) presenter.viewWillDisappear() } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) presenter.viewDidDisappear() } deinit { presenter.viewDidDestroy() } // - MARK: Public methods. /// A method called when the view controller is initialized. This method cannot be overriden, /// but if you provide your own `init` (which doesn't override existing ones) you must call it. public func initPresenter() { if P.self == VoidPresenter.self { presenter = VoidPresenter() as! P } else if let view = self as? P.View { presenter = P.init(view: view, ()) } else { fatalError("\(type(of: self)) doesn't conform to \(type(of: P.View.self))") } } }
mit
e4793728de3ad1f56829cf44c1fd1fd0
33.813187
187
0.661932
5.044586
false
false
false
false
tmukammel/iOSKickStart
iOSKickStart/Classes/UIScrollView+Extension.swift
1
3094
// // UIScrollView+Extension.swift // BeWithFriends // // Created by Twaha Mukammel on 10/13/16. // Copyright © 2016 Twaha Mukammel. All rights reserved. // import UIKit public extension UIScrollView { } // MARK: - Solve keyboard hides input field public extension ScrollView { // MARK: - Public API func parentViewControllerWillAppear() { if actAsInputForm == true { registerForKeyboardNotifications(true); } } func parentViewControllerWillDisappear() { if actAsInputForm == true { registerForKeyboardNotifications(false) } } /// Checks and scrolls the active control to visible screen /// /// - Parameter control: the control to check if visible func scrollControlRectToVisible(_ control: UIControl) { var rect = bounds rect.size.height -= (contentInset.bottom + contentInset.top) let responderFrame = convert(control.frame, from: control.superview) let intersects = rect.contains(responderFrame) if (intersects == false) { scrollRectToVisible(responderFrame, animated: true) } } // MARK: - Private functions private func registerForKeyboardNotifications(_ register: Bool) { switch register { case true: NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) case false: NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } } @objc final func keyboardWillShow(notification: Notification) { let userInfo = notification.userInfo! var keyboardFrame: CGRect = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue keyboardFrame = self.convert(keyboardFrame, from: nil) // Considering superview as the UIViewController.contentView guard let screenSize = self.superview?.bounds else { return } var contentInset = self.contentInset contentInset.bottom = keyboardFrame.size.height - (screenSize.height - (frame.origin.y + frame.size.height)) self.contentInset = contentInset scrollIndicatorInsets = contentInset if let responder = customFirstRespnder { scrollControlRectToVisible(responder) } flashScrollIndicators() } @objc final func keyboardWillHide(notification: Notification) { let contentInset: UIEdgeInsets = .zero self.contentInset = contentInset scrollIndicatorInsets = contentInset } }
mit
2afe02a72c8b8be8c834e6832a319c38
33.366667
171
0.662464
5.603261
false
false
false
false
andersklenke/CS193p
Calculator/Calculator/ViewController.swift
1
1828
// // ViewController.swift // Calculator // // Created by Anders Friis Klenke on 28/01/15. // Copyright (c) 2015 Anders Friis Klenke. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var display: UILabel! var userIsInTheMiddleOfTypingAnumber = false var operandStack = Array<Double>() var displayValue: Double { get { return NSNumberFormatter().numberFromString(display.text!)!.doubleValue } set { display.text = "\(newValue)" userIsInTheMiddleOfTypingAnumber = false } } @IBAction func appendDigit(sender: UIButton) { let digit = sender.currentTitle! if userIsInTheMiddleOfTypingAnumber { display.text = display.text! + digit } else { display.text = digit userIsInTheMiddleOfTypingAnumber = true } } @IBAction func enter() { userIsInTheMiddleOfTypingAnumber = false operandStack.append(displayValue) println("operandStack = \(operandStack)") } @IBAction func operate(sender: UIButton) { let operation = sender.currentTitle! if userIsInTheMiddleOfTypingAnumber { enter() } switch operation { case "×": performOperation { $0 * $1 } case "÷": performOperation { $1 / $0 } case "+": performOperation { $0 + $1 } case "−": performOperation { $1 - $0 } case "√": performOperation { sqrt($0) } default: break } } func performOperation(operation: Double -> Double) { if operandStack.count >= 2 { displayValue = operation(operandStack.removeLast()) enter() } } func performOperation(operation: (Double, Double) -> Double) { if operandStack.count >= 2 { displayValue = operation(operandStack.removeLast(), operandStack.removeLast()) enter() } } }
mit
ec9aaef581e83f69ea1a09319309f0f6
23.621622
84
0.647091
4.671795
false
false
false
false
CoderSLZeng/SLWeiBo
SLWeiBo/SLWeiBo/Classes/Compose/Emoticon/Model/Emoticon.swift
1
1764
// // Emoticon.swift // 表情键盘 // // Created by Anthony on 17/3/17. // Copyright © 2017年 SLZeng. All rights reserved. // import UIKit class Emoticon: NSObject { // MARK:- 定义属性 var code : String? { // emoji的code didSet { guard let code = code else { return } // 1.创建扫描器 let scanner = Scanner(string: code) // 2.调用方法,扫描出code中的值 var value : UInt32 = 0 scanner.scanHexInt32(&value) // 3.将value转成字符 let c = Character(UnicodeScalar(value)!) // 4.将字符转成字符串 emojiCode = String(c) } } var png : String? { // 普通表情对应的图片名称 didSet { guard let png = png else { return } pngPath = Bundle.main.bundlePath + "/Emoticons.bundle/" + png } } var chs : String? // 普通表情对应的文字 // MARK:- 数据处理 var pngPath : String? var emojiCode : String? var isRemove : Bool = false var isEmpty : Bool = false // MARK:- 自定义构造函数 init(dict : [String : String]) { super.init() setValuesForKeys(dict) } init (isRemove : Bool) { self.isRemove = isRemove } init (isEmpty : Bool) { self.isEmpty = isEmpty } override func setValue(_ value: Any?, forUndefinedKey key: String) {} override var description : String { return dictionaryWithValues(forKeys: ["emojiCode", "pngPath", "chs"]).description } }
mit
15118b0d86aa15f9e66cfedbf2e53009
22.214286
89
0.491077
4.48895
false
false
false
false
huangboju/Moots
UICollectionViewLayout/SectionReactor-master/Examples/ArticleFeed/ArticleFeed/Sources/ViewControllers/ArticleViewController.swift
1
7399
// // ArticleViewController.swift // ArticleFeed // // Created by Suyeol Jeon on 07/09/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import UIKit import ReactorKit import RxDataSources import RxSwift import UICollectionViewFlexLayout final class ArticleViewController: UIViewController, View { // MARK: Properties var disposeBag = DisposeBag() lazy var dataSource = self.createDataSource() let articleSectionDelegate = ArticleSectionDelegate() private let articleCardAuthorCellDependencyFactory: (Article, UIViewController) -> ArticleCardAuthorCell.Dependency private let articleCardTextCellDependencyFactory: (Article, UIViewController) -> ArticleCardTextCell.Dependency private let articleCardReactionCellDependencyFactory: (Article, UIViewController) -> ArticleCardReactionCell.Dependency // MARK: UI let collectionView: UICollectionView = UICollectionView( frame: .zero, collectionViewLayout: UICollectionViewFlexLayout() ).then { $0.backgroundColor = .clear $0.alwaysBounceVertical = true } // MARK: Initializing init( reactor: ArticleViewReactor, articleCardAuthorCellDependencyFactory: @escaping (Article, UIViewController) -> ArticleCardAuthorCell.Dependency, articleCardTextCellDependencyFactory: @escaping (Article, UIViewController) -> ArticleCardTextCell.Dependency, articleCardReactionCellDependencyFactory: @escaping (Article, UIViewController) -> ArticleCardReactionCell.Dependency ) { defer { self.reactor = reactor } self.articleCardAuthorCellDependencyFactory = articleCardAuthorCellDependencyFactory self.articleCardTextCellDependencyFactory = articleCardTextCellDependencyFactory self.articleCardReactionCellDependencyFactory = articleCardReactionCellDependencyFactory super.init(nibName: nil, bundle: nil) self.title = "Article" self.articleSectionDelegate.registerReusables(to: self.collectionView) } required convenience init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func createDataSource() -> RxCollectionViewSectionedReloadDataSource<ArticleViewSection> { return .init( configureCell: { [weak self] dataSource, collectionView, indexPath, sectionItem in guard let `self` = self else { collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "__empty") return collectionView.dequeueReusableCell(withReuseIdentifier: "__empty", for: indexPath) } let articleCardAuthorCellDependency: ArticleCardAuthorCell.Dependency let articleCardTextCellDependency: ArticleCardTextCell.Dependency let articleCardReactionCellDependency: ArticleCardReactionCell.Dependency let section = dataSource[indexPath.section] switch section { case let .article(sectionReactor): let article = sectionReactor.currentState.article articleCardAuthorCellDependency = self.articleCardAuthorCellDependencyFactory(article, self) articleCardTextCellDependency = self.articleCardTextCellDependencyFactory(article, self) articleCardReactionCellDependency = self.articleCardReactionCellDependencyFactory(article, self) } return self.articleSectionDelegate.cell( collectionView: collectionView, indexPath: indexPath, sectionItem: sectionItem, articleCardAuthorCellDependency: articleCardAuthorCellDependency, articleCardTextCellDependency: articleCardTextCellDependency, articleCardReactionCellDependency: articleCardReactionCellDependency ) }, configureSupplementaryView: { [weak self] dataSource, collectionView, kind, indexPath in guard let `self` = self else { collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: kind, withReuseIdentifier: "__empty") return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "__empty", for: indexPath) } switch dataSource[indexPath.section] { case .article: return self.articleSectionDelegate.background( collectionView: collectionView, kind: kind, indexPath: indexPath, sectionItems: dataSource[indexPath.section].items ) } } ) } // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = 0xEDEDED.color self.view.addSubview(self.collectionView) self.collectionView.snp.makeConstraints { make in make.edges.equalToSuperview() } } // MARK: Binding func bind(reactor: ArticleViewReactor) { // State reactor.state.map { $0.authorName } .distinctUntilChanged() .map { $0.components(separatedBy: " ").first ?? $0 } .map { "\($0)'s Article" } .bind(to: self.rx.title) .disposed(by: self.disposeBag) reactor.state.map { $0.sections } .bind(to: self.collectionView.rx.items(dataSource: self.dataSource)) .disposed(by: self.disposeBag) // View self.collectionView.rx .setDelegate(self) .disposed(by: self.disposeBag) } } extension ArticleViewController: UICollectionViewDelegateFlexLayout { // section padding func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlexLayout, paddingForSectionAt section: Int ) -> UIEdgeInsets { return .init(top: 10, left: 10, bottom: 10, right: 10) } // section spacing func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlexLayout, verticalSpacingBetweenSectionAt section: Int, and nextSection: Int) -> CGFloat { return 10 } // item spacing func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlexLayout, verticalSpacingBetweenItemAt indexPath: IndexPath, and nextIndexPath: IndexPath ) -> CGFloat { return self.articleSectionDelegate.cellVerticalSpacing( sectionItem: self.dataSource[indexPath], nextSectionItem: self.dataSource[nextIndexPath] ) } // item margin func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlexLayout, marginForItemAt indexPath: IndexPath ) -> UIEdgeInsets { return self.articleSectionDelegate.cellMargin( collectionView: collectionView, layout: collectionViewLayout, indexPath: indexPath, sectionItem: self.dataSource[indexPath] ) } // item padding func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlexLayout, paddingForItemAt indexPath: IndexPath ) -> UIEdgeInsets { return self.articleSectionDelegate.cellPadding( layout: collectionViewLayout, indexPath: indexPath, sectionItem: self.dataSource[indexPath] ) } // item size func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlexLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let maxWidth = collectionViewLayout.maximumWidth(forItemAt: indexPath) return self.articleSectionDelegate.cellSize( maxWidth: maxWidth, sectionItem: self.dataSource[indexPath] ) } }
mit
65a53977f0dfb28c671196a00325436b
35.44335
195
0.740335
5.69515
false
false
false
false
bgrozev/jitsi-meet
ios/sdk/src/picture-in-picture/PiPViewCoordinator.swift
1
8779
/* * Copyright @ 2017-present Atlassian Pty Ltd * * 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. */ public typealias AnimationCompletion = (Bool) -> Void public protocol PiPViewCoordinatorDelegate: class { func exitPictureInPicture() } /// Coordinates the view state of a specified view to allow /// to be presented in full screen or in a custom Picture in Picture mode. /// This object will also provide the drag and tap interactions of the view /// when is presented in Picure in Picture mode. public class PiPViewCoordinator { /// Limits the boundries of view position on screen when minimized public var dragBoundInsets: UIEdgeInsets = UIEdgeInsets(top: 25, left: 5, bottom: 5, right: 5) { didSet { dragController.insets = dragBoundInsets } } public enum Position { case lowerRightCorner case upperRightCorner case lowerLeftCorner case upperLeftCorner } public var initialPositionInSuperview = Position.lowerRightCorner /// The size ratio of the view when in PiP mode public var pipSizeRatio: CGFloat = { let deviceIdiom = UIScreen.main.traitCollection.userInterfaceIdiom switch deviceIdiom { case .pad: return 0.25 case .phone: return 0.33 default: return 0.25 } }() public weak var delegate: PiPViewCoordinatorDelegate? private(set) var isInPiP: Bool = false // true if view is in PiP mode private(set) var view: UIView private var currentBounds: CGRect = CGRect.zero private var tapGestureRecognizer: UITapGestureRecognizer? private var exitPiPButton: UIButton? private let dragController: DragGestureController = DragGestureController() public init(withView view: UIView) { self.view = view } /// Configure the view to be always on top of all the contents /// of the provided parent view. /// If a parentView is not provided it will try to use the main window public func configureAsStickyView(withParentView parentView: UIView? = nil) { guard let parentView = parentView ?? UIApplication.shared.keyWindow else { return } parentView.addSubview(view) currentBounds = parentView.bounds view.frame = currentBounds view.layer.zPosition = CGFloat(Float.greatestFiniteMagnitude) } /// Show view with fade in animation public func show(completion: AnimationCompletion? = nil) { if view.isHidden || view.alpha < 1 { view.isHidden = false view.alpha = 0 animateTransition(animations: { [weak self] in self?.view.alpha = 1 }, completion: completion) } } /// Hide view with fade out animation public func hide(completion: AnimationCompletion? = nil) { if view.isHidden || view.alpha > 0 { animateTransition(animations: { [weak self] in self?.view.alpha = 0 self?.view.isHidden = true }, completion: completion) } } /// Resize view to and change state to custom PictureInPicture mode /// This will resize view, add a gesture to enable user to "drag" view /// around screen, and add a button of top of the view to be able to exit mode public func enterPictureInPicture() { isInPiP = true animateViewChange() dragController.startDragListener(inView: view) dragController.insets = dragBoundInsets // add single tap gesture recognition for displaying exit PiP UI let exitSelector = #selector(toggleExitPiP) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: exitSelector) self.tapGestureRecognizer = tapGestureRecognizer view.addGestureRecognizer(tapGestureRecognizer) } /// Exit Picture in picture mode, this will resize view, remove /// exit pip button, and disable the drag gesture @objc public func exitPictureInPicture() { isInPiP = false animateViewChange() dragController.stopDragListener() // hide PiP UI exitPiPButton?.removeFromSuperview() exitPiPButton = nil // remove gesture let exitSelector = #selector(toggleExitPiP) tapGestureRecognizer?.removeTarget(self, action: exitSelector) tapGestureRecognizer = nil delegate?.exitPictureInPicture() } /// Reset view to provide bounds, use this method on rotation or /// screen size changes public func resetBounds(bounds: CGRect) { currentBounds = bounds exitPictureInPicture() } /// Stop the dragging gesture of the root view public func stopDragGesture() { dragController.stopDragListener() } /// Customize the presentation of exit pip button open func configureExitPiPButton(target: Any, action: Selector) -> UIButton { let buttonImage = UIImage.init(named: "image-resize", in: Bundle(for: type(of: self)), compatibleWith: nil) let button = UIButton(type: .custom) let size: CGSize = CGSize(width: 44, height: 44) button.setImage(buttonImage, for: .normal) button.backgroundColor = .gray button.layer.cornerRadius = size.width / 2 button.frame = CGRect(origin: CGPoint.zero, size: size) button.center = view.convert(view.center, from: view.superview) button.addTarget(target, action: action, for: .touchUpInside) return button } // MARK: - Interactions @objc private func toggleExitPiP() { if exitPiPButton == nil { // show button let exitSelector = #selector(exitPictureInPicture) let button = configureExitPiPButton(target: self, action: exitSelector) view.addSubview(button) exitPiPButton = button } else { // hide button exitPiPButton?.removeFromSuperview() exitPiPButton = nil } } // MARK: - Size calculation private func animateViewChange() { UIView.animate(withDuration: 0.25) { self.view.frame = self.changeViewRect() self.view.setNeedsLayout() } } private func changeViewRect() -> CGRect { let bounds = currentBounds guard isInPiP else { return bounds } // resize to suggested ratio and position to the bottom right let adjustedBounds = bounds.inset(by: dragBoundInsets) let size = CGSize(width: bounds.size.width * pipSizeRatio, height: bounds.size.height * pipSizeRatio) let origin = initialPositionFor(pipSize: size, bounds: adjustedBounds) return CGRect(x: origin.x, y: origin.y, width: size.width, height: size.height) } private func initialPositionFor(pipSize size: CGSize, bounds: CGRect) -> CGPoint { switch initialPositionInSuperview { case .lowerLeftCorner: return CGPoint(x: bounds.minX, y: bounds.maxY - size.height) case .lowerRightCorner: return CGPoint(x: bounds.maxX - size.width, y: bounds.maxY - size.height) case .upperLeftCorner: return CGPoint(x: bounds.minX, y: bounds.minY) case .upperRightCorner: return CGPoint(x: bounds.maxX - size.width, y: bounds.minY) } } // MARK: - Animation helpers private func animateTransition(animations: @escaping () -> Void, completion: AnimationCompletion?) { UIView.animate(withDuration: 0.1, delay: 0, options: .beginFromCurrentState, animations: animations, completion: completion) } }
apache-2.0
8fbd5955e1d896d92f50fa5974cb7eaf
34.832653
87
0.613168
5.19775
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/SlideInPresentationAnimator.swift
1
2351
// // SlideInPresentationAnimator.swift // Slide for Reddit // // Created by Jonathan Cole on 8/3/18. // Copyright © 2018 Haptic Apps. All rights reserved. // import UIKit final class SlideInPresentationAnimator: NSObject { // MARK: - Properties let direction: PresentationDirection let isPresentation: Bool // MARK: - Initializers init(direction: PresentationDirection, isPresentation: Bool) { self.direction = direction self.isPresentation = isPresentation super.init() } } extension SlideInPresentationAnimator: UIViewControllerAnimatedTransitioning { func transitionDuration( using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let key = isPresentation ? UITransitionContextViewControllerKey.to : UITransitionContextViewControllerKey.from let keyV = isPresentation ? UITransitionContextViewKey.to : UITransitionContextViewKey.from let controller = transitionContext.viewController(forKey: key)! let view = transitionContext.view(forKey: keyV)! if isPresentation { transitionContext.containerView.addSubview(view) } let presentedFrame = transitionContext.finalFrame(for: controller) var dismissedFrame = presentedFrame switch direction { case .left: dismissedFrame.origin.x = -presentedFrame.width case .right: dismissedFrame.origin.x = transitionContext.containerView.frame.size.width case .top: dismissedFrame.origin.y = -presentedFrame.height case .bottom: dismissedFrame.origin.y = transitionContext.containerView.frame.size.height } let initialFrame = isPresentation ? dismissedFrame : presentedFrame let finalFrame = isPresentation ? presentedFrame : dismissedFrame let animationDuration = transitionDuration(using: transitionContext) view.frame = initialFrame UIView.animate(withDuration: animationDuration, animations: { view.frame = finalFrame }, completion: { finished in transitionContext.completeTransition(finished) }) } }
apache-2.0
762d26af82e4c2a234413eab0a81f9e1
33.057971
91
0.691064
5.994898
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothGATT/GATTCharacteristic.swift
1
4597
// // GATTCharacteristic.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/10/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// GATT Characteristic protocol. /// /// Describes a type that can encode / decode data to a characteristic type. public protocol GATTCharacteristic { /// The Bluetooth UUID of the characteristic. static var uuid: BluetoothUUID { get } /// Decode from data. init?(data: Data) /// Encode to data. var data: Data { get } } // MARK: - Supporting Types @frozen public enum GATTBeatsPerMinute { public struct Byte: BluetoothUnit, Equatable, Hashable { internal static let length = MemoryLayout<UInt8>.size public static var unitType: UnitIdentifier { return .beatsPerMinute } public var rawValue: UInt8 public init(rawValue: UInt8) { self.rawValue = rawValue } } } extension GATTBeatsPerMinute.Byte: CustomStringConvertible { public var description: String { return rawValue.description } } extension GATTBeatsPerMinute.Byte: ExpressibleByIntegerLiteral { public init(integerLiteral value: UInt8) { self.init(rawValue: value) } } @frozen public struct GATTBatteryPercentage: BluetoothUnit, Equatable, Hashable { internal static let length = MemoryLayout<UInt8>.size public static let min = GATTBatteryPercentage(0) public static let max = GATTBatteryPercentage(100) public static var unitType: UnitIdentifier { return .percentage } public var rawValue: UInt8 public init?(rawValue value: UInt8) { guard value <= GATTBatteryPercentage.max.rawValue, value >= GATTBatteryPercentage.min.rawValue else { return nil } self.rawValue = value } private init(_ unsafe: UInt8) { self.rawValue = unsafe } } extension GATTBatteryPercentage: CustomStringConvertible { public var description: String { return "\(rawValue)%" } } @frozen public struct GATTE2ecrc: RawRepresentable, Equatable, Hashable { internal static let length = MemoryLayout<UInt16>.size public var rawValue: UInt16 public init(rawValue: UInt16) { self.rawValue = rawValue } } extension GATTE2ecrc: CustomStringConvertible { public var description: String { return "\(rawValue)" } } extension GATTE2ecrc: ExpressibleByIntegerLiteral { public init(integerLiteral value: UInt16) { self.init(rawValue: value) } } @frozen public enum GATTKilogramCalorie { public struct Byte: BluetoothUnit { internal static let length = MemoryLayout<UInt8>.size public static var unitType: UnitIdentifier { return .kilogramCalorie } public var rawValue: UInt8 public init(rawValue: UInt8) { self.rawValue = rawValue } } public struct Bits16: BluetoothUnit { internal static let length = MemoryLayout<UInt16>.size public static var unitType: UnitIdentifier { return .kilogramCalorie } public var rawValue: UInt16 public init(rawValue: UInt16) { self.rawValue = rawValue } } } extension GATTKilogramCalorie.Byte: Equatable { public static func == (lhs: GATTKilogramCalorie.Byte, rhs: GATTKilogramCalorie.Byte) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTKilogramCalorie.Byte: CustomStringConvertible { public var description: String { return "\(rawValue)" } } extension GATTKilogramCalorie.Byte: ExpressibleByIntegerLiteral { public init(integerLiteral value: UInt8) { self.init(rawValue: value) } } extension GATTKilogramCalorie.Bits16: Equatable { public static func == (lhs: GATTKilogramCalorie.Bits16, rhs: GATTKilogramCalorie.Bits16) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTKilogramCalorie.Bits16: CustomStringConvertible { public var description: String { return "\(rawValue)" } } extension GATTKilogramCalorie.Bits16: ExpressibleByIntegerLiteral { public init(integerLiteral value: UInt16) { self.init(rawValue: value) } }
mit
46fee7c187edcc963f9cf814882cc6d8
21.419512
102
0.625762
5.164045
false
false
false
false
ansinlee/meteorology
meteorology/ProfSubjectViewController.swift
1
7661
// // ProfTopicViewController.swift // meteorology // // Created by sunsing on 6/19/15. // Copyright (c) 2015 LeeAnsin. All rights reserved. // import UIKit class ProfSubjectViewController: UITableViewController { var currentDataSource:[Subject] = [] var currentPage = 0 override 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() loadListData(false) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if tableView.respondsToSelector("layoutMargins") { self.tableView.layoutMargins = UIEdgeInsetsZero } self.tableView.separatorInset = UIEdgeInsetsZero } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source func loadListData(readmore:Bool) { dispatch_async(dispatch_get_global_queue(0, 0)) { self.isLoading = true if !readmore { self.currentDataSource = [] self.currentPage = 0 } var url = NSURL(string:GetUrl("/subject?offset=\(PediaListProvider.pageSize*self.currentPage)&limit=\(PediaListProvider.pageSize)&query=creatorid:\(GetCurrentUser().Id!)")) //获取JSON数据 var data = NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingUncached, error: nil) if data != nil { var json:AnyObject = NSJSONSerialization.JSONObjectWithData(data!,options:NSJSONReadingOptions.AllowFragments,error:nil)! //解析获取JSON字段值 var errcode:NSNumber = json.objectForKey("errcode") as! NSNumber //json结构字段名。 var errmsg:String? = json.objectForKey("errmsg") as? String var retdata:NSArray? = json.objectForKey("data") as? NSArray NSLog("errcode:\(errcode) errmsg:\(errmsg) data:\(retdata)") if errcode == 0 && retdata != nil { var list = retdata! var len = list.count-1 for i in 0...len { var subject = Subject(data: list[i]) self.currentDataSource.append(subject) } self.currentPage++ } } dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() self.isLoading = false } } } // MARK: scrollview delagate var isLoading = false override func scrollViewDidScroll(scrollView: UIScrollView) { //println("77777777 \(scrollView.contentSize.height - scrollView.frame.size.height): \(currentPage*10) \(self.currentDataSource.count) \(isLoading)") if scrollView == tableView && scrollView.contentSize.height - scrollView.frame.size.height > 0 && currentPage*PediaListProvider.pageSize == self.currentDataSource.count && !isLoading { if scrollView.contentOffset.y > scrollView.contentSize.height - scrollView.frame.size.height + 44 { self.loadListData(true) } } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return self.currentDataSource.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("subjectcell", forIndexPath: indexPath) as! UITableViewCell if currentDataSource.count <= indexPath.row { return cell } let subject = currentDataSource[indexPath.row] if (subject.Img == nil) { (cell.viewWithTag(1) as! UIImageView).image = UIImage(named: "default") } else { dispatch_async(dispatch_get_global_queue(0, 0)) { var data = NSData(contentsOfURL: NSURL(string: subject.Img!)!) dispatch_async(dispatch_get_main_queue()) { if data != nil { (cell.viewWithTag(1) as! UIImageView).image = UIImage(data: data!) } else { (cell.viewWithTag(1) as! UIImageView).image = UIImage(named: "default") } } } } (cell.viewWithTag(2) as! UILabel).text = subject.Title (cell.viewWithTag(3) as! UILabel).text = subject.Abstract return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 120 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) if indexPath.row < currentDataSource.count { let subject = currentDataSource[indexPath.row] let detailVC = PediaDetailViewController(subject: subject) self.navigationController?.pushViewController(detailVC, animated: true) } } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if cell.respondsToSelector("layoutMargins") { cell.layoutMargins = UIEdgeInsetsZero } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // 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. } */ }
apache-2.0
243cc74fd3a684f5bbe9a92fe3f438e5
40.451087
192
0.629081
5.341036
false
false
false
false
ray3132138/TestKitchen_1606
TestKitchen/TestKitchen/classes/common/Util.swift
1
644
// // Util.swift // TestKitchen // // Created by qianfeng on 16/8/18. // Copyright © 2016年 ray. All rights reserved. // import Foundation //这个文件用来定义枚举 //食材首页推荐的数据类型 public enum WidgetType: Int{ case GuessYourLike = 1 //猜你喜欢 case RedPackage = 2 //红包入口 case NewProduct = 5 //今日新品 case Special = 3 //早餐日记,健康一百岁 case Scene = 9 //全部场景 case Talent = 4 //推荐达人 case Works = 8 //精选作品 case Subject = 7 //专题 }
mit
2d18dc65fe2149940b532e2211bf4ab1
14.558824
47
0.521739
3.30625
false
false
false
false
sstanic/OnTheMap
On The Map/On The Map/LoginViewController.swift
1
7266
// // LoginViewController.swift // On The Map // // Created by Sascha Stanic on 31.03.16. // Copyright © 2016 Sascha Stanic. All rights reserved. // import UIKit class LoginViewController: UIViewController, UITextFieldDelegate, FBSDKLoginButtonDelegate { //# MARK: Outlets @IBOutlet weak var signUpStack: UIStackView! @IBOutlet weak var accountQuestionText: UITextField! @IBOutlet weak var emailText: UITextField! @IBOutlet weak var passwordText: UITextField! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var loginFacebookButton: FBSDKLoginButton! //# MARK: Attributes let signInURL = URL(string: "https://www.udacity.com/account/auth#!/signin") // let signUpURL = NSURL(string: "https://www.udacity.com/account/auth#!/signup") // app spec: Link to sign-in (not to sign-up) //# MARK: Overrides override func viewDidLoad() { super.viewDidLoad() // hide border signUpStack.layer.borderWidth = 0 Utils.hideActivityIndicator(view, activityIndicator: activityIndicator) initializeTextfields() initializeFacebook() } //# MARK: - Actions @IBAction func login(_ sender: AnyObject) { let email = emailText.text! let pass = passwordText.text! Utils.showActivityIndicator(view, activityIndicator: activityIndicator) OTMClient.sharedInstance().authenticateWithUdacity(email, password: pass) { (success, error) in Utils.GlobalMainQueue.async { if success { self.openOnTheMap() Utils.hideActivityIndicator(self.view, activityIndicator: self.activityIndicator) } else { let userInfo = error!.userInfo[NSLocalizedDescriptionKey] as! String switch userInfo { case "400", "401", "403": Utils.showAlert(self, alertMessage: "Login failed. Wrong username or password.", completion: nil) case String(NSURLErrorTimedOut): Utils.showAlert(self, alertMessage: OTMClient.ErrorMessage.NetworkTimeout, completion: nil) default: Utils.showAlert(self, alertMessage: userInfo, completion: nil) } Utils.hideActivityIndicator(self.view, activityIndicator: self.activityIndicator) } } } } @IBAction func loginWithFacebook(_ sender: AnyObject) { // The login is handeled by the FB framework (see loginButton(...)), this action is only called to show the activity indicator Utils.showActivityIndicator(view, activityIndicator: activityIndicator) } @IBAction func signUp(_ sender: AnyObject) { if let requestUrl = signInURL { UIApplication.shared.openURL(requestUrl) } } fileprivate func openOnTheMap() { let tabViewController = self.storyboard!.instantiateViewController(withIdentifier: "navigationController") present(tabViewController, animated: true, completion: nil) } //# MARK: - Initialization fileprivate func initializeTextfields() { let textAttributes = [ NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 20) ] let emailPaddingView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: self.emailText.frame.height)) let passwordPaddingView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: self.passwordText.frame.height)) emailText.leftView = emailPaddingView emailText.leftViewMode = UITextFieldViewMode.always passwordText.leftView = passwordPaddingView passwordText.leftViewMode = UITextFieldViewMode.always emailText.defaultTextAttributes = textAttributes passwordText.defaultTextAttributes = textAttributes emailText.delegate = self passwordText.delegate = self } fileprivate func initializeFacebook() { loginFacebookButton.delegate = self loginFacebookButton.loginBehavior = .native if let cachedToken = FBSDKAccessToken.current() { Utils.showActivityIndicator(view, activityIndicator: activityIndicator) OTMClient.sharedInstance().authenticateWithFacebook(cachedToken.tokenString) { (success, bool) in if success { self.openOnTheMap() } else { OTMClient.sharedInstance().logoutFromFacebook() } Utils.hideActivityIndicator(self.view, activityIndicator: self.activityIndicator) } } } //# MARK: UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { if (textField == passwordText) { textField.resignFirstResponder() login("return tapped :)" as AnyObject) } return true } func textFieldDidBeginEditing(_ textField: UITextField) { // clear textfield only, if initial text 'Email' is shown if (textField == emailText) { if textField.text == "Email" { textField.text = "" } } } //# MARK: - FBSDKLoginButtonDelegate func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { if let error = error { let userInfo = error.localizedDescription Utils.showAlert(self, alertMessage: userInfo, completion: nil) Utils.hideActivityIndicator(view, activityIndicator: activityIndicator) } else { if let fbAccessToken = FBSDKAccessToken.current() { OTMClient.sharedInstance().authenticateWithFacebook(fbAccessToken.tokenString) { (success, error) in if success { self.openOnTheMap() } else { let userInfo = error!.userInfo[NSLocalizedDescriptionKey] as! String Utils.showAlert(self, alertMessage: userInfo, completion: nil) } Utils.hideActivityIndicator(self.view, activityIndicator: self.activityIndicator) } } else { //User did not login Utils.hideActivityIndicator(view, activityIndicator: activityIndicator) } } } func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) { // This function will usually never be called. let loginManager: FBSDKLoginManager = FBSDKLoginManager() loginManager.logOut() Utils.hideActivityIndicator(view, activityIndicator: activityIndicator) } }
mit
d804ef90642ff67fd963e90c6b00952c
36.25641
134
0.595595
6.054167
false
false
false
false
gouyz/GYZBaking
baking/Classes/Home/Controller/GYZContractUsVC.swift
1
12031
// // GYZContractUsVC.swift // baking // 联系我们 // Created by gouyz on 2017/5/5. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit import MBProgressHUD class GYZContractUsVC: GYZBaseVC,UITextViewDelegate { let notePlaceHolder: String = "请输入备注" var noteTxt: String = "" /// 联系类型 var contractTypeList: [GYZContractTypeModel] = [GYZContractTypeModel]() var typeNameList: [String] = [String]() var selectTypeId: String = "" override func viewDidLoad() { super.viewDidLoad() self.title = "联系我们" setupUI() requestType() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupUI(){ let viewBg1: UIView = UIView() viewBg1.backgroundColor = kWhiteColor view.addSubview(viewBg1) let nameLab: UILabel = UILabel() nameLab.text = "姓名:" nameLab.textColor = kBlackFontColor nameLab.font = k15Font viewBg1.addSubview(nameLab) viewBg1.addSubview(nameFiled) let line1: UIView = UIView() line1.backgroundColor = kGrayLineColor viewBg1.addSubview(line1) let phoneLab: UILabel = UILabel() phoneLab.text = "电话:" phoneLab.textColor = kBlackFontColor phoneLab.font = k15Font viewBg1.addSubview(phoneLab) viewBg1.addSubview(phoneFiled) let line2: UIView = UIView() line2.backgroundColor = kGrayLineColor viewBg1.addSubview(line2) let addressLab: UILabel = UILabel() addressLab.text = "地址:" addressLab.textColor = kBlackFontColor addressLab.font = k15Font viewBg1.addSubview(addressLab) viewBg1.addSubview(addressFiled) let line3: UIView = UIView() line3.backgroundColor = kGrayLineColor viewBg1.addSubview(line3) viewBg1.addSubview(typeLab) viewBg1.addSubview(selectTypeLab) viewBg1.addSubview(rightIconView) let viewBg2: UIView = UIView() viewBg2.backgroundColor = kWhiteColor view.addSubview(viewBg2) viewBg2.addSubview(desLab) viewBg2.addSubview(noteTxtView) noteTxtView.delegate = self view.addSubview(submitBtn) viewBg1.snp.makeConstraints { (make) in make.top.equalTo(kMargin) make.left.right.equalTo(view) make.height.equalTo(kTitleHeight*4+klineWidth*3) } nameLab.snp.makeConstraints { (make) in make.left.equalTo(viewBg1).offset(kMargin) make.top.equalTo(viewBg1) make.size.equalTo(CGSize.init(width: 60, height: kTitleHeight)) } nameFiled.snp.makeConstraints { (make) in make.left.equalTo(nameLab.snp.right) make.top.height.equalTo(nameLab) make.right.equalTo(viewBg1).offset(-kMargin) } line1.snp.makeConstraints { (make) in make.left.right.equalTo(viewBg1) make.top.equalTo(nameLab.snp.bottom) make.height.equalTo(klineWidth) } phoneLab.snp.makeConstraints { (make) in make.left.size.equalTo(nameLab) make.top.equalTo(line1.snp.bottom) } phoneFiled.snp.makeConstraints { (make) in make.left.size.equalTo(nameFiled) make.top.equalTo(phoneLab) } line2.snp.makeConstraints { (make) in make.left.right.height.equalTo(line1) make.top.equalTo(phoneLab.snp.bottom) } addressLab.snp.makeConstraints { (make) in make.left.size.equalTo(nameLab) make.top.equalTo(line2.snp.bottom) } addressFiled.snp.makeConstraints { (make) in make.left.size.equalTo(nameFiled) make.top.equalTo(addressLab) } line3.snp.makeConstraints { (make) in make.left.right.height.equalTo(line1) make.top.equalTo(addressLab.snp.bottom) } typeLab.snp.makeConstraints { (make) in make.left.size.equalTo(nameLab) make.top.equalTo(line3.snp.bottom) } selectTypeLab.snp.makeConstraints { (make) in make.left.equalTo(typeLab.snp.right) make.right.equalTo(rightIconView.snp.left) make.top.height.equalTo(typeLab) } rightIconView.snp.makeConstraints { (make) in make.right.equalTo(nameFiled) make.bottom.equalTo(viewBg1).offset(-12) make.size.equalTo(CGSize.init(width: 20, height: 20)) } viewBg2.snp.makeConstraints { (make) in make.left.right.equalTo(viewBg1) make.top.equalTo(viewBg1.snp.bottom).offset(kMargin) make.height.equalTo(80) } desLab.snp.makeConstraints { (make) in make.left.equalTo(viewBg2).offset(kMargin) make.top.equalTo(viewBg2) make.width.equalTo(50) make.height.equalTo(30) } noteTxtView.snp.makeConstraints { (make) in make.left.equalTo(desLab.snp.right) make.top.equalTo(desLab) make.height.equalTo(viewBg2) make.right.equalTo(viewBg2).offset(-kMargin) } submitBtn.snp.makeConstraints { (make) in make.left.equalTo(kMargin) make.right.equalTo(-kMargin) make.top.equalTo(viewBg2.snp.bottom).offset(30) make.height.equalTo(kTitleHeight) } } /// 姓名输入框 lazy var nameFiled : UITextField = { let textFiled = UITextField() textFiled.font = k15Font textFiled.textColor = kBlackFontColor textFiled.clearButtonMode = .whileEditing textFiled.placeholder = "请输入姓名" return textFiled }() /// 手机号输入框 lazy var phoneFiled : UITextField = { let textFiled = UITextField() textFiled.font = k15Font textFiled.textColor = kBlackFontColor textFiled.placeholder = "请输入手机号" textFiled.keyboardType = .namePhonePad return textFiled }() /// 地址输入框 lazy var addressFiled : UITextField = { let textFiled = UITextField() textFiled.font = k15Font textFiled.textColor = kBlackFontColor textFiled.placeholder = "请输入地址" return textFiled }() /// lazy var typeLab : UILabel = { let lab = UILabel() lab.font = k15Font lab.textColor = kBlackFontColor lab.text = "联系类别" return lab }() lazy var selectTypeLab : UILabel = { let lab = UILabel() lab.font = k15Font lab.textColor = kGaryFontColor lab.textAlignment = .right lab.text = "联系类别" lab.addOnClickListener(target: self, action: #selector(clickSelectType)) return lab }() /// 右侧箭头图标 fileprivate lazy var rightIconView: UIImageView = UIImageView.init(image: UIImage.init(named: "icon_right_gray")) // 描述 lazy var desLab : UILabel = { let lab = UILabel() lab.font = k15Font lab.textColor = kBlackFontColor lab.text = "备注" return lab }() /// 备注 lazy var noteTxtView : UITextView = { let txtView = UITextView() txtView.textColor = kGaryFontColor txtView.font = k15Font txtView.text = "请输入备注" return txtView }() /// 提交 lazy var submitBtn : UIButton = { let btn = UIButton.init(type: .custom) btn.backgroundColor = kYellowFontColor btn.titleLabel?.font = k15Font btn.setTitleColor(kWhiteColor, for: .normal) btn.cornerRadius = kCornerRadius btn.setTitle("提交", for: .normal) btn.addTarget(self, action: #selector(clickSubmitBtn), for: .touchUpInside) return btn }() /// 提交 func clickSubmitBtn(){ if (nameFiled.text?.isEmpty)! { MBProgressHUD.showAutoDismissHUD(message: "请输入姓名") return } if (phoneFiled.text?.isEmpty)! { MBProgressHUD.showAutoDismissHUD(message: "请输入电话") return } if (addressFiled.text?.isEmpty)! { MBProgressHUD.showAutoDismissHUD(message: "请输入地址") return } if selectTypeId.isEmpty { MBProgressHUD.showAutoDismissHUD(message: "请选择联系类别") return } requestSubmit() } /// 提交联系类型 func requestSubmit(){ weak var weakSelf = self createHUD(message: "加载中...") GYZNetWork.requestNetwork("Index/addContact",parameters: ["name":nameFiled.text!,"tel":phoneFiled.text!,"address": addressFiled.text!,"contact_type":selectTypeId,"message": noteTxt], success: { (response) in weakSelf?.hud?.hide(animated: true) // GYZLog(response) if response["status"].intValue == kQuestSuccessTag{//请求成功 _ = weakSelf?.navigationController?.popViewController(animated: true) } MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue) }, failture: { (error) in weakSelf?.hud?.hide(animated: true) GYZLog(error) }) } ///选择联系类型 func clickSelectType(){ weak var weakSelf = self GYZAlertViewTools.alertViewTools.showSheet(title: "选择联系类型", message: nil, cancleTitle: "取消", titleArray: typeNameList, viewController: self) { (index) in if index != cancelIndex{ let item = weakSelf?.contractTypeList[index] weakSelf?.selectTypeLab.text = item?.type_name weakSelf?.selectTypeId = (item?.id)! } } } /// 获取联系类型 func requestType(){ weak var weakSelf = self createHUD(message: "加载中...") GYZNetWork.requestNetwork("Index/contactType", success: { (response) in weakSelf?.hud?.hide(animated: true) // GYZLog(response) if response["status"].intValue == kQuestSuccessTag{//请求成功 let data = response["result"] guard let info = data["info"].array else { return } for item in info{ guard let itemInfo = item.dictionaryObject else { return } let model = GYZContractTypeModel.init(dict: itemInfo) weakSelf?.typeNameList.append(model.type_name!) weakSelf?.contractTypeList.append(model) } }else{ MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue) } }, failture: { (error) in weakSelf?.hud?.hide(animated: true) GYZLog(error) }) } ///MARK UITextViewDelegate func textViewDidBeginEditing(_ textView: UITextView) { let text = textView.text if text == notePlaceHolder { textView.text = "" } } func textViewDidChange(_ textView: UITextView) { let text : String = textView.text if text.isEmpty { textView.text = notePlaceHolder }else{ noteTxt = text } } }
mit
952f2a45bd0ba02ab48de0e0faccd1ac
30.777778
215
0.568139
4.666136
false
false
false
false
andr3a88/ASProgressHud
Pod/Classes/ASProgressHud.swift
1
13028
// // ASProgress.swift // Pods // // Created by Andrea Stevanato on 17/02/16. // // /** * Specify the property for the Hud. */ public struct HudProperty { /// The images predix name (eg. For a image with format "my_loader_XX.png" with NN from 0 to 20 the predix name is "my:loader") public let prefixName: String /// The number of images used to animate the loader let frameNumber: Int /// The size for the loader. Defaut value 60 px let size: CGFloat /// The animation duration for a single cycles. Default value 1.0 second let animationDuration: TimeInterval /// An optional background color. The defuault value is clear color let backgroundColor: UIColor? fileprivate var mainBundle: Bool = false /** Specify the property for the Hud - parameter prefixName: The images predix name (eg. For a image with format "my_loader_XX.png" with NN from 0 to 20 the predix name is "my:loader") - parameter frameNumber: The number of images used to animate the loader - parameter size: The size for the loader. Defaut value 60 px - parameter animationDuration: The animation duration for a single cycles. Default value 1.0 second - parameter backgroundColor: An optional background color. The defuault value is clear color - returns: The property struct */ public init(prefixName: String, frameNumber: Int, size: CGFloat = 60, animationDuration: TimeInterval = 1.0, backgroundColor: UIColor? = UIColor.clear) { self.prefixName = prefixName self.frameNumber = frameNumber self.size = size self.animationDuration = animationDuration self.backgroundColor = backgroundColor } } /// A set of custom Hud public enum HudType: Int { case `default`, flag, google var properties: HudProperty { switch self { case .default: return HudProperty(prefixName: "default", frameNumber: 18) case .flag: return HudProperty(prefixName: "flag", frameNumber: 20) case .google: return HudProperty(prefixName: "google", frameNumber: 30) } } } /** * ASProgressHud is UIView subclass */ open class ASProgressHud: UIView { fileprivate var useAnimation = true fileprivate var showStarted: Date? fileprivate var hudImageView: UIImageView? var removeFromSuperViewOnHide: Bool? = false // MARK: - Init public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** Init with Progress Hud Type :param: frame frame :param: type Progress Hud Type :returns: ASProgressHud istance */ init(frame: CGRect, type: HudType) { super.init(frame: frame) let hudProperty = type.properties self.initializeWithHudProperty(hudProperty) self.customTypeBasedConfiguration(type) self.addSubview(self.hudImageView!) } /** Init with custom loader :param: frame Frame :param: hudProperty Hud property :returns: ASProgressHud istance */ init(frame: CGRect, hudProperty: HudProperty) { super.init(frame: frame) self.initializeWithHudProperty(hudProperty) self.addSubview(self.hudImageView!) } fileprivate func initializeWithHudProperty(_ hudProperty: HudProperty) { self.removeFromSuperViewOnHide = true self.backgroundColor = UIColor.black.withAlphaComponent(0.2) self.isOpaque = false self.alpha = 0.0 self.contentMode = UIView.ContentMode.center self.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin] // Configure HudImageView self.hudImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: hudProperty.size, height: hudProperty.size)) self.hudImageView?.center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2) self.hudImageView?.contentMode = UIView.ContentMode.scaleAspectFit self.hudImageView?.backgroundColor = hudProperty.backgroundColor // Load images let imagesArray = self.loadImages(hudProperty) // Animation configuration self.hudImageView?.animationImages = imagesArray self.hudImageView?.animationDuration = hudProperty.animationDuration self.hudImageView?.animationRepeatCount = 0 self.hudImageView?.clipsToBounds = true self.hudImageView?.layer.cornerRadius = 10.0 } fileprivate func customTypeBasedConfiguration(_ type: HudType) { switch type { case .default: // Add a black shadow with radius offset and opacity self.hudImageView?.layer.shadowColor = UIColor.black.cgColor self.hudImageView?.layer.shadowOpacity = 0.4 self.hudImageView?.layer.shadowRadius = 3.0 self.hudImageView?.layer.shadowOffset = CGSize(width: 0, height: 3) self.hudImageView?.clipsToBounds = false default: break } } // MARK: - Utils fileprivate func loadImages(_ property: HudProperty) -> [UIImage] { // Load images var imageArray: [UIImage] = [] for c in 0 ..< property.frameNumber { guard let image = UIImage(named: String(format: "%@_%02d.png", property.prefixName, c), in: property.mainBundle ? nil : self.podBundle(), compatibleWith: nil) else { assertionFailure("Cannot load the image") return [] } imageArray.append(image) } return imageArray } fileprivate func podBundle() -> Bundle { let podBundle = Bundle(for: self.classForCoder) if let bundleURL = podBundle.url(forResource: "Resources", withExtension: "bundle") { if let bundle = Bundle(url: bundleURL) { return bundle } else { assertionFailure("Could not load the bundle") } } else { assertionFailure("Could not create a path to the bundle") } return podBundle } // MARK: - Class methods /** Creates a new HUD, adds it to provided view and shows it. The counterpart to this method is hideHUDForView:animated:. :note: This method sets `removeFromSuperViewOnHide`. The HUD will automatically be removed from the view hierarchy when hidden. :param: view The view that the HUD will be added to :param: animated If set to YES the HUD will appear using the current animationType. If set to NO the HUD will not use animations while appearing. :param: type The type for the HUD :returns: A reference to the created HUD. :see: hideHUDForView:animated: :see: animationType */ @discardableResult public static func showHUDAddedTo(_ view: UIView, animated: Bool, type: HudType) -> ASProgressHud { let hud = ASProgressHud(frame: view.bounds, type: type) view.addSubview(hud) hud.show(animated) return hud } /** Creates a new HUD, adds it to provided view and shows it. The counterpart to this method is hideHUDForView:animated:. :note: This method sets `removeFromSuperViewOnHide`. The HUD will automatically be removed from the view hierarchy when hidden. :param: view The view that the HUD will be added to :param: animated If set to YES the HUD will appear using the current animationType. If set to NO the HUD will not use animations while appearing. :param: type The type for the HUD :returns: A reference to the created HUD. :see: hideHUDForView:animated: :see: animationType */ @discardableResult public static func showCustomHUDAddedTo(_ view: UIView, animated: Bool, property: HudProperty) -> ASProgressHud { var hudProperty = property hudProperty.mainBundle = true let hud = ASProgressHud(frame: view.bounds, hudProperty: hudProperty) view.addSubview(hud) hud.show(animated) return hud } /** Finds the top-most HUD subview and hides it. The counterpart to this method is showHUDAddedTo:animated:. :note: This method sets `removeFromSuperViewOnHide`. The HUD will automatically be removed from the view hierarchy when hidden. :param: view The view that is going to be searched for a HUD subview. :param: animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use animations while disappearing. :returns: YES if a HUD was found and removed, NO otherwise. :see: showHUDAddedTo:animated: :see: animationType */ @discardableResult public static func hideHUDForView(_ view: UIView, animated: Bool) -> Bool { let hud = self.HUDForView(view) if hud != nil { hud?.removeFromSuperViewOnHide = true hud?.hide(animated) return true } return false } /** Finds all the HUD subviews and hides them. :param: view The view that is going to be searched for HUD subviews. :param: animated If set to YES the HUDs will disappear using the current animationType. If set to NO the HUDs will not use animations while disappearing. :returns: The number of HUDs found and removed. :see: hideHUDForView:animated: :see: animationType */ public static func hideAllHUDsForView(_ view: UIView, animated: Bool) -> NSInteger { let huds = ASProgressHud.allHUDsForView(view) for hud in huds { hud.removeFromSuperViewOnHide = true hud.hide(animated) } return huds.count } fileprivate static func HUDForView(_ view: UIView) -> ASProgressHud? { let subviewsEnum = view.subviews as NSArray let array = subviewsEnum.reverseObjectEnumerator() for subView in array { if (subView as AnyObject).isKind(of: self) { return subView as? ASProgressHud } } return nil } fileprivate static func allHUDsForView(_ view: UIView) -> [ASProgressHud] { var huds: [ASProgressHud]? = [] let subviews = view.subviews as Array for aView in subviews { if aView.isKind(of: self) { huds?.append(aView as! ASProgressHud) } } return huds! } // MARK: - Show & hide fileprivate func showUsingAnimation(_ animated: Bool) { // Cancel any scheduled hideDelayed: calls NSObject.cancelPreviousPerformRequests(withTarget: self) self.setNeedsDisplay() self.hudImageView?.startAnimating() self.showStarted = Date() // Fade in if animated == true { UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(0.30) self.alpha = 1.0 UIView.commitAnimations() } else { self.alpha = 1.0 } } fileprivate func hideUsingAnimation(_ animated: Bool) { // Fade out if animated == true && showStarted != nil { UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(0.30) UIView.setAnimationDelegate(self) UIView.setAnimationDidStop(#selector(ASProgressHud.animationFinished)) // 0.02 prevents the hud from passing through touches during the animation the hud will get completely hidden // in the done method self.alpha = 0.02 UIView.commitAnimations() } else { self.alpha = 0.0 self.done() } self.showStarted = nil } fileprivate func show(_ animated: Bool) { assert(Thread.isMainThread, "ASProgressHud needs to be accessed on the main thread.") self.useAnimation = animated self.showUsingAnimation(useAnimation) } fileprivate func hide(_ animated: Bool) { assert(Thread.isMainThread, "ASProgressHud needs to be accessed on the main thread.") self.useAnimation = animated self.hideUsingAnimation(useAnimation) } // MARK: - Internal show & hide operations @objc func animationFinished() { self.done() } fileprivate func done() { NSObject.cancelPreviousPerformRequests(withTarget: self) self.alpha = 0.0 self.hudImageView?.stopAnimating() if removeFromSuperViewOnHide == true { self.removeFromSuperview() } } }
mit
a60542549c00aaad354addee8727881b
33.834225
177
0.625422
5.039845
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Tools/SettingsCommon.swift
3
3393
import UIKit import WordPressKit import CocoaLumberjack protocol SettingsController: ImmuTableController {} // MARK: - Actions extension SettingsController { func insideNavigationController(_ generator: @escaping ImmuTableRowControllerGenerator) -> ImmuTableRowControllerGenerator { return { row in let controller = generator(row) let navigation = UINavigationController(rootViewController: controller) navigation.modalPresentationStyle = .formSheet return navigation } } func editText(_ changeType: @escaping AccountSettingsChangeWithString, hint: String? = nil, service: AccountSettingsService) -> (ImmuTableRow) -> SettingsTextViewController { return { row in let editableRow = row as! EditableTextRow return self.controllerForEditableText(editableRow, changeType: changeType, hint: hint, service: service) } } func editMultilineText(_ changeType: @escaping AccountSettingsChangeWithString, hint: String? = nil, service: AccountSettingsService) -> (ImmuTableRow) -> SettingsMultiTextViewController { return { row in let editableRow = row as! EditableTextRow return self.controllerForEditableMultilineText(editableRow, changeType: changeType, hint: hint, service: service) } } func editEmailAddress(_ changeType: @escaping AccountSettingsChangeWithString, hint: String? = nil, service: AccountSettingsService) -> (ImmuTableRow) -> SettingsTextViewController { return { row in let editableRow = row as! EditableTextRow let settingsViewController = self.controllerForEditableText(editableRow, changeType: changeType, hint: hint, service: service) settingsViewController.mode = .email return settingsViewController } } func controllerForEditableText(_ row: EditableTextRow, changeType: @escaping AccountSettingsChangeWithString, hint: String? = nil, service: AccountSettingsService) -> SettingsTextViewController { let title = row.title let value = row.value let controller = SettingsTextViewController(text: value, placeholder: "\(title)...", hint: hint) controller.title = title controller.onValueChanged = { value in let change = changeType(value) service.saveChange(change) DDLogDebug("\(title) changed: \(value)") } return controller } func controllerForEditableMultilineText(_ row: EditableTextRow, changeType: @escaping AccountSettingsChangeWithString, hint: String? = nil, service: AccountSettingsService) -> SettingsMultiTextViewController { let title = row.title let value = row.value let controller = SettingsMultiTextViewController(text: value, placeholder: "\(title)...", hint: hint, isPassword: false) controller.title = title controller.onValueChanged = { value in let change = changeType(value) service.saveChange(change) DDLogDebug("\(title) changed: \(value)") } return controller } }
gpl-2.0
c0dff0bbbf874d7eca876a5e2b9a1aba
39.879518
192
0.642794
6.180328
false
false
false
false
tjw/swift
stdlib/public/core/Availability.swift
2
2831
//===----------------------------------------------------------------------===// // // 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 /// Returns 1 if the running OS version is greater than or equal to /// major.minor.patchVersion and 0 otherwise. /// /// This is a magic entry point known to the compiler. It is called in /// generated code for API availability checking. @inlinable // FIXME(sil-serialize-all) @_semantics("availability.osversion") public func _stdlib_isOSVersionAtLeast( _ major: Builtin.Word, _ minor: Builtin.Word, _ patch: Builtin.Word ) -> Builtin.Int1 { #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) let runningVersion = _swift_stdlib_operatingSystemVersion() let queryVersion = _SwiftNSOperatingSystemVersion( majorVersion: Int(major), minorVersion: Int(minor), patchVersion: Int(patch) ) let result = runningVersion >= queryVersion return result._value #else // FIXME: As yet, there is no obvious versioning standard for platforms other // than Darwin-based OSes, so we just assume false for now. // rdar://problem/18881232 return false._value #endif } extension _SwiftNSOperatingSystemVersion : Comparable { @inlinable // FIXME(sil-serialize-all) public static func == ( lhs: _SwiftNSOperatingSystemVersion, rhs: _SwiftNSOperatingSystemVersion ) -> Bool { return lhs.majorVersion == rhs.majorVersion && lhs.minorVersion == rhs.minorVersion && lhs.patchVersion == rhs.patchVersion } /// Lexicographic comparison of version components. @inlinable // FIXME(sil-serialize-all) public static func < ( lhs: _SwiftNSOperatingSystemVersion, rhs: _SwiftNSOperatingSystemVersion ) -> Bool { guard lhs.majorVersion == rhs.majorVersion else { return lhs.majorVersion < rhs.majorVersion } guard lhs.minorVersion == rhs.minorVersion else { return lhs.minorVersion < rhs.minorVersion } return lhs.patchVersion < rhs.patchVersion } @inlinable // FIXME(sil-serialize-all) public static func >= ( lhs: _SwiftNSOperatingSystemVersion, rhs: _SwiftNSOperatingSystemVersion ) -> Bool { guard lhs.majorVersion == rhs.majorVersion else { return lhs.majorVersion >= rhs.majorVersion } guard lhs.minorVersion == rhs.minorVersion else { return lhs.minorVersion >= rhs.minorVersion } return lhs.patchVersion >= rhs.patchVersion } }
apache-2.0
8bf08bbe03cf52ec7af1ae0ed5413b37
30.455556
80
0.668315
4.687086
false
false
false
false
eure/ReceptionApp
iOS/ReceptionApp/Screens/ContactToViewController.swift
1
8440
// // ContactToViewController.swift // ReceptionApp // // Created by Hiroshi Kimura on 8/23/15. // Copyright © 2016 eureka, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import CoreStore import RxCocoa import RxSwift // MARK: - ContactToViewController final class ContactToViewController: BaseTransactionViewController, UITableViewDelegate, UITableViewDataSource { // MARK: Internal @IBOutlet private(set) dynamic weak var inputFieldView: UIView! @IBOutlet private(set) dynamic weak var tableView: UITableView! // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = Configuration.Color.backgroundColor self.inputFieldView.backgroundColor = Configuration.Color.backgroundColor self.iconImageView.tintColor = Configuration.Color.imageTintColor self.tableViewContainerView.backgroundColor = UIColor.clearColor() self.tableView.rowHeight = 116 self.tableView.backgroundColor = UIColor.clearColor() self.tableView.separatorColor = Configuration.Color.separatorColor self.tableView.tableFooterView = UIView() self.tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0) self.messageLabel.textColor = Configuration.Color.textColor self.messageLabel.font = Configuration.Font.baseBoldFont(size: 18) self.messageLabel.text = "ContactToViewController.label.charge".l10n self.textField.attributedPlaceholder = NSAttributedString.baseBoldAttributedString( "CONTACT TO...", color: Configuration.Color.placeholderColor, size: 55 ) self.textField.tintColor = Configuration.Color.textColor self.textField .rx_text .subscribeNext { [weak self] text in guard let `self` = self else { return } self.results = self.usersListMonitor.objectsInAllSections().filter { $0.matches(text) } } .addDisposableTo(self.disposeBag) self.textField .rx_text .filter { $0.characters.count > 0 } .subscribeNext { [weak self] _ in guard let `self` = self where !(self.textFieldTop.constant == 30) else { return } UIView.animateWithDuration( 0.3, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in self.textFieldTop.constant = 30 self.messageLabel.alpha = 0 self.view.layoutIfNeeded() }, completion: { _ in } ) } .addDisposableTo(self.disposeBag) self.textField .rx_text .filter { $0.characters.count == 0 } .subscribeNext { [weak self] _ in guard let `self` = self where !(self.textFieldTop.constant == 100) else { return } UIView.animateWithDuration( 0.3, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in self.textFieldTop.constant = 200 self.messageLabel.alpha = 1 self.view.layoutIfNeeded() }, completion: { _ in } ) } .addDisposableTo(self.disposeBag) self.tableViewMask.colors = [ UIColor.clearColor().CGColor, Configuration.Color.backgroundColor.CGColor, Configuration.Color.backgroundColor.CGColor, UIColor.clearColor().CGColor, ] self.tableViewMask.locations = [ 0, 0.02, 0.98, 1 ] self.tableViewMask.startPoint = CGPoint(x: 0.5, y: 0) self.tableViewMask.endPoint = CGPoint(x: 0.5, y: 1) self.tableViewContainerView.layer.mask = tableViewMask } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.textField.becomeFirstResponder() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if let indexPath = self.tableView.indexPathForSelectedRow { self.tableView.deselectRowAtIndexPath(indexPath, animated: true) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.tableViewMask.frame = self.tableViewContainerView.bounds } // MARK: UITableViewDataSource @objc dynamic func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } @objc dynamic func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.results.count } @objc dynamic func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithClass(ContactToSuggestCell.self, forIndexPath: indexPath) cell.user = self.results[indexPath.row] return cell } // MARK: UITableViewDelegate @objc dynamic func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let user = self.results[indexPath.row] let controller = YourNameViewController.viewControllerFromStoryboard() controller.contactType = .Appointment let transaction = AppointmentTransaction(user: user) controller.transaction = transaction self.navigationController?.pushViewController(controller, animated: true) } @objc dynamic func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.separatorInset = UIEdgeInsets(top: 0, left: 90, bottom: 0, right: 0) } // MARK: Private @IBOutlet private dynamic weak var tableViewContainerView: UIView! @IBOutlet private dynamic weak var textFieldTop: NSLayoutConstraint! @IBOutlet private dynamic weak var iconImageView: UIImageView! @IBOutlet private dynamic weak var textField: UITextField! @IBOutlet private dynamic weak var messageLabel: UILabel! private var results: [User] = [] { didSet { self.tableView?.reloadData() } } private let tableViewMask = CAGradientLayer() private let disposeBag = DisposeBag() private let usersListMonitor = CoreStore.monitorList( From(User), Where("removed == false"), OrderBy(.Ascending("id")) ) }
mit
6d2ef40c61de4af5a0efd7d16cec797b
33.165992
139
0.594146
5.622252
false
false
false
false
LawrenceHan/iOS-project-playground
Scattered/Scattered/ViewController.swift
1
5873
// // ViewController.swift // Scattered // // Created by Hanguang on 1/3/16. // Copyright © 2016 Hanguang. All rights reserved. // import Cocoa class ViewController: NSViewController { let processingQueue: NSOperationQueue = { let result = NSOperationQueue() result.maxConcurrentOperationCount = 4 return result }() var textLayer: CATextLayer! var text: String? { didSet { let font = NSFont.systemFontOfSize(textLayer.fontSize) let attributes = [NSFontAttributeName : font] var size = text?.sizeWithAttributes(attributes) ?? CGSize.zero // Ensure that the size is in whole numbers: size.width = ceil(size.width) size.height = ceil(size.height) textLayer.bounds = CGRect(origin: CGPoint.zero, size: size) textLayer.superlayer!.bounds = CGRect(x: 0, y: 0, width: size.width + 16, height: size.height + 20) textLayer.string = text } } func thumbImageFromImage(image: NSImage) -> NSImage { let targetHeight: CGFloat = 200.0 let imageSize = image.size let smallerSize = NSSize(width: targetHeight * imageSize.width / imageSize.height, height: targetHeight) let smallerImage = NSImage(size: smallerSize, flipped: false) { (rect) -> Bool in image.drawInRect(rect) return true } return smallerImage } func addImagesFromFolderURL(folderURL: NSURL) { processingQueue.addOperationWithBlock { let t0 = NSDate.timeIntervalSinceReferenceDate() let fileManager = NSFileManager() let directoryEnumerator = fileManager.enumeratorAtURL(folderURL, includingPropertiesForKeys: nil, options: [], errorHandler: nil)! while let url = directoryEnumerator.nextObject() as? NSURL { // Skip directories: var isDirectoryValue: AnyObject? do { try url.getResourceValue(&isDirectoryValue, forKey: NSURLIsDirectoryKey) } catch { print("error checking whether URL is directory: \(error)") continue } self.processingQueue.addOperationWithBlock { guard let isDirectory = isDirectoryValue as? Bool where isDirectory == false else { return } guard let image = NSImage(contentsOfURL: url) else { return } let thumbImage = self.thumbImageFromImage(image) NSOperationQueue.mainQueue().addOperationWithBlock { self.presentImage(thumbImage) let t1 = NSDate.timeIntervalSinceReferenceDate() let interval = t1 - t0 self.text = String(format: "%0.1fs", interval) } } } } } func presentImage(image: NSImage) { let superLayerBounds = view.layer!.bounds let center = CGPoint(x: superLayerBounds.midX, y: superLayerBounds.midY) let imageBounds = CGRect(origin: CGPoint.zero, size: image.size) let randomPoint = CGPoint(x: CGFloat(arc4random_uniform(UInt32(superLayerBounds.maxX))), y: CGFloat(arc4random_uniform(UInt32(superLayerBounds.maxY)))) let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) let positionAnimation = CABasicAnimation() positionAnimation.fromValue = NSValue(point: center) positionAnimation.duration = 1.5 positionAnimation.timingFunction = timingFunction let boundsAnimation = CABasicAnimation() boundsAnimation.fromValue = NSValue(rect: CGRect.zero) boundsAnimation.duration = 1.5 boundsAnimation.timingFunction = timingFunction let layer = CALayer() layer.contents = image layer.actions = ["position" : positionAnimation, "bounds" : boundsAnimation] CATransaction.begin() view.layer!.addSublayer(layer) layer.position = randomPoint layer.bounds = imageBounds CATransaction.commit() } override func viewDidLoad() { super.viewDidLoad() // Set view to be layer-hosting: view.layer = CALayer() view.wantsLayer = true let textContainer = CALayer() textContainer.anchorPoint = CGPoint.zero textContainer.position = CGPointMake(10, 10) textContainer.zPosition = 100 textContainer.backgroundColor = NSColor.blackColor().CGColor textContainer.borderColor = NSColor.whiteColor().CGColor textContainer.borderWidth = 2 textContainer.cornerRadius = 15 textContainer.shadowOpacity = 0.5 view.layer!.addSublayer(textContainer) let textLayer = CATextLayer() textLayer.anchorPoint = CGPoint.zero textLayer.position = CGPointMake(10, 6) textLayer.zPosition = 100 textLayer.fontSize = 24 textLayer.foregroundColor = NSColor.whiteColor().CGColor self.textLayer = textLayer textContainer.addSublayer(textLayer) // Rely on text's didSet to update textLayer's bounds: text = "Loading" let url = NSURL(fileURLWithPath: "/Library/Desktop Pictures") addImagesFromFolderURL(url) } }
mit
11ad16d0a6e14675fa3283cefb580fed
35.246914
111
0.57408
5.808111
false
false
false
false
krzysztofzablocki/Sourcery
SourceryTests/Helpers/Builders.swift
1
3677
import Foundation import SourceryRuntime extension TypeName { static func buildArray(of elementType: TypeName, useGenericName: Bool = false) -> TypeName { let name = useGenericName ? "Array<\(elementType.asSource)>": "[\(elementType.asSource)]" let array = ArrayType(name: name, elementTypeName: elementType) return TypeName(name: array.name, array: array, generic: array.asGeneric) } static func buildSet(of elementType: TypeName) -> TypeName { let generic = GenericType(name: "Set", typeParameters: [.init(typeName: elementType)]) return TypeName(name: generic.asSource, generic: generic) } static func buildDictionary(key keyTypeName: TypeName, value valueTypeName: TypeName, useGenericName: Bool = false) -> TypeName { let name = useGenericName ? "Dictionary<\(keyTypeName.asSource), \(valueTypeName.asSource)>": "[\(keyTypeName.asSource): \(valueTypeName.asSource)]" let dictionary = DictionaryType(name: name, valueTypeName: valueTypeName, keyTypeName: keyTypeName) return TypeName(name: dictionary.name, dictionary: dictionary, generic: dictionary.asGeneric) } static func buildTuple(_ elements: TupleElement...) -> TypeName { let name = "(\(elements.enumerated().map { "\($1.name == "\($0)" ? $1.typeName.asSource : $1.asSource)" }.joined(separator: ", ")))" let tuple = TupleType(name: name, elements: elements) return TypeName(name: tuple.name, tuple: tuple) } static func buildTuple(_ elements: TypeName...) -> TypeName { let name = "(\(elements.map { "\($0.asSource)" }.joined(separator: ", ")))" let tuple = TupleType(name: name, elements: elements.enumerated().map { TupleElement(name: "\($0)", typeName: $1) }) return TypeName(name: name, tuple: tuple) } static func buildClosure(_ returnTypeName: TypeName, attributes: AttributeList = [:]) -> TypeName { let closure = ClosureType(name: "() -> \(returnTypeName)", parameters: [], returnTypeName: returnTypeName) return TypeName(name: closure.name, attributes: attributes, closure: closure) } static func buildClosure(_ parameters: ClosureParameter..., returnTypeName: TypeName) -> TypeName { let closure = ClosureType(name: "\(parameters.asSource) -> \(returnTypeName)", parameters: parameters, returnTypeName: returnTypeName) return TypeName(name: closure.name, closure: closure) } static func buildClosure(_ parameters: TypeName..., returnTypeName: TypeName) -> TypeName { let parameters = parameters.map({ ClosureParameter(typeName: $0) }) let closure = ClosureType(name: "\(parameters.asSource) -> \(returnTypeName)", parameters: parameters, returnTypeName: returnTypeName) return TypeName(name: closure.name, closure: closure) } var asOptional: TypeName { let type = self return TypeName(name: type.name, isOptional: true, isImplicitlyUnwrappedOptional: type.isImplicitlyUnwrappedOptional, tuple: type.tuple, array: type.array, dictionary: type.dictionary, closure: type.closure, generic: type.generic ) } static var Void: TypeName { TypeName(name: "Void") } static var `Any`: TypeName { TypeName(name: "Any") } static var Int: TypeName { TypeName(name: "Int") } static var String: TypeName { TypeName(name: "String") } static var Float: TypeName { TypeName(name: "Float") } }
mit
7cb4bc866f76b19542a301c2c2c5b11e
43.841463
156
0.639652
4.794003
false
false
false
false
plus44/hcr-2016
app/PiNAOqio/Camera/GLViewController.swift
1
1566
// // GLViewController.swift // Camera // // Created by Matteo Caldari on 28/01/15. // Copyright (c) 2015 Matteo Caldari. All rights reserved. // import UIKit import GLKit import CoreImage import OpenGLES class GLViewController: UIViewController { var cameraController:CameraController! fileprivate var glContext:EAGLContext? fileprivate var ciContext:CIContext? fileprivate var renderBuffer:GLuint = GLuint() fileprivate var glView:GLKView { get { return view as! GLKView } } override func viewDidLoad() { super.viewDidLoad() glContext = EAGLContext(api: .openGLES2) glView.context = glContext! // glView.drawableDepthFormat = .Format24 glView.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2)) if let window = glView.window { glView.frame = window.bounds } ciContext = CIContext(eaglContext: glContext!) cameraController = CameraController(previewType: .manual, delegate: self) } override func viewDidAppear(_ animated: Bool) { cameraController.startRunning() } } // MARK: CameraControllerDelegate extension GLViewController : CameraControllerDelegate { func cameraController(_ cameraController: CameraController, didDetectFaces faces: [(id: Int, frame: CGRect)]) { } func cameraController(_ cameraController: CameraController, didOutputImage image: CIImage) { if glContext != EAGLContext.current() { EAGLContext.setCurrent(glContext) } glView.bindDrawable() ciContext?.draw(image, in:image.extent, from: image.extent) glView.display() } }
apache-2.0
47e6a55998914de821538e304ac5f6e9
19.605263
112
0.732439
3.876238
false
false
false
false
Takanu/Pelican
Sources/Pelican/API/Types/Inline/InlineQueryResult/InlineResultContact.swift
1
1863
// // InlineResultContact.swift // Pelican // // Created by Takanu Kyriako on 20/12/2017. // import Foundation /** Represents a contact with a phone number. By default, this contact will be sent by the user. Alternatively, you can use the `content` property to send a message with the specified content instead of the file. */ public struct InlineResultContact: InlineResult { /// A metatype, used to Encode and Decode itself as part of the InlineResult protocol. public var metatype: InlineResultType = .contact /// Type of the result being given. public var type: String = "contact" /// Unique identifier for the result, 1-64 bytes. public var id: String /// Content of the message to be sent. public var content: InputMessageContent? /// Inline keyboard attached to the message public var markup: MarkupInline? /// Contact's phone number. public var phoneNumber: String /// Contact's first name. public var firstName: String /// Contact's last name. public var lastName: String? /// URL of the thumbnail to use for the result. public var thumbURL: String? /// Thumbnail width. public var thumbWidth: Int? /// Thumbnail height. public var thumbHeight: Int? /// Coding keys to map values when Encoding and Decoding. enum CodingKeys: String, CodingKey { case type case id case content = "input_message_content" case markup = "reply_markup" case phoneNumber = "phone_number" case firstName = "first_name" case lastName = "last_name" case thumbURL = "thumb_url" case thumbWidth = "thumb_width" case thumbHeight = "thumb_height" } init(id: String, phoneNumber: String, firstName: String, lastName: String?, content: InputMessageContent?) { self.id = id self.phoneNumber = phoneNumber self.firstName = firstName self.lastName = lastName self.content = content } }
mit
7579644bbe80fe007e16b23bb1966bfb
23.513158
167
0.714976
3.809816
false
false
false
false
courteouselk/Relations
Sources/KeyedWeak1toNRelationIndex.swift
1
936
// // KeyedWeak1toNRelationIndex.swift // Relations // // Created by Anton Bronnikov on 18/04/2017. // Copyright © 2017 Anton Bronnikov. All rights reserved. // /// Index used by `KeyedWeak1toNRelation` collection. public struct KeyedWeak1toNRelationIndex<UnarySide: AnyObject, NarySide: AnyObject, NarySideKey: Hashable> : Comparable { let index: DictionaryIndex<NarySideKey, WeakWrapper<KeyedWeakNto1Relation<NarySide, UnarySide, NarySideKey>>> init(_ index: DictionaryIndex<NarySideKey, WeakWrapper<KeyedWeakNto1Relation<NarySide, UnarySide, NarySideKey>>>) { self.index = index } // MARK: - Operators public static func == (lhs: KeyedWeak1toNRelationIndex, rhs: KeyedWeak1toNRelationIndex) -> Bool { return lhs.index == rhs.index } public static func < (lhs: KeyedWeak1toNRelationIndex, rhs: KeyedWeak1toNRelationIndex) -> Bool { return lhs.index < rhs.index } }
mit
c684cc254697843f93bb243e637fd39f
31.241379
121
0.724064
4.137168
false
false
false
false
BurlApps/SLPagingViewSwift
Demos/TinderLike/TinderLike/AppDelegate.swift
1
5121
// // AppDelegate.swift // TinderLike // // Created by Stefan Lage on 10/01/15. // Copyright (c) 2015 Stefan Lage. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var nav: UINavigationController? var controller: SLPagingViewSwift! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) let orange = UIColor(red: 255/255, green: 69.0/255, blue: 0.0/255, alpha: 1.0) let gray = UIColor(red: 0.84, green: 0.84, blue: 0.84, alpha: 1.0) let ctr1 = UIViewController() ctr1.title = "Ctr1" ctr1.view.backgroundColor = orange let ctr2 = UIViewController() ctr2.title = "Ctr2" ctr2.view.backgroundColor = UIColor.yellowColor() let ctr3 = UIViewController() ctr3.title = "Ctr3" ctr3.view.backgroundColor = gray var img1 = UIImage(named: "gear") img1 = img1?.imageWithRenderingMode(.AlwaysTemplate) var img2 = UIImage(named: "profile") img2 = img2?.imageWithRenderingMode(.AlwaysTemplate) var img3 = UIImage(named: "chat") img3 = img3?.imageWithRenderingMode(.AlwaysTemplate) let items = [UIImageView(image: img1), UIImageView(image: img2), UIImageView(image: img3)] let controllers = [ctr1, ctr2, ctr3] controller = SLPagingViewSwift(items: items, controllers: controllers, showPageControl: false) controller.pagingViewMoving = ({ subviews in if let imageViews = subviews as? [UIImageView] { for imgView in imageViews { var c = gray let originX = Double(imgView.frame.origin.x) if (originX > 45 && originX < 145) { c = self.gradient(originX, topX: 46, bottomX: 144, initC: orange, goal: gray) } else if (originX > 145 && originX < 245) { c = self.gradient(originX, topX: 146, bottomX: 244, initC: gray, goal: orange) } else if(originX == 145){ c = orange } imgView.tintColor = c } } }) self.nav = UINavigationController(rootViewController: self.controller) self.window?.rootViewController = self.nav self.window?.backgroundColor = UIColor.whiteColor() self.window?.makeKeyAndVisible() 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 throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func viewWithBackground(color: UIColor) -> UIView{ let v = UIView() v.backgroundColor = color return v } func gradient(percent: Double, topX: Double, bottomX: Double, initC: UIColor, goal: UIColor) -> UIColor{ let t = (percent - bottomX) / (topX - bottomX) let cgInit = CGColorGetComponents(initC.CGColor) let cgGoal = CGColorGetComponents(goal.CGColor) let r = cgInit[0] + CGFloat(t) * (cgGoal[0] - cgInit[0]) let g = cgInit[1] + CGFloat(t) * (cgGoal[1] - cgInit[1]) let b = cgInit[2] + CGFloat(t) * (cgGoal[2] - cgInit[2]) return UIColor(red: r, green: g, blue: b, alpha: 1.0) } }
mit
dcd06b53f21e1792b91230362e3d9b25
43.530435
285
0.634251
4.750464
false
false
false
false
mfk-ableton/MusicKit
MusicKit/MIDIMessage.swift
2
2337
// Copyright (c) 2015 Ben Guo. All rights reserved. import Foundation public protocol MIDIMessage { /// The message's channel var channel: UInt { get } /// Returns the MIDI packet data representation of this message func data() -> [UInt8] /// Returns a copy of this message on the given channel func copyOnChannel(channel: UInt) -> Self } public struct MIDINoteMessage: MIDIMessage { /// Note on: true, Note off: false public let on: Bool public let channel: UInt public let noteNumber: UInt public let velocity: UInt public init(on: Bool, channel: UInt = 0, noteNumber: UInt, velocity: UInt) { self.on = on self.channel = channel self.noteNumber = noteNumber self.velocity = velocity } public func data() -> [UInt8] { let messageType = self.on ? MKMIDIMessage.NoteOn.rawValue : MKMIDIMessage.NoteOff.rawValue let status = UInt8(messageType + UInt8(self.channel)) return [UInt8(status), UInt8(self.noteNumber), UInt8(self.velocity)] } public func copyOnChannel(channel: UInt) -> MIDINoteMessage { return MIDINoteMessage(on: on, channel: channel, noteNumber: noteNumber, velocity: velocity) } /// The message's pitch public var pitch: Pitch { return Pitch(midi: Float(noteNumber)) } /// Applies the given `Harmonizer` to the message. public func harmonize(harmonizer: Harmonizer) -> [MIDINoteMessage] { let ps = harmonizer(pitch) var messages = [MIDINoteMessage]() // TODO: add a PitchSet -> Array method so this can be mapped for p in ps { messages.append(MIDINoteMessage(on: self.on, channel: self.channel, noteNumber: UInt(p.midi), velocity: self.velocity)) } return messages } } extension MIDINoteMessage: CustomStringConvertible { public var description: String { let onString = on ? "On" : "Off" return "\(channel): Note \(onString): \(noteNumber) \(velocity)" } } extension MIDINoteMessage: Transposable { public func transpose(semitones: Float) -> MIDINoteMessage { return MIDINoteMessage(on: self.on, channel: self.channel, noteNumber: self.noteNumber + UInt(semitones), velocity: self.velocity) } }
mit
1410cb90535b684978dcab690b6c5f09
31.458333
100
0.646128
4.351955
false
false
false
false
petester42/RxSwift
RxSwift/Observers/TailRecursiveSink.swift
4
3043
// // TailRecursiveSink.swift // Rx // // Created by Krunoslav Zaher on 3/21/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation enum TailRecursiveSinkCommand { case MoveNext case Dispose } /// This class is usually used with `Generator` version of the operators. class TailRecursiveSink<S: SequenceType, O: ObserverType where S.Generator.Element: ObservableConvertibleType, S.Generator.Element.E == O.E> : Sink<O> , InvocableWithValueType { typealias Value = TailRecursiveSinkCommand typealias E = O.E var _generators:[S.Generator] = [] var _disposed = false var _subscription = SerialDisposable() // this is thread safe object var _gate = AsyncLock<InvocableScheduledItem<TailRecursiveSink<S, O>>>() override init(observer: O) { super.init(observer: observer) } func run(sources: S.Generator) -> Disposable { _generators.append(sources) schedule(.MoveNext) return _subscription } func invoke(command: TailRecursiveSinkCommand) { switch command { case .Dispose: disposeCommand() case .MoveNext: moveNextCommand() } } // simple implementation for now func schedule(command: TailRecursiveSinkCommand) { _gate.invoke(InvocableScheduledItem(invocable: self, state: command)) } func done() { forwardOn(.Completed) dispose() } func extract(observable: Observable<E>) -> S.Generator? { abstractMethod() } // should be done on gate locked private func moveNextCommand() { var next: Observable<E>? = nil repeat { if _generators.count == 0 { break } if _disposed { return } var e = _generators.last! let nextCandidate = e.next()?.asObservable() _generators.removeLast() _generators.append(e) if nextCandidate == nil { _generators.removeLast() continue; } let nextGenerator = extract(nextCandidate!) if let nextGenerator = nextGenerator { self._generators.append(nextGenerator) } else { next = nextCandidate } } while next == nil if next == nil { done() return } let subscription2 = subscribeToNext(next!) _subscription.disposable = subscription2 } func subscribeToNext(source: Observable<E>) -> Disposable { abstractMethod() } func disposeCommand() { _disposed = true _generators.removeAll(keepCapacity: false) } override func dispose() { super.dispose() _subscription.dispose() schedule(.Dispose) } }
mit
b69862bd505288ab956afe2d7da77bc6
23.344
140
0.553401
5.046434
false
false
false
false
LuizZak/TaskMan
TaskMan/TaskList.swift
1
1448
// // TaskList.swift // TaskMan // // Created by Luiz Fernando Silva on 05/12/16. // Copyright © 2016 Luiz Fernando Silva. All rights reserved. // import Cocoa import SwiftyJSON /// Describes a collection of tasks. /// Used mostly to store tasks and associated segments to a persistency interface. struct TaskList { /// List of tasks var tasks: [Task] = [] /// List of task segments registered for the tasks above var taskSegments: [TaskSegment] = [] init(tasks: [Task] = [], taskSegments: [TaskSegment] = []) { self.tasks = tasks self.taskSegments = taskSegments } } // MARK: Json extension TaskList: JsonInitializable, JsonSerializable { init(json: JSON) throws { try tasks = json[JsonKey.tasks].tryParseModels() try taskSegments = json[JsonKey.taskSegments].tryParseModels() } func serialize() -> JSON { var dict: [JsonKey: Any] = [:] dict[.tasks] = tasks.jsonSerialize().map { $0.object } dict[.taskSegments] = taskSegments.jsonSerialize().map { $0.object } return dict.mapToJSON() } } extension TaskList { /// Inner enum containing the JSON key names for the model enum JsonKey: String, JSONSubscriptType { case tasks case taskSegments = "task_segments" var jsonKey: JSONKey { return JSONKey.key(self.rawValue) } } }
mit
8aac1adb0b2c1ee2f43152ff81af28cd
24.385965
82
0.615757
4.345345
false
false
false
false
superk589/DereGuide
DereGuide/Unit/Simulation/Controller/ScoreDashboardController.swift
2
2360
// // ScoreDashboardController.swift // DereGuide // // Created by zzk on 23/02/2018. // Copyright © 2018 zzk. All rights reserved. // import UIKit class ScoreDashboardController: BaseViewController, UITableViewDelegate, UITableViewDataSource { lazy var tableView: IndicatorTableView = { let tableView = IndicatorTableView() tableView.indicator.strokeColor = UIColor.life.withAlphaComponent(0.5) tableView.sectionHeaderHeight = 30 tableView.sectionFooterHeight = 30 tableView.delegate = self tableView.dataSource = self tableView.register(NoteScoreTableViewCell.self, forCellReuseIdentifier: "Note Cell") tableView.register(NoteScoreTableViewSectionHeader.self, forHeaderFooterViewReuseIdentifier: "Note Header") tableView.register(NoteScoreTableViewSectionFooter.self, forHeaderFooterViewReuseIdentifier: "Note Footer") tableView.separatorStyle = .none tableView.allowsSelection = false return tableView }() var logs = [LSLog]() { didSet { tableView.reloadData() } } // MARK: TableViewDataSource & Delegate func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return logs.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Note Cell", for: indexPath) as! NoteScoreTableViewCell cell.setup(with: logs[indexPath.row]) return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "Note Header") return header } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let footer = tableView.dequeueReusableHeaderFooterView(withIdentifier: "Note Footer") as! NoteScoreTableViewSectionFooter if let baseScore = logs.first?.baseScore, let totalScore = logs.last?.sum { footer.setupWith(baseScore: baseScore, totalScore: totalScore) } return footer } }
mit
b92a2fe6d938438f7790bab7c815ae01
35.292308
129
0.687156
5.473318
false
false
false
false
podverse/podverse-ios
Podverse/Int64+MediaPlayerString.swift
1
1368
// // Int64+MediaPlayerString.swift // Podverse // // Created by Mitchell Downey on 5/29/17. // Copyright © 2017 Podverse LLC. All rights reserved. // extension Int64 { func toMediaPlayerString() -> String { let hours = self / 3600 let minutes = self / 60 % 60 let seconds = self % 60 var timeString = String(format:"%02i:%02i:%02i", hours, minutes, seconds) if hours < 10 { timeString = String(format:"%01i:%02i:%02i", hours, minutes, seconds) } if hours == 0 { if minutes > 9 { timeString = String(format:"%02i:%02i", minutes, seconds) } else { timeString = String(format:"%01i:%02i", minutes, seconds) } } return timeString } func toDurationString() -> String { let hours = self / 3600 let minutes = self / 60 % 60 let seconds = self % 60 var timeString = "" if hours > 0 { timeString += String(hours) + "h " } if minutes > 0 { timeString += String(minutes) + "m " } if seconds > 0 { timeString += String(seconds) + "s" } return timeString.trimmingCharacters(in: .whitespaces) } }
agpl-3.0
42edfeb4c5baf7ad9769f4f911533ea7
24.792453
81
0.48793
4.481967
false
false
false
false
himani93/heimdall
Sources/Provider.swift
1
1709
import Vapor public final class Provider: Vapor.Provider { public static let repositoryName = "heimdall" public let logger: Logger enum ConfigError: Error { case configNotFound case invalidConfig } public func beforeRun(_: Vapor.Droplet) {} public init(config: Config) throws { guard let heimdallConfig = config["heimdall"]?.object else { logger = Logger() return } // Both file and format specified if let path = heimdallConfig["path"]?.string, let formatString = heimdallConfig["format"]?.string, let format = LogType(rawValue: formatString) { self.logger = Logger(format: format, path: path) } else if let path = heimdallConfig["path"]?.string { // Only file specified self.logger = Logger(path: path) } else if let formatString = heimdallConfig["format"]?.string, let format = LogType(rawValue: formatString) { // Only format specified self.logger = Logger(format: format) } else { throw ConfigError.invalidConfig } } public init() { logger = Logger() } public init(format: LogType) { logger = Logger(format: format) } public init(path: String) { logger = Logger(path: path) } public init(format: LogType, path: String) { logger = Logger(format: format, path: path) } public func boot(_ drop: Droplet) { } public func boot(_ config: Config) throws { config.addConfigurable(middleware: logger, name: "heimdall") } }
mit
dd347803cbc6eb3b85fdeea063032083
27.483333
70
0.571679
4.827684
false
true
false
false
tassiahmed/SplitScreen
OSX/SplitScreen/SnapHighlighter.swift
1
3201
// SnapHighlighter.swift // SplitScreen // // Created by Evan Thompson on 7/1/16. // Copyright © 2016 SplitScreen. All rights reserved. import Foundation import AppKit class SnapHighlighter { fileprivate var creationDelayTimer: Timer // Timer used to delay creation of the highlighting window fileprivate var updateTimer: Timer // Timer used for window updating (.4 seconds) fileprivate var highlightWindow: NSWindow? // The actual highlighting window fileprivate var windowDimensions: (Int, Int, Int, Int) // The dimensions for the hightlighting window /** Inits `SnapHighlighter` with timer vairiables and actual window */ init() { creationDelayTimer = Timer() updateTimer = Timer() highlightWindow = NSWindow() windowDimensions = (0,0,0,0) } /** Creates and draws the actual window also setting it up to update */ func draw_create () { let window_rect = NSRect(x: windowDimensions.0, y: Int((NSScreen.main?.frame.height)!) - (windowDimensions.1 + windowDimensions.3), width: windowDimensions.2, height: windowDimensions.3) // The setup for the highlighting window highlightWindow = NSWindow(contentRect: window_rect, styleMask: NSWindow.StyleMask(rawValue: UInt(0)), backing: NSWindow.BackingStoreType.nonretained, defer: true) highlightWindow?.isOpaque = true highlightWindow?.backgroundColor = NSColor.blue highlightWindow?.setIsVisible(true) highlightWindow?.alphaValue = 0.3 highlightWindow?.orderFrontRegardless() // need to make the window the front most window? // want it to be an overlay as opposed to behind the dragged window // user needs to be able to see it // Start updating the window updateTimer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(highlight_update), userInfo: nil, repeats: true) } /** Callback for the delay timer */ @objc func update_on_delay() { // Adds the dimensions info so that a window can be created snapHighlighter.update_window(layout.get_snap_dimensions(lastKnownMouseDrag!.x, y: lastKnownMouseDrag!.y)) snapHighlighter.draw_create() } /** Sets up the timer to delay the creation of the window */ func delay_update(_ delay: Double) { creationDelayTimer = Timer.scheduledTimer(timeInterval: delay, target: self, selector: #selector(update_on_delay), userInfo: nil, repeats: false) } /** Stops timer for delayed creation */ func kill_delay_create(){ creationDelayTimer.invalidate() } /** Updates the window for highlighting */ @objc func highlight_update() { highlightWindow?.update() } /** Destroys the window */ func draw_destroy () { updateTimer.invalidate() highlightWindow?.isOpaque = false highlightWindow?.setIsVisible(false) } /** Updates the window dimensions */ func update_window(_ new_dimensions: (Int, Int, Int, Int)) { windowDimensions = new_dimensions let new_frame = NSRect(x: windowDimensions.0, y: Int((NSScreen.main?.frame.height)!) - (windowDimensions.1 + windowDimensions.3), width: windowDimensions.2, height: windowDimensions.3) highlightWindow?.setFrame(new_frame, display: true, animate: true) } }
apache-2.0
e8068ef0d68f960e2c35d822edf781d5
32.333333
190
0.719063
4.183007
false
false
false
false