repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Nimbow/Client-iOS
refs/heads/master
client/client/NimbowApiClientAsync.swift
mit
1
// // NimbowApiClientAsync.swift // client // // Created by Awesome Developer on 17/01/16. // Copyright © 2015 Nimbow. All rights reserved. // public class NimbowApiClientAsync { public static let SharedInstance = NimbowApiClientAsync() private var infoValues: NSDictionary! private init() { let filePath = NSBundle.mainBundle().pathForResource("Info", ofType: "plist")! self.infoValues = NSDictionary(contentsOfFile:filePath) } var baseUrl: String { return infoValues["Nimbow.Api.Url"] as! String } var apiKey: String { return infoValues["Nimbow.Api.Key"] as! String } public func SendSmsAsync(request: Sms, completitionHandler: (response: SendSmsResponse) -> ()) throws { let url = NSURL(string: baseUrl + "sms.json") let session = NSURLSession.sharedSession() let mutableRequest = NSMutableURLRequest(URL: url!) mutableRequest.setValue(apiKey, forHTTPHeaderField: "X-Nimbow-API-Key") mutableRequest.HTTPMethod = "POST" mutableRequest.HTTPBody = try request.ToSendSmsRequest().ToQueryParameterString().dataUsingEncoding(NSUTF8StringEncoding) let task = session.dataTaskWithRequest(mutableRequest, completionHandler: {(data, response, error) in let responseStr = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String let response = SendSmsResponse.FromString(responseStr) completitionHandler(response: response) }) task.resume() } public func GetBalanceAsync(completitionHandler: (response: GetBalanceResponse) -> ()) throws { let url = NSURL(string: baseUrl + "balance.json") let session = NSURLSession.sharedSession() let mutableRequest = NSMutableURLRequest(URL: url!) mutableRequest.setValue(apiKey, forHTTPHeaderField: "X-Nimbow-API-Key") mutableRequest.HTTPMethod = "POST" mutableRequest.HTTPBody = try GetBalanceRequest(getDT: true, getTS: true, getFMC: true).ToQueryParameterString().dataUsingEncoding(NSUTF8StringEncoding) let task = session.dataTaskWithRequest(mutableRequest, completionHandler: {(data, response, error) in let responseStr = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String let response = GetBalanceResponse.FromString(responseStr) completitionHandler(response: response) }) task.resume() } }
025f05c4eb200f070012256806d02bdd
40.766667
160
0.68024
false
false
false
false
dukemedicine/Duke-Medicine-Mobile-Companion
refs/heads/master
Classes/Utilities/MCHaikuOrCanto.swift
mit
1
// // MCHaikuOrCanto.swift // Duke Medicine Mobile Companion // // Created by Ricky Bloomfield on 7/7/14. // Copyright (c) 2014 Duke Medicine // // 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 /** Opens the Canto app */ func openCanto() { UIApplication.sharedApplication().openURL(NSURL(string: "epiccanto://")!) } /** Opens the Haiku app */ func openHaiku() { UIApplication.sharedApplication().openURL(NSURL(string: "epichaiku://")!) } /** Opens the App Store to the Canto app */ func downloadCanto() { UIApplication.sharedApplication().openURL(NSURL(string: "itms-apps://itunes.apple.com/us/app/epic-canto/id395395172?mt=8")!) } /** Opens the App Store to the Haiku app */ func downloadHaiku() { UIApplication.sharedApplication().openURL(NSURL(string: "itms-apps://itunes.apple.com/us/app/epic-haiku/id348308661?mt=8")!) } /** Returns the string "Haiku" or "Canto" based on whether each is installed. If on iPad and both are installed, returns the preference in settings */ func HaikuOrCanto() -> String! { let HaikuInstalled: Bool = UIApplication.sharedApplication().canOpenURL(NSURL(string: "epichaiku://")!) let CantoInstalled: Bool = UIApplication.sharedApplication().canOpenURL(NSURL(string: "epiccanto://")!) if IPAD() { if HaikuInstalled && CantoInstalled { return USER_DEFAULTS().objectForKey("returnTo") as String } else if (HaikuInstalled) { return "Haiku" } else if (CantoInstalled) { return "Canto" } } else if (HaikuInstalled) { return "Haiku" } return nil } /** Opens the appropriate app based on app availability and preference (per HaikuOrCanto() function above) */ func openHaikuOrCanto() { if HaikuOrCanto()? == "Haiku" {openHaiku()} else if HaikuOrCanto()? == "Canto" {openCanto()} }
2e2ad6fb019361246cafe33cba58a0f0
33.247059
144
0.704811
false
false
false
false
bravelocation/yeltzland-ios
refs/heads/main
watchkitapp Extension/Views/GamesListView.swift
mit
1
// // FixtureListView.swift // watchkitapp Extension // // Created by John Pollard on 25/10/2019. // Copyright © 2019 John Pollard. All rights reserved. // import SwiftUI struct GamesListView: View { @ObservedObject var fixtureData: FixtureData var selection: FixtureData.FixtureSelection var body: some View { VStack { if self.fixtureData.state != .isLoading && self.fixtureData.fixturesAvailable(selection: self.selection) == false { Text("No games").padding() } List(self.fixtureData.allFixtures(selection: self.selection, reverseOrder: selection == .resultsOnly), id: \.self) { fixture in HStack { Group { if fixture.status == .fixture || fixture.status == .inProgress { FixtureView(fixture: fixture, teamImage: self.fixtureData.teamImage(fixture)) } else { ResultView(fixture: fixture, teamImage: self.fixtureData.teamImage(fixture), resultColor: self.resultColor(fixture)) } } Spacer() } .listRowPlatterColor(Color("dark-blue")) } .listStyle(CarouselListStyle()) } .overlay( Button(action: { self.fixtureData.refreshData() }, label: { Image(systemName: "arrow.clockwise") .font(.footnote) .padding() }) .frame(width: 24.0, height: 24.0, alignment: .center) .background(Color.gray.opacity(0.5)) .cornerRadius(12), alignment: .topTrailing ) .foregroundColor(Color("light-blue")) .onAppear { self.fixtureData.refreshData() } .navigationBarTitle(Text(self.fixtureData.state == .isLoading ? "Loading ..." : self.navTitle)) } var navTitle: String { switch self.selection { case .resultsOnly: return "Results" case .fixturesOnly: return "Fixtures" default: return "" } } func resultColor(_ fixture: TimelineFixture) -> Color { switch fixture.result { case .win: return Color("watch-fixture-win") case .lose: return Color("watch-fixture-lose") default: return Color("watch-fixture-draw") } } } #if DEBUG struct GamesListView_Previews: PreviewProvider { static var previews: some View { Group { GamesListView( fixtureData: AllGamesData(fixtureManager: PreviewFixtureManager(), gameScoreManager: PreviewGameScoreManager(), useResults: false) ) GamesListView( fixtureData: AllGamesData(fixtureManager: PreviewFixtureManager(), gameScoreManager: PreviewGameScoreManager(), useResults: true) ) } } } #endif
4b95bbe627d2d49259534ae9a88e97a7
31.571429
146
0.52381
false
false
false
false
BrandonMA/SwifterUI
refs/heads/master
Pods/DeepDiff/Sources/Shared/DiffAware.swift
mit
1
// // DiffAware.swift // DeepDiff // // Created by khoa on 22/02/2019. // Copyright © 2019 Khoa Pham. All rights reserved. // import Foundation /// Model must conform to DiffAware for diffing to work properly /// diffId: Each object must be uniquely identified by id. This is to tell if there is deletion or insertion /// compareContent: An object can change some properties but having its id intact. This is to tell if there is replacement public protocol DiffAware { var diffId: Int { get } static func compareContent(_ a: Self, _ b: Self) -> Bool } extension String: DiffAware { public var diffId: Int { return hashValue } public static func compareContent(_ a: String, _ b: String) -> Bool { return a == b } } extension Character: DiffAware { public var diffId: Int { return hashValue } public static func compareContent(_ a: Character, _ b: Character) -> Bool { return a == b } } extension Int: DiffAware { public var diffId: Int { return hashValue } public static func compareContent(_ a: Int, _ b: Int) -> Bool { return a == b } }
149b21b373322bfa508ba9b38a5998bd
22.446809
122
0.676951
false
false
false
false
wordpress-mobile/WordPress-iOS
refs/heads/trunk
WordPress/Classes/ViewRelated/Media/CameraCaptureCoordinator.swift
gpl-2.0
1
import MobileCoreServices /// Encapsulates capturing media from a device camera final class CameraCaptureCoordinator { private var capturePresenter: WPMediaCapturePresenter? private weak var origin: UIViewController? func presentMediaCapture(origin: UIViewController, blog: Blog) { self.origin = origin capturePresenter = WPMediaCapturePresenter(presenting: origin) capturePresenter!.completionBlock = { [weak self] mediaInfo in if let mediaInfo = mediaInfo as NSDictionary? { self?.processMediaCaptured(mediaInfo, blog: blog) } self?.capturePresenter = nil } capturePresenter!.presentCapture() } private func processMediaCaptured(_ mediaInfo: NSDictionary, blog: Blog, origin: UIViewController? = nil) { let completionBlock: WPMediaAddedBlock = { media, error in if error != nil || media == nil { print("Adding media failed: ", error?.localizedDescription ?? "no media") return } guard let media = media as? PHAsset, blog.canUploadAsset(media) else { if let origin = origin ?? self.origin { self.presentVideoLimitExceededAfterCapture(on: origin) } return } let info = MediaAnalyticsInfo(origin: .mediaLibrary(.camera), selectionMethod: .fullScreenPicker) MediaCoordinator.shared.addMedia(from: media, to: blog, analyticsInfo: info) } guard let mediaType = mediaInfo[UIImagePickerController.InfoKey.mediaType.rawValue] as? String else { return } switch mediaType { case String(kUTTypeImage): if let image = mediaInfo[UIImagePickerController.InfoKey.originalImage.rawValue] as? UIImage, let metadata = mediaInfo[UIImagePickerController.InfoKey.mediaMetadata.rawValue] as? [AnyHashable: Any] { WPPHAssetDataSource().add(image, metadata: metadata, completionBlock: completionBlock) } case String(kUTTypeMovie): if let mediaURL = mediaInfo[UIImagePickerController.InfoKey.mediaURL.rawValue] as? URL { WPPHAssetDataSource().addVideo(from: mediaURL, completionBlock: completionBlock) } default: break } } } /// User messages for video limits allowances extension CameraCaptureCoordinator: VideoLimitsAlertPresenter {}
7a9247473e3cd108ec66f618ba88f5bf
41.898305
121
0.638483
false
false
false
false
MChainZhou/DesignPatterns
refs/heads/master
Birdge/Birdge/Bridge/Simple_4_优化代码/VerticalProgress.swift
mit
1
// // VerticalProgress.swift // Birdge // // Created by apple on 2017/8/29. // Copyright © 2017年 apple. All rights reserved. // import UIKit class VerticalProgress: BaseProgress { override func getRect() -> CGRect { return CGRect(x: 100, y: 100, width: 50, height: 20) } override func draw(view: UIView) { for index in 0..<self.sportCount { let layer = CAShapeLayer() layer.fillColor = UIColor.black.cgColor layer.strokeColor = UIColor.black.cgColor layer.path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 4, height: 4)).cgPath let y = CGFloat(index) * view.bounds.width / CGFloat(sportCount - 1) let x = view.bounds.height / 2.0 layer.position = CGPoint(x: x, y: y) } } }
c8a8f1a49ff5a6ae21c46c488e0125f0
28.464286
93
0.581818
false
false
false
false
Keenan144/SpaceKase
refs/heads/master
SpaceKase/Booster.swift
mit
1
// // Booster.swift // SpaceKase // // Created by Keenan Sturtevant on 6/22/16. // Copyright © 2016 Keenan Sturtevant. All rights reserved. // import SpriteKit class Boost: SKSpriteNode { static var canSpawn:Bool! static var timer:NSTimer! class func spawnInvincibility() -> SKSpriteNode { if canSpawn == nil || canSpawn == true { let boostColor = UIColor.yellowColor() let boostSize = CGSize(width: 20, height: 20) let boost = SKSpriteNode(color: boostColor, size: boostSize) boost.texture = SKTexture(imageNamed: "Shield") boost.physicsBody = SKPhysicsBody(rectangleOfSize: boostSize) boost.physicsBody?.dynamic = true boost.physicsBody?.usesPreciseCollisionDetection = true boost.physicsBody?.affectedByGravity = false boost.physicsBody?.velocity.dy = -250 boost.name = "Invincibility" canSpawn = false print("BOOST: spawnInvincibility") return boost } print("BOOST: spawnScoreBump()") return Boost.spawnScoreBump() } class func spawnScoreBump() -> SKSpriteNode { let boostColor = UIColor.cyanColor() let boostSize = CGSize(width: 20, height: 20) let boost = SKSpriteNode(color: boostColor, size: boostSize) boost.texture = SKTexture(imageNamed: "Point") boost.physicsBody = SKPhysicsBody(rectangleOfSize: boostSize) boost.physicsBody?.dynamic = true boost.physicsBody?.usesPreciseCollisionDetection = true boost.physicsBody?.affectedByGravity = false boost.physicsBody?.velocity.dy = -250 boost.name = "ScoreBump" print("BOOST: spawnScoreBump") return boost } }
c27f67b1a5ae40c087c22e8d8b8c7082
31.754386
73
0.610932
false
false
false
false
leoneparise/iLog
refs/heads/master
iLogUI/TimelineTableViewHeader.swift
mit
1
// // TimleineTableViewHeader.swift // StumpExample // // Created by Leone Parise Vieira da Silva on 06/05/17. // Copyright © 2017 com.leoneparise. All rights reserved. // import UIKit public class TimelineTableViewHeader: UIVisualEffectView { @IBOutlet weak var bulletView:TimelineBulletView! @IBOutlet weak var titleLabel:UILabel! var dateFormatter:DateFormatter = { let df = DateFormatter() df.doesRelativeDateFormatting = true df.dateStyle = .medium df.timeStyle = .short return df }() static func fromNib() -> TimelineTableViewHeader { let bundle = Bundle(for: TimelineTableViewHeader.self) let nib = UINib(nibName: "TimelineTableViewHeader", bundle: bundle) return nib.instantiate(withOwner: nil, options: nil).first as! TimelineTableViewHeader } var date:Date? { didSet { titleLabel.text = date != nil ? dateFormatter.string(from: date!) : "" } } var title:String? { didSet { titleLabel.text = title } } var isFirst:Bool = false { didSet { bulletView.isFirst = isFirst bulletView.isLast = false } } }
52401d17df65f10aa55662e56ee2817f
27.069767
94
0.63546
false
false
false
false
cocoascientist/Passengr
refs/heads/master
Passengr/HTML.swift
mit
1
// // HTML.swift // Passengr // // Created by Andrew Shepard on 11/17/15. // Copyright © 2015 Andrew Shepard. All rights reserved. // import Foundation final class HTMLNode { internal let nodePtr: xmlNodePtr private let node: xmlNode init(node nodePtr: xmlNodePtr) { self.nodePtr = nodePtr self.node = nodePtr.pointee } lazy var nodeValue: String = { let document = self.nodePtr.pointee.doc let children = self.nodePtr.pointee.children guard let textValue = xmlNodeListGetString(document, children, 1) else { return "" } defer { free(textValue) } let value = textValue.withMemoryRebound(to: CChar.self, capacity: 1) { return String(validatingUTF8: $0) } guard value != nil else { return "" } return value! }() } extension HTMLNode { func evaluate(xpath: String) -> [HTMLNode] { let document = nodePtr.pointee.doc guard let context = xmlXPathNewContext(document) else { return [] } defer { xmlXPathFreeContext(context) } context.pointee.node = nodePtr guard let result = xmlXPathEvalExpression(xpath, context) else { return [] } defer { xmlXPathFreeObject(result) } guard let nodeSet = result.pointee.nodesetval else { return [] } if nodeSet.pointee.nodeNr == 0 || nodeSet.pointee.nodeTab == nil { return [] } let size = Int(nodeSet.pointee.nodeNr) let nodes: [HTMLNode] = [Int](0..<size).compactMap { guard let node = nodeSet.pointee.nodeTab[$0] else { return nil } return HTMLNode(node: node) } return nodes } } final class HTMLDoc { final let documentPtr: htmlDocPtr init?(data: Data) { let cfEncoding = CFStringConvertNSStringEncodingToEncoding(String.Encoding.utf8.rawValue) let cfEncodingAsString = CFStringConvertEncodingToIANACharSetName(cfEncoding) let cEncoding = CFStringGetCStringPtr(cfEncodingAsString, 0) // HTML_PARSE_RECOVER | HTML_PARSE_NOERROR | HTML_PARSE_NOWARNING let htmlParseOptions: CInt = 1 << 0 | 1 << 5 | 1 << 6 var ptr: htmlDocPtr? = nil data.withUnsafeBytes { result -> Void in guard let bytes = result.baseAddress?.assumingMemoryBound(to: Int8.self) else { return } ptr = htmlReadMemory(bytes, CInt(data.count), nil, cEncoding, htmlParseOptions) } guard let _ = ptr else { return nil } self.documentPtr = ptr! } deinit { xmlFreeDoc(documentPtr) self._root = nil } private weak var _root: HTMLNode? var root: HTMLNode? { if let root = _root { return root } else { guard let root = xmlDocGetRootElement(documentPtr) else { return nil } let node = HTMLNode(node: root) self._root = node return node } } }
26106caeb3317a9bb975e9e65de01964
29.949495
100
0.591384
false
false
false
false
linbin00303/Dotadog
refs/heads/master
DotaDog/DotaDog/Classes/LeftView/Controller/DDogMatchTableViewController.swift
mit
1
// // DDogMatchTableViewController.swift // DotaDog // // Created by 林彬 on 16/5/25. // Copyright © 2016年 linbin. All rights reserved. // import UIKit import MJExtension import SVProgressHUD class DDogMatchTableViewController: UITableViewController { var j = 0 private lazy var playerNames : [String:String]? = { let playerNames = [String:String]() return playerNames }() var match : DDogMatchListModel? let MatchHero = "DDogMatchCell" // 懒加载本场比赛模型 private lazy var matchModel : DDogMatchModel = { let matchModel:DDogMatchModel = DDogMatchModel() return matchModel }() // // 懒加载本场比赛英雄模型 // private lazy var heros : [DDogMatchHeroModel] = { // let heros:[DDogMatchHeroModel] = [DDogMatchHeroModel]() // return heros // }() // 懒加载本场比赛英雄模型 private lazy var heros : NSMutableArray = { let heros:NSMutableArray = NSMutableArray() return heros }() override func viewDidLoad() { super.viewDidLoad() setUpTableView() getNetData() } private func setUpTableView() { view.backgroundColor = UIColor.blackColor() title = "比赛详情" // 去掉Cell的间隔线 self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None // 注册cell tableView.registerNib(UINib(nibName: "DDogMatchCell", bundle: nil), forCellReuseIdentifier: MatchHero) } } // MARK:- 获取网络数据 extension DDogMatchTableViewController{ private func getNetData() { SVProgressHUD.setMinimumDismissTimeInterval(2) SVProgressHUD.show() let matchID = String(format: "%@" , (match?.match_id)!) let parameters = ["key":"75571F3D1597EA1E8E287E127F7C563F" , "match_id" : matchID] DDogLeftViewHttp.getMatchDataByUrl(parameters) { [weak self](resultMs,heroModels,error) -> () in if resultMs == nil { // 服务器大姨妈 SVProgressHUD.showErrorWithStatus("Steam服务器无法连接") return }else if resultMs! == []{ SVProgressHUD.showErrorWithStatus("该用户未公开数据") return }else if error != nil { SVProgressHUD.showErrorWithStatus("网络错误") } self?.matchModel = resultMs! // 设置headerView let headerV = DDogMatchHeader.showMatchHeadFromNib() headerV.matchModle = self?.matchModel self?.tableView.tableHeaderView = headerV self?.heros = heroModels! // 获取10个玩家姓名的字典 let count = heroModels!.count var hero : DDogMatchHeroModel? for i in 0..<count { hero = heroModels![i] as? DDogMatchHeroModel self?.getPlayerName(hero!.account_id) } self?.tableView.reloadData() } } } extension DDogMatchTableViewController { override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let _ = heros.count if heros == [] { return 0 } return 5 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(MatchHero, forIndexPath: indexPath) as! DDogMatchCell cell.selectionStyle = .None var accountID : NSNumber = 0 if indexPath.section == 0 { accountID = (self.heros[indexPath.row] as? DDogMatchHeroModel)!.account_id cell.name = playerNames![accountID.stringValue] cell.hero = self.heros[indexPath.row] as? DDogMatchHeroModel }else { accountID = (self.heros[indexPath.row + 5 ] as? DDogMatchHeroModel)!.account_id cell.name = playerNames![accountID.stringValue] cell.hero = self.heros[indexPath.row + 5 ] as? DDogMatchHeroModel } return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 194 } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 25 } override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 40 } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let text : UILabel = UILabel() text.textAlignment = .Center text.backgroundColor = UIColor.whiteColor() text.textColor = mainColor if section == 0 { text.text = "天辉" return text }else { text.text = "夜魇" return text } } func getPlayerName(accountID:NSNumber) { let tempID = Int64(accountID.intValue) + 76561197960265728 let stringTemp = String(format: "\(tempID)") var namedic = [String:String]() // 直接用ID查 let parameters = ["key":"75571F3D1597EA1E8E287E127F7C563F" , "steamids" : stringTemp] DDogLeftViewHttp.getPlayerNameByID(parameters) { [weak self](playerNameDic,model,error) in if error != nil { SVProgressHUD.showErrorWithStatus("网络错误") return } if playerNameDic != nil { namedic = playerNameDic! }else { namedic = [accountID.stringValue : "匿名玩家"] } self?.playerNames?.updateValue(namedic[accountID.stringValue]!, forKey:accountID.stringValue ) self?.j = self!.j + 1 if self?.j == 10 { SVProgressHUD.dismiss() self?.tableView.reloadData() self?.j = 0 } } } }
bd6323589764feb5984e869684b175ce
29.683168
119
0.57696
false
false
false
false
intellum/neeman
refs/heads/master
Tests/WebViewNavigationDelegateTests.swift
mit
1
import XCTest import WebKit @testable import Neeman class WebViewNavigationDelegateTests: XCTestCase { func testInitialRequest() { let url = URL(string: "http://example.com/") let navigationDelegate = WebViewNavigationDelegate(rootURL: url!, delegate: nil) let request = URLRequest(url: url!) let webView = WKWebView() let navigationAction = NavigationAction(request: request) XCTAssertFalse(navigationDelegate.shouldPushForRequestFromWebView(webView, navigationAction: navigationAction), "The initial request should not be pushed") } func testFaultyURLNavigation() { let url = URL(string: "http://example.com/") let urlFaulty = URL(string: "#hi") let navigationDelegate = WebViewNavigationDelegate(rootURL: url!, delegate: nil) var request = URLRequest(url: urlFaulty!) request.url = nil let navigationAction = NavigationAction(request: request) let webView = WKWebView() XCTAssertFalse(navigationDelegate.shouldPushForRequestFromWebView(webView, navigationAction: navigationAction), "Faulty URLs should not be pushed") } func testHashNavigation() { let url = URL(string: "http://example.com/#hash") let navigationDelegate = WebViewNavigationDelegate(rootURL: url!, delegate: nil) let request = URLRequest(url: url!) let navigationAction = NavigationAction(request: request) let webView = WKWebView() XCTAssertFalse(navigationDelegate.shouldPushForRequestFromWebView(webView, navigationAction: navigationAction), "Hash navigation should not be pushed") } func testNavigateForward() { let url1 = URL(string: "http://example.com/") let url2 = URL(string: "http://example.com/user/profile/me") let navigationDelegate = WebViewNavigationDelegate(rootURL: url1!, delegate: nil) let request = URLRequest(url: url2!) let navigationAction = NavigationAction(request: request) let webView = WKWebView() XCTAssertTrue(navigationDelegate.shouldPushForRequestFromWebView(webView, navigationAction: navigationAction), "New URLs should not be pushed") } // MARK: Delegation func testPreventPush() { class NeemanWebViewController: TestNeemanNavigationDelegate { override func shouldPreventPushOfNavigationAction(_ navigationAction: WKNavigationAction) -> Bool { return true } } let url = URL(string: "https://groupdock.com/a/Level") let request = URLRequest(url: url!) let navigationAction = NavigationAction(request: request) let delegate = NeemanWebViewController() let navigationDelegate = WebViewNavigationDelegate(rootURL: url!, delegate: delegate) let webView = WKWebView() XCTAssertFalse(navigationDelegate.shouldPushForRequestFromWebView(webView, navigationAction: navigationAction), "The delegate should prevent the URL being pushed") } func testErrorPassedToDelegate() { let expectation = self.expectation(description: "Pass Error to Delegate") class NeemanWebViewController: TestNeemanNavigationDelegate { override func webView(_ webView: WKWebView, didFinishLoadingWithError error: NSError) { XCTAssertNotNil(error, "The delegate should be passed a non nil error") expectation?.fulfill() } } let url = URL(string: "https://groupdock.com/a/Level") let delegate = NeemanWebViewController(expectation: expectation) let navigationDelegate = WebViewNavigationDelegate(rootURL: url!, delegate: delegate) let error = NSError(domain: "", code: 1, userInfo: nil) navigationDelegate.webView(WKWebView(), didFailProvisionalNavigation: nil, withError: error) waitForExpectations(timeout: 1) { (error) -> Void in if let _ = error { XCTFail("Error Passing Failed") } } } func testDecidePolicyForNavigationAction() { let expectation = self.expectation(description: "Call Callback") let url = URL(string: "https://groupdock.com/a/Level") let navigationDelegate = WebViewNavigationDelegate(rootURL: url!, delegate: nil) let request = URLRequest(url: url!) let navigationAction = NavigationAction(request: request) navigationDelegate.webView(WKWebView(), decidePolicyFor: navigationAction) { (policy: WKNavigationActionPolicy) -> Void in expectation.fulfill() } waitForExpectations(timeout: 1) { (error) -> Void in if let _ = error { XCTFail("Error Passing Failed") } } } func testShouldPreventPushOfNewWebView() { class MyWKNavigation: NSObject { } class MyNeemanWebViewController: TestNeemanNavigationDelegate { override func shouldPreventPushOfNavigationAction(_ navigationAction: WKNavigationAction) -> Bool { return true } } let url = URL(string: "https://groupdock.com/a/Level") let delegate = MyNeemanWebViewController() let navigationDelegate = WebViewNavigationDelegate(rootURL: url!, delegate: delegate) let webView = WKWebView() let navigationAction = NavigationAction(request: URLRequest(url:url!)) XCTAssertFalse(navigationDelegate.shouldPushForRequestFromWebView(webView, navigationAction: navigationAction), "The delegate should prevent the URL being pushed") } func testDelegateDefaultImplementations() { class MyNeemanWebViewController: TestNeemanNavigationDelegate { } let webView = WKWebView() let navigationAction = NavigationAction(request: URLRequest(url: URL(string: "#hi")!)) let delegate = MyNeemanWebViewController() delegate.webView(webView, didFinishNavigationWithURL:nil) delegate.webView(webView, didFinishLoadingWithError: NSError(domain: "", code: 1, userInfo: nil)) delegate.webView(webView, didReceiveServerRedirectToURL: nil) let _ = delegate.shouldForcePushOfNavigationAction(navigationAction) delegate.pushNewWebViewControllerWithURL(URL(string: "#ho")!) let _ = delegate.shouldPreventPushOfNavigationAction(navigationAction) } func testDelegateMethodsCalled() { let expectation = self.expectation(description: "Pass Error to Delegate") class NeemanWebViewController: TestNeemanNavigationDelegate { override func webView(_ webView: WKWebView, didFinishNavigationWithURL: URL?) { expectation?.fulfill() } } let url = URL(string: "https://intellum.com/cool/new/link")! let delegate = NeemanWebViewController(expectation: expectation) let navigationDelegate = WebViewNavigationDelegate(rootURL: url, delegate: delegate) navigationDelegate.webView(WKWebView(), didFinish: nil) waitForExpectations(timeout: 1) { (error) -> Void in if let _ = error { XCTFail("Error Passing Failed") } } } func testDelegateRedirectMethodsCalled() { let expectation = self.expectation(description: "Pass Error to Delegate") class NeemanWebViewController: TestNeemanNavigationDelegate { override func webView(_ webView: WKWebView, didReceiveServerRedirectToURL: URL?) { expectation?.fulfill() } } let url = URL(string: "https://intellum.com/cool/new/link")! let delegate = NeemanWebViewController(expectation: expectation) let navigationDelegate = WebViewNavigationDelegate(rootURL: url, delegate: delegate) navigationDelegate.webView(WKWebView(), didReceiveServerRedirectForProvisionalNavigation: nil) waitForExpectations(timeout: 1) { (error) -> Void in if let _ = error { XCTFail("Error Passing Failed") } } } func testPushIsCalled() { let expectation = self.expectation(description: "Pass Error to Delegate") class NeemanWebViewController: TestNeemanNavigationDelegate { override func shouldForcePushOfNavigationAction(_ navigationAction: WKNavigationAction) -> Bool { return true } override func pushNewWebViewControllerWithURL(_ url: URL) { expectation?.fulfill() } } class MyWKNavigationAction: NavigationAction { override var navigationType: WKNavigationType { get { return .linkActivated } } } let url = URL(string: "https://intellum.com/cool/new/link")! let delegate = NeemanWebViewController(expectation: expectation) let navigationDelegate = WebViewNavigationDelegate(rootURL: url, delegate: delegate) let action = MyWKNavigationAction(request: URLRequest(url: url)) navigationDelegate.webView(WKWebView(), decidePolicyFor: action) { (WKNavigationActionPolicy) -> Void in } waitForExpectations(timeout: 1) { (error) -> Void in if let _ = error { XCTFail("Error Passing Failed") } } } }
fe8e62b5aefdbabd2f273a972b229019
43.059091
130
0.644176
false
true
false
false
carabina/DDMathParser
refs/heads/master
MathParser/Function.swift
mit
2
// // Function.swift // DDMathParser // // Created by Dave DeLong on 9/17/15. // // import Foundation public typealias FunctionEvaluator = (Array<Expression>, Substitutions, Evaluator) throws -> Double public struct Function { public let names: Set<String> public let evaluator: FunctionEvaluator public init(name: String, evaluator: FunctionEvaluator) { self.names = [name] self.evaluator = evaluator } public init(names: Set<String>, evaluator: FunctionEvaluator) { self.names = names self.evaluator = evaluator } }
169e5b9169bacc4b9ab01a3200212d79
21.037037
99
0.660504
false
false
false
false
akhilstanislavose/echo
refs/heads/master
Echo/EventMonitor.swift
mit
1
// // EventMonitor.swift // Echo // // Created by Akhil Stanislavose on 08/10/15. // Copyright (c) 2015 Akhil Stanislavose. All rights reserved. // import Cocoa public class EventMonitor { private var monitor: AnyObject? private let mask: NSEventMask private let handler: NSEvent? -> () public init(mask: NSEventMask, handler: NSEvent? -> ()) { self.mask = mask self.handler = handler } deinit { stop() } public func start() { monitor = NSEvent.addGlobalMonitorForEventsMatchingMask(mask, handler: handler) } public func stop() { if monitor != nil { NSEvent.removeMonitor(monitor!) monitor = nil } } }
ed0b3405cce1d2cca6a2c1f787cf2e4b
19.8
87
0.601648
false
false
false
false
wujianguo/GitHubKit
refs/heads/master
GitHubApp/Classes/Profile/OrganizationTableViewController.swift
mit
1
// // OrganizationTableViewController.swift // GitHubKit // // Created by wujianguo on 16/8/24. // // import UIKit import GitHubKit import ObjectMapper import Alamofire class OrganizationTableViewController: ProfileTableViewController { override var profile: Profile? { return org } var org: Organization! = nil init(org: Organization) { super.init(style: .Grouped) self.org = org } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = org.name refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(refresh), forControlEvents: .ValueChanged) refreshControl?.beginRefreshing() tableView.dataSource = dataSource tableView.registerClass(RepositoryTableViewCell.self, forCellReuseIdentifier: RepositoryTableViewCell.cellIdentifier) // tableView.registerClass(PersonTableViewCell.self, forCellReuseIdentifier: PersonTableViewCell.cellIdentifier) dataSource.refresh(tableView) if let name = org.name { title = name } else { org.updateSelfRequest().responseObject { (response: Response<Organization, NSError>) in guard response.result.isSuccess else { return } self.org.eTag = response.result.value?.eTag self.org.lastModified = response.result.value?.lastModified if let json = response.result.value?.toJSON() { self.org.mapping(Map(mappingType: .FromJSON, JSONDictionary: json)) self.profileView.updateUI(self.org) self.title = self.org.name } } } profileView.updateUI(org) } lazy var dataSource: RepositoriesTableViewDataSource = { let ds = RepositoriesTableViewDataSource(cellIdentifier: RepositoryTableViewCell.cellIdentifier, refreshable: self.refreshControl!, firstRequest: GitHubKit.orgReposRequest(self.org.login!)) return ds }() func refresh() { dataSource.refresh(tableView) } }
4d55f709f58dae8fff7a9e0c8fcc9f0c
32.074627
197
0.65704
false
false
false
false
JaSpa/swift
refs/heads/master
test/SILGen/complete_object_init.swift
apache-2.0
2
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests %s -emit-silgen | %FileCheck %s struct X { } class A { // CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A // CHECK: bb0([[SELF_PARAM:%[0-9]+]] : $A): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var A } // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*A // CHECK: store [[SELF_PARAM]] to [init] [[SELF]] : $*A // CHECK: [[SELFP:%[0-9]+]] = load_borrow [[SELF]] : $*A // CHECK: [[INIT:%[0-9]+]] = class_method [[SELFP]] : $A, #A.init!initializer.1 : (A.Type) -> (X) -> A , $@convention(method) (X, @owned A) -> @owned A // CHECK: [[X_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT]]([[X]], [[SELFP]]) : $@convention(method) (X, @owned A) -> @owned A // CHECK: store [[INIT_RESULT]] to [init] [[SELF]] : $*A // CHECK: [[RESULT:%[0-9]+]] = load [copy] [[SELF]] : $*A // CHECK: destroy_value [[SELF_BOX]] : ${ var A } // CHECK: return [[RESULT]] : $A // CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick A.Type) -> @owned A convenience init() { // CHECK: bb0([[SELF_META:%[0-9]+]] : $@thick A.Type): // CHECK: [[SELF:%[0-9]+]] = alloc_ref_dynamic [[SELF_META]] : $@thick A.Type, $A // CHECK: [[OTHER_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A // CHECK: [[RESULT:%[0-9]+]] = apply [[OTHER_INIT]]([[SELF]]) : $@convention(method) (@owned A) -> @owned A // CHECK: return [[RESULT]] : $A self.init(x: X()) } init(x: X) { } }
151903e6e82c7ed721a83df7c147470f
56.514286
153
0.54148
false
false
false
false
grandiere/box
refs/heads/master
box/Model/Store/Base/MStoreItem.swift
mit
1
import Foundation import StoreKit class MStoreItem { let purchaseId:String let title:String let descr:String var skProduct:SKProduct? private(set) var price:String? private(set) var status:MStoreStatusProtocol? init( purchaseId:String, title:String, descr:String) { self.purchaseId = purchaseId self.title = title self.descr = descr status = MStoreStatusNotAvailable() } //MARK: public func purchaseAction() { } func buyingError() -> String? { return nil } func validatePurchase() -> Bool { return false } //MARK: final final func foundPurchase(price:String) { self.price = price let isPurchased:Bool = validatePurchase() if isPurchased { statusPurchased(callAction:false) } else { statusNew() } } final func statusNew() { status = MStoreStatusNew() } final func statusDeferred() { status = MStoreStatusDeferred() } final func statusPurchasing() { status = MStoreStatusPurchasing() } final func statusPurchased(callAction:Bool) { status = MStoreStatusPurchased() DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in if callAction { self?.purchaseAction() } } } }
9b2f1c0fdd3cf786825dfe06e5c5ebe0
17.546512
71
0.527273
false
false
false
false
ben-ng/swift
refs/heads/master
test/SILGen/auto_generated_super_init_call.swift
apache-2.0
4
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s // Test that we emit a call to super.init at the end of the initializer, when none has been previously added. class Parent { init() {} } class SomeDerivedClass : Parent { var y: Int func foo() {} override init() { y = 42 // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call16SomeDerivedClassc{{.*}} : $@convention(method) (@owned SomeDerivedClass) -> @owned SomeDerivedClass // CHECK: integer_literal $Builtin.Int2048, 42 // CHECK: [[SELFLOAD:%[0-9]+]] = load_borrow [[SELF:%[0-9]+]] : $*SomeDerivedClass // CHECK-NEXT: [[PARENT:%[0-9]+]] = upcast [[SELFLOAD]] : $SomeDerivedClass to $Parent // CHECK: [[INITCALL1:%[0-9]+]] = function_ref @_TFC30auto_generated_super_init_call6ParentcfT_S0_ : $@convention(method) (@owned Parent) -> @owned Parent // CHECK-NEXT: [[RES1:%[0-9]+]] = apply [[INITCALL1]]([[PARENT]]) // CHECK-NEXT: [[DOWNCAST:%[0-9]+]] = unchecked_ref_cast [[RES1]] : $Parent to $SomeDerivedClass // CHECK-NEXT: store [[DOWNCAST]] to [init] [[SELF]] : $*SomeDerivedClass } init(x: Int) { y = x // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call16SomeDerivedClassc{{.*}} : $@convention(method) (Int, @owned SomeDerivedClass) -> @owned SomeDerivedClass // CHECK: function_ref @_TFC30auto_generated_super_init_call6ParentcfT_S0_ : $@convention(method) (@owned Parent) -> @owned Parent } init(b: Bool) { if b { y = 0 return } else { y = 10 } return // Check that we are emitting the super.init expr into the epilog block. // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call16SomeDerivedClassc{{.*}} : $@convention(method) (Bool, @owned SomeDerivedClass) -> @owned SomeDerivedClass // CHECK: bb4: // SEMANTIC ARC TODO: Another case of needing a mutable load_borrow. // CHECK: [[SELFLOAD:%[0-9]+]] = load_borrow [[SELF:%[0-9]+]] : $*SomeDerivedClass // CHECK: [[SELFLOAD_PARENT_CAST:%.*]] = upcast [[SELFLOAD]] // CHECK: [[PARENT_INIT:%.*]] = function_ref @_TFC30auto_generated_super_init_call6ParentcfT_S0_ : $@convention(method) (@owned Parent) -> @owned Parent, // CHECK: [[PARENT:%.*]] = apply [[PARENT_INIT]]([[SELFLOAD_PARENT_CAST]]) // CHECK: [[SELFAGAIN:%.*]] = unchecked_ref_cast [[PARENT]] // CHECK: store [[SELFAGAIN]] to [init] [[SELF]] // CHECK: [[SELFLOAD:%.*]] = load [copy] [[SELF]] // CHECK: destroy_value // CHECK: return [[SELFLOAD]] } // CHECK: } // end sil function '_TFC30auto_generated_super_init_call16SomeDerivedClassc{{.*}}' // One init has a call to super init. Make sure we don't insert more than one. init(b: Bool, i: Int) { if (b) { y = i } else { y = 0 } super.init() // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call16SomeDerivedClassc{{.*}} : $@convention(method) (Bool, Int, @owned SomeDerivedClass) -> @owned SomeDerivedClass // CHECK: function_ref @_TFC30auto_generated_super_init_call6ParentcfT_S0_ : $@convention(method) (@owned Parent) -> @owned Parent // CHECK: return } } // Check that we do call super.init. class HasNoIVars : Parent { override init() { // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call10HasNoIVarsc{{.*}} : $@convention(method) (@owned HasNoIVars) -> @owned HasNoIVars // CHECK: function_ref @_TFC30auto_generated_super_init_call6ParentcfT_S0_ : $@convention(method) (@owned Parent) -> @owned Parent } } // Check that we don't call super.init. class ParentLess { var y: Int init() { y = 0 } } class Grandparent { init() {} } // This should have auto-generated default initializer. class ParentWithNoExplicitInit : Grandparent { } // Check that we add a call to super.init. class ChildOfParentWithNoExplicitInit : ParentWithNoExplicitInit { var y: Int override init() { y = 10 // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call31ChildOfParentWithNoExplicitInitc // CHECK: function_ref @_TFC30auto_generated_super_init_call24ParentWithNoExplicitInitcfT_S0_ : $@convention(method) (@owned ParentWithNoExplicitInit) -> @owned ParentWithNoExplicitInit } } // This should have auto-generated default initializer. class ParentWithNoExplicitInit2 : Grandparent { var i: Int = 0 } // Check that we add a call to super.init. class ChildOfParentWithNoExplicitInit2 : ParentWithNoExplicitInit2 { var y: Int override init() { y = 10 // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call32ChildOfParentWithNoExplicitInit2c // CHECK: function_ref @_TFC30auto_generated_super_init_call25ParentWithNoExplicitInit2cfT_S0_ : $@convention(method) (@owned ParentWithNoExplicitInit2) -> @owned ParentWithNoExplicitInit2 } } // Do not insert the call nor warn - the user should call init(5). class ParentWithNoDefaultInit { var i: Int init(x: Int) { i = x } } class ChildOfParentWithNoDefaultInit : ParentWithNoDefaultInit { var y: Int init() { // CHECK-LABEL: sil hidden @_TFC30auto_generated_super_init_call30ChildOfParentWithNoDefaultInitc{{.*}} : $@convention(method) (@owned ChildOfParentWithNoDefaultInit) -> @owned ChildOfParentWithNoDefaultInit // CHECK: bb0 // CHECK-NOT: apply // CHECK: return } }
60129c9a623eb1628a164702fa4e8448
38.340909
207
0.68939
false
false
false
false
Crowdmix/Buildasaur
refs/heads/master
Buildasaur/UIUtils.swift
mit
4
// // UIUtils.swift // Buildasaur // // Created by Honza Dvorsky on 07/03/2015. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation import AppKit import BuildaUtils public class UIUtils { public class func showAlertWithError(error: NSError) { let alert = self.createErrorAlert(error) self.presentAlert(alert, completion: { (resp) -> () in // }) } public class func showAlertAskingForRemoval(text: String, completion: (remove: Bool) -> ()) { let removeText = "Remove" let buttons = ["Cancel", removeText] self.showAlertWithButtons(text, buttons: buttons) { (tappedButton) -> () in completion(remove: removeText == tappedButton) } } public class func showAlertWithButtons(text: String, buttons: [String], completion: (tappedButton: String) -> ()) { let alert = self.createAlert(text, style: nil) buttons.forEach { alert.addButtonWithTitle($0) } self.presentAlert(alert, completion: { (resp) -> () in //some magic where indices are starting at 1000... so subtract 1000 to get the array index of tapped button let idx = resp - NSAlertFirstButtonReturn let buttonText = buttons[idx] completion(tappedButton: buttonText) }) } public class func showAlertWithText(text: String, style: NSAlertStyle? = nil, completion: ((NSModalResponse) -> ())? = nil) { let alert = self.createAlert(text, style: style) self.presentAlert(alert, completion: completion) } private class func createErrorAlert(error: NSError) -> NSAlert { return NSAlert(error: error) } private class func createAlert(text: String, style: NSAlertStyle?) -> NSAlert { let alert = NSAlert() alert.alertStyle = style ?? .InformationalAlertStyle alert.messageText = text return alert } private class func presentAlert(alert: NSAlert, completion: ((NSModalResponse) -> ())?) { if let _ = NSApp.windows.first { let resp = alert.runModal() completion?(resp) // alert.beginSheetModalForWindow(window, completionHandler: completion) } else { //no window to present in, at least print Log.info("Alert: \(alert.messageText)") } } }
3301f335e595decdad819dda6d86051e
30.974359
129
0.597434
false
false
false
false
thisfin/HostsManager
refs/heads/develop
HostsManager/AlertPanel.swift
mit
1
// // AlertPanel.swift // HostsManager // // Created by wenyou on 2017/7/1. // Copyright © 2017年 wenyou. All rights reserved. // import AppKit import SnapKit class AlertPanel { static func show(_ content: String, fontSize: CGFloat = 32) { let font = NSFont.systemFont(ofSize: fontSize) let size = (content as NSString).size(withAttributes: [NSFontAttributeName: font]) let panel = NSPanel(contentRect: NSMakeRect(0, 0, size.width + 100, size.height + 40), styleMask: [.borderless, .hudWindow], backing: .buffered, defer: true) let textField = NSTextField.init(frame: panel.contentLayoutRect) textField.cell = WYVerticalCenterTextFieldCell() textField.isEditable = false textField.isSelectable = false textField.isBordered = false textField.alignment = .center textField.textColor = .white textField.font = font textField.stringValue = content if let contentView = panel.contentView { // 此处做颜色和圆角的处理 contentView.addSubview(textField) contentView.wantsLayer = true contentView.layer?.cornerRadius = 5 contentView.layer?.backgroundColor = panel.backgroundColor.cgColor // 使用默认 hudWindow 的颜色 panel.backgroundColor = .clear } panel.center() panel.orderFront(self) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.8, execute: { // 自动关闭 panel.orderOut(self) panel.close() }) } }
63858cac35246bf919d86411f11a72d4
37.225
165
0.650098
false
false
false
false
jaouahbi/OMCircularProgress
refs/heads/master
Example/Example/OMShadingGradientLayer/Classes/OMGradientLayer.swift
apache-2.0
2
// // OMGradientLayer.swift // // Created by Jorge Ouahbi on 19/8/16. // Copyright © 2016 Jorge Ouahbi. All rights reserved. // // // Copyright 2015 - Jorge Ouahbi // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit public typealias GradientColors = (UIColor,UIColor) typealias TransformContextClosure = (_ ctx:CGContext, _ startPoint:CGPoint, _ endPoint:CGPoint, _ startRadius:CGFloat, _ endRadius:CGFloat) -> (Void) open class OMGradientLayer : CALayer, OMGradientLayerProtocol { // MARK: - OMColorsAndLocationsProtocol @objc open var colors: [UIColor] = [] { didSet { // if only exist one color, duplicate it. if (colors.count == 1) { let color = colors.first! colors = [color, color]; } // map monochrome colors to rgba colors colors = colors.map({ return ($0.colorSpace?.model == .monochrome) ? UIColor(red: $0.components[0], green : $0.components[0], blue : $0.components[0], alpha : $0.components[1]) : $0 }) self.setNeedsDisplay() } } @objc open var locations : [CGFloat]? = nil { didSet { if locations != nil{ locations!.sort { $0 < $1 } } self.setNeedsDisplay() } } open var isAxial : Bool { return (gradientType == .axial) } open var isRadial : Bool { return (gradientType == .radial) } // MARK: - OMAxialGradientLayerProtocol open var gradientType :OMGradientType = .axial { didSet { self.setNeedsDisplay(); } } @objc open var startPoint: CGPoint = CGPoint(x: 0.0, y: 0.5) { didSet { self.setNeedsDisplay(); } } @objc open var endPoint: CGPoint = CGPoint(x: 1.0, y: 0.5) { didSet{ self.setNeedsDisplay(); } } open var extendsBeforeStart : Bool = false { didSet { self.setNeedsDisplay() } } open var extendsPastEnd : Bool = false { didSet { self.setNeedsDisplay() } } // MARK: - OMRadialGradientLayerProtocol @objc open var startRadius: CGFloat = 0 { didSet { startRadius = clamp(startRadius, lower: 0, upper: 1.0) self.setNeedsDisplay(); } } @objc open var endRadius: CGFloat = 0 { didSet { endRadius = clamp(endRadius, lower: 0, upper: 1.0) self.setNeedsDisplay(); } } // MARK: OMMaskeableLayerProtocol open var lineWidth : CGFloat = 1.0 { didSet { self.setNeedsDisplay() } } open var stroke : Bool = false { didSet { self.setNeedsDisplay() } } open var path: CGPath? { didSet { self.setNeedsDisplay() } } /// Transform the radial gradient /// example: oval gradient = CGAffineTransform(scaleX: 2, y: 1.0); open var radialTransform: CGAffineTransform = CGAffineTransform.identity { didSet { self.setNeedsDisplay() } } // Some predefined Gradients (from WebKit) public lazy var insetGradient:GradientColors = { return (UIColor(red:0 / 255.0, green:0 / 255.0,blue: 0 / 255.0,alpha: 0 ), UIColor(red: 0 / 255.0, green:0 / 255.0,blue: 0 / 255.0,alpha: 0.2 )) }() public lazy var shineGradient:GradientColors = { return (UIColor(red:1, green:1,blue: 1,alpha: 0 ), UIColor(red: 1, green:1,blue:1,alpha: 0.8 )) }() public lazy var shadeGradient:GradientColors = { return (UIColor(red: 252 / 255.0, green: 252 / 255.0,blue: 252 / 255.0,alpha: 0.65 ), UIColor(red: 178 / 255.0, green:178 / 255.0,blue: 178 / 255.0,alpha: 0.65 )) }() public lazy var convexGradient:GradientColors = { return (UIColor(red:1,green:1,blue:1,alpha: 0.43 ), UIColor(red:1,green:1,blue:1,alpha: 0.5 )) }() public lazy var concaveGradient:GradientColors = { return (UIColor(red:1,green:1,blue:1,alpha: 0.0 ), UIColor(red:1,green:1,blue:1,alpha: 0.46 )) }() // Here's a method that creates a view that allows 360 degree rotation of its two-colour // gradient based upon input from a slider (or anything). The incoming slider value // ("x" variable below) is between 0.0 and 1.0. // // At 0.0 the gradient is horizontal (with colour A on top, and colour B below), rotating // through 360 degrees to value 1.0 (identical to value 0.0 - or a full rotation). // // E.g. when x = 0.25, colour A is left and colour B is right. At 0.5, colour A is below // and colour B is above, 0.75 colour A is right and colour B is left. It rotates anti-clockwise // from right to left. // // It takes four arguments: frame, colourA, colourB and the input value (0-1). // // from: http://stackoverflow.com/a/29168654/6387073 public class func pointsFromNormalizedAngle(_ normalizedAngle:Double) -> (CGPoint,CGPoint) { //x is between 0 and 1, eg. from a slider, representing 0 - 360 degrees //colour A starts on top, with colour B below //rotations move anti-clockwise //create coordinates let r = 2.0 * .pi; let a = pow(sin((r*((normalizedAngle+0.75)/2))),2); let b = pow(sin((r*((normalizedAngle+0.0)/2))),2); let c = pow(sin((r*((normalizedAngle+0.25)/2))),2); let d = pow(sin((r*((normalizedAngle+0.5)/2))),2); //set the gradient direction return (CGPoint(x: a, y: b),CGPoint(x: c, y: d)) } // MARK: - Object constructors required public init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } convenience public init(type:OMGradientType) { self.init() self.gradientType = type } // MARK: - Object Overrides override public init() { super.init() self.allowsEdgeAntialiasing = true self.contentsScale = UIScreen.main.scale self.needsDisplayOnBoundsChange = true; self.drawsAsynchronously = true; } override public init(layer: Any) { super.init(layer: layer) if let other = layer as? OMGradientLayer { // common self.colors = other.colors self.locations = other.locations self.gradientType = other.gradientType // axial gradient properties self.startPoint = other.startPoint self.endPoint = other.endPoint self.extendsBeforeStart = other.extendsBeforeStart self.extendsPastEnd = other.extendsPastEnd // radial gradient properties self.startRadius = other.startRadius self.endRadius = other.endRadius // OMMaskeableLayerProtocol self.path = other.path self.stroke = other.stroke self.lineWidth = other.lineWidth self.radialTransform = other.radialTransform } } // MARK: - Functions override open class func needsDisplay(forKey event: String) -> Bool { if (event == OMGradientLayerProperties.startPoint || event == OMGradientLayerProperties.locations || event == OMGradientLayerProperties.colors || event == OMGradientLayerProperties.endPoint || event == OMGradientLayerProperties.startRadius || event == OMGradientLayerProperties.endRadius) { return true } return super.needsDisplay(forKey: event) } override open func action(forKey event: String) -> CAAction? { if (event == OMGradientLayerProperties.startPoint || event == OMGradientLayerProperties.locations || event == OMGradientLayerProperties.colors || event == OMGradientLayerProperties.endPoint || event == OMGradientLayerProperties.startRadius || event == OMGradientLayerProperties.endRadius) { return animationActionForKey(event); } return super.action(forKey: event) } override open func draw(in ctx: CGContext) { // super.drawInContext(ctx) do nothing let clipBoundingBox = ctx.boundingBoxOfClipPath ctx.clear(clipBoundingBox); ctx.clip(to: clipBoundingBox) } func prepareContextIfNeeds(_ ctx:CGContext, scale:CGAffineTransform, closure:TransformContextClosure) { let sp = self.startPoint * self.bounds.size let ep = self.endPoint * self.bounds.size let mr = minRadius(self.bounds.size) // Scaling transformation and keeping track of the inverse let invScaleT = scale.inverted(); // Extract the Sx and Sy elements from the inverse matrix (See the Quartz documentation for the math behind the matrices) let invS = CGPoint(x:invScaleT.a, y:invScaleT.d); // Transform center and radius of gradient with the inverse let startPointAffined = CGPoint(x:sp.x * invS.x, y:sp.y * invS.y); let endPointAffined = CGPoint(x:ep.x * invS.x, y:ep.y * invS.y); let startRadiusAffined = mr * startRadius * invS.x; let endRadiusAffined = mr * endRadius * invS.x; // Draw the gradient with the scale transform on the context ctx.scaleBy(x: scale.a, y: scale.d); closure(ctx, startPointAffined, endPointAffined, startRadiusAffined, endRadiusAffined) // Reset the context ctx.scaleBy(x: invS.x, y: invS.y); } func addPathAndClipIfNeeded(_ ctx:CGContext) { if (self.path != nil) { ctx.addPath(self.path!); if (self.stroke) { ctx.setLineWidth(self.lineWidth); ctx.replacePathWithStrokedPath(); } ctx.clip(); } } func isDrawable() -> Bool { if (colors.count == 0) { // nothing to do Log.v("\(self.name ?? "") Unable to do the shading without colors.") return false } if (startPoint.isZero && endPoint.isZero) { // nothing to do Log.v("\(self.name ?? "") Start point and end point are {x:0, y:0}.") return false } if (startRadius == endRadius && self.isRadial) { // nothing to do Log.v("\(self.name ?? "") Start radius and end radius are equal. \(startRadius) \(endRadius)") return false } return true; } override open var description:String { get { var currentDescription:String = "type: \((self.isAxial ? "Axial" : "Radial")) " if let locations = locations { if(locations.count == colors.count) { _ = zip(colors,locations).compactMap { currentDescription += "color: \($0.0.shortDescription) location: \($0.1) " } } else { if (locations.count > 0) { _ = locations.map({currentDescription += "\($0) "}) } if (colors.count > 0) { _ = colors.map({currentDescription += "\($0.shortDescription) "}) } } } if (self.isRadial) { currentDescription += "center from : \(startPoint) to \(endPoint), radius from : \(startRadius) to \(endRadius)" } else if (self.isAxial) { currentDescription += "from : \(startPoint) to \(endPoint)" } if (self.extendsPastEnd) { currentDescription += " draws after end location " } if (self.extendsBeforeStart) { currentDescription += " draws before start location " } return currentDescription } } }
881085b8673b011e54ae4b55b6cf75c8
34.091153
150
0.551455
false
false
false
false
hsavit1/LeetCode-Solutions-in-Swift
refs/heads/master
Solutions/Solutions/Medium/Medium_059_Spiral_Matrix_II.swift
mit
4
/* https://leetcode.com/problems/spiral-matrix-ii/ #59 Spiral Matrix II Level: medium Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] Inspired by @yike at https://leetcode.com/discuss/21677/simple-c-solution-with-explaination */ import Foundation struct Medium_059_Spiral_Matrix_II { static func generateMatrix(n: Int) -> [[Int]] { var res = Array<[Int]>(count: n, repeatedValue: Array<Int>(count: n, repeatedValue: 0)) var k = 1 var i = 0 while k <= n * n { var j = i while j < n - i { res[i][j++] = k++ } j = i + 1 while j < n - i { res[j++][n-i-1] = k++ } j = n - i - 2 while j > i { res[n-i-1][j--] = k++ } j = n - i - 1 while j > i { res[j--][i] = k++ } i++ } return res } }
b62d35dc5f63a4fd90fabdb09e2af304
20.169811
95
0.458519
false
false
false
false
ianyh/Amethyst
refs/heads/development
Amethyst/Managers/WindowTransitionCoordinator.swift
mit
1
// // WindowTransitionCoordinator.swift // Amethyst // // Created by Ian Ynda-Hummel on 3/24/19. // Copyright © 2019 Ian Ynda-Hummel. All rights reserved. // import Cocoa import Foundation import Silica enum WindowTransition<Window: WindowType> { typealias Screen = Window.Screen case switchWindows(_ window1: Window, _ window2: Window) case moveWindowToScreen(_ window: Window, screen: Screen) case moveWindowToSpaceAtIndex(_ window: Window, spaceIndex: Int) case resetFocus } protocol WindowTransitionTarget: class { associatedtype Application: ApplicationType typealias Window = Application.Window typealias Screen = Window.Screen func executeTransition(_ transition: WindowTransition<Window>) func isWindowFloating(_ window: Window) -> Bool func currentLayout() -> Layout<Application.Window>? func screen(at index: Int) -> Screen? func activeWindows(on screen: Screen) -> [Window] func nextScreenIndexClockwise(from screen: Screen) -> Int func nextScreenIndexCounterClockwise(from screen: Screen) -> Int } class WindowTransitionCoordinator<Target: WindowTransitionTarget> { typealias Window = Target.Window typealias Screen = Window.Screen weak var target: Target? init() {} func swapFocusedWindowToMain() { guard let focusedWindow = Window.currentlyFocused(), target?.isWindowFloating(focusedWindow) == false, let screen = focusedWindow.screen() else { return } guard let windows = target?.activeWindows(on: screen), let focusedIndex = windows.index(of: focusedWindow) else { return } if windows.count <= 1 { return } if focusedIndex == 0 && target?.currentLayout()?.layoutKey == TwoPaneLayout<Window>.layoutKey { // If main window is focused and layout is two-pane - swap the two top-most windows, keep focus on the main window target?.executeTransition(.switchWindows(focusedWindow, windows[1])) windows[1].focus() return } if focusedIndex != 0 { // Swap focused window with main window if other window is focused target?.executeTransition(.switchWindows(focusedWindow, windows[0])) } } func swapFocusedWindowCounterClockwise() { guard let focusedWindow = Window.currentlyFocused(), target?.isWindowFloating(focusedWindow) == false else { target?.executeTransition(.resetFocus) return } guard let screen = focusedWindow.screen() else { return } guard let windows = target?.activeWindows(on: screen), let focusedWindowIndex = windows.index(of: focusedWindow) else { return } let windowToSwapWith = windows[(focusedWindowIndex == 0 ? windows.count - 1 : focusedWindowIndex - 1)] target?.executeTransition(.switchWindows(focusedWindow, windowToSwapWith)) } func swapFocusedWindowClockwise() { guard let focusedWindow = Window.currentlyFocused(), target?.isWindowFloating(focusedWindow) == false else { target?.executeTransition(.resetFocus) return } guard let screen = focusedWindow.screen() else { return } guard let windows = target?.activeWindows(on: screen), let focusedWindowIndex = windows.index(of: focusedWindow) else { return } let windowToSwapWith = windows[(focusedWindowIndex + 1) % windows.count] target?.executeTransition(.switchWindows(focusedWindow, windowToSwapWith)) } func throwToScreenAtIndex(_ screenIndex: Int) { guard let screen = target?.screen(at: screenIndex), let focusedWindow = Window.currentlyFocused() else { return } // If the window is already on the screen do nothing. guard let focusedScreen = focusedWindow.screen(), focusedScreen.screenID() != screen.screenID() else { return } target?.executeTransition(.moveWindowToScreen(focusedWindow, screen: screen)) } func swapFocusedWindowScreenClockwise() { guard let focusedWindow = Window.currentlyFocused(), target?.isWindowFloating(focusedWindow) == false else { target?.executeTransition(.resetFocus) return } guard let screen = focusedWindow.screen() else { return } guard let nextScreenIndex = target?.nextScreenIndexClockwise(from: screen), let nextScreen = target?.screen(at: nextScreenIndex) else { return } target?.executeTransition(.moveWindowToScreen(focusedWindow, screen: nextScreen)) } func swapFocusedWindowScreenCounterClockwise() { guard let focusedWindow = Window.currentlyFocused(), target?.isWindowFloating(focusedWindow) == false else { target?.executeTransition(.resetFocus) return } guard let screen = focusedWindow.screen() else { return } guard let nextScreenIndex = target?.nextScreenIndexCounterClockwise(from: screen), let nextScreen = target?.screen(at: nextScreenIndex) else { return } target?.executeTransition(.moveWindowToScreen(focusedWindow, screen: nextScreen)) } func pushFocusedWindowToSpace(_ space: Int) { guard let focusedWindow = Window.currentlyFocused(), focusedWindow.screen() != nil else { return } target?.executeTransition(.moveWindowToSpaceAtIndex(focusedWindow, spaceIndex: space)) } func pushFocusedWindowToSpaceLeft() { guard let currentFocusedSpace = CGSpacesInfo<Window>.currentFocusedSpace(), let spaces = CGSpacesInfo<Window>.spacesForFocusedScreen() else { return } guard let index = spaces.index(of: currentFocusedSpace), index > 0 else { return } pushFocusedWindowToSpace(index - 1) } func pushFocusedWindowToSpaceRight() { guard let currentFocusedSpace = CGSpacesInfo<Window>.currentFocusedSpace(), let spaces = CGSpacesInfo<Window>.spacesForFocusedScreen() else { return } guard let index = spaces.index(of: currentFocusedSpace), index + 1 < spaces.count else { return } pushFocusedWindowToSpace(index + 1) } }
888559eeccc89b52929e7f8ee57e486f
33.446237
153
0.659435
false
false
false
false
CallMeMrAlex/DYTV
refs/heads/master
DYTV-AlexanderZ-Swift/DYTV-AlexanderZ-Swift/Classes/Home(首页)/View/AmuseMenuView.swift
mit
1
// // AmuseMenuView.swift // DYTV-AlexanderZ-Swift // // Created by Alexander Zou on 2016/10/17. // Copyright © 2016年 Alexander Zou. All rights reserved. // import UIKit private let kMenuCellID = "kMenuCellID" class AmuseMenuView: UIView { var groups : [AnchorGroupModel]? { didSet { collectionView.reloadData() } } @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! override func awakeFromNib() { super.awakeFromNib() collectionView.register(UINib(nibName: "AmuseMenuViewCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size } } extension AmuseMenuView { class func amuseMenuView() -> AmuseMenuView { return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView } } extension AmuseMenuView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if groups == nil { return 0 } let pageNum = (groups!.count - 1) / 8 + 1 pageControl.numberOfPages = pageNum return pageNum } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! AmuseMenuViewCell setupCellDataWithCell(cell, indexPath: indexPath) return cell } fileprivate func setupCellDataWithCell(_ cell : AmuseMenuViewCell, indexPath : IndexPath) { // 0页: 0 ~ 7 // 1页: 8 ~ 15 // 2页: 16 ~ 23 // 取出起始位置&终点位置 let startIndex = indexPath.item * 8 var endIndex = (indexPath.item + 1) * 8 - 1 // 判断越界问题 if endIndex > groups!.count - 1 { endIndex = groups!.count - 1 } cell.groups = Array(groups![startIndex...endIndex]) } } extension AmuseMenuView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width) } }
9352400e26d63b53569e3c552d5020d0
25.670213
125
0.644994
false
false
false
false
ccrama/Slide-iOS
refs/heads/master
Slide for Reddit/ShadowboxViewController.swift
apache-2.0
1
// // ShadowboxViewController.swift // Slide for Reddit // // Created by Carlos Crane on 8/5/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import Anchorage import AVKit import reddift import UIKit class ShadowboxViewController: SwipeDownModalVC, UIPageViewControllerDataSource, UIPageViewControllerDelegate { var submissionDataSource: SubmissionsDataSource var index: Int func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { color2 = (pendingViewControllers[0] as! ShadowboxLinkViewController).backgroundColor color1 = (currentVc as! ShadowboxLinkViewController).backgroundColor } func getURLToLoad(_ submission: RSubmission) -> URL? { let url = submission.url if url != nil && ContentType.isGif(uri: url!) { if !submission.videoPreview.isEmpty() && !ContentType.isGfycat(uri: url!) { return URL.init(string: submission.videoPreview)! } else { return url! } } else { return url } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) DispatchQueue.global(qos: .background).async { do { try AVAudioSession.sharedInstance().setCategory(.ambient, options: [.mixWithOthers]) try AVAudioSession.sharedInstance().setActive(false, options: AVAudioSession.SetActiveOptions.notifyOthersOnDeactivation) } catch { NSLog(error.localizedDescription) } } } public init(index: Int, submissionDataSource: SubmissionsDataSource) { self.submissionDataSource = submissionDataSource self.index = index super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.automaticallyAdjustsScrollViewInsets = false self.edgesForExtendedLayout = UIRectEdge.all self.extendedLayoutIncludesOpaqueBars = true submissionDataSource.delegate = self } var navItem: UINavigationItem? @objc func exit() { self.dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() self.dataSource = self self.delegate = self view.backgroundColor = UIColor.black.withAlphaComponent(0.7) self.navigationController?.view.backgroundColor = UIColor.clear viewToMux = self.background let s = submissionDataSource.content[index] let firstViewController = ShadowboxLinkViewController(url: self.getURLToLoad(s), content: s, parent: self) currentVc = firstViewController (currentVc as! ShadowboxLinkViewController).populateContent() self.setViewControllers([firstViewController], direction: .forward, animated: true, completion: { [weak self](_) in guard let self = self else { return } if (self.currentVc as! ShadowboxLinkViewController).embeddedVC == nil { self.viewToMove = (self.currentVc as! ShadowboxLinkViewController).thumbImageContainer.superview } else { self.viewToMove = (self.currentVc as! ShadowboxLinkViewController).embeddedVC.view } }) } @objc func color() { SettingValues.blackShadowbox = !SettingValues.blackShadowbox UserDefaults.standard.set(SettingValues.blackShadowbox, forKey: SettingValues.pref_blackShadowbox) UserDefaults.standard.synchronize() if SettingValues.blackShadowbox { UIView.animate(withDuration: 0.25) { self.background?.backgroundColor = .black } } else { (currentVc as! ShadowboxLinkViewController).doBackground() } } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating: Bool, previousViewControllers: [UIViewController], transitionCompleted: Bool) { guard didFinishAnimating else { return } currentVc = self.viewControllers!.first! if (self.currentVc as! ShadowboxLinkViewController).embeddedVC == nil { self.viewToMove = (self.currentVc as! ShadowboxLinkViewController).topBody } else { self.viewToMove = (self.currentVc as! ShadowboxLinkViewController).embeddedVC.view } } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { let id = (viewController as! ShadowboxLinkViewController).submission.getId() var viewControllerIndex = -1 for item in submissionDataSource.content { viewControllerIndex += 1 if item.getId() == id { break } } if viewControllerIndex < 0 || viewControllerIndex > submissionDataSource.content.count { return nil } var previousIndex = viewControllerIndex - 1 guard previousIndex >= 0 else { return nil } guard submissionDataSource.content.count > previousIndex else { return nil } if submissionDataSource.content[previousIndex].author == "PAGE_SEPARATOR" { previousIndex -= 1 } let s = submissionDataSource.content[previousIndex] let shadowbox = ShadowboxLinkViewController(url: self.getURLToLoad(s), content: s, parent: self) if !shadowbox.populated { shadowbox.populated = true shadowbox.populateContent() } return shadowbox } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { let id = (viewController as! ShadowboxLinkViewController).submission.getId() var viewControllerIndex = -1 for item in submissionDataSource.content { viewControllerIndex += 1 if item.getId() == id { break } } if viewControllerIndex < 0 || viewControllerIndex > submissionDataSource.content.count { return nil } var nextIndex = viewControllerIndex + 1 let orderedViewControllersCount = submissionDataSource.content.count guard orderedViewControllersCount != nextIndex else { return nil } guard orderedViewControllersCount > nextIndex else { return nil } if submissionDataSource.content[nextIndex].author == "PAGE_SEPARATOR" { nextIndex += 1 } if nextIndex == submissionDataSource.content.count - 2 && !submissionDataSource.loading { DispatchQueue.main.async { self.submissionDataSource.getData(reload: false) } } let s = submissionDataSource.content[nextIndex] let shadowbox = ShadowboxLinkViewController(url: self.getURLToLoad(s), content: s, parent: self) if !shadowbox.populated { shadowbox.populated = true shadowbox.populateContent() } return shadowbox } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } var selected = false var currentVc = UIViewController() override var prefersHomeIndicatorAutoHidden: Bool { return true } } extension ShadowboxViewController: SubmissionDataSouceDelegate { func showIndicator() { } func generalError(title: String, message: String) { } func loadSuccess(before: Int, count: Int) { DispatchQueue.main.async { self.setViewControllers([self.currentVc], direction: .forward, animated: false, completion: nil) } } func preLoadItems() { } func doPreloadImages(values: [RSubmission]) { } func loadOffline() { } func emptyState(_ listing: Listing) { } func vcIsGallery() -> Bool { return false } } private var hasSwizzled = false extension UIPanGestureRecognizer { final public class func swizzle() { guard !hasSwizzled else { return } hasSwizzled = true guard self === UIPanGestureRecognizer.self else { return } func replace(_ method: Selector, with anotherMethod: Selector, for clаss: AnyClass) { let original = class_getInstanceMethod(clаss, method) let swizzled = class_getInstanceMethod(clаss, anotherMethod) switch class_addMethod(clаss, method, method_getImplementation(swizzled!), method_getTypeEncoding(swizzled!)) { case true: class_replaceMethod(clаss, anotherMethod, method_getImplementation(original!), method_getTypeEncoding(original!)) case false: method_exchangeImplementations(original!, swizzled!) } } let selector1 = #selector(UIPanGestureRecognizer.touchesBegan(_:with:)) let selector2 = #selector(UIPanGestureRecognizer.swizzling_touchesBegan(_:with:)) replace(selector1, with: selector2, for: self) let selector3 = #selector(UIPanGestureRecognizer.touchesMoved(_:with:)) let selector4 = #selector(UIPanGestureRecognizer.swizzling_touchesMoved(_:with:)) replace(selector3, with: selector4, for: self) } @objc private func swizzling_touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) { self.swizzling_touchesBegan(touches, with: event) guard direction != nil else { return } touchesBegan = true } @objc private func swizzling_touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) { self.swizzling_touchesMoved(touches, with: event) guard let direction = direction, touchesBegan == true else { return } defer { touchesBegan = false } let forbiddenDirectionsCount = touches .compactMap({ ($0.location(in: $0.view) - $0.previousLocation(in: $0.view)).direction }) .filter({ $0 != direction }) .count if forbiddenDirectionsCount > 0 { state = .failed } } } public extension UIPanGestureRecognizer { enum Direction: Int { case horizontal = 0 case vertical } private struct UIPanGestureRecognizerRuntimeKeys { static var directions = "\(#file)+\(#line)" static var touchesBegan = "\(#file)+\(#line)" } var direction: UIPanGestureRecognizer.Direction? { get { let object = objc_getAssociatedObject(self, &UIPanGestureRecognizerRuntimeKeys.directions) return object as? UIPanGestureRecognizer.Direction } set { let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC objc_setAssociatedObject(self, &UIPanGestureRecognizerRuntimeKeys.directions, newValue, policy) } } private var touchesBegan: Bool { get { let object = objc_getAssociatedObject(self, &UIPanGestureRecognizerRuntimeKeys.touchesBegan) return (object as? Bool) ?? false } set { let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC objc_setAssociatedObject(self, &UIPanGestureRecognizerRuntimeKeys.touchesBegan, newValue, policy) } } } private extension CGPoint { var direction: UIPanGestureRecognizer.Direction? { guard self != .zero else { return nil } switch abs(x) > abs(y) { case true: return .horizontal case false: return .vertical } } static func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y) } }
1e99a765c548db710902c9f441673f35
34.20274
171
0.606818
false
false
false
false
kyleweiner/KWButtonNode
refs/heads/master
Demo/KWButtonNodeDemo/Controllers/GameViewController.swift
mit
1
// // GameViewController.swift // Created by Kyle Weiner on 4/18/15. // import UIKit import SpriteKit class GameViewController: UIViewController { override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() let skview = view as! SKView skview.ignoresSiblingOrder = true skview.multipleTouchEnabled = true if let scene = GameScene(fileNamed: "GameScene") { scene.scaleMode = .AspectFill scene.blendMode = .Replace skview.presentScene(scene) } #if DEBUG skview.showsFPS = true skview.showsDrawCount = true skview.showsNodeCount = true #endif } }
267e4ea5bf83231f00903e0d0dc53b1d
22.181818
58
0.60733
false
false
false
false
MillmanY/MMPlayerView
refs/heads/master
MMPlayerView/Classes/Extension/MMPlayer+String+SRTTime.swift
mit
1
// // String+SRTTime.swift // MMPlayerView // // Created by Millman on 2019/12/9. // import Foundation extension String { var timeToInterval: TimeInterval { let split = self.split(separator: ",") let count = split.count if count == 0 { return 0 } else if count == 2 { let time = split[0] let hms = time.split(separator: ":") if hms.count == 3 { let h = (Double(String(hms[0])) ?? 0)*3600 let m = (Double(String(hms[1])) ?? 0)*60 let s = (Double(String(hms[2])) ?? 0) let mile = (Double(String(split[1])) ?? 0)/1000 return h+m+s+mile } } return 0 } var splitSRTTime: ClosedRange<TimeInterval> { let slice = self.components(separatedBy: CharacterSet.whitespaces) if slice.count == 3 { return slice[0].timeToInterval...slice[2].timeToInterval } return 0...0 } }
81223afa2e40a87dc735cc3f6a2bc60e
27.111111
74
0.507905
false
false
false
false
ZeldaIV/TDC2015-FP
refs/heads/master
Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift
gpl-3.0
13
// // UIBarButtonItem.swift // RxCocoa // // Created by Daniel Tartaglia on 5/31/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift #endif extension UIBarButtonItem { /** Reactive wrapper for target action pattern on `self`. */ public var rx_tap: ControlEvent<Void> { let source: Observable<Void> = AnonymousObservable { observer in let target = BarButtonItemTarget(barButtonItem: self) { observer.on(.Next()) } return target }.takeUntil(rx_deallocated) return ControlEvent(source: source) } } @objc class BarButtonItemTarget: NSObject, Disposable { typealias Callback = () -> Void weak var barButtonItem: UIBarButtonItem? var callback: Callback! init(barButtonItem: UIBarButtonItem, callback: () -> Void) { self.barButtonItem = barButtonItem self.callback = callback super.init() barButtonItem.target = self barButtonItem.action = Selector("action:") } deinit { dispose() } func dispose() { MainScheduler.ensureExecutingOnScheduler() barButtonItem?.target = nil barButtonItem?.action = nil callback = nil } func action(sender: AnyObject) { callback() } }
358cd8c418adfd0e8fe1974863eab1b2
20.861538
72
0.596479
false
false
false
false
MangoMade/MMSegmentedControl
refs/heads/master
Source/Extension.swift
mit
1
// // Extension.swift // MMSegmentedControl // // Created by Aqua on 2017/4/25. // Copyright © 2017年 Aqua. All rights reserved. // internal extension UIImage { static func image(color: UIColor) -> UIImage { let size = CGSize(width: 1, height: 1) let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setFill() UIRectFill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } internal extension String { func getTextRectSize(font:UIFont, size:CGSize) -> CGRect { let attributes = [NSAttributedStringKey.font: font] let rect:CGRect = self.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil) return rect; } } internal extension UIColor { convenience init(hex hexValue: Int, alpha: CGFloat = 1) { let redValue = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 let greenValue = CGFloat((hexValue & 0xFF00) >> 8) / 255.0 let blueValue = CGFloat(hexValue & 0xFF) / 255.0 self.init(red: redValue, green: greenValue, blue: blueValue, alpha: alpha) } }
f6922970879d40fb88d7baf79ac78166
30.585366
127
0.647876
false
false
false
false
googlearchive/cannonball-ios
refs/heads/master
Cannonball/Theme.swift
apache-2.0
1
// // Copyright (C) 2018 Google, Inc. and other 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 Foundation open class Theme { let name: String let words: [String] let pictures: [String] init?(jsonDictionary: [String : AnyObject]) { if let optionalName = jsonDictionary["name"] as? String, let optionalWords = jsonDictionary["words"] as? [String], let optionalPictures = jsonDictionary["pictures"] as? [String] { name = optionalName words = optionalWords pictures = optionalPictures } else { name = "" words = [] pictures = [] return nil } } open func getRandomWords(_ wordCount: Int) -> [String] { var wordsCopy = [String](words) // Sort randomly the elements of the dictionary. wordsCopy.sort(by: { (_,_) in return arc4random() < arc4random() }) // Return the desired number of words. return Array(wordsCopy[0..<wordCount]) } open func getRandomPicture() -> String? { var picturesCopy = [String](pictures) // Sort randomly the pictures. picturesCopy.sort(by: { (_,_) in return arc4random() < arc4random() }) // Return the first picture. return picturesCopy.first } class func getThemes() -> [Theme] { var themes = [Theme]() let path = Bundle.main.path(forResource: "Themes", ofType: "json")! if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe), let jsonArray = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? [AnyObject] { themes = jsonArray.compactMap() { return Theme(jsonDictionary: $0 as! [String : AnyObject]) } } return themes } }
6151994cf23b0751753adb8f76d7649a
31.053333
109
0.612313
false
false
false
false
andinfinity/idrop.link-osx
refs/heads/master
JWT/JWT.swift
apache-2.0
6
import Foundation import CryptoSwift public typealias Payload = [String:AnyObject] /// The supported Algorithms public enum Algorithm : CustomStringConvertible { /// No Algorithm, i-e, insecure case None /// HMAC using SHA-256 hash algorithm case HS256(String) /// HMAC using SHA-384 hash algorithm case HS384(String) /// HMAC using SHA-512 hash algorithm case HS512(String) static func algorithm(name:String, key:String?) -> Algorithm? { if name == "none" { if key != nil { return nil // We don't allow nil when we configured a key } return Algorithm.None } else if let key = key { if name == "HS256" { return .HS256(key) } else if name == "HS384" { return .HS384(key) } else if name == "HS512" { return .HS512(key) } } return nil } public var description:String { switch self { case .None: return "none" case .HS256: return "HS256" case .HS384: return "HS384" case .HS512: return "HS512" } } /// Sign a message using the algorithm func sign(message:String) -> String { func signHS(key:String, variant:CryptoSwift.HMAC.Variant) -> String { let keyData = key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let messageData = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let mac = Authenticator.HMAC(key: keyData.arrayOfBytes(), variant:variant) let result = mac.authenticate(messageData.arrayOfBytes())! return base64encode(NSData.withBytes(result)) } switch self { case .None: return "" case .HS256(let key): return signHS(key, variant: .sha256) case .HS384(let key): return signHS(key, variant: .sha384) case .HS512(let key): return signHS(key, variant: .sha512) } } /// Verify a signature for a message using the algorithm func verify(message:String, signature:NSData) -> Bool { return sign(message) == base64encode(signature) } } // MARK: Encoding /*** Encode a payload - parameter payload: The payload to sign - parameter algorithm: The algorithm to sign the payload with - returns: The JSON web token as a String */ public func encode(payload:Payload, algorithm:Algorithm) -> String { func encodeJSON(payload:Payload) -> String? { if let data = try? NSJSONSerialization.dataWithJSONObject(payload, options: NSJSONWritingOptions(rawValue: 0)) { return base64encode(data) } return nil } let header = encodeJSON(["typ": "JWT", "alg": algorithm.description])! let payload = encodeJSON(payload)! let signingInput = "\(header).\(payload)" let signature = algorithm.sign(signingInput) return "\(signingInput).\(signature)" } public class PayloadBuilder { var payload = Payload() public var issuer:String? { get { return payload["iss"] as? String } set { payload["iss"] = newValue } } public var audience:String? { get { return payload["aud"] as? String } set { payload["aud"] = newValue } } public var expiration:NSDate? { get { if let expiration = payload["exp"] as? NSTimeInterval { return NSDate(timeIntervalSince1970: expiration) } return nil } set { payload["exp"] = newValue?.timeIntervalSince1970 } } public var notBefore:NSDate? { get { if let notBefore = payload["nbf"] as? NSTimeInterval { return NSDate(timeIntervalSince1970: notBefore) } return nil } set { payload["nbf"] = newValue?.timeIntervalSince1970 } } public var issuedAt:NSDate? { get { if let issuedAt = payload["iat"] as? NSTimeInterval { return NSDate(timeIntervalSince1970: issuedAt) } return nil } set { payload["iat"] = newValue?.timeIntervalSince1970 } } public subscript(key: String) -> AnyObject? { get { return payload[key] } set { payload[key] = newValue } } } public func encode(algorithm:Algorithm, closure:(PayloadBuilder -> ())) -> String { let builder = PayloadBuilder() closure(builder) return encode(builder.payload, algorithm: algorithm) }
94bd1e55fe3c618f16041fe077ab0f07
22.755556
116
0.637278
false
false
false
false
LarsStegman/helios-for-reddit
refs/heads/master
Sources/Authorization/AuthorizationPageLoader.swift
mit
1
// // AuthorizationPageLoader.swift // Helios // // Created by Lars Stegman on 16-01-17. // Copyright © 2017 Stegman. All rights reserved. // import Foundation protocol AuthorizationLocationCreator { func urlForAuthorization(using parameters: AuthorizationParameters) throws -> URL } protocol AuthorizationParameters { var clientId: String { get } var redirectUri: URL { get } var scopes: [Scope] { get } var preferredDuration: AuthorizationDuration { get } var sentState: String { get } var responseType: AuthorizationFlowType { get } } extension AuthorizationParameters { var scopeList: String { return scopes.map( { return $0.rawValue }).joined(separator: " ") } } extension AuthorizationContext: AuthorizationParameters {} /// Creates the URL at which users can authorize an application struct AuthorizationPageLoader: AuthorizationLocationCreator { var compact: Bool = false init(compact: Bool = false) { self.compact = compact } private var authorizationURL: URLComponents { var urlComponents = URLComponents() urlComponents.scheme = "https" urlComponents.host = "www.reddit.com" urlComponents.path = compact ? "/api/v1/authorize.compact" : "/api/v1/authorize" return urlComponents } /// Generates the url where the user can authorize the application /// /// - Parameter parameters: <#parameters description#> /// - Returns: <#return value description#> /// - Throws: <#throws value description#> func urlForAuthorization(using parameters: AuthorizationParameters) throws -> URL { guard let encodedState = parameters.sentState.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { throw AuthorizationError.invalidStateString } var url = authorizationURL url.queryItems = [URLQueryItem(name: "client_id", value: parameters.clientId), URLQueryItem(name: "response_type", value: parameters.responseType.rawValue), URLQueryItem(name: "state", value: encodedState), URLQueryItem(name: "redirect_uri", value: parameters .redirectUri.absoluteString), URLQueryItem(name: "duration", value: parameters.preferredDuration.rawValue), URLQueryItem(name: "scope", value: parameters.scopeList)] return url.url! } }
afc183ff4226dae54ef1c67cf2b6f96f
36.242424
123
0.673312
false
false
false
false
yannickl/AwaitKit
refs/heads/master
Tests/AwaitKitTests/AwaitKitAwaitTests.swift
mit
1
/* * AwaitKit * * Copyright 2016-present Yannick Loriot. * http://yannickloriot.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 AwaitKit import PromiseKit import XCTest class AwaitKitAwaitTests: XCTestCase { let backgroundQueue = DispatchQueue(label: "com.yannickloriot.testqueue", attributes: .concurrent) let commonError = NSError(domain: "com.yannickloriot.error", code: 320, userInfo: nil) func testSimpleAwaitPromise() { let promise: Promise<String> = Promise { seal in let deadlineTime = DispatchTime.now() + .seconds(1) backgroundQueue.asyncAfter(deadline: deadlineTime, execute: { seal.fulfill("AwaitedPromiseKit") }) } let name = try! await(promise) XCTAssertEqual(name, "AwaitedPromiseKit") } func testSimpleAwaitGuarantee() { let guarantee: Guarantee<String> = Guarantee { fulfill in let deadlineTime = DispatchTime.now() + .seconds(1) backgroundQueue.asyncAfter(deadline: deadlineTime, execute: { fulfill("AwaitedPromiseKit") }) } let name = try! await(guarantee) XCTAssertEqual(name, "AwaitedPromiseKit") } func testSimpleFailedAwaitPromise() { let promise: Promise<String> = Promise { seal in let deadlineTime = DispatchTime.now() + .seconds(1) backgroundQueue.asyncAfter(deadline: deadlineTime, execute: { seal.reject(self.commonError) }) } XCTAssertThrowsError(try await(promise)) } func testNoValueAwaitPromise() { let promise: Promise<Void> = Promise { seal in seal.fulfill(()) } XCTAssertNotNil(promise.value) } func testNoValueAwaitGuarantee() { let guarantee: Guarantee<Void> = Guarantee { fulfill in fulfill(()) } XCTAssertNotNil(guarantee.value) } func testAwaitBlock() { var name: String = try! await { return "AwaitedPromiseKit" } XCTAssertEqual(name, "AwaitedPromiseKit") name = try! await { Thread.sleep(forTimeInterval: 0.2) return "PromiseKit" } XCTAssertEqual(name, "PromiseKit") do { try await { throw self.commonError } XCTAssertTrue(false) } catch { XCTAssertTrue(true) } } func testAsyncInsideAwaitBlock() { let name: String = try! await(async({ return "AwaitedPromiseKit" })) XCTAssertEqual(name, "AwaitedPromiseKit") let error: String? = try? await(async({ throw self.commonError })) XCTAssertNil(error) } }
a15a444a20b900afbb8b449e2ad2bcf4
26.341085
100
0.693224
false
true
false
false
SanctionCo/pilot-ios
refs/heads/master
Example/Pods/Locksmith/Source/LocksmithInternetProtocol.swift
apache-2.0
13
import Foundation public enum LocksmithInternetProtocol: RawRepresentable { case ftp, ftpAccount, http, irc, nntp, pop3, smtp, socks, imap, ldap, appleTalk, afp, telnet, ssh, ftps, https, httpProxy, httpsProxy, ftpProxy, smb, rtsp, rtspProxy, daap, eppc, ipp, nntps, ldaps, telnetS, imaps, ircs, pop3S public init?(rawValue: String) { switch rawValue { case String(kSecAttrProtocolFTP): self = .ftp case String(kSecAttrProtocolFTPAccount): self = .ftpAccount case String(kSecAttrProtocolHTTP): self = .http case String(kSecAttrProtocolIRC): self = .irc case String(kSecAttrProtocolNNTP): self = .nntp case String(kSecAttrProtocolPOP3): self = .pop3 case String(kSecAttrProtocolSMTP): self = .smtp case String(kSecAttrProtocolSOCKS): self = .socks case String(kSecAttrProtocolIMAP): self = .imap case String(kSecAttrProtocolLDAP): self = .ldap case String(kSecAttrProtocolAppleTalk): self = .appleTalk case String(kSecAttrProtocolAFP): self = .afp case String(kSecAttrProtocolTelnet): self = .telnet case String(kSecAttrProtocolSSH): self = .ssh case String(kSecAttrProtocolFTPS): self = .ftps case String(kSecAttrProtocolHTTPS): self = .https case String(kSecAttrProtocolHTTPProxy): self = .httpProxy case String(kSecAttrProtocolHTTPSProxy): self = .httpsProxy case String(kSecAttrProtocolFTPProxy): self = .ftpProxy case String(kSecAttrProtocolSMB): self = .smb case String(kSecAttrProtocolRTSP): self = .rtsp case String(kSecAttrProtocolRTSPProxy): self = .rtspProxy case String(kSecAttrProtocolDAAP): self = .daap case String(kSecAttrProtocolEPPC): self = .eppc case String(kSecAttrProtocolIPP): self = .ipp case String(kSecAttrProtocolNNTPS): self = .nntps case String(kSecAttrProtocolLDAPS): self = .ldaps case String(kSecAttrProtocolTelnetS): self = .telnetS case String(kSecAttrProtocolIMAPS): self = .imaps case String(kSecAttrProtocolIRCS): self = .ircs case String(kSecAttrProtocolPOP3S): self = .pop3S default: self = .http } } public var rawValue: String { switch self { case .ftp: return String(kSecAttrProtocolFTP) case .ftpAccount: return String(kSecAttrProtocolFTPAccount) case .http: return String(kSecAttrProtocolHTTP) case .irc: return String(kSecAttrProtocolIRC) case .nntp: return String(kSecAttrProtocolNNTP) case .pop3: return String(kSecAttrProtocolPOP3) case .smtp: return String(kSecAttrProtocolSMTP) case .socks: return String(kSecAttrProtocolSOCKS) case .imap: return String(kSecAttrProtocolIMAP) case .ldap: return String(kSecAttrProtocolLDAP) case .appleTalk: return String(kSecAttrProtocolAppleTalk) case .afp: return String(kSecAttrProtocolAFP) case .telnet: return String(kSecAttrProtocolTelnet) case .ssh: return String(kSecAttrProtocolSSH) case .ftps: return String(kSecAttrProtocolFTPS) case .https: return String(kSecAttrProtocolHTTPS) case .httpProxy: return String(kSecAttrProtocolHTTPProxy) case .httpsProxy: return String(kSecAttrProtocolHTTPSProxy) case .ftpProxy: return String(kSecAttrProtocolFTPProxy) case .smb: return String(kSecAttrProtocolSMB) case .rtsp: return String(kSecAttrProtocolRTSP) case .rtspProxy: return String(kSecAttrProtocolRTSPProxy) case .daap: return String(kSecAttrProtocolDAAP) case .eppc: return String(kSecAttrProtocolEPPC) case .ipp: return String(kSecAttrProtocolIPP) case .nntps: return String(kSecAttrProtocolNNTPS) case .ldaps: return String(kSecAttrProtocolLDAPS) case .telnetS: return String(kSecAttrProtocolTelnetS) case .imaps: return String(kSecAttrProtocolIMAPS) case .ircs: return String(kSecAttrProtocolIRCS) case .pop3S: return String(kSecAttrProtocolPOP3S) } } }
ae077fce6e67fa2291642fd64d667615
33.553191
229
0.590928
false
false
false
false
kyouko-taiga/anzen
refs/heads/master
Tests/ParserTests/ExpressionParserTests.swift
apache-2.0
1
import XCTest import AST @testable import Parser class ExpressionParserTests: XCTestCase, ParserTestCase { func testParseNullRef() { var pr: Parser.Result<Expr?> pr = parse("nullref", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: NullRef.self)) } func testParseIntegerLiteral() { var pr: Parser.Result<Expr?> pr = parse("42", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Literal<Int>.self)) assertThat((pr.value as? Literal<Int>)?.value, .equals(42)) } func testParseFloatingPointLiteral() { var pr: Parser.Result<Expr?> pr = parse("4.2", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Literal<Double>.self)) assertThat((pr.value as? Literal<Double>)?.value, .equals(4.2)) } func testParseStringLiteral() { var pr: Parser.Result<Expr?> pr = parse("\"Hello, World!\"", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Literal<String>.self)) assertThat((pr.value as? Literal<String>)?.value, .equals("Hello, World!")) } func testParseBoolLiteral() { var pr: Parser.Result<Expr?> pr = parse("true", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Literal<Bool>.self)) assertThat((pr.value as? Literal<Bool>)?.value, .equals(true)) pr = parse("false", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Literal<Bool>.self)) assertThat((pr.value as? Literal<Bool>)?.value, .equals(false)) } func testParseUnaryExpression() { var pr: Parser.Result<Expr?> pr = parse("+1", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: UnExpr.self)) if let expression = pr.value as? UnExpr { assertThat(expression.op, .equals(.add)) assertThat(expression.operand, .isInstance(of: Literal<Int>.self)) } } func testCastExpression() { var pr: Parser.Result<Expr?> pr = parse("a as Int", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CastExpr.self)) pr = parse("a as Int as Any", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CastExpr.self)) if let expression = pr.value as? CastExpr { assertThat(expression.castType, .isInstance(of: TypeIdent.self)) if let typeIdentifier = expression.castType as? TypeIdent { assertThat(typeIdentifier.name, .equals("Any")) } } let source = "a as Int".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CastExpr.self)) } func testBinaryExpression() { var pr: Parser.Result<Expr?> pr = parse("a + b", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: BinExpr.self)) pr = parse("a + b * c", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: BinExpr.self)) if let expression = pr.value as? BinExpr { assertThat(expression.right, .isInstance(of: BinExpr.self)) } pr = parse("a * b + c", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: BinExpr.self)) if let expression = pr.value as? BinExpr { assertThat(expression.right, .isInstance(of: Ident.self)) } let source = "a + b".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: BinExpr.self)) } func testParseIdentifier() { var pr: Parser.Result<Expr?> pr = parse("x", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Ident.self)) if let identifier = pr.value as? Ident { assertThat(identifier.name, .equals("x")) assertThat(identifier.specializations, .isEmpty) } pr = parse("Map<Key=String, Value=Int>", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Ident.self)) if let identifier = pr.value as? Ident { assertThat(identifier.name, .equals("Map")) assertThat(identifier.specializations, .count(2)) assertThat(identifier.specializations.keys, .contains("Key")) assertThat(identifier.specializations.keys, .contains("Value")) } let source = "Map < Key = String , Value = Int , >" .split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: Ident.self)) } func testParseIfExpression() { var pr: Parser.Result<Expr?> pr = parse("if c1 {}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: IfExpr.self)) if let conditional = pr.value as? IfExpr { assertThat(conditional.elseBlock, .isNil) } pr = parse("if c1 {} else {}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: IfExpr.self)) if let conditional = pr.value as? IfExpr { assertThat(conditional.elseBlock, .isInstance(of: Block.self)) } pr = parse("if c1 {} else if c2 {}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: IfExpr.self)) if let conditional = pr.value as? IfExpr { assertThat(conditional.elseBlock, .isInstance(of: IfExpr.self)) } let source = "if c1 { } else if c2 { }".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: IfExpr.self)) } func testParseLambda() { var pr: Parser.Result<Expr?> pr = parse("fun {}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: LambdaExpr.self)) if let lambda = pr.value as? LambdaExpr { assertThat(lambda.parameters, .isEmpty) assertThat(lambda.codomain, .isNil) } pr = parse("fun (a: Int, _ b: Int, c d: Int) {}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: LambdaExpr.self)) if let lambda = pr.value as? LambdaExpr { assertThat(lambda.parameters, .count(3)) if lambda.parameters.count > 2 { assertThat(lambda.parameters[0].label, .equals("a")) assertThat(lambda.parameters[0].name, .equals("a")) assertThat(lambda.parameters[0].typeAnnotation, .not(.isNil)) assertThat(lambda.parameters[1].label, .isNil) assertThat(lambda.parameters[1].name, .equals("b")) assertThat(lambda.parameters[1].typeAnnotation, .not(.isNil)) assertThat(lambda.parameters[2].label, .equals("c")) assertThat(lambda.parameters[2].name, .equals("d")) assertThat(lambda.parameters[2].typeAnnotation, .not(.isNil)) } assertThat(lambda.codomain, .isNil) } pr = parse("fun -> Int {}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: LambdaExpr.self)) if let lambda = pr.value as? LambdaExpr { assertThat(lambda.parameters, .isEmpty) assertThat(lambda.codomain, .not(.isNil)) } pr = parse("fun (_ x: Int) -> Int {}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: LambdaExpr.self)) if let lambda = pr.value as? LambdaExpr { assertThat(lambda.parameters, .count(1)) assertThat(lambda.codomain, .not(.isNil)) } let source = "fun ( _ x: Int , ) -> Int { }".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: LambdaExpr.self)) } func testParseArrayLiteral() { var pr: Parser.Result<Expr?> pr = parse("[]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: ArrayLiteral.self)) if let literal = pr.value as? ArrayLiteral { assertThat(literal.elements, .isEmpty) } pr = parse("[ a ]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: ArrayLiteral.self)) if let literal = pr.value as? ArrayLiteral { assertThat(literal.elements, .count(1)) for element in literal.elements { assertThat(element, .isInstance(of: Ident.self)) } } pr = parse("[ a, b, c ]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: ArrayLiteral.self)) if let literal = pr.value as? ArrayLiteral { assertThat(literal.elements, .count(3)) for element in literal.elements { assertThat(element, .isInstance(of: Ident.self)) } } let source = "[ a , b , c , ]".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: ArrayLiteral.self)) } func testParseSetLiteral() { var pr: Parser.Result<Expr?> pr = parse("{}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SetLiteral.self)) if let literal = pr.value as? SetLiteral { assertThat(literal.elements, .isEmpty) } pr = parse("{ a }", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SetLiteral.self)) if let literal = pr.value as? SetLiteral { assertThat(literal.elements, .count(1)) for element in literal.elements { assertThat(element, .isInstance(of: Ident.self)) } } pr = parse("{ a, b, c }", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SetLiteral.self)) if let literal = pr.value as? SetLiteral { assertThat(literal.elements, .count(3)) for element in literal.elements { assertThat(element, .isInstance(of: Ident.self)) } } let source = "{ a , b , c , }".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SetLiteral.self)) } func testParseMapLiteral() { var pr: Parser.Result<Expr?> pr = parse("{:}", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: MapLiteral.self)) if let literal = pr.value as? MapLiteral { assertThat(literal.elements, .isEmpty) } pr = parse("{ a: 1 }", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: MapLiteral.self)) if let literal = pr.value as? MapLiteral { assertThat(literal.elements, .count(1)) assertThat(literal.elements["a"], .isInstance(of: Literal<Int>.self)) } pr = parse("{ a: 1, b: 2, c: 3 }", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: MapLiteral.self)) if let literal = pr.value as? MapLiteral { assertThat(literal.elements, .count(3)) assertThat(literal.elements["a"], .isInstance(of: Literal<Int>.self)) assertThat(literal.elements["b"], .isInstance(of: Literal<Int>.self)) assertThat(literal.elements["c"], .isInstance(of: Literal<Int>.self)) } let source = "{ a : 1 , b : 2 , c : 3 , }".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: MapLiteral.self)) } func testParseImplicitSelect() { var pr: Parser.Result<Expr?> pr = parse(".a", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SelectExpr.self)) if let select = pr.value as? SelectExpr { assertThat(select.owner, .isNil) assertThat(select.ownee.name, .equals("a")) } pr = parse(".+", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SelectExpr.self)) if let select = pr.value as? SelectExpr { assertThat(select.owner, .isNil) assertThat(select.ownee.name, .equals("+")) } } func testParseSelect() { var pr: Parser.Result<Expr?> pr = parse("a.a", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SelectExpr.self)) if let select = pr.value as? SelectExpr { assertThat(select.owner, .isInstance(of: Ident.self)) assertThat(select.ownee.name, .equals("a")) } pr = parse("a.+", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SelectExpr.self)) if let select = pr.value as? SelectExpr { assertThat(select.owner, .isInstance(of: Ident.self)) assertThat(select.ownee.name, .equals("+")) } let source = "a .+".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SelectExpr.self)) } func testParseCall() { var pr: Parser.Result<Expr?> pr = parse("f()", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CallExpr.self)) if let call = pr.value as? CallExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .isEmpty) } pr = parse("f()()", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CallExpr.self)) if let call = pr.value as? CallExpr { assertThat(call.callee, .isInstance(of: CallExpr.self)) } pr = parse("f(x)", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CallExpr.self)) if let call = pr.value as? CallExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .count(1)) if call.arguments.count > 0 { assertThat(call.arguments[0].label, .isNil) assertThat(call.arguments[0].bindingOp, .equals(.copy)) assertThat(call.arguments[0].value, .isInstance(of: Ident.self)) } } pr = parse("f(a := x)", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CallExpr.self)) if let call = pr.value as? CallExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .count(1)) if call.arguments.count > 0 { assertThat(call.arguments[0].label, .equals("a")) assertThat(call.arguments[0].bindingOp, .equals(.copy)) assertThat(call.arguments[0].value, .isInstance(of: Ident.self)) } } pr = parse("f(x, b := y)", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CallExpr.self)) if let call = pr.value as? CallExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .count(2)) if call.arguments.count > 0 { assertThat(call.arguments[0].label, .isNil) assertThat(call.arguments[0].bindingOp, .equals(.copy)) assertThat(call.arguments[0].value, .isInstance(of: Ident.self)) } if call.arguments.count > 1 { assertThat(call.arguments[1].label, .equals("b")) assertThat(call.arguments[1].bindingOp, .equals(.copy)) assertThat(call.arguments[1].value, .isInstance(of: Ident.self)) } } let source = "f( x , b := y , )".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: CallExpr.self)) } func testParseSubscript() { var pr: Parser.Result<Expr?> pr = parse("f[]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SubscriptExpr.self)) if let call = pr.value as? SubscriptExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .isEmpty) } pr = parse("f[][]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SubscriptExpr.self)) if let call = pr.value as? CallExpr { assertThat(call.callee, .isInstance(of: SubscriptExpr.self)) } pr = parse("f[x]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SubscriptExpr.self)) if let call = pr.value as? SubscriptExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .count(1)) if call.arguments.count > 0 { assertThat(call.arguments[0].label, .isNil) assertThat(call.arguments[0].bindingOp, .equals(.copy)) assertThat(call.arguments[0].value, .isInstance(of: Ident.self)) } } pr = parse("f[a := x]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SubscriptExpr.self)) if let call = pr.value as? SubscriptExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .count(1)) if call.arguments.count > 0 { assertThat(call.arguments[0].label, .equals("a")) assertThat(call.arguments[0].bindingOp, .equals(.copy)) assertThat(call.arguments[0].value, .isInstance(of: Ident.self)) } } pr = parse("f[x, b := y]", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SubscriptExpr.self)) if let call = pr.value as? SubscriptExpr { assertThat(call.callee, .isInstance(of: Ident.self)) assertThat(call.arguments, .count(2)) if call.arguments.count > 0 { assertThat(call.arguments[0].label, .isNil) assertThat(call.arguments[0].bindingOp, .equals(.copy)) assertThat(call.arguments[0].value, .isInstance(of: Ident.self)) } if call.arguments.count > 1 { assertThat(call.arguments[1].label, .equals("b")) assertThat(call.arguments[1].bindingOp, .equals(.copy)) assertThat(call.arguments[1].value, .isInstance(of: Ident.self)) } } let source = "f[ x , b := y , ]".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: SubscriptExpr.self)) } func testParseEnclosed() { var pr: Parser.Result<Expr?> pr = parse("(a)", with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: EnclosedExpr.self)) if let enclosed = pr.value as? EnclosedExpr { assertThat(enclosed.expression, .isInstance(of: Ident.self)) } let source = "( a )".split(separator: " ").joined(separator: "\n") pr = parse(source, with: Parser.parseExpression) assertThat(pr.errors, .isEmpty) assertThat(pr.value, .isInstance(of: EnclosedExpr.self)) if let enclosed = pr.value as? EnclosedExpr { assertThat(enclosed.expression, .isInstance(of: Ident.self)) } } }
232f864e00db678c5530763192323020
35.885185
94
0.657194
false
false
false
false
mozilla-mobile/focus
refs/heads/master
Blockzilla/AppDelegate.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Telemetry import Glean protocol AppSplashController { var splashView: UIView { get } func toggleSplashView(hide: Bool) } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, ModalDelegate, AppSplashController { static let prefIntroDone = "IntroDone" static let prefIntroVersion = 2 static let prefWhatsNewDone = "WhatsNewDone" static let prefWhatsNewCounter = "WhatsNewCounter" static var needsAuthenticated = false // This enum can be expanded to support all new shortcuts added to menu. enum ShortcutIdentifier: String { case EraseAndOpen init?(fullIdentifier: String) { guard let shortIdentifier = fullIdentifier.components(separatedBy: ".").last else { return nil } self.init(rawValue: shortIdentifier) } } var window: UIWindow? var splashView: UIView = UIView() private lazy var browserViewController = { BrowserViewController(appSplashController: self) }() private var queuedUrl: URL? private var queuedString: String? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { if AppInfo.testRequestsReset() { if let bundleID = Bundle.main.bundleIdentifier { UserDefaults.standard.removePersistentDomain(forName: bundleID) } UserDefaults.standard.removePersistentDomain(forName: AppInfo.sharedContainerIdentifier) } setupContinuousDeploymentTooling() setupErrorTracking() setupTelemetry() TPStatsBlocklistChecker.shared.startup() // Count number of app launches for requesting a review let currentLaunchCount = UserDefaults.standard.integer(forKey: UIConstants.strings.userDefaultsLaunchCountKey) UserDefaults.standard.set(currentLaunchCount + 1, forKey: UIConstants.strings.userDefaultsLaunchCountKey) // Set original default values for showing tips let tipDefaults = [TipManager.TipKey.autocompleteTip: true, TipManager.TipKey.sitesNotWorkingTip: true, TipManager.TipKey.siriFavoriteTip: true, TipManager.TipKey.biometricTip: true, TipManager.TipKey.shareTrackersTip: true, TipManager.TipKey.siriEraseTip: true, TipManager.TipKey.requestDesktopTip: true] UserDefaults.standard.register(defaults: tipDefaults) // Disable localStorage. // We clear the Caches directory after each Erase, but WebKit apparently maintains // localStorage in-memory (bug 1319208), so we just disable it altogether. UserDefaults.standard.set(false, forKey: "WebKitLocalStorageEnabledPreferenceKey") UserDefaults.standard.removeObject(forKey: "searchedHistory") // Re-register the blocking lists at startup in case they've changed. Utils.reloadSafariContentBlocker() LocalWebServer.sharedInstance.start() window = UIWindow(frame: UIScreen.main.bounds) browserViewController.modalDelegate = self window?.rootViewController = browserViewController window?.makeKeyAndVisible() WebCacheUtils.reset() displaySplashAnimation() KeyboardHelper.defaultHelper.startObserving() // Override default keyboard appearance UITextField.appearance().keyboardAppearance = .dark let prefIntroDone = UserDefaults.standard.integer(forKey: AppDelegate.prefIntroDone) if AppInfo.isTesting() { let firstRunViewController = IntroViewController() firstRunViewController.modalPresentationStyle = .fullScreen self.browserViewController.present(firstRunViewController, animated: false, completion: nil) return true } let needToShowFirstRunExperience = prefIntroDone < AppDelegate.prefIntroVersion if needToShowFirstRunExperience { // Show the first run UI asynchronously to avoid the "unbalanced calls to begin/end appearance transitions" warning. DispatchQueue.main.async { // Set the prefIntroVersion viewed number in the same context as the presentation. UserDefaults.standard.set(AppDelegate.prefIntroVersion, forKey: AppDelegate.prefIntroDone) UserDefaults.standard.set(AppInfo.shortVersion, forKey: AppDelegate.prefWhatsNewDone) let introViewController = IntroViewController() introViewController.modalPresentationStyle = .fullScreen self.browserViewController.present(introViewController, animated: false, completion: nil) } } // Don't highlight whats new on a fresh install (prefIntroDone == 0 on a fresh install) if let lastShownWhatsNew = UserDefaults.standard.string(forKey: AppDelegate.prefWhatsNewDone)?.first, let currentMajorRelease = AppInfo.shortVersion.first { if prefIntroDone != 0 && lastShownWhatsNew != currentMajorRelease { let counter = UserDefaults.standard.integer(forKey: AppDelegate.prefWhatsNewCounter) switch counter { case 4: // Shown three times, remove counter UserDefaults.standard.set(AppInfo.shortVersion, forKey: AppDelegate.prefWhatsNewDone) UserDefaults.standard.removeObject(forKey: AppDelegate.prefWhatsNewCounter) default: // Show highlight UserDefaults.standard.set(counter+1, forKey: AppDelegate.prefWhatsNewCounter) } } } return true } func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return false } guard let urlTypes = Bundle.main.object(forInfoDictionaryKey: "CFBundleURLTypes") as? [AnyObject], let urlSchemes = urlTypes.first?["CFBundleURLSchemes"] as? [String] else { // Something very strange has happened; org.mozilla.Blockzilla should be the zeroeth URL type. return false } guard let scheme = components.scheme, let host = url.host, urlSchemes.contains(scheme) else { return false } let query = getQuery(url: url) let isHttpScheme = scheme == "http" || scheme == "https" if isHttpScheme { if application.applicationState == .active { // If we are active then we can ask the BVC to open the new tab right away. // Otherwise, we remember the URL and we open it in applicationDidBecomeActive. browserViewController.submit(url: url) } else { queuedUrl = url } } else if host == "open-url" { let urlString = unescape(string: query["url"]) ?? "" guard let url = URL(string: urlString) else { return false } if application.applicationState == .active { // If we are active then we can ask the BVC to open the new tab right away. // Otherwise, we remember the URL and we open it in applicationDidBecomeActive. browserViewController.submit(url: url) } else { queuedUrl = url } } else if host == "open-text" || isHttpScheme { let text = unescape(string: query["text"]) ?? "" if application.applicationState == .active { // If we are active then we can ask the BVC to open the new tab right away. // Otherwise, we remember the URL and we open it in applicationDidBecomeActive. browserViewController.openOverylay(text: text) } else { queuedString = text } } return true } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) { completionHandler(handleShortcut(shortcutItem: shortcutItem)) } private func handleShortcut(shortcutItem: UIApplicationShortcutItem) -> Bool { let shortcutType = shortcutItem.type guard let shortcutIdentifier = ShortcutIdentifier(fullIdentifier: shortcutType) else { return false } switch shortcutIdentifier { case .EraseAndOpen: browserViewController.resetBrowser(hidePreviousSession: true) } return true } public func getQuery(url: URL) -> [String: String] { var results = [String: String]() let keyValues = url.query?.components(separatedBy: "&") if keyValues?.count ?? 0 > 0 { for pair in keyValues! { let kv = pair.components(separatedBy: "=") if kv.count > 1 { results[kv[0]] = kv[1] } } } return results } public func unescape(string: String?) -> String? { guard let string = string else { return nil } return CFURLCreateStringByReplacingPercentEscapes( kCFAllocatorDefault, string as CFString, "" as CFString) as String } private func displaySplashAnimation() { let splashView = self.splashView splashView.backgroundColor = UIConstants.colors.background window!.addSubview(splashView) let logoImage = UIImageView(image: AppInfo.config.wordmark) splashView.addSubview(logoImage) splashView.snp.makeConstraints { make in make.edges.equalTo(window!) } logoImage.snp.makeConstraints { make in make.center.equalTo(splashView) } let animationDuration = 0.25 UIView.animate(withDuration: animationDuration, delay: 0.0, options: UIView.AnimationOptions(), animations: { logoImage.layer.transform = CATransform3DMakeScale(0.8, 0.8, 1.0) }, completion: { success in UIView.animate(withDuration: animationDuration, delay: 0.0, options: UIView.AnimationOptions(), animations: { splashView.alpha = 0 logoImage.layer.transform = CATransform3DMakeScale(2.0, 2.0, 1.0) }, completion: { success in splashView.isHidden = true logoImage.layer.transform = CATransform3DIdentity }) }) } func applicationWillResignActive(_ application: UIApplication) { toggleSplashView(hide: false) browserViewController.exitFullScreenVideo() } func applicationDidBecomeActive(_ application: UIApplication) { if Settings.siriRequestsErase() { browserViewController.photonActionSheetDidDismiss() browserViewController.dismiss(animated: true, completion: nil) browserViewController.navigationController?.popViewController(animated: true) browserViewController.resetBrowser(hidePreviousSession: true) Settings.setSiriRequestErase(to: false) Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.siri, object: TelemetryEventObject.eraseInBackground) } Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.foreground, object: TelemetryEventObject.app) if let url = queuedUrl { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.openedFromExtension, object: TelemetryEventObject.app) browserViewController.ensureBrowsingMode() browserViewController.submit(url: url) queuedUrl = nil } else if let text = queuedString { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.openedFromExtension, object: TelemetryEventObject.app) browserViewController.openOverylay(text: text) queuedString = nil } } func applicationDidEnterBackground(_ application: UIApplication) { // Record an event indicating that we have entered the background and end our telemetry // session. This gets called every time the app goes to background but should not get // called for *temporary* interruptions such as an incoming phone call until the user // takes action and we are officially backgrounded. AppDelegate.needsAuthenticated = true let orientation = UIDevice.current.orientation.isPortrait ? "Portrait" : "Landscape" Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.background, object: TelemetryEventObject.app, value: nil, extras: ["orientation": orientation]) } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { guard #available(iOS 12.0, *) else { return false } browserViewController.photonActionSheetDidDismiss() browserViewController.dismiss(animated: true, completion: nil) browserViewController.navigationController?.popViewController(animated: true) switch userActivity.activityType { case "org.mozilla.ios.Klar.eraseAndOpen": browserViewController.resetBrowser(hidePreviousSession: true) Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.siri, object: TelemetryEventObject.eraseAndOpen) case "org.mozilla.ios.Klar.openUrl": guard let urlString = userActivity.userInfo?["url"] as? String, let url = URL(string: urlString) else { return false } browserViewController.resetBrowser(hidePreviousSession: true) browserViewController.ensureBrowsingMode() browserViewController.submit(url: url) Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.siri, object: TelemetryEventObject.openFavoriteSite) case "EraseIntent": guard userActivity.interaction?.intent as? EraseIntent != nil else { return false } browserViewController.resetBrowser() Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.siri, object: TelemetryEventObject.eraseInBackground) default: break } return true } func toggleSplashView(hide: Bool) { let duration = 0.25 splashView.animateHidden(hide, duration: duration) if !hide { browserViewController.deactivateUrlBarOnHomeView() } else { browserViewController.activateUrlBarOnHomeView() } } } // MARK: - Telemetry & Tooling setup extension AppDelegate { func setupContinuousDeploymentTooling() { #if BUDDYBUILD BuddyBuildSDK.setup() #endif } func setupErrorTracking() { // Set up Sentry let sendUsageData = Settings.getToggle(.sendAnonymousUsageData) SentryIntegration.shared.setup(sendUsageData: sendUsageData) } func setupTelemetry() { let telemetryConfig = Telemetry.default.configuration telemetryConfig.appName = AppInfo.isKlar ? "Klar" : "Focus" telemetryConfig.userDefaultsSuiteName = AppInfo.sharedContainerIdentifier telemetryConfig.appVersion = AppInfo.shortVersion // Since Focus always clears the caches directory and Telemetry files are // excluded from iCloud backup, we store pings in documents. telemetryConfig.dataDirectory = .documentDirectory let activeSearchEngine = SearchEngineManager(prefs: UserDefaults.standard).activeEngine let defaultSearchEngineProvider = activeSearchEngine.isCustom ? "custom" : activeSearchEngine.name telemetryConfig.defaultSearchEngineProvider = defaultSearchEngineProvider telemetryConfig.measureUserDefaultsSetting(forKey: SearchEngineManager.prefKeyEngine, withDefaultValue: defaultSearchEngineProvider) telemetryConfig.measureUserDefaultsSetting(forKey: SettingsToggle.blockAds, withDefaultValue: Settings.getToggle(.blockAds)) telemetryConfig.measureUserDefaultsSetting(forKey: SettingsToggle.blockAnalytics, withDefaultValue: Settings.getToggle(.blockAnalytics)) telemetryConfig.measureUserDefaultsSetting(forKey: SettingsToggle.blockSocial, withDefaultValue: Settings.getToggle(.blockSocial)) telemetryConfig.measureUserDefaultsSetting(forKey: SettingsToggle.blockOther, withDefaultValue: Settings.getToggle(.blockOther)) telemetryConfig.measureUserDefaultsSetting(forKey: SettingsToggle.blockFonts, withDefaultValue: Settings.getToggle(.blockFonts)) telemetryConfig.measureUserDefaultsSetting(forKey: SettingsToggle.biometricLogin, withDefaultValue: Settings.getToggle(.biometricLogin)) telemetryConfig.measureUserDefaultsSetting(forKey: SettingsToggle.enableSearchSuggestions, withDefaultValue: Settings.getToggle(.enableSearchSuggestions)) #if DEBUG telemetryConfig.updateChannel = "debug" telemetryConfig.isCollectionEnabled = false telemetryConfig.isUploadEnabled = false #else telemetryConfig.updateChannel = "release" telemetryConfig.isCollectionEnabled = Settings.getToggle(.sendAnonymousUsageData) telemetryConfig.isUploadEnabled = Settings.getToggle(.sendAnonymousUsageData) #endif Telemetry.default.add(pingBuilderType: CorePingBuilder.self) Telemetry.default.add(pingBuilderType: FocusEventPingBuilder.self) // Start the telemetry session and record an event indicating that we have entered the Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.foreground, object: TelemetryEventObject.app) if let clientId = UserDefaults .standard.string(forKey: "telemetry-key-prefix-clientId") .flatMap(UUID.init(uuidString:)) { GleanMetrics.LegacyIds.clientId.set(clientId) } Glean.shared.initialize(uploadEnabled: Settings.getToggle(.sendAnonymousUsageData)) } func presentModal(viewController: UIViewController, animated: Bool) { window?.rootViewController?.present(viewController, animated: animated, completion: nil) } } protocol ModalDelegate { func presentModal(viewController: UIViewController, animated: Bool) } extension UINavigationController { override open var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
d74ad19f25f9ecab4a150c6f83087a77
44.907363
167
0.680447
false
true
false
false
AlexeyGolovenkov/DocGenerator
refs/heads/master
GRMustache.swift/Tests/Public/LambdaTests.swift
mit
1
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest import Mustache class LambdaTests: XCTestCase { func testMustacheSpecInterpolation() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L15 let lambda = Lambda { "world" } let template = try! Template(string: "Hello, {{lambda}}!") let data = [ "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "Hello, world!") } func testMustacheSpecInterpolationExpansion() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L29 let lambda = Lambda { "{{planet}}" } let template = try! Template(string: "Hello, {{lambda}}!") let data = [ "planet": Box("world"), "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "Hello, world!") } func testMustacheSpecInterpolationAlternateDelimiters() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L44 // With a difference: remove the "\n" character because GRMustache does // not honor mustache spec white space rules. let lambda = Lambda { "|planet| => {{planet}}" } let template = try! Template(string: "{{= | | =}}Hello, (|&lambda|)!") let data = [ "planet": Box("world"), "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "Hello, (|planet| => world)!") } func testMustacheSpecMultipleCalls() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L59 var calls = 0 let lambda = Lambda { calls += 1; return "\(calls)" } let template = try! Template(string: "{{lambda}} == {{{lambda}}} == {{lambda}}") let data = [ "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "1 == 2 == 3") } func testMustacheSpecEscaping() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L73 let lambda = Lambda { ">" } let template = try! Template(string: "<{{lambda}}{{{lambda}}}") let data = [ "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "<&gt;>") } func testMustacheSpecSection() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L87 let lambda = Lambda { (string: String) in if string == "{{x}}" { return "yes" } else { return "no" } } let template = try! Template(string: "<{{#lambda}}{{x}}{{/lambda}}>") let data = [ "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "<yes>") } func testMustacheSpecSectionExpansion() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L102 let lambda = Lambda { (string: String) in return "\(string){{planet}}\(string)" } let template = try! Template(string: "<{{#lambda}}-{{/lambda}}>") let data = [ "planet": Box("Earth"), "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "<-Earth->") } func testMustacheSpecSectionAlternateDelimiters() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L117 let lambda = Lambda { (string: String) in return "\(string){{planet}} => |planet|\(string)" } let template = try! Template(string: "{{= | | =}}<|#lambda|-|/lambda|>") let data = [ "planet": Box("Earth"), "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "<-{{planet}} => Earth->") } func testMustacheSpecSectionMultipleCalls() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L132 let lambda = Lambda { (string: String) in return "__\(string)__" } let template = try! Template(string: "{{#lambda}}FILE{{/lambda}} != {{#lambda}}LINE{{/lambda}}") let data = [ "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "__FILE__ != __LINE__") } func testMustacheSpecInvertedSection() { // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L146 let lambda = Lambda { (string: String) in return "" } let template = try! Template(string: "<{{^lambda}}{{static}}{{/lambda}}>") let data = [ "lambda": Box(lambda), ] let rendering = try! template.render(Box(data)) XCTAssertEqual(rendering, "<>") } func testPartialInArity0Lambda() { // Lambda can't render partials let partials = ["partial" : "success"] let templateRepository = TemplateRepository(templates: partials) let lambda = Lambda { "{{>partial}}" } let template = try! templateRepository.template(string: "<{{lambda}}>") let data = [ "lambda": Box(lambda), ] do { try template.render(Box(data)) XCTFail("Expected MustacheError") } catch let error as MustacheError { XCTAssertEqual(error.kind, MustacheError.Kind.TemplateNotFound) } catch { XCTFail("Expected MustacheError") } } func testPartialInArity1Lambda() { // Lambda can't render partials let partials = ["partial" : "success"] let templateRepository = TemplateRepository(templates: partials) let lambda = Lambda { (string: String) in "{{>partial}}" } let template = try! templateRepository.template(string: "<{{#lambda}}...{{/lambda}}>") let data = [ "lambda": Box(lambda), ] do { try template.render(Box(data)) XCTFail("Expected MustacheError") } catch let error as MustacheError { XCTAssertEqual(error.kind, MustacheError.Kind.TemplateNotFound) } catch { XCTFail("Expected MustacheError") } } func testArity0LambdaInSectionTag() { let lambda = Lambda { "success" } let template = try! Template(string: "{{#lambda}}<{{.}}>{{/lambda}}") let rendering = try! template.render(Box(["lambda": Box(lambda)])) XCTAssertEqual(rendering, "<success>") } func testArity1LambdaInVariableTag() { let lambda = Lambda { (string) in string } let template = try! Template(string: "<{{lambda}}>") let rendering = try! template.render(Box(["lambda": Box(lambda)])) XCTAssertEqual(rendering, "<(Lambda)>") } }
ea838446d6f009431b9443381c582f1c
39.815166
115
0.601719
false
true
false
false
indragiek/Ares
refs/heads/master
client/AresKit/IncomingFileTransfer.swift
mit
1
// // IncomingFileTransfer.swift // Ares // // Created by Indragie on 1/31/16. // Copyright © 2016 Indragie Karunaratne. All rights reserved. // import Foundation import MultipeerConnectivity public protocol IncomingFileTransferDelegate: AnyObject { func incomingFileTransfer(transfer: IncomingFileTransfer, didStartReceivingFileWithName name: String, progress: NSProgress) func incomingFileTransfer(transfer: IncomingFileTransfer, didReceiveFileWithName name: String, URL: NSURL) func incomingFileTransfer(transfer: IncomingFileTransfer, didFailToReceiveFileWithName name: String, error: NSError) } @objc public final class IncomingFileTransfer: NSObject, MCSessionDelegate { public let context: FileTransferContext let session: MCSession private let remotePeerID: MCPeerID public weak var delegate: IncomingFileTransferDelegate? init(context: FileTransferContext, localPeerID: MCPeerID, remotePeerID: MCPeerID) { self.context = context self.session = MCSession(peer: localPeerID) self.remotePeerID = remotePeerID super.init() self.session.delegate = self } // MARK: MCSessionDelegate public func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress) { guard peerID == remotePeerID else { return } delegate?.incomingFileTransfer(self, didStartReceivingFileWithName: resourceName, progress: progress) } public func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) { guard peerID == remotePeerID else { return } if let error = error { delegate?.incomingFileTransfer(self, didFailToReceiveFileWithName: resourceName, error: error) } else { delegate?.incomingFileTransfer(self, didReceiveFileWithName: resourceName, URL: localURL) } session.disconnect() } public func session(session: MCSession, didReceiveCertificate certificate: [AnyObject]?, fromPeer peerID: MCPeerID, certificateHandler: (Bool) -> Void) { guard peerID == remotePeerID else { return } certificateHandler(true) } // Unused public func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) {} public func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) {} public func session(session: MCSession, didReceiveStream stream: NSInputStream, withName streamName: String, fromPeer peerID: MCPeerID) {} }
979cb84b32c79ce71dd0e6220f112db9
41.640625
179
0.729938
false
false
false
false
SASAbus/SASAbus-ios
refs/heads/master
SASAbus/Data/Networking/Model/EcoPoints/LeaderboardPlayer.swift
gpl-3.0
1
import Foundation import SwiftyJSON final class LeaderboardPlayer: JSONable, JSONCollection { let id: String let username: String let points: Int let profile: Int required init(parameter: JSON) { id = parameter["id"].stringValue username = parameter["username"].stringValue points = parameter["points"].intValue profile = parameter["profile"].intValue } static func collection(parameter: JSON) -> [LeaderboardPlayer] { var items: [LeaderboardPlayer] = [] for itemRepresentation in parameter.arrayValue { items.append(LeaderboardPlayer(parameter: itemRepresentation)) } return items } }
cc9ffe944135f99fdf0256647f7df708
23.206897
74
0.65812
false
false
false
false
annecruz/MDCSwipeToChoose
refs/heads/master
Examples/SwiftLikedOrNope/SwiftLikedOrNope/Person.swift
mit
3
// // Person.swift // SwiftLikedOrNope // // Copyright (c) 2014 to present, Richard Burdish @rjburdish // // 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 Person: NSObject { let Name: NSString let Image: UIImage! let Age: NSNumber let NumberOfSharedFriends: NSNumber? let NumberOfSharedInterests: NSNumber let NumberOfPhotos: NSNumber override var description: String { return "Name: \(Name), \n Image: \(Image), \n Age: \(Age) \n NumberOfSharedFriends: \(NumberOfSharedFriends) \n NumberOfSharedInterests: \(NumberOfSharedInterests) \n NumberOfPhotos/: \(NumberOfPhotos)" } init(name: NSString?, image: UIImage?, age: NSNumber?, sharedFriends: NSNumber?, sharedInterest: NSNumber?, photos:NSNumber?) { self.Name = name ?? "" self.Image = image self.Age = age ?? 0 self.NumberOfSharedFriends = sharedFriends ?? 0 self.NumberOfSharedInterests = sharedInterest ?? 0 self.NumberOfPhotos = photos ?? 0 } }
173278716d4a4772159618ba0e2fd33c
41.081633
210
0.719068
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Components/Views/IconImageView/VideoIconStyle.swift
gpl-3.0
1
// // Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireCommonComponents import WireSyncEngine enum VideoIconStyle: String, IconImageStyle { case video case screenshare case hidden var icon: StyleKitIcon? { switch self { case .hidden: return .none case .screenshare: return .screenshare case .video: return .camera } } var accessibilitySuffix: String { return rawValue } var accessibilityLabel: String { return rawValue } } extension VideoIconStyle { init(state: VideoState?) { guard let state = state else { self = .hidden return } switch state { case .screenSharing: self = .screenshare case .started, .paused, .badConnection: self = .video case .stopped: self = .hidden } } }
8ec4737891f5421b0919ad65564b4be7
24.507937
71
0.634101
false
false
false
false
delannoyk/BoumBoum
refs/heads/master
sources/BoumBoum/CVImageBuffer+RGBHSVAverage.swift
mit
1
// // CVImageBuffer+RGBHSVAverage.swift // BoumBoum // // Created by Kevin DELANNOY on 20/01/16. // Copyright © 2016 Kevin Delannoy. All rights reserved. // import UIKit import AVFoundation typealias RGB = (r: CGFloat, g: CGFloat, b: CGFloat) typealias HSV = (h: CGFloat, s: CGFloat, v: CGFloat) extension CVImageBuffer { func averageRGBHSVValueFromImageBuffer() -> (rgb: RGB, hsv: HSV) { CVPixelBufferLockBaseAddress(self, 0) let width = CVPixelBufferGetWidth(self) let height = CVPixelBufferGetHeight(self) var buffer = UnsafeMutablePointer<UInt8>(CVPixelBufferGetBaseAddress(self)) let bytesPerRow = CVPixelBufferGetBytesPerRow(self) //Let's compute average RGB value of the frame var r = CGFloat(0) var g = CGFloat(0) var b = CGFloat(0) for _ in 0..<height { for x in 0..<width { let rx = x * 4 b = b + CGFloat(buffer[rx]) g = g + CGFloat(buffer[rx + 1]) r = r + CGFloat(buffer[rx + 2]) } buffer += bytesPerRow } CVPixelBufferUnlockBaseAddress(self, 0) let bufferSize = width * height r = r / CGFloat(255 * bufferSize) g = g / CGFloat(255 * bufferSize) b = b / CGFloat(255 * bufferSize) let rgb = (r, g, b) let hsv = RGBToHSV(rgb) return (rgb, hsv) } private func RGBToHSV(value: RGB) -> HSV { let minimum = min(value.r, min(value.g, value.b)) let maximum = max(value.r, max(value.g, value.b)) let delta = maximum - minimum if maximum > CGFloat(FLT_EPSILON) { let h: CGFloat let v = maximum let s = delta / maximum if value.r == maximum { h = (value.g - value.b) / delta } else if value.g == maximum { h = 2 + (value.b - value.r) / delta } else { h = 4 + (value.r - value.g) / delta } if h < 0 { return (h + 360, 0, 0) } return (h, s, v) } return (0, 0, 0) } }
36f45e3e5efc18a54ee9ca5a4281496f
26.936709
83
0.517898
false
false
false
false
ringohub/swift-todo
refs/heads/master
ToDo/ToDoListViewController.swift
mit
1
import UIKit import CoreData class ToDoListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var todoEntities: [ToDo]! func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return todoEntities.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "ToDoListItem")! cell.textLabel!.text = todoEntities[indexPath.row].item return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { todoEntities.remove(at: indexPath.row).mr_deleteEntity() NSManagedObjectContext.mr_default().mr_saveToPersistentStoreAndWait() tableView.reloadData() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // TODO: 文字列比較以外の方法は? // TODO: 少し改善したけど、まだString if segue.identifier == StoryboardSegue.Main.Edit.rawValue { let todoController = segue.destination as! ToDoItemViewController let task = todoEntities[tableView.indexPathForSelectedRow!.row] todoController.task = task } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) todoEntities = ToDo.mr_findAll() as? [ToDo] tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() todoEntities = ToDo.mr_findAll() as? [ToDo] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
162d6abbe918f1538f196f566e55f74c
30.125
125
0.726908
false
false
false
false
Tsiems/mobile-sensing-apps
refs/heads/master
06-Daily/code/Daily/IBAnimatable/SystemMoveInAnimator.swift
gpl-3.0
5
// // Created by Tom Baranes on 02/04/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public class SystemMoveInAnimator: NSObject, AnimatedTransitioning { // MARK: - AnimatorProtocol public var transitionAnimationType: TransitionAnimationType public var transitionDuration: Duration = defaultTransitionDuration public var reverseAnimationType: TransitionAnimationType? public var interactiveGestureType: InteractiveGestureType? // MARK: - private fileprivate var fromDirection: TransitionAnimationType.Direction public init(from direction: TransitionAnimationType.Direction, transitionDuration: Duration) { fromDirection = direction self.transitionDuration = transitionDuration switch fromDirection { case .right: self.transitionAnimationType = .systemMoveIn(from: .right) self.reverseAnimationType = .systemMoveIn(from: .left) self.interactiveGestureType = .pan(from: .left) case .top: self.transitionAnimationType = .systemMoveIn(from: .top) self.reverseAnimationType = .systemMoveIn(from: .bottom) self.interactiveGestureType = .pan(from: .bottom) case .bottom: self.transitionAnimationType = .systemMoveIn(from: .bottom) self.reverseAnimationType = .systemMoveIn(from: .top) self.interactiveGestureType = .pan(from: .top) default: self.transitionAnimationType = .systemMoveIn(from: .left) self.reverseAnimationType = .systemMoveIn(from: .right) self.interactiveGestureType = .pan(from: .right) } super.init() } } extension SystemMoveInAnimator: UIViewControllerAnimatedTransitioning { public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return retrieveTransitionDuration(transitionContext: transitionContext) } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { animateWithCATransition(transitionContext: transitionContext, type: TransitionAnimationType.SystemTransitionType.moveIn, subtype: fromDirection.caTransitionSubtype) } }
c153cf74fcbe4671a5d3140234fcfcf7
39.245283
168
0.766995
false
false
false
false
oNguyenVanHung/TODO-App
refs/heads/master
TO-DO-APP/TimelineViewController.swift
mit
1
// // TimelineViewController.swift // TO-DO-APP // // Created by ha.van.duc on 8/9/17. // Copyright © 2017 framgia. All rights reserved. // import UIKit class TimelineViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { @IBOutlet weak var timelineCollectionView: UICollectionView! @IBOutlet weak var labelNumberDay: UILabel! @IBOutlet weak var labelNameDay: UILabel! @IBOutlet weak var labelFullDay: UILabel! var listTask = [[String : Any]]() override func viewDidLoad() { super.viewDidLoad() timelineCollectionView.dataSource = self timelineCollectionView.delegate = self let nidName = UINib(nibName: "TimelineCollectionViewCell", bundle: nil) timelineCollectionView.register(nidName, forCellWithReuseIdentifier: "Cell") let currentDay = Date() let query = "SELECT * FROM tasks WHERE tasks.selectedDate = '\(CommonUtility.formatToString(currentDay))'" listTask = SqliteManager.shared.getDataWithQuery(query: query) labelFullDay.text = CommonUtility.getMonthInYear(currentDay) labelNameDay.text = CommonUtility.getDayName(currentDay) labelNumberDay.text = CommonUtility.getNumberDay(currentDay) navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.setBackgroundImage(UIImage(named: "header_backgroud_create_task"), for: .default) navigationItem.title = "Timeline" navigationItem.setLeftBarButton(UIBarButtonItem(image: UIImage(named: "icon_menu")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), style: .done, target: self, action: #selector(openMenuSidebar(_:))), animated: true) var image = UIImage(named: "avatar.png") image = image?.withRenderingMode(.alwaysOriginal) navigationItem.setRightBarButton(UIBarButtonItem(image: image, style: .done, target: self, action: nil), animated: true) } func openMenuSidebar(_ sender: Any) { navigationController?.popViewController(animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return listTask.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! TimelineCollectionViewCell if let fromTime = listTask[indexPath.row]["fromTime"] as? String, let toTime = listTask[indexPath.row]["toTime"] as? String, let title = listTask[indexPath.row]["title"] as? String, let description = listTask[indexPath.row]["description"] as? String, let status = listTask[indexPath.row]["status"] as? String { let timeTask = "\(fromTime) - \(toTime)" cell.update(timeTask: timeTask, title: title, description: description, status: status) } return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 300, height: 100) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return CGFloat(0) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return CGFloat(0) } }
9ccbda2c52cd41d4ed2aa3560b5f55cd
43.770115
232
0.717073
false
false
false
false
freak4pc/SMWebView
refs/heads/master
Pods/SMWebView/SMWebView.swift
mit
2
// // SMWebView // // Created by Shai Mishali on 8/19/15. // Copyright (c) 2015 Shai Mishali. All rights reserved. // import Foundation import UIKit open class SMWebView: UIWebView, UIWebViewDelegate{ //MARK: Typealiasing for Closure Types public typealias SMWebViewClosure = (_ webView :SMWebView) -> () public typealias SMWebViewFailClosure = (_ webView :SMWebView, _ error: Error?) -> () public typealias SMWebViewShouldLoadClosure = (_ webView :SMWebView, _ request: URLRequest, _ navigationType: UIWebViewNavigationType) -> (Bool) //MARK: Internal storage for Closures fileprivate var didStartLoadingHandler: SMWebViewClosure? = nil fileprivate var didFinishLoadingHandler: SMWebViewClosure? = nil fileprivate var didCompleteLoadingHandler: SMWebViewClosure? = nil fileprivate var didFailLoadingHandler: SMWebViewFailClosure? = nil fileprivate var shouldStartLoadingHandler: SMWebViewShouldLoadClosure? = nil //MARK: Initializers override init(frame: CGRect) { super.init(frame: frame) delegate = self } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) delegate = self } // URL/String loaders with Chaining-support public class func loadURL(_ URL: URL) -> SMWebView { let wv = SMWebView() wv.loadRequest(URLRequest(url: URL)) return wv } public class func loadHTML(_ string: String, baseURL: URL) -> SMWebView { let wv = SMWebView() wv.loadHTMLString(string, baseURL: baseURL) return wv } @discardableResult public func loadURL(_ URL: URL) -> SMWebView { loadRequest(URLRequest(url: URL)) return self } @discardableResult public func loadHTML(_ string: String, baseURL: URL) -> SMWebView { loadHTMLString(string, baseURL: baseURL) return self } //MARK: Closure methods @discardableResult public func didStartLoading(handler: @escaping SMWebViewClosure) -> SMWebView { didStartLoadingHandler = handler return self } @discardableResult public func didFinishLoading(handler: @escaping SMWebViewClosure) -> SMWebView { didFinishLoadingHandler = handler return self } @discardableResult public func didFailLoading(handler: @escaping SMWebViewFailClosure) -> SMWebView { didFailLoadingHandler = handler return self } @discardableResult public func didCompleteLoading(handler: @escaping SMWebViewClosure) -> SMWebView { didCompleteLoadingHandler = handler return self } @discardableResult public func shouldStartLoading(handler: @escaping SMWebViewShouldLoadClosure) -> SMWebView { shouldStartLoadingHandler = handler return self } //MARK: UIWebView Delegate & Closure Handling public func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { didFailLoadingHandler?(self, error) } public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { guard let handler = shouldStartLoadingHandler, shouldStartLoadingHandler != nil else { return true } return handler(self, request, navigationType) } public func webViewDidStartLoad(_ webView: UIWebView) { didStartLoadingHandler?(self) } public func webViewDidFinishLoad(_ webView: UIWebView) { didFinishLoadingHandler?(self) if !webView.isLoading { didCompleteLoadingHandler?(self) } } }
98d421adf86a6b93b5f69e5990142d46
32.068376
176
0.646162
false
false
false
false
KrishMunot/swift
refs/heads/master
test/IDE/import_as_member_cf.swift
apache-2.0
1
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t -I %S/Inputs/custom-modules) -print-module -source-filename %s -module-to-print=ImportAsMember.C -always-argument-labels > %t.printed.C.txt // REQUIRES: objc_interop // RUN: FileCheck %s -check-prefix=PRINTC -strict-whitespace < %t.printed.C.txt // PRINTC: extension CCPowerSupply { // PRINTC-NEXT: /*not inherited*/ init(watts watts: Double) // PRINTC-NEXT: } // PRINTC: extension CCRefrigerator { // PRINTC-NEXT: /*not inherited*/ init(powerSupply power: CCPowerSupply) // PRINTC-NEXT: func open() // PRINTC-NEXT: var powerSupply: CCPowerSupply // PRINTC-NEXT: } // PRINTC: extension CCMutableRefrigerator { // PRINTC-NEXT: /*not inherited*/ init(powerSupply power: CCPowerSupply) // PRINTC-NEXT: } // RUN: %target-parse-verify-swift -I %S/Inputs/custom-modules import ImportAsMember.C let powerSupply = CCPowerSupply(watts: 500.0) let refrigerator = CCRefrigerator(powerSupply: powerSupply) refrigerator.open(); refrigerator.powerSupply = powerSupply
619fa2b8cba5226b5c4894b6a18ac041
37.25
223
0.722689
false
false
false
false
ainopara/Stage1st-Reader
refs/heads/master
Stage1st/Model/Forum.swift
bsd-3-clause
1
// // Forum.swift // Stage1st // // Created by Zheng Li on 09/02/2017. // Copyright © 2017 Renaissance. All rights reserved. // import Foundation public struct Forum: Codable { public let id: Int public let name: String public let threadCount: Int public let postCount: Int public let rules: String? } extension Forum { init?(rawForum: RawForum) { guard let id = Int(rawForum.id), let threadCount = Int(rawForum.threadCount), let postCount = Int(rawForum.postCount) else { return nil } self.id = id self.name = rawForum.name self.threadCount = threadCount self.postCount = postCount self.rules = rawForum.rules } }
f16fff785d5c8cfecd23d84a5535ecc5
20.8
56
0.600262
false
false
false
false
SusanDoggie/Doggie
refs/heads/main
Sources/DoggieGraphics/PDFDocument/PDFRenderer/PDFColorSpace.swift
mit
1
// // PDFColorSpace.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. // public enum PDFColorSpace: Hashable { case deviceGray case deviceRGB case deviceCMYK case colorSpace(AnyColorSpace) indirect case indexed(PDFColorSpace, [Data]) indirect case pattern(PDFColorSpace?) public init(_ colorSpace: AnyColorSpace) { self = .colorSpace(colorSpace) } } extension PDFColorSpace { var numberOfComponents: Int { switch self { case .deviceGray: return 1 case .deviceRGB: return 3 case .deviceCMYK: return 4 case .indexed: return 1 case let .colorSpace(colorSpace): return colorSpace.numberOfComponents case let .pattern(base): return base?.numberOfComponents ?? 0 } } var black: [Double]? { switch self { case .deviceGray: return [0] case .deviceRGB: return [0, 0, 0] case .deviceCMYK: return [0, 0, 0, 1] case .indexed: return nil case let .colorSpace(colorSpace): switch colorSpace.base { case is ColorSpace<GrayColorModel>: return [0] case is ColorSpace<RGBColorModel>: return [0, 0, 0] case is ColorSpace<CMYColorModel>: return [1, 1, 1] case is ColorSpace<CMYKColorModel>: return [0, 0, 0, 1] default: return Array(repeating: 0, count: colorSpace.numberOfComponents) } case let .pattern(base): return base?.black } } } extension PDFColorSpace { init?(_ object: PDFObject, _ colorSpaces: [PDFName: PDFColorSpace] = [:]) { switch object.name ?? object.array?.first?.name { case "DeviceGray", "G": self = .deviceGray case "DeviceRGB", "RGB": self = .deviceRGB case "DeviceCMYK", "CMYK": self = .deviceCMYK case "CalGray": guard let parameter = object.array?.dropFirst().first else { return nil } guard let white = parameter["WhitePoint"].vector else { return nil } let black = parameter["BlackPoint"].vector ?? Vector() let gamma = parameter["Gamma"].doubleValue ?? 1 let _white = XYZColorModel(x: white.x, y: white.y, z: white.z) let _black = XYZColorModel(x: black.x, y: black.y, z: black.z) self.init(.calibratedGray(white: _white, black: _black, gamma: gamma)) case "CalRGB": guard let parameter = object.array?.dropFirst().first else { return nil } guard let white = parameter["WhitePoint"].vector else { return nil } let black = parameter["BlackPoint"].vector ?? Vector() let gamma = parameter["Gamma"].vector ?? Vector(x: 1, y: 1, z: 1) let matrix = parameter["Matrix"].matrix ?? [1, 0, 0, 0, 1, 0, 0, 0, 1] let _white = XYZColorModel(x: white.x, y: white.y, z: white.z) let _black = XYZColorModel(x: black.x, y: black.y, z: black.z) let red = XYZColorModel(x: matrix[0], y: 0, z: 0) let green = XYZColorModel(x: 0, y: matrix[4], z: 0) let blue = XYZColorModel(x: 0, y: 0, z: matrix[8]) self.init(.calibratedRGB(white: _white, black: _black, red: red.point, green: green.point, blue: blue.point, gamma: (gamma.x, gamma.y, gamma.z))) case "Lab": guard let parameter = object.array?.dropFirst().first else { return nil } guard let white = parameter["WhitePoint"].vector else { return nil } let black = parameter["BlackPoint"].vector ?? Vector() let _white = XYZColorModel(x: white.x, y: white.y, z: white.z) let _black = XYZColorModel(x: black.x, y: black.y, z: black.z) self.init(.cieLab(white: _white, black: _black)) case "ICCBased": guard let parameter = object.array?.dropFirst().first else { return nil } guard let iccData = parameter.stream?.decode() else { return nil } guard let colorSpace = try? AnyColorSpace(iccData: iccData) else { return nil } self.init(colorSpace) case "Indexed", "I": guard let array = object.array else { return nil } guard array.count >= 4 else { return nil } guard let base = PDFColorSpace(array[1], colorSpaces) else { return nil } guard let hival = array[2].intValue else { return nil } guard let data = array[3].string?.data ?? array[3].stream?.decode() else { return nil } guard (hival + 1) * base.numberOfComponents <= data.count else { return nil } let table = data.chunks(ofCount: base.numberOfComponents).prefix(hival + 1) self = .indexed(base, Array(table)) case "Pattern": if let array = object.array, let base = PDFColorSpace(PDFObject(array.dropFirst()), colorSpaces) { self = .pattern(base) } else { self = .pattern(nil) } default: return nil } } } extension PDFColorSpace { static func deviceGrayFromRGB(_ colorSpace: ColorSpace<RGBColorModel>) -> ColorSpace<GrayColorModel> { return ColorSpace.wrapped( base: colorSpace, convertFromBase: { GrayColorModel(white: 0.3 * $0.red + 0.59 * $0.green + 0.11 * $0.blue) }, convertToBase: RGBColorModel.init ) } static func deviceGrayFromCMYK(_ colorSpace: ColorSpace<CMYKColorModel>) -> ColorSpace<GrayColorModel> { return ColorSpace.wrapped( base: colorSpace, convertFromBase: { GrayColorModel(white: 1 - min(1, 0.3 * $0.cyan + 0.59 * $0.magenta + 0.11 * $0.yellow + $0.black)) }, convertToBase: CMYKColorModel.init ) } static func deviceRGBFromGray(_ colorSpace: ColorSpace<GrayColorModel>) -> ColorSpace<RGBColorModel> { return ColorSpace.wrapped( base: colorSpace, convertFromBase: RGBColorModel.init, convertToBase: { GrayColorModel(white: 0.3 * $0.red + 0.59 * $0.green + 0.11 * $0.blue) } ) } static func deviceRGBFromCMYK(_ colorSpace: ColorSpace<CMYKColorModel>) -> ColorSpace<RGBColorModel> { return ColorSpace.wrapped(base: colorSpace, convertFromBase: RGBColorModel.init, convertToBase: CMYKColorModel.init) } static func deviceCMYKFromGray(_ colorSpace: ColorSpace<GrayColorModel>) -> ColorSpace<CMYKColorModel> { return ColorSpace.wrapped( base: colorSpace, convertFromBase: CMYKColorModel.init, convertToBase: { GrayColorModel(white: 1 - min(1, 0.3 * $0.cyan + 0.59 * $0.magenta + 0.11 * $0.yellow + $0.black)) } ) } static func deviceCMYKFromRGB(_ colorSpace: ColorSpace<RGBColorModel>) -> ColorSpace<CMYKColorModel> { return ColorSpace.wrapped(base: colorSpace, convertFromBase: CMYKColorModel.init, convertToBase: RGBColorModel.init) } } extension PDFColorSpace { func create_color(_ color: [PDFNumber], device colorSpace: AnyColorSpace?) -> AnyColor? { switch self { case .deviceGray: let _colorSpace: AnyColorSpace switch colorSpace?.base { case let colorSpace as ColorSpace<GrayColorModel>: _colorSpace = AnyColorSpace(colorSpace) case let colorSpace as ColorSpace<RGBColorModel>: _colorSpace = AnyColorSpace(PDFColorSpace.deviceGrayFromRGB(colorSpace)) case let colorSpace as ColorSpace<CMYKColorModel>: _colorSpace = AnyColorSpace(PDFColorSpace.deviceGrayFromCMYK(colorSpace)) default: _colorSpace = .genericGamma22Gray } return AnyColor(colorSpace: _colorSpace, components: color.map { $0.doubleValue ?? 0 }) case .deviceRGB: let _colorSpace: AnyColorSpace switch colorSpace?.base { case let colorSpace as ColorSpace<GrayColorModel>: _colorSpace = AnyColorSpace(PDFColorSpace.deviceRGBFromGray(colorSpace)) case let colorSpace as ColorSpace<RGBColorModel>: _colorSpace = AnyColorSpace(colorSpace) case let colorSpace as ColorSpace<CMYKColorModel>: _colorSpace = AnyColorSpace(PDFColorSpace.deviceRGBFromCMYK(colorSpace)) default: _colorSpace = .sRGB } return AnyColor(colorSpace: _colorSpace, components: color.map { $0.doubleValue ?? 0 }) case .deviceCMYK: let _colorSpace: AnyColorSpace switch colorSpace?.base { case let colorSpace as ColorSpace<GrayColorModel>: _colorSpace = AnyColorSpace(PDFColorSpace.deviceCMYKFromGray(colorSpace)) case let colorSpace as ColorSpace<RGBColorModel>: _colorSpace = AnyColorSpace(PDFColorSpace.deviceCMYKFromRGB(colorSpace)) case let colorSpace as ColorSpace<CMYKColorModel>: _colorSpace = AnyColorSpace(colorSpace) default: _colorSpace = AnyColorSpace(PDFColorSpace.deviceCMYKFromRGB(.sRGB)) } return AnyColor(colorSpace: _colorSpace, components: color.map { $0.doubleValue ?? 0 }) case let .indexed(base, table): guard let index = color[0].int64Value else { return nil } let _color = table[Int(index)].map { PDFNumber(Double($0) / 255) } return 0..<table.count ~= Int(index) ? base.create_color(_color, device: colorSpace) : nil case let .colorSpace(colorSpace): return AnyColor(colorSpace: colorSpace, components: color.map { $0.doubleValue ?? 0 }) case let .pattern(base): return base.flatMap { $0.create_color(color, device: colorSpace) } } } }
3535a10c9d3493d733a715460fe9af10
41.169118
157
0.595815
false
false
false
false
steelwheels/KiwiControls
refs/heads/master
Source/Controls/KCIconViewCore.swift
lgpl-2.1
1
/** * @file KCIconViewCore.swift * @brief Define KCIconViewCore class * @par Copyright * Copyright (C) 2021 Steel Wheels Project */ #if os(OSX) import Cocoa #else import UIKit #endif import CoconutData #if os(OSX) public class KCIconButtonCell: NSButtonCell { public override func highlight(_ flag: Bool, withFrame cellFrame: NSRect, in controlView: NSView) { self.isHighlighted = flag } } #endif open class KCIconViewCore : KCCoreView { static let SmallSizeValue : CGFloat = 32.0 static let RegularSizeValue : CGFloat = 64.0 static let LargeSizeValue : CGFloat = 129.0 public var buttonPressedCallback: (() -> Void)? = nil #if os(OSX) @IBOutlet weak var mImageButton: NSButton! @IBOutlet weak var mLabelView: NSTextField! #else @IBOutlet weak var mImageButton: UIButton! @IBOutlet weak var mLabelView: UILabel! #endif private var mSize: CNIconSize = .regular public func setup(frame frm: CGRect){ super.setup(isSingleView: false, coreView: mImageButton) KCView.setAutolayoutMode(views: [self, mImageButton]) self.title = "Untitled" #if os(OSX) mImageButton.imageScaling = .scaleProportionallyUpOrDown mImageButton.imagePosition = .imageOnly mImageButton.isTransparent = true mLabelView.isEditable = false mLabelView.isSelectable = false #else mImageButton.contentMode = .scaleAspectFit //mImageButton.imagePosition = .imageAbove #endif } #if os(OSX) @IBAction func buttonPressed(_ sender: Any) { if let callback = buttonPressedCallback { callback() } } #else @IBAction func buttonPressed(_ sender: Any) { if let callback = buttonPressedCallback { callback() } } #endif public var image: CNImage? { get { #if os(OSX) return mImageButton.image #else return mImageButton.image(for: .normal) #endif } set(newimg) { guard let img = newimg else { CNLog(logLevel: .error, message: "No image") return } #if os(OSX) mImageButton.image = img #else mImageButton.setImage(img, for: .normal) #endif mImageButton.invalidateIntrinsicContentSize() } } public var title: String { get { #if os(OSX) return mLabelView.stringValue #else if let str = mLabelView.text { return str } else { return "" } #endif } set(newstr){ #if os(OSX) mLabelView.stringValue = newstr #else mLabelView.text = newstr #endif mLabelView.invalidateIntrinsicContentSize() } } public var size: CNIconSize { get { return mSize } set(newsize) { mSize = newsize } } open override func setFrameSize(_ newsize: CGSize) { let _ = adjustSize(in: newsize) super.setFrameSize(newsize) } public override func invalidateIntrinsicContentSize() { super.invalidateIntrinsicContentSize() // The size of image is NOT invalidated } #if os(OSX) open override var fittingSize: CGSize { get { return requiredSize() } } #else open override func sizeThatFits(_ size: CGSize) -> CGSize { return adjustSize(in: size) } #endif open override var intrinsicContentSize: CGSize { get { return requiredSize() } } private func requiredSize() -> CGSize { let btnsize = mImageButton.intrinsicContentSize let labsize = mLabelView.intrinsicContentSize return CNUnionSize(sizeA: btnsize, sizeB: labsize, doVertical: true, spacing: CNPreference.shared.windowPreference.spacing) } private func adjustSize(in sz: CGSize) -> CGSize { if sz.width <= KCIconViewCore.SmallSizeValue || sz.height <= KCIconViewCore.SmallSizeValue { return adjustSize(sizeType: .small) } else if sz.width <= KCIconViewCore.RegularSizeValue || sz.height <= KCIconViewCore.RegularSizeValue { return adjustSize(sizeType: .regular) } else { return adjustSize(sizeType: .large) } } private func adjustSize(sizeType styp: CNIconSize) -> CGSize { let targsize = sizeToValue(size: styp) let spacing = CNPreference.shared.windowPreference.spacing /* Get label size */ let labsize: CGSize mLabelView.sizeToFit() labsize = mLabelView.frame.size #if os(OSX) mLabelView.setFrameSize(labsize) #else mLabelView.setFrame(size: labsize) #endif /* Adjust image size */ let imgsize: CGSize if targsize.height > (labsize.height + spacing) { if let img = imageInButton() { let reqsize = CGSize(width: targsize.width, height: targsize.height - (labsize.height + spacing)) imgsize = adjustImageSize(image: img, targetSize: reqsize) } else { CNLog(logLevel: .error, message: "No image in icon", atFunction: #function, inFile: #file) imgsize = CGSize.zero } } else { CNLog(logLevel: .error, message: "No space to put image in icon", atFunction: #function, inFile: #file) imgsize = CGSize.zero } return CNUnionSize(sizeA: imgsize, sizeB: labsize, doVertical: true, spacing: 0.0) } private func adjustImageSize(image img: CNImage, targetSize target: CGSize) -> CGSize { let newsize = img.size.resizeWithKeepingAscpect(inSize: target) if let newimg = img.resized(to: newsize) { setImageToButton(image: newimg) #if os(OSX) mImageButton.setFrameSize(newsize) #else mImageButton.setFrame(size: newsize) #endif return newsize } else { CNLog(logLevel: .error, message: "Failed to resize image", atFunction: #function, inFile: #file) return img.size } } private func sizeToValue(size sz: CNIconSize) -> CGSize { let val: CGFloat switch sz { case .small: val = KCIconViewCore.SmallSizeValue case .regular: val = KCIconViewCore.RegularSizeValue case .large: val = KCIconViewCore.LargeSizeValue @unknown default: CNLog(logLevel: .error, message: "Unknown icon size", atFunction: #function, inFile: #file) val = KCIconViewCore.RegularSizeValue } return CGSize(width: val, height: val) } private func imageInButton() -> CNImage? { #if os(OSX) return mImageButton.image #else return mImageButton.image(for: .normal) #endif } private func setImageToButton(image img: CNImage) { #if os(OSX) mImageButton.image = img #else mImageButton.setImage(img, for: .normal) #endif } public override func setExpandabilities(priorities prival: KCViewBase.ExpansionPriorities) { super.setExpandabilities(priorities: prival) mImageButton.setExpansionPriorities(priorities: prival) let labpri = KCViewBase.ExpansionPriorities(holizontalHugging: prival.holizontalHugging, holizontalCompression: prival.holizontalCompression, verticalHugging: .low, verticalCompression: .low) mLabelView.setExpansionPriorities(priorities: labpri) } }
d2886e1250cddb7b69bc9e202b787e59
25.495968
125
0.713286
false
false
false
false
leo-lp/LPIM
refs/heads/master
LPIM/Classes/Login/LPRegisterViewController.swift
mit
1
// // LPRegisterViewController.swift // LPIM // // Created by lipeng on 2017/6/16. // Copyright © 2017年 lipeng. All rights reserved. // import UIKit import UIColor_Hex_Swift protocol LPRegisterViewControllerDelegate: NSObjectProtocol { func registDidComplete(account: String?, password: String?) -> Void } class LPRegisterViewController: LPBaseViewController { @IBOutlet weak var accountTextField: UITextField! @IBOutlet weak var nicknameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! weak var delegate: LPRegisterViewControllerDelegate? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupNav() } override func viewDidLoad() { super.viewDidLoad() resetTextField(accountTextField) resetTextField(nicknameTextField) resetTextField(passwordTextField) } func setupNav() { let registerBtn = UIButton(type: .custom) registerBtn.setTitle("完成", for: .normal) registerBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15) registerBtn.setTitleColor(UIColor(hex6: 0x2294ff), for: .normal) registerBtn.setBackgroundImage(#imageLiteral(resourceName: "login_btn_done_normal"), for: .normal) registerBtn.setBackgroundImage(#imageLiteral(resourceName: "login_btn_done_pressed"), for: .highlighted) registerBtn.addTarget(self, action: #selector(doneButtonClicked), for: .touchUpInside) registerBtn.sizeToFit() navigationItem.rightBarButtonItem = UIBarButtonItem(customView: registerBtn) navigationItem.rightBarButtonItem?.isEnabled = false let image = #imageLiteral(resourceName: "icon_back_normal") navigationController?.navigationBar.backIndicatorImage = image navigationController?.navigationBar.backIndicatorTransitionMaskImage = image let backItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) navigationController?.navigationBar.tintColor = UIColor.white navigationItem.backBarButtonItem = backItem } @IBAction func textFieldEditingChanged(_ sender: UITextField) { var enabled = false if let account = accountTextField.text, let nickname = nicknameTextField.text, let pwd = passwordTextField.text { enabled = account.characters.count > 0 && nickname.characters.count > 0 && pwd.characters.count > 0 } navigationItem.rightBarButtonItem?.isEnabled = enabled } @IBAction func existedButtonClicked(_ sender: UIButton) { navigationController?.popViewController(animated: true) } func doneButtonClicked(_ sender: UIButton?) { UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: nil, for: nil) if !check() { return } let data = LPRegisterData(account: accountTextField.text!, token: passwordTextField.text!.tokenByPassword(), nickname: nicknameTextField.text!) LPHUD.showHUD(at: nil, text: nil) LPHTTPSession.shared.registerUser(with: data) { (errorMsg) in LPHUD.hide(true) if let errorMsg = errorMsg { self.delegate?.registDidComplete(account: nil, password: nil) LPHUD.showError(at: nil, text: "注册失败(\(errorMsg))") return } LPHUD.showSuccess(at: nil, text: "注册成功") self.delegate?.registDidComplete(account: data.account, password: self.passwordTextField.text) self.navigationController?.popViewController(animated: true) } } } extension LPRegisterViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if string == "\n" { doneButtonClicked(nil) return false } return true } } // MARK: - // MARK: - Private extension LPRegisterViewController { fileprivate func resetTextField(_ textField: UITextField) { textField.tintColor = UIColor.white let dict = [NSForegroundColorAttributeName: UIColor(hex6: 0xffffff, alpha: 0.6)] let mas = NSAttributedString(string: textField.placeholder!, attributes: dict) textField.attributedPlaceholder = mas if let clearButton = textField.value(forKey: "_clearButton") as? UIButton { clearButton.setImage(#imageLiteral(resourceName: "login_icon_clear"), for: .normal) } } fileprivate func check() -> Bool { var checkAccount: Bool { guard let account = accountTextField.text else { return false } return account.characters.count > 0 && account.characters.count <= 20 } var checkPassword: Bool { guard let pwd = passwordTextField.text else { return false } return pwd.characters.count >= 6 && pwd.characters.count <= 20 } var checkNickname: Bool { guard let nickname = nicknameTextField.text else { return false } return nickname.characters.count > 0 && nickname.characters.count <= 10 } if !checkAccount { LPHUD.showError(at: view, text: "账号长度有误") return false } if !checkPassword { LPHUD.showError(at: view, text: "密码长度有误") return false } if !checkNickname { LPHUD.showError(at: view, text: "昵称长度有误") return false } return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } }
ca8dec97c23d53e634e5a6ef06cabf1e
37.381579
129
0.645183
false
false
false
false
withcopper/CopperKit
refs/heads/master
CopperKit/C29UserDevice.swift
mit
1
// // C29UserDevice // Copper // // Created by Doug Williams on 12/1/15. // Copyright (c) 2014 Doug Williams. All rights reserved. // import Foundation public class C29UserDevice: NSObject, NSCoding { public enum Key: String { case DeviceId = "device_id" case Timestamp = "created" case LastActive = "last_active" case Name = "name" case Type = "type" case Label = "label" case DeviceToken = "device_token" case PushEnabled = "push_enabled" case BundleId = "bundle_id" } public enum DeviceType: String { case Mobile = "mobile" case Desktop = "desktop" case Browser = "browser" case Chrome = "chrome" case Safari = "safari" case Other = "other" } public let id: String! public let timestamp: NSDate! public let name: String! public let type: DeviceType! public let lastActive: NSDate! public let label: String! public let pushEnabled: Bool! public let deviceToken: String? public let bundleId: String? init(id: String, timestamp: NSDate, name: String, lastActive: NSDate, type: DeviceType, label: String, pushEnabled: Bool = false, deviceToken: String! = nil, bundleId: String! = nil) { self.id = id self.timestamp = timestamp self.name = name self.lastActive = lastActive self.type = type self.label = label self.pushEnabled = pushEnabled self.deviceToken = deviceToken self.bundleId = bundleId } // MARK: - NSCoding convenience required public init?(coder decoder: NSCoder) { let id = decoder.decodeObjectForKey(Key.DeviceId.rawValue) as! String let timestamp = decoder.decodeObjectForKey(Key.Timestamp.rawValue) as! NSDate let name = decoder.decodeObjectForKey(Key.Name.rawValue) as! String let lastActive = decoder.decodeObjectForKey(Key.LastActive.rawValue) as? NSDate ?? NSDate() var type = DeviceType.Other if let typeRawValue = decoder.decodeObjectForKey(C29UserDevice.Key.Type.rawValue) as? String, let _type = DeviceType(rawValue: typeRawValue) { type = _type } let label = decoder.decodeObjectForKey(Key.Label.rawValue) as! String let pushEnabled = decoder.decodeObjectForKey(Key.PushEnabled.rawValue) as? Bool ?? false let deviceToken = decoder.decodeObjectForKey(Key.DeviceToken.rawValue) as? String let bundleId = decoder.decodeObjectForKey(Key.BundleId.rawValue) as? String self.init(id: id, timestamp: timestamp, name: name, lastActive: lastActive, type: type, label: label, pushEnabled: pushEnabled, deviceToken: deviceToken, bundleId: bundleId) } public func encodeWithCoder(coder: NSCoder) { coder.encodeObject(id, forKey: Key.DeviceId.rawValue) coder.encodeObject(timestamp, forKey: Key.Timestamp.rawValue) coder.encodeObject(name, forKey: Key.Name.rawValue) coder.encodeObject(lastActive, forKey: Key.LastActive.rawValue) coder.encodeObject(type?.rawValue, forKey: C29UserDevice.Key.Type.rawValue) coder.encodeObject(label, forKey: Key.Label.rawValue) coder.encodeObject(pushEnabled, forKey: Key.PushEnabled.rawValue) coder.encodeObject(deviceToken, forKey: Key.DeviceToken.rawValue) coder.encodeObject(bundleId, forKey: Key.BundleId.rawValue) } public class func fromDictionary(dataDict: NSDictionary) -> C29UserDevice? { if let id = dataDict[Key.DeviceId.rawValue] as? String, let createdTimestamp = dataDict[Key.Timestamp.rawValue] as? Double, let name = dataDict[Key.Name.rawValue] as? String, let label = dataDict[Key.Label.rawValue] as? String, let lastActiveTimestamp = dataDict[Key.LastActive.rawValue] as? Double, let typeRawValue = dataDict[C29UserDevice.Key.Type.rawValue] as? String { let timestamp = NSDate(timeIntervalSince1970: createdTimestamp) let lastActive = NSDate(timeIntervalSince1970: lastActiveTimestamp) let type = DeviceType(rawValue: typeRawValue) ?? .Other let pushEnabled = dataDict[Key.PushEnabled.rawValue] as? Bool ?? false let deviceToken = dataDict[Key.DeviceToken.rawValue] as? String let bundleId = dataDict[Key.BundleId.rawValue] as? String return C29UserDevice(id: id, timestamp: timestamp, name: name, lastActive: lastActive, type: type, label: label, pushEnabled: pushEnabled, deviceToken: deviceToken, bundleId: bundleId) } else { // we are receiving Application json of an unexpected format C29LogWithRemote(.Error, error: Error.InvalidFormat.nserror, infoDict: dataDict as! [String : AnyObject]) return C29UserDevice?() } } // expected dataDict format is {{deviceid,name,timestamp},{deviceid,...}}" public class func getDevicesFromDictionary(dataDict: [NSDictionary]) -> [C29UserDevice]? { var devices = [C29UserDevice]() for deviceDict in dataDict { if let device = C29UserDevice.fromDictionary(deviceDict) { devices.append(device) } else { C29LogWithRemote(.Error, error: Error.InvalidFormat.nserror, infoDict: deviceDict as! [String : AnyObject]) return nil } } return devices } override public func isEqual(object: AnyObject?) -> Bool { if let rhs = object as? C29UserDevice { return rhs.id == self.id } return false } } extension C29UserDevice { enum Error: Int { case InvalidFormat = 1 case DeleteUnsuccessful = 2 var reason: String { switch self { case DeleteUnsuccessful: return "C29UserDevice delete failed unexpectedly" case InvalidFormat: return "C29UserDevice fromDictionary failed because some required data was omitted or in the wrong format" } } var nserror: NSError { return NSError(domain: self.domain, code: self.rawValue, userInfo: [NSLocalizedFailureReasonErrorKey: self.reason]) } var domain: String { return "\(NSBundle.mainBundle().bundleIdentifier!).C29UserDevice" } } }
b211224bc0ee9670a6f404e9617fdb03
41.084416
196
0.645525
false
false
false
false
LongPF/FaceTube
refs/heads/master
FaceTube/Home/FTHomeViewController.swift
mit
1
// // HomeViewController.swift // FaceTube // // Created by 龙鹏飞 on 2017/3/1. // Copyright © 2017年 https://github.com/LongPF/FaceTube. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import AMScrollingNavbar import MJRefresh class FTHomeViewController: FTViewController, ScrollingNavigationControllerDelegate { var tableView: FTTableView! var dataSource: FTHomeLiveDataSource! var palyUrl = "" var player: IJKFFMoviePlayerController! = nil; var toolbar: UIToolbar! var selectedCell: FTHomeLiveTableViewCell? //MARK: ************************ life cycle ************************ override func viewDidLoad() { super.viewDidLoad() title = "FaceTube" view.backgroundColor = UIColor.backgroundColor() //dataSource self.dataSource = FTHomeLiveDataSource() self.dataSource.fetchDataCompleted = { (dataSource: FTDataSource) in self.tableView.reloadData() self.tableView.mj_header.endRefreshing() } //tableView self.tableView = FTTableView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_SIZE.width, height: SCREEN_SIZE.height-40), style: .plain) self.tableView.register(FTHomeLiveTableViewCell.classForCoder(), forCellReuseIdentifier: "cell") self.tableView.backgroundColor = UIColor.white self.tableView.dataSource = self self.tableView.delegate = self self.tableView.separatorStyle = .none self.tableView.backgroundColor = UIColor.backgroundColor() self.view.addSubview(self.tableView) //refresh let header: MJRefreshNormalHeader = MJRefreshNormalHeader() header.setRefreshingTarget(self.dataSource, refreshingAction: #selector(FTDataSource.fetchNewestData)) self.tableView.mj_header = header //获取数据 self.tableView.mj_header.beginRefreshing() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if (navigationController?.delegate == nil){ navigationController?.delegate = self } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.barTintColor = UIColor.navigationBarColor() if let navigationController = self.navigationController as? ScrollingNavigationController { navigationController.followScrollView(tableView, delay: 0.0) navigationController.scrollingNavbarDelegate = self } self.tableView.mj_header.isHidden = false } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.tableView.mj_header.isHidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK: 转场动画 override func captureView() -> UIView { return (selectedCell?.thumbImageView)! } override func needBlur() -> Bool { return true } override func needHiddenTabBar() -> Bool { return true } } extension FTHomeViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let count: NSInteger! = (self.dataSource.dataArray?.count)! return count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: FTHomeLiveTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FTHomeLiveTableViewCell let model: FTHomeLiveModel = self.dataSource.dataArray?.object(at: indexPath.row) as! FTHomeLiveModel cell.updateHomeLiveCell(model: model) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return SCREEN_SIZE.width+50 } } extension FTHomeViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedCell = tableView.cellForRow(at: indexPath) as! FTHomeLiveTableViewCell? let model: FTHomeLiveModel = dataSource.dataArray[indexPath.row] as! FTHomeLiveModel let detailCon: FTLiveDetailViewController = FTLiveDetailViewController() detailCon.homeLiveModel = model detailCon.hidesBottomBarWhenPushed = true navigationController?.pushViewController(detailCon, animated: true) } } extension FTHomeViewController { func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == UINavigationControllerOperation.push { return FTMagicMoveTransion() } else { return nil } } }
ecca58342528b26e6077ea17ebb6c750
32.414474
246
0.677299
false
false
false
false
silence0201/Swift-Study
refs/heads/master
Swifter/32Singleton.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import Foundation #if swift(>=3.0) #else // Swift之前的版本 class MyManager1 { class var shared : MyManager1 { struct Static { static var onceToken : dispatch_once_t = 0 static var staticInstance : MyManager1? = nil } dispatch_once(&Static.onceToken) { Static.staticInstance = MyManager1() } return Static.staticInstance! } } MyManager1.shared #endif class MyManager2 { private static let sharedInstance = MyManager2() class var sharedManager : MyManager2 { return sharedInstance } } MyManager2.sharedManager class MyManager3 { class var sharedManager : MyManager3 { return sharedInstance } } private let sharedInstance = MyManager3() MyManager3.sharedManager // 现在用这种 class MyManager { static let sharedManager = MyManager() private init() {} } MyManager.sharedManager
e78f3d1ed978d76deb4a29d0ab04c627
17.25
52
0.669125
false
false
false
false
Daltron/Spartan
refs/heads/master
Example/Pods/AlamoRecord/AlamoRecord/Classes/AlamoRecordObject.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2017 Tunespeak 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 Alamofire import AlamofireObjectMapper import ObjectMapper open class AlamoRecordObject<U: URLProtocol, E: AlamoRecordError>: NSObject, Mappable { /// Key to encode/decode the id variable private let idKey: String = "id" /// The RequestManager that is tied to all instances of this class open class var requestManager: RequestManager<U, E> { fatalError("requestManager must be overriden in your AlamoRecordObject subclass") } /// The RequestManager that is tied to this instance open var requestManager: RequestManager<U, E> { return type(of: self).requestManager } /// The id of this instance. This can be a String or an Int. open var id: Any! /// The root of all instances of this class. This is used when making URL's that relate to a component of this class. // Example: '/comment/id' --> '/\(Comment.root)/id' open class var root: String { fatalError("root must be overriden in your AlamoRecordObject subclass") } /// The root of this instance open var root: String { return type(of: self).root } /// The plural root of all instances of this class. This is used when making URL's that relate to a component of this class. // Example: '/comments/id' --> '/\(Comment.pluralRoot)/id' open class var pluralRoot: String { return "\(root)s" } /// The pluralRoot of this instance open var pluralRoot: String { return type(of: self).pluralRoot } /// The key path of all instances of this class. This is used when mapping instances of this class from JSON. /* Example: { comment: { // json encpasulated here } } If this is nil, then the expected JSON woud look like: { // json encpasulated here } */ open class var keyPath: String? { return nil } /// The keyPath of this instance open var keyPath: String? { return type(of: self).keyPath } /// The key path of all instances of this class. This is used when mapping instances of this class from JSON. See keyPath for example open class var pluralKeyPath: String? { guard let keyPath = keyPath else { return nil } return "\(keyPath)s" } /// The pluralKeyPath of this instance open var pluralKeyPath: String? { return type(of: self).pluralKeyPath } public override init() { super.init() } public required init?(map: Map) { super.init() mapping(map: map) } open func mapping(map: Map) { id <- map["id"] } /** Returns an array of all objects of this instance if the server supports it - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open class func all<T: AlamoRecordObject>(parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: (([T]) -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return requestManager.findArray(T.urlForAll(), parameters: parameters, keyPath: T.pluralKeyPath, encoding: encoding, headers: headers, success: success, failure: failure) } /** Creates an object of this instance - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open class func create<T: AlamoRecordObject>(parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: ((T) -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return requestManager.createObject(parameters: parameters, keyPath: keyPath, encoding: encoding, headers: headers, success: success, failure: failure) } /** Creates an object of this instance - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open class func create(parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: (() -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return requestManager.createObject(url: urlForCreate(), parameters: parameters, encoding: encoding, headers: headers, success: success, failure: failure) } /** Finds an object of this instance based on the given id - parameter id: The id of the object to find - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open class func find<T: AlamoRecordObject>(id: Any, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: ((T) -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return requestManager.findObject(id: id, parameters: parameters, keyPath: keyPath, encoding: encoding, headers: headers, success: success, failure: failure) } /** Updates the object - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open func update<T: AlamoRecordObject>(parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: ((T) -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return T.update(id: id, parameters: parameters, encoding: encoding, headers: headers, success: success, failure: failure) } /** Updates an object of this instance based with the given id - parameter id: The id of the object to update - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open class func update<T: AlamoRecordObject>(id: Any, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: ((T) -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return requestManager.updateObject(id: id, parameters: parameters, keyPath: keyPath, encoding: encoding, headers: headers, success: success, failure: failure) } /** Updates an object of this instance based with the given id - parameter id: The id of the object to update - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open class func update(id: Any, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: (() -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return requestManager.updateObject(url: urlForUpdate(id), parameters: parameters, encoding: encoding, headers: headers, success: success, failure: failure) } /** Updates an object of this instance based with the given id - parameter id: The id of the object to update - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open func update(parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: (() -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return type(of: self).update(id: id, parameters: parameters, encoding: encoding, headers: headers, success: success, failure: failure) } /** Destroys the object - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open func destroy(parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: (() -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return type(of: self).destroy(id: id, parameters: parameters, encoding: encoding, headers: headers, success: success, failure: failure) } /** Finds an object of this instance based on the given id - parameter id: The id of the object to destroy - parameter parameters: The parameters. `nil` by default - parameter encoding: The parameter encoding. `URLEncoding.default` by default - parameter headers: The HTTP headers. `nil` by default - parameter success: The block to execute if the request succeeds - parameter failure: The block to execute if the request fails */ @discardableResult open class func destroy(id: Any, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, success: (() -> Void)?, failure: ((E) -> Void)?) -> DataRequest { return requestManager.destroyObject(url: urlForDestroy(id), parameters: parameters, encoding: encoding, headers: headers, success: success, failure: failure) } /** The URL to use when making a create request for all objects of this instance */ open class func urlForCreate() -> U { return U(url: "\(pluralRoot)") } public func urlForCreate() -> U { return type(of: self).urlForCreate() } /** The URL to use when making a find request for all objects of this instance - parameter id: The id of the object to find */ open class func urlForFind(_ id: Any) -> U { return U(url: "\(pluralRoot)/\(id)") } public func urlForFind() -> U { return type(of: self).urlForFind(id) } /** The URL to use when making an update request for all objects of this instance - parameter id: The id of the object to update */ open class func urlForUpdate(_ id: Any) -> U { return U(url: "\(pluralRoot)/\(id)") } public func urlForUpdate() -> U { return type(of: self).urlForUpdate(id) } /** The URL to use when making a destroy request for all objects this instance - parameter id: The id of the object to destroy */ open class func urlForDestroy(_ id: Any) -> U { return U(url: "\(pluralRoot)/\(id)") } public func urlForDestroy() -> U { return type(of: self).urlForDestroy(id) } /** The URL to use when making an all request for all objects of this instance */ open class func urlForAll() -> U { return U(url: "\(pluralRoot)") } public func urlForAll() -> U { return type(of: self).urlForAll() } }
4cf0c25ec2b2ff36df247fa05605d92f
41.128954
147
0.542651
false
false
false
false
namanhams/Swift-UIImageView-AFNetworking
refs/heads/master
UIImageView+AFNetworking.swift
apache-2.0
1
// // UIImageView+AFNetworking.swift // // Created by Pham Hoang Le on 23/2/15. // Copyright (c) 2015 Pham Hoang Le. All rights reserved. // import UIKit @objc public protocol AFImageCacheProtocol:class{ func cachedImageForRequest(request:NSURLRequest) -> UIImage? func cacheImage(image:UIImage, forRequest request:NSURLRequest); } extension UIImageView { private struct AssociatedKeys { static var SharedImageCache = "SharedImageCache" static var RequestImageOperation = "RequestImageOperation" static var URLRequestImage = "UrlRequestImage" } public class func setSharedImageCache(cache:AFImageCacheProtocol?) { objc_setAssociatedObject(self, &AssociatedKeys.SharedImageCache, cache, .OBJC_ASSOCIATION_RETAIN) } public class func sharedImageCache() -> AFImageCacheProtocol { struct Static { static var token : dispatch_once_t = 0 static var defaultImageCache:AFImageCache? } dispatch_once(&Static.token, { () -> Void in Static.defaultImageCache = AFImageCache() NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationDidReceiveMemoryWarningNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (NSNotification) -> Void in Static.defaultImageCache!.removeAllObjects() } }) return objc_getAssociatedObject(self, &AssociatedKeys.SharedImageCache) as? AFImageCacheProtocol ?? Static.defaultImageCache! } private class func af_sharedImageRequestOperationQueue() -> NSOperationQueue { struct Static { static var token:dispatch_once_t = 0 static var queue:NSOperationQueue? } dispatch_once(&Static.token, { () -> Void in Static.queue = NSOperationQueue() Static.queue!.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount }) return Static.queue! } private var af_requestImageOperation:(operation:NSOperation?, request: NSURLRequest?) { get { let operation:NSOperation? = objc_getAssociatedObject(self, &AssociatedKeys.RequestImageOperation) as? NSOperation let request:NSURLRequest? = objc_getAssociatedObject(self, &AssociatedKeys.URLRequestImage) as? NSURLRequest return (operation, request) } set { objc_setAssociatedObject(self, &AssociatedKeys.RequestImageOperation, newValue.operation, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(self, &AssociatedKeys.URLRequestImage, newValue.request, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public func setImageWithUrl(url:NSURL, placeHolderImage:UIImage? = nil) { let request:NSMutableURLRequest = NSMutableURLRequest(URL: url) request.addValue("image/*", forHTTPHeaderField: "Accept") self.setImageWithUrlRequest(request, placeHolderImage: placeHolderImage, success: nil, failure: nil) } public func setImageWithUrlRequest(request:NSURLRequest, placeHolderImage:UIImage? = nil, success:((request:NSURLRequest?, response:NSURLResponse?, image:UIImage, fromCache:Bool) -> Void)?, failure:((request:NSURLRequest?, response:NSURLResponse?, error:NSError) -> Void)?) { self.cancelImageRequestOperation() if let cachedImage = UIImageView.sharedImageCache().cachedImageForRequest(request) { if success != nil { success!(request: nil, response:nil, image: cachedImage, fromCache:true) } else { self.image = cachedImage } return } if placeHolderImage != nil { self.image = placeHolderImage } self.af_requestImageOperation = (NSBlockOperation(block: { () -> Void in var response:NSURLResponse? do { let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) dispatch_async(dispatch_get_main_queue(), { () -> Void in if request.URL!.isEqual(self.af_requestImageOperation.request?.URL) { let image:UIImage? = UIImage(data: data) if image != nil { if success != nil { success!(request: request, response: response, image: image!, fromCache:false) } else { self.image = image! } UIImageView.sharedImageCache().cacheImage(image!, forRequest: request) } self.af_requestImageOperation = (nil, nil) } }) } catch { if failure != nil { failure!(request: request, response:response, error: error as NSError) } } }), request: request) UIImageView.af_sharedImageRequestOperationQueue().addOperation(self.af_requestImageOperation.operation!) } private func cancelImageRequestOperation() { self.af_requestImageOperation.operation?.cancel() self.af_requestImageOperation = (nil, nil) } } func AFImageCacheKeyFromURLRequest(request:NSURLRequest) -> String { return request.URL!.absoluteString! } class AFImageCache: NSCache, AFImageCacheProtocol { func cachedImageForRequest(request: NSURLRequest) -> UIImage? { switch request.cachePolicy { case NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData: return nil default: break } return self.objectForKey(AFImageCacheKeyFromURLRequest(request)) as? UIImage } func cacheImage(image: UIImage, forRequest request: NSURLRequest) { self.setObject(image, forKey: AFImageCacheKeyFromURLRequest(request)) } }
b2875610155a4ee39103942d270c1b08
39.986755
197
0.625626
false
false
false
false
chuckwired/ios-scroll-test
refs/heads/master
scrollTest/ViewController.swift
gpl-2.0
1
// // ViewController.swift // scrollTest // // Created by Charles Rice on 04/11/2014. // Copyright (c) 2014 Cake Solutions. All rights reserved. // import UIKit class ViewController: UIViewController, UIScrollViewDelegate { @IBOutlet var scrollView: UIScrollView! var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do cool stuff //Part 1 let image2 = UIImage(named: "photo2.png") let image = UIImage(named: "photo1.png") imageView = UIImageView(image: image) var theImageSize = CGSizeZero if let image = image { theImageSize = image.size } imageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size:theImageSize) scrollView.addSubview(imageView) //Part2 scrollView.contentSize = theImageSize //Part 3 var doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "scrollViewDoubleTapped:") doubleTapRecognizer.numberOfTapsRequired = 2 doubleTapRecognizer.numberOfTouchesRequired = 1 scrollView.addGestureRecognizer(doubleTapRecognizer) //Part 4 let scrollViewFrame = scrollView.frame let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height let minScale = min(scaleWidth, scaleHeight) scrollView.minimumZoomScale = minScale //Part 5 scrollView.maximumZoomScale = 1.0 scrollView.zoomScale = minScale //Part 6 centerScrollViewContents() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Scroll delegates func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(scrollView: UIScrollView) { centerScrollViewContents() } //Double tap to zoom func scrollViewDoubleTapped(recognizer: UITapGestureRecognizer){ //Part 1 let pointInView = recognizer.locationInView(imageView) //Part 2 var newZoomScale = scrollView.zoomScale * 1.5 newZoomScale = min(newZoomScale, scrollView.maximumZoomScale) //Part 3 let scrollViewSize = scrollView.bounds.size let w = scrollViewSize.width / newZoomScale let h = scrollViewSize.height / newZoomScale let x = pointInView.x - (w / 2.0) let y = pointInView.y - (h / 2.0) let rectToZoomTo = CGRect(x: x, y: y, width: w, height: h) //Part 4 scrollView.zoomToRect(rectToZoomTo, animated: true) } //Fixes UIScrollView autodisplay in top-left func centerScrollViewContents(){ let boundsSize = scrollView.bounds.size var contentsFrame = imageView.frame if(contentsFrame.size.width < boundsSize.width){ contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0 } else { contentsFrame.origin.x = 0.0 } if contentsFrame.size.height < boundsSize.height { contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0 } else { contentsFrame.origin.y = 0.0 } imageView.frame = contentsFrame } }
976278514a3df00720c0d0f0d763a7b9
31.145455
105
0.626414
false
false
false
false
fabiomassimo/eidolon
refs/heads/master
Kiosk/Bid Fulfillment/ConfirmYourBidEnterYourEmailViewController.swift
mit
1
import UIKit import ReactiveCocoa import Swift_RAC_Macros public class ConfirmYourBidEnterYourEmailViewController: UIViewController { @IBOutlet public var emailTextField: UITextField! @IBOutlet public var confirmButton: UIButton! @IBOutlet public var bidDetailsPreviewView: BidDetailsPreviewView! class public func instantiateFromStoryboard(storyboard: UIStoryboard) -> ConfirmYourBidEnterYourEmailViewController { return storyboard.viewControllerWithID(.ConfirmYourBidEnterEmail) as! ConfirmYourBidEnterYourEmailViewController } override public func viewDidLoad() { super.viewDidLoad() let emailTextSignal = emailTextField.rac_textSignal() let inputIsEmail = emailTextSignal.map(stringIsEmailAddress) confirmButton.rac_command = RACCommand(enabled: inputIsEmail) { [weak self] _ in if (self == nil) { return RACSignal.empty() } let endpoint: ArtsyAPI = ArtsyAPI.FindExistingEmailRegistration(email: self!.emailTextField.text) return XAppRequest(endpoint).filterStatusCode(200).doNext({ (__) -> Void in self?.performSegue(.ExistingArtsyUserFound) return }).doError { (error) -> Void in self?.performSegue(.EmailNotFoundonArtsy) return } } let unbindSignal = confirmButton.rac_command.executing.ignore(false) let nav = self.fulfillmentNav() bidDetailsPreviewView.bidDetails = nav.bidDetails RAC(nav.bidDetails.newUser, "email") <~ emailTextSignal.takeUntil(unbindSignal) emailTextField.returnKeySignal().subscribeNext { [weak self] (_) -> Void in self?.confirmButton.rac_command.execute(nil) return } } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.emailTextField.becomeFirstResponder() } } private extension ConfirmYourBidEnterYourEmailViewController { @IBAction func dev_emailFound(sender: AnyObject) { performSegue(.ExistingArtsyUserFound) } @IBAction func dev_emailNotFound(sender: AnyObject) { performSegue(.EmailNotFoundonArtsy) } }
ad9302833fc5cf37c01ae29a14466136
32.25
121
0.684956
false
false
false
false
CodaFi/swift
refs/heads/main
stdlib/public/core/ArrayBufferProtocol.swift
apache-2.0
11
//===--- ArrayBufferProtocol.swift ----------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// The underlying buffer for an ArrayType conforms to /// `_ArrayBufferProtocol`. This buffer does not provide value semantics. @usableFromInline internal protocol _ArrayBufferProtocol : MutableCollection, RandomAccessCollection where Indices == Range<Int> { /// Create an empty buffer. init() /// Adopt the entire buffer, presenting it at the provided `startIndex`. init(_buffer: _ContiguousArrayBuffer<Element>, shiftedToStartIndex: Int) init(copying buffer: Self) /// Copy the elements in `bounds` from this buffer into uninitialized /// memory starting at `target`. Return a pointer "past the end" of the /// just-initialized memory. @discardableResult __consuming func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> /// If this buffer is backed by a uniquely-referenced mutable /// `_ContiguousArrayBuffer` that can be grown in-place to allow the `self` /// buffer store `minimumCapacity` elements, returns that buffer. /// Otherwise, returns `nil`. /// /// - Note: The result's firstElementAddress may not match ours, if we are a /// _SliceBuffer. /// /// - Note: This function must remain mutating; otherwise the buffer /// may acquire spurious extra references, which will cause /// unnecessary reallocation. mutating func requestUniqueMutableBackingBuffer( minimumCapacity: Int ) -> _ContiguousArrayBuffer<Element>? /// Returns `true` iff this buffer is backed by a uniquely-referenced mutable /// _ContiguousArrayBuffer. /// /// - Note: This function must remain mutating; otherwise the buffer /// may acquire spurious extra references, which will cause /// unnecessary reallocation. mutating func isMutableAndUniquelyReferenced() -> Bool /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? /// Replace the given `subRange` with the first `newCount` elements of /// the given collection. /// /// - Precondition: This buffer is backed by a uniquely-referenced /// `_ContiguousArrayBuffer`. mutating func replaceSubrange<C>( _ subrange: Range<Int>, with newCount: Int, elementsOf newValues: __owned C ) where C: Collection, C.Element == Element /// Returns a `_SliceBuffer` containing the elements in `bounds`. subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. If no such storage exists, it is /// created on-demand. func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. /// /// - Precondition: Such contiguous storage exists or the buffer is empty. mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R /// The number of elements the buffer stores. override var count: Int { get set } /// The number of elements the buffer can store without reallocation. var capacity: Int { get } /// An object that keeps the elements stored in this buffer alive. var owner: AnyObject { get } /// A pointer to the first element. /// /// - Precondition: The elements are known to be stored contiguously. var firstElementAddress: UnsafeMutablePointer<Element> { get } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { get } /// Returns a base address to which you can add an index `i` to get the /// address of the corresponding element at `i`. var subscriptBaseAddress: UnsafeMutablePointer<Element> { get } /// A value that identifies the storage used by the buffer. Two /// buffers address the same elements when they have the same /// identity and count. var identity: UnsafeRawPointer { get } } extension _ArrayBufferProtocol where Indices == Range<Int>{ @inlinable internal var subscriptBaseAddress: UnsafeMutablePointer<Element> { return firstElementAddress } // Make sure the compiler does not inline _copyBuffer to reduce code size. @inline(never) @inlinable // This code should be specializable such that copying an array is // fast and does not end up in an unspecialized entry point. internal init(copying buffer: Self) { let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: buffer.count, minimumCapacity: buffer.count) buffer._copyContents( subRange: buffer.indices, initializing: newBuffer.firstElementAddress) self = Self( _buffer: newBuffer, shiftedToStartIndex: buffer.startIndex) } @inlinable internal mutating func replaceSubrange<C>( _ subrange: Range<Int>, with newCount: Int, elementsOf newValues: __owned C ) where C: Collection, C.Element == Element { _internalInvariant(startIndex == 0, "_SliceBuffer should override this function.") let oldCount = self.count let eraseCount = subrange.count let growth = newCount - eraseCount // This check will prevent storing a 0 count to the empty array singleton. if growth != 0 { self.count = oldCount + growth } let elements = self.subscriptBaseAddress let oldTailIndex = subrange.upperBound let oldTailStart = elements + oldTailIndex let newTailIndex = oldTailIndex + growth let newTailStart = oldTailStart + growth let tailCount = oldCount - subrange.upperBound if growth > 0 { // Slide the tail part of the buffer forwards, in reverse order // so as not to self-clobber. newTailStart.moveInitialize(from: oldTailStart, count: tailCount) // Assign over the original subrange var i = newValues.startIndex for j in subrange { elements[j] = newValues[i] newValues.formIndex(after: &i) } // Initialize the hole left by sliding the tail forward for j in oldTailIndex..<newTailIndex { (elements + j).initialize(to: newValues[i]) newValues.formIndex(after: &i) } _expectEnd(of: newValues, is: i) } else { // We're not growing the buffer // Assign all the new elements into the start of the subrange var i = subrange.lowerBound var j = newValues.startIndex for _ in 0..<newCount { elements[i] = newValues[j] i += 1 newValues.formIndex(after: &j) } _expectEnd(of: newValues, is: j) // If the size didn't change, we're done. if growth == 0 { return } // Move the tail backward to cover the shrinkage. let shrinkage = -growth if tailCount > shrinkage { // If the tail length exceeds the shrinkage // Assign over the rest of the replaced range with the first // part of the tail. newTailStart.moveAssign(from: oldTailStart, count: shrinkage) // Slide the rest of the tail back oldTailStart.moveInitialize( from: oldTailStart + shrinkage, count: tailCount - shrinkage) } else { // Tail fits within erased elements // Assign over the start of the replaced range with the tail newTailStart.moveAssign(from: oldTailStart, count: tailCount) // Destroy elements remaining after the tail in subrange (newTailStart + tailCount).deinitialize( count: shrinkage - tailCount) } } } }
92b36d560f18f31636c33035fc966206
36.479638
86
0.680792
false
false
false
false
domenicosolazzo/practice-swift
refs/heads/master
Views/Sliders/SliderExample/SliderExample/ViewController.swift
mit
1
// // ViewController.swift // SliderExample // // Created by Domenico Solazzo on 05/05/15. // LICENSE MIT // import UIKit class ViewController: UIViewController { // Slider var slider:UISlider? override func viewDidLoad() { super.viewDidLoad() slider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 23)) slider!.center = self.view.center // Max value slider?.maximumValue = 100 // Min value slider?.minimumValue = 0 // Current Value slider?.value = slider!.maximumValue / 2.0 // Set thumb images slider?.setThumbImage(UIImage(named: "ThumbNormal"), for: UIControlState()) slider?.setThumbImage(UIImage(named: "ThumbHighlighted"), for: .highlighted) self.view.addSubview(slider!) } }
d690ba22dc42b70019413fde0f2103be
22.081081
84
0.59719
false
false
false
false
hivinau/LivingElectro
refs/heads/master
iOS/LivingElectro/LivingElectro/TitleCell.swift
mit
1
// // TitleCell.swift // LivingElectro // // Created by Aude Sautier on 14/05/2017. // Copyright © 2017 Hivinau GRAFFE. All rights reserved. // import UIKit @objc(TitleCell) public class TitleCell: UICollectionViewCell { @IBOutlet weak var titleLabel: PaddingLabel! public override var isSelected: Bool { didSet { titleLabel.textColor = isSelected ? .white : .gray } } public var titleValue: String? { didSet { titleLabel.text = titleValue titleLabel.sizeToFit() } } public override func layoutSubviews() { super.layoutSubviews() titleLabel.numberOfLines = 0 titleLabel.lineBreakMode = .byTruncatingTail titleLabel.textAlignment = .center titleLabel.textColor = isSelected ? .white : .gray if let font = UIFont(name: "Helvetica", size: 14.0) { titleLabel.font = font } } public override func prepareForReuse() { super.prepareForReuse() titleLabel.text?.removeAll() } }
beb0ba14367095c260de4b3e1b20419c
22.08
62
0.571924
false
false
false
false
huonw/swift
refs/heads/master
tools/SwiftSyntax/RawSyntax.swift
apache-2.0
1
//===------------------ RawSyntax.swift - Raw Syntax nodes ----------------===// // // 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 Foundation /// Represents the raw tree structure underlying the syntax tree. These nodes /// have no notion of identity and only provide structure to the tree. They /// are immutable and can be freely shared between syntax nodes. indirect enum RawSyntax: Codable { /// A tree node with a kind, an array of children, and a source presence. case node(SyntaxKind, [RawSyntax?], SourcePresence) /// A token with a token kind, leading trivia, trailing trivia, and a source /// presence. case token(TokenKind, Trivia, Trivia, SourcePresence) /// The syntax kind of this raw syntax. var kind: SyntaxKind { switch self { case .node(let kind, _, _): return kind case .token(_, _, _, _): return .token } } var tokenKind: TokenKind? { switch self { case .node(_, _, _): return nil case .token(let kind, _, _, _): return kind } } /// The layout of the children of this Raw syntax node. var layout: [RawSyntax?] { switch self { case .node(_, let layout, _): return layout case .token(_, _, _, _): return [] } } /// The source presence of this node. var presence: SourcePresence { switch self { case .node(_, _, let presence): return presence case .token(_, _, _, let presence): return presence } } /// Whether this node is present in the original source. var isPresent: Bool { return presence == .present } /// Whether this node is missing from the original source. var isMissing: Bool { return presence == .missing } /// Keys for serializing RawSyntax nodes. enum CodingKeys: String, CodingKey { // Keys for the `node` case case kind, layout, presence // Keys for the `token` case case tokenKind, leadingTrivia, trailingTrivia } /// Creates a RawSyntax from the provided Foundation Decoder. init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let presence = try container.decode(SourcePresence.self, forKey: .presence) if let kind = try container.decodeIfPresent(SyntaxKind.self, forKey: .kind) { let layout = try container.decode([RawSyntax?].self, forKey: .layout) self = .node(kind, layout, presence) } else { let kind = try container.decode(TokenKind.self, forKey: .tokenKind) let leadingTrivia = try container.decode(Trivia.self, forKey: .leadingTrivia) let trailingTrivia = try container.decode(Trivia.self, forKey: .trailingTrivia) self = .token(kind, leadingTrivia, trailingTrivia, presence) } } /// Encodes the RawSyntax to the provided Foundation Encoder. func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case let .node(kind, layout, presence): try container.encode(kind, forKey: .kind) try container.encode(layout, forKey: .layout) try container.encode(presence, forKey: .presence) case let .token(kind, leadingTrivia, trailingTrivia, presence): try container.encode(kind, forKey: .tokenKind) try container.encode(leadingTrivia, forKey: .leadingTrivia) try container.encode(trailingTrivia, forKey: .trailingTrivia) try container.encode(presence, forKey: .presence) } } /// Creates a RawSyntax node that's marked missing in the source with the /// provided kind and layout. /// - Parameters: /// - kind: The syntax kind underlying this node. /// - layout: The children of this node. /// - Returns: A new RawSyntax `.node` with the provided kind and layout, with /// `.missing` source presence. static func missing(_ kind: SyntaxKind) -> RawSyntax { return .node(kind, [], .missing) } /// Creates a RawSyntax token that's marked missing in the source with the /// provided kind and no leading/trailing trivia. /// - Parameter kind: The token kind. /// - Returns: A new RawSyntax `.token` with the provided kind, no /// leading/trailing trivia, and `.missing` source presence. static func missingToken(_ kind: TokenKind) -> RawSyntax { return .token(kind, [], [], .missing) } /// Returns a new RawSyntax node with the provided layout instead of the /// existing layout. /// - Note: This function does nothing with `.token` nodes --- the same token /// is returned. /// - Parameter newLayout: The children of the new node you're creating. func replacingLayout(_ newLayout: [RawSyntax?]) -> RawSyntax { switch self { case let .node(kind, _, presence): return .node(kind, newLayout, presence) case .token(_, _, _, _): return self } } /// Creates a new RawSyntax with the provided child appended to its layout. /// - Parameter child: The child to append /// - Note: This function does nothing with `.token` nodes --- the same token /// is returned. /// - Return: A new RawSyntax node with the provided child at the end. func appending(_ child: RawSyntax) -> RawSyntax { var newLayout = layout newLayout.append(child) return replacingLayout(newLayout) } /// Returns the child at the provided cursor in the layout. /// - Parameter index: The index of the child you're accessing. /// - Returns: The child at the provided index. subscript<CursorType: RawRepresentable>(_ index: CursorType) -> RawSyntax? where CursorType.RawValue == Int { return layout[index.rawValue] } /// Replaces the child at the provided index in this node with the provided /// child. /// - Parameters: /// - index: The index of the child to replace. /// - newChild: The new child that should occupy that index in the node. func replacingChild(_ index: Int, with newChild: RawSyntax) -> RawSyntax { precondition(index < layout.count, "Cursor \(index) reached past layout") var newLayout = layout newLayout[index] = newChild return replacingLayout(newLayout) } } extension RawSyntax: TextOutputStreamable { /// Prints the RawSyntax node, and all of its children, to the provided /// stream. This implementation must be source-accurate. /// - Parameter stream: The stream on which to output this node. func write<Target>(to target: inout Target) where Target: TextOutputStream { switch self { case .node(_, let layout, _): for child in layout { guard let child = child else { continue } child.write(to: &target) } case let .token(kind, leadingTrivia, trailingTrivia, presence): guard case .present = presence else { return } for piece in leadingTrivia { piece.write(to: &target) } target.write(kind.text) for piece in trailingTrivia { piece.write(to: &target) } } } } extension RawSyntax { func accumulateAbsolutePosition(_ pos: AbsolutePosition) { switch self { case .node(_, let layout, _): for child in layout { guard let child = child else { continue } child.accumulateAbsolutePosition(pos) } case let .token(kind, leadingTrivia, trailingTrivia, presence): guard case .present = presence else { return } for piece in leadingTrivia { piece.accumulateAbsolutePosition(pos) } pos.add(text: kind.text) for piece in trailingTrivia { piece.accumulateAbsolutePosition(pos) } } } var leadingTrivia: Trivia? { switch self { case .node(_, let layout, _): for child in layout { guard let child = child else { continue } guard let result = child.leadingTrivia else { continue } return result } return nil case let .token(_, leadingTrivia, _, presence): guard case .present = presence else { return nil } return leadingTrivia } } var trailingTrivia: Trivia? { switch self { case .node(_, let layout, _): for child in layout.reversed() { guard let child = child else { continue } guard let result = child.trailingTrivia else { continue } return result } return nil case let .token(_, _, trailingTrivia, presence): guard case .present = presence else { return nil } return trailingTrivia } } func accumulateLeadingTrivia(_ pos: AbsolutePosition) { guard let trivia = leadingTrivia else { return } for piece in trivia { piece.accumulateAbsolutePosition(pos) } } func accumulateTrailingTrivia(_ pos: AbsolutePosition) { guard let trivia = trailingTrivia else { return } for piece in trivia { piece.accumulateAbsolutePosition(pos) } } }
22e7aca0aa76f89cd7a3bc56ddd688ab
34.142308
85
0.653825
false
false
false
false
svd-zp/SDPagingViewController
refs/heads/master
SDPagingViewController/SDPagingViewController/ModelController.swift
mit
1
// // ModelController.swift // SDPagingViewController // // Created by SvD on 09.12.15. // Copyright © 2015 SvD. All rights reserved. // import UIKit /* A controller object that manages a simple model -- a collection of month names. The controller serves as the data source for the page view controller; it therefore implements pageViewController:viewControllerBeforeViewController: and pageViewController:viewControllerAfterViewController:. It also implements a custom method, viewControllerAtIndex: which is useful in the implementation of the data source methods, and in the initial configuration of the application. There is no need to actually create view controllers for each page in advance -- indeed doing so incurs unnecessary overhead. Given the data model, these methods create, configure, and return a new view controller on demand. */ class ModelController: NSObject, UIPageViewControllerDataSource { var pageData: [String] = [] override init() { super.init() // Create the data model. let dateFormatter = NSDateFormatter() pageData = dateFormatter.monthSymbols } func viewControllerAtIndex(index: Int, storyboard: UIStoryboard) -> DataViewController? { // Return the data view controller for the given index. if (self.pageData.count == 0) || (index >= self.pageData.count) { return nil } // Create a new view controller and pass suitable data. let dataViewController = storyboard.instantiateViewControllerWithIdentifier("DataViewController") as! DataViewController dataViewController.dataObject = self.pageData[index] return dataViewController } func indexOfViewController(viewController: DataViewController) -> Int { // Return the index of the given data view controller. // For simplicity, this implementation uses a static array of model objects and the view controller stores the model object; you can therefore use the model object to identify the index. return pageData.indexOf(viewController.dataObject) ?? NSNotFound } // MARK: - Page View Controller Data Source func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { var index = self.indexOfViewController(viewController as! DataViewController) if (index == 0) || (index == NSNotFound) { // return nil index = self.pageData.count } if index > 0 { index-- } return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!) } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { var index = self.indexOfViewController(viewController as! DataViewController) if index == NSNotFound { index = 0 } index++ if index == self.pageData.count { index = 0 } return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!) } }
cc35cd9051cc61e732a01981978bc6be
38.9
225
0.7099
false
false
false
false
herrkaefer/AccelerateWatch
refs/heads/master
AccelerateWatch/Classes/DSBuffer.swift
mit
1
/// DSBuffer /// /// Created by Yang Liu (gloolar [at] gmail [dot] com) on 16/6/20. /// Copyright © 2016年 Yang Liu. All rights reserved. import Foundation /// Fixed-length buffer for windowed signal processing public class DSBuffer { private var buffer: OpaquePointer private var size: Int private var fftIsSupported: Bool private var fftData: [dsbuffer_complex]? private var fftIsUpdated: Bool? // MARK: Initializer and deinitializer /// Initializer /// /// - parameter size: Buffer length. If you set fftIsSupperted to be true, the size should be **even** number /// - parameter fftIsSupported: Whether FFT will be performed on the buffer /// - returns: DSBuffer object /// /// *Tips*: /// /// - If you do not need to perform FFT on the buffer, set fftIsSupperted to be false could save 50% memory. /// - If you need to perform FFT, set buffer size to power of 2 could accelerate more. init(_ size: Int, fftIsSupported: Bool = true) { if (fftIsSupported && size % 2 == 1) { print(String(format: "WARNING: size must be even for FFT. Reset size to: %d.", size+1)) self.size = size + 1 } else { self.size = size } self.buffer = dsbuffer_new(size, fftIsSupported) self.fftIsSupported = fftIsSupported if (fftIsSupported) { self.fftData = [dsbuffer_complex](repeating: dsbuffer_complex(real: 0.0, imag: 0.0), count: self.size/2+1) self.fftIsUpdated = false } } /// :nodoc: deinitializer deinit { dsbuffer_free_unsafe(self.buffer) } // MARK: Regular operations /// Push new value to buffer (and the foremost will be dropped) /// /// - parameter value: New value to be added func push(_ value: Float) { dsbuffer_push(self.buffer, value) if (self.fftIsSupported) { self.fftIsUpdated = false } } /// Get data by index func dataAt(_ index: Int) -> Float { return dsbuffer_at(self.buffer, index) } /// Get Buffer size var bufferSize: Int { return self.size } /// Dump buffer as array var data: [Float] { var dumped = [Float](repeating: 0.0, count: self.size) dsbuffer_dump(self.buffer, &dumped) return dumped } /// Reset buffer to be zero filled func clear() { dsbuffer_clear(self.buffer) if (self.fftIsSupported) { self.fftIsUpdated = false } } /// Print buffer func printBuffer(_ dataFormat: String) { print("DSBuffer size: \(self.size)") for idx in 0..<self.size { print(String(format: dataFormat, dsbuffer_at(self.buffer, idx)), terminator: " ") } print("\n") } // MARK: Vector-like operations /// Add value to each buffer data func add(_ withValue: Float) -> [Float] { var result = [Float](repeating: 0.0, count: self.size) dsbuffer_add(self.buffer, withValue, &result) return result } /// Multiply each buffer data with value func multiply(_ withValue: Float) -> [Float] { var result = [Float](repeating: 0.0, count: self.size) dsbuffer_multiply(self.buffer, withValue, &result) return result } /// Modulus by value of each buffer data func mod(_ withValue: Float) -> [Float] { var result = [Float](repeating: 0.0, count: self.size) dsbuffer_mod(self.buffer, withValue, &result) return result } /// Remove mean value var centralized: [Float] { var result = [Float](repeating: 0.0, count: self.size) dsbuffer_remove_mean(self.buffer, &result) return result } /// Normalize vector to have unit length /// /// - parameter centralized: Should remove mean? func normalizedToUnitLength(_ centralized: Bool) -> [Float] { var result = [Float](repeating: 0.0, count: self.size) dsbuffer_normalize_to_unit_length(self.buffer, centralized, &result) return result } /// Normalize vector to have unit variance /// /// - parameter centralized: Should remove mean? func normalizedToUnitVariance(_ centralized: Bool) -> [Float] { var result = [Float](repeating: 0.0, count: self.size) dsbuffer_normalize_to_unit_variance(self.buffer, centralized, &result) return result } /// Perform dot production with array func dotProduct(_ with: [Float]) -> Float { assert(self.size == with.count) return dsbuffer_dot_product(self.buffer, with) } // MARK: Time-domain features /// Mean value var mean: Float { return dsbuffer_mean(self.buffer) } /// Mean value var sum: Float { return dsbuffer_sum(self.buffer) } /// Vector length var length: Float { return dsbuffer_length(self.buffer) } /// Square of length var energy: Float { return dsbuffer_energy(self.buffer) } /// Max value var max: Float { return dsbuffer_max(self.buffer) } /// Min value var min: Float { return dsbuffer_min(self.buffer) } /// Variance var variance: Float { return dsbuffer_variance(self.buffer) } /// Standard deviation var std: Float { return dsbuffer_std(self.buffer) } // MARK: FFT & frequency-domain features // Perform FFT if it is not updated private func updateFFT() { assert (self.fftIsSupported) if (!self.fftIsUpdated!) { _ = fft() } } /// Perform FFT /// /// **Note for FFT related methods**: /// /// - Set fftIsSupported to true when creating the buffer. /// - Buffer size should be even. If you pass odd size when creating the buffer, it is automatically increased by 1. /// - Only results in nfft/2+1 complex frequency bins from DC to Nyquist are returned. func fft() -> (real: [Float], imaginary: [Float]) { assert (self.fftIsSupported, "FFT is not supported on this buffer") dsbuffer_fftr(self.buffer, &self.fftData!) self.fftIsUpdated = true return (self.fftData!.map{$0.real}, self.fftData!.map{$0.imag}) } /// FFT sample frequencies /// /// - returns: array of size nfft/2+1 func fftFrequencies(_ fs: Float) -> [Float] { assert (self.fftIsSupported) var fftFreq = [Float](repeating: 0.0, count: self.size/2+1) dsbuffer_fft_freq(self.buffer, fs, &fftFreq) return fftFreq } /// FFT magnitudes, i.e. abs(fft()) /// /// - returns: array of size nfft/2+1 func fftMagnitudes() -> [Float] { updateFFT() return self.fftData!.map{sqrt($0.real*$0.real + $0.imag*$0.imag)} } /// Square of FFT magnitudes, i.e. (abs(fft()))^2 /// /// - returns: array of size nfft/2+1 func squaredPowerSpectrum() -> [Float] { updateFFT() var sps = self.fftData!.map{($0.real*$0.real + $0.imag*$0.imag) * 2} sps[0] /= 2.0 // DC return sps } /// Mean-squared power spectrum, i.e. (abs(fft()))^2 / N /// /// - returns: array of size nfft/2+1 func meanSquaredPowerSpectrum() -> [Float] { updateFFT() var pxx = self.fftData!.map{($0.real*$0.real + $0.imag*$0.imag) * 2 / Float(self.size)} pxx[0] /= 2.0 // DC return pxx } /// Power spectral density (PSD), i.e. (abs(fft()))^2 / (fs*N) /// /// - returns: array of size nfft/2+1 func powerSpectralDensity(_ fs: Float) -> [Float] { updateFFT() var psd = self.fftData!.map{($0.real*$0.real + $0.imag*$0.imag) * 2.0 / (fs * Float(self.size))} psd[0] /= 2.0 // DC return psd } /// Average power over specific frequency band, i.e. mean(abs(fft(from...to))^2) func averageBandPower(_ fromFreq: Float = 0, toFreq: Float, fs: Float) -> Float { assert (fromFreq >= 0) assert (toFreq <= fs/2.0) assert (fromFreq <= toFreq) updateFFT() // Compute index range corresponding to given frequency band // f = idx*df = idx*fs/N ==> idx = N*f/fs let fromIdx = Int(floor(fromFreq * Float(self.size) / fs)) let toIdx = Int(ceil(toFreq * Float(self.size) / fs)) let bandPower = self.fftData![fromIdx...toIdx].map{$0.real*$0.real+$0.imag*$0.imag} // Averaging return bandPower.reduce(0.0, +) / Float(toIdx - fromIdx + 1) } // MARK: FIR filter // Setup FIR filter func setupFIRFilter(_ FIRTaps: [Float]) { assert (self.size >= FIRTaps.count) dsbuffer_setup_fir(self.buffer, FIRTaps, FIRTaps.count) } /// Get latest FIR output func latestFIROutput() -> Float { return dsbuffer_latest_fir_output(self.buffer) } /// FIR filtered buffer func FIRFiltered() -> [Float] { var output = [Float](repeating: 0.0, count: self.size) dsbuffer_fir_filter(self.buffer, &output) return output } /// :nodoc: Self test public class func test() { print("\nDSBuffer test: ==============\n") let size = 16 let buf = DSBuffer(size, fftIsSupported: true) buf.printBuffer("%.2f") let signalData: [Float] = [1.0, 4, 2, 5, 6, 7, -1, -8] for value in signalData { buf.push(value) // print(buf.signals) } buf.printBuffer("%.2f") let startTime = CFAbsoluteTimeGetCurrent() let fft = buf.fft() let deltaTime = CFAbsoluteTimeGetCurrent() - startTime print("FFT time: \(deltaTime)") print(fft) let fftSM = buf.squaredPowerSpectrum() print(fftSM) buf.clear() for _ in 0 ..< 10000 { let a = Float(arc4random_uniform(100)) buf.push(a) let signals = buf.data // print(a) // print(signals) assert(signals[size-1] == a) } let norm = buf.normalizedToUnitLength(true) let coeff = vDotProduct(norm, v2: norm) print(String(format: "coeff: %.2f\n", coeff)) print("\nDSBuffer test OK.\n\n") } }
ef0bd274aef951ca9803dfa39261340a
27.070681
120
0.55367
false
false
false
false
almazrafi/Metatron
refs/heads/master
Sources/ID3v2/FrameStuffs/ID3v2SyncedLyrics.swift
mit
1
// // ID3v2SyncedLyrics.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 public class ID3v2SyncedLyrics: ID3v2FrameStuff { // MARK: Nested Types public enum ContentType: UInt8 { case other case lyrics case transcription case movement case events case chord case trivia case webpageURLs case imageURLs } public struct Syllable: Equatable { // MARK: Instance Properties public var text: String = "" public var timeStamp: UInt32 = 0 // MARK: public var isEmpty: Bool { return self.text.isEmpty } // MARK: Initializers init(_ text: String, timeStamp: UInt32) { self.text = text self.timeStamp = timeStamp } init() { } } // MARK: Instance Properties public var textEncoding: ID3v2TextEncoding = ID3v2TextEncoding.utf8 public var language: ID3v2Language = ID3v2Language.und public var timeStampFormat: ID3v2TimeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds public var contentType: ContentType = ContentType.other public var description: String = "" public var syllables: [Syllable] = [] // MARK: public var isEmpty: Bool { return self.syllables.isEmpty } // MARK: Initializers public init() { } public required init(fromData data: [UInt8], version: ID3v2Version) { guard data.count > 11 else { return } guard let textEncoding = ID3v2TextEncoding(rawValue: data[0]) else { return } guard let language = ID3v2Language(code: [UInt8](data[1..<4])) else { return } guard let timeStampFormat = ID3v2TimeStampFormat(rawValue: data[4]) else { return } guard let contentType = ContentType(rawValue: data[5]) else { return } guard let description = textEncoding.decode([UInt8](data.suffix(from: 6))) else { return } var offset = 6 + description.endIndex var syllables: [Syllable] = [] if textEncoding == ID3v2TextEncoding.utf16 { guard offset <= data.count - 8 else { return } let utf16TextEncoding: ID3v2TextEncoding if (data[offset] == 255) && (data[offset + 1] == 254) { utf16TextEncoding = ID3v2TextEncoding.utf16LE } else if (data[offset] == 254) && (data[offset + 1] == 255) { utf16TextEncoding = ID3v2TextEncoding.utf16BE } else { utf16TextEncoding = textEncoding } repeat { guard let text = utf16TextEncoding.decode([UInt8](data.suffix(from: offset))) else { return } offset += text.endIndex guard offset < data.count - 3 else { return } var timeStamp = UInt32(data[offset + 3]) timeStamp |= UInt32(data[offset + 2]) << 8 timeStamp |= UInt32(data[offset + 1]) << 16 timeStamp |= UInt32(data[offset + 0]) << 24 syllables.append(Syllable(text.text, timeStamp: timeStamp)) offset += 4 } while offset < data.count } else { guard offset <= data.count - 5 else { return } repeat { guard let text = textEncoding.decode([UInt8](data.suffix(from: offset))) else { return } offset += text.endIndex guard offset < data.count - 3 else { return } var timeStamp = UInt32(data[offset + 3]) timeStamp |= UInt32(data[offset + 2]) << 8 timeStamp |= UInt32(data[offset + 1]) << 16 timeStamp |= UInt32(data[offset + 0]) << 24 syllables.append(Syllable(text.text, timeStamp: timeStamp)) offset += 4 } while offset < data.count } self.textEncoding = textEncoding self.language = language self.timeStampFormat = timeStampFormat self.contentType = contentType self.description = description.text self.syllables = syllables } // MARK: Instance Methods public func toData(version: ID3v2Version) -> [UInt8]? { guard !self.isEmpty else { return nil } let textEncoding: ID3v2TextEncoding switch version { case ID3v2Version.v2, ID3v2Version.v3: if self.textEncoding == ID3v2TextEncoding.latin1 { textEncoding = ID3v2TextEncoding.latin1 } else { textEncoding = ID3v2TextEncoding.utf16 } case ID3v2Version.v4: textEncoding = self.textEncoding } var data = [textEncoding.rawValue] data.append(contentsOf: self.language.code) data.append(self.timeStampFormat.rawValue) data.append(self.contentType.rawValue) data.append(contentsOf: textEncoding.encode(self.description, termination: true)) var timeStamp: UInt32 = 0 for syllable in self.syllables { if timeStamp < syllable.timeStamp { timeStamp = syllable.timeStamp } data.append(contentsOf: textEncoding.encode(syllable.text, termination: true)) data.append(contentsOf: [UInt8((timeStamp >> 24) & 255), UInt8((timeStamp >> 16) & 255), UInt8((timeStamp >> 8) & 255), UInt8((timeStamp) & 255)]) } return data } public func toData() -> (data: [UInt8], version: ID3v2Version)? { guard let data = self.toData(version: ID3v2Version.v4) else { return nil } return (data: data, version: ID3v2Version.v4) } } public class ID3v2SyncedLyricsFormat: ID3v2FrameStuffSubclassFormat { // MARK: Type Properties public static let regular = ID3v2SyncedLyricsFormat() // MARK: Instance Methods public func createStuffSubclass(fromData data: [UInt8], version: ID3v2Version) -> ID3v2SyncedLyrics { return ID3v2SyncedLyrics(fromData: data, version: version) } public func createStuffSubclass(fromOther other: ID3v2SyncedLyrics) -> ID3v2SyncedLyrics { let stuff = ID3v2SyncedLyrics() stuff.textEncoding = other.textEncoding stuff.language = other.language stuff.timeStampFormat = other.timeStampFormat stuff.contentType = other.contentType stuff.description = other.description stuff.syllables = other.syllables return stuff } public func createStuffSubclass() -> ID3v2SyncedLyrics { return ID3v2SyncedLyrics() } } public func == (left: ID3v2SyncedLyrics.Syllable, right: ID3v2SyncedLyrics.Syllable) -> Bool { if left.text != right.text { return false } if left.timeStamp != right.timeStamp { return false } return true } public func != (left: ID3v2SyncedLyrics.Syllable, right: ID3v2SyncedLyrics.Syllable) -> Bool { return !(left == right) }
9ad3264362471c4c57454737809672a2
27.306931
105
0.587968
false
false
false
false
cocoaswifty/V2EX
refs/heads/master
V2EX/UIView.swift
apache-2.0
1
// // UIView.swift // EngineerMaster // // Created by tracetw on 2016/2/17. // Copyright © 2016年 mycena. All rights reserved. // import UIKit extension UIView { func squareTurnCircle() { // self.layer.cornerRadius = self.frame.width/2 layer.cornerRadius = frame.width/2 } class func loadNib<T: UIView>(_ viewType: T.Type) -> T { let className = String.className(viewType) return Bundle(for: viewType).loadNibNamed(className, owner: nil, options: nil)!.first as! T } class func loadNib() -> Self { return loadNib(self) } // @IBInspectable var cornerRadius: CGFloat { // get { // return layer.cornerRadius // } // set { // layer.cornerRadius = newValue // layer.masksToBounds = newValue > 0 // } // } }
aa6286ceb90c6eba5d9a54aecc700fca
22.722222
99
0.576112
false
false
false
false
JGiola/swift
refs/heads/main
test/decl/init/failable.swift
apache-2.0
5
// Run in compatibility modes that disable and enable optional flattening // in 'try?' to verify that initializer delegation diagnostics that are related // to 'try?' are stable. // RUN: %target-typecheck-verify-swift -swift-version 4 // RUN: %target-typecheck-verify-swift -swift-version 5 // REQUIRES: objc_interop import Foundation struct S0 { init!(int: Int) { } init! (uint: UInt) { } init !(float: Float) { } init?(string: String) { } init ?(double: Double) { } init ? (char: Character) { } } struct S1<T> { init?(value: T) { } } class DuplicateDecls { init!() { } // expected-note{{'init()' previously declared here}} init?() { } // expected-error{{invalid redeclaration of 'init()'}} init!(string: String) { } // expected-note{{'init(string:)' previously declared here}} init(string: String) { } // expected-error{{invalid redeclaration of 'init(string:)'}} init(double: Double) { } // expected-note{{'init(double:)' previously declared here}} init?(double: Double) { } // expected-error{{invalid redeclaration of 'init(double:)'}} } // Construct via a failable initializer. func testConstruction(_ i: Int, s: String) { let s0Opt = S0(string: s) assert(s0Opt != nil) var _: S0 = s0Opt // expected-error{{value of optional type 'S0?' must be unwrapped}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let s0IUO = S0(int: i) assert(s0IUO != nil) _ = s0IUO } // ---------------------------------------------------------------------------- // Superclass initializer chaining // ---------------------------------------------------------------------------- class Super { init?(fail: String) { } init!(failIUO: String) { } init() { } // expected-note 2{{non-failable initializer 'init()' overridden here}} } class Sub : Super { override init() { super.init() } // okay, never fails init(nonfail: Int) { // expected-note{{propagate the failure with 'init?'}}{{7-7=?}} super.init(fail: "boom") // expected-error{{a non-failable initializer cannot chain to failable initializer 'init(fail:)' written with 'init?'}} // expected-note@-1{{force potentially-failing result with '!'}}{{29-29=!}} } convenience init(forceNonfail: Int) { self.init(nonfail: forceNonfail)! // expected-error{{cannot force unwrap value of non-optional type}} {{37-38=}} } init(nonfail2: Int) { // okay, traps on nil super.init(failIUO: "boom") } init(nonfail3: Int) { super.init(fail: "boom")! } override init?(fail: String) { super.init(fail: fail) // okay, propagates ? } init?(fail2: String) { // okay, propagates ! as ? super.init(failIUO: fail2) } init?(fail3: String) { // okay, can introduce its own failure super.init() } override init!(failIUO: String) { super.init(failIUO: failIUO) // okay, propagates ! } init!(failIUO2: String) { // okay, propagates ? as ! super.init(fail: failIUO2) } init!(failIUO3: String) { // okay, can introduce its own failure super.init() } } // ---------------------------------------------------------------------------- // Initializer delegation // ---------------------------------------------------------------------------- extension Super { convenience init(convenienceNonFailNonFail: String) { // okay, non-failable self.init() } convenience init(convenienceNonFailFail: String) { // expected-note{{propagate the failure with 'init?'}}{{19-19=?}} self.init(fail: convenienceNonFailFail) // expected-error{{a non-failable initializer cannot delegate to failable initializer 'init(fail:)' written with 'init?'}} // expected-note@-1{{force potentially-failing result with '!'}}{{44-44=!}} } convenience init(convenienceNonFailFailForce: String) { self.init(fail: convenienceNonFailFailForce)! } convenience init(convenienceNonFailFailIUO: String) { // okay, trap on failure self.init(failIUO: convenienceNonFailFailIUO) } convenience init?(convenienceFailNonFail: String) { self.init() // okay, can introduce its own failure } convenience init?(convenienceFailFail: String) { self.init(fail: convenienceFailFail) // okay, propagates ? } convenience init?(convenienceFailFailIUO: String) { // okay, propagates ! as ? self.init(failIUO: convenienceFailFailIUO) } convenience init!(convenienceFailIUONonFail: String) { self.init() // okay, can introduce its own failure } convenience init!(convenienceFailIUOFail: String) { self.init(fail: convenienceFailIUOFail) // okay, propagates ? as ! } convenience init!(convenienceFailIUOFailIUO: String) { // okay, propagates ! self.init(failIUO: convenienceFailIUOFailIUO) } } struct SomeStruct { init?(failable: Void) {} init!(failableIUO: Void) {} init(throws: Void) throws {} init?(failableAndThrows: Void) throws {} init!(failableIUOAndThrows: Void) throws {} init(delegationOk1: Void) { self.init(failable: ())! } init(delegationOk2: Void) { try! self.init(throws: ()) } init(delegationOk3: Void) { try! self.init(failableAndThrows: ())! } init(delegationOk4: Void) { try! self.init(failableIUOAndThrows: ()) } init(nonFailable: Void) { // expected-note{{propagate the failure with 'init?'}}{{7-7=?}} self.init(failable: ()) // expected-error{{a non-failable initializer cannot delegate to failable initializer 'init(failable:)' written with 'init?'}} // expected-note@-1{{force potentially-failing result with '!'}}{{28-28=!}} } init(delegationBad1: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try? self.init(nonFailable: ()) // expected-warning@-1 {{no calls to throwing functions occur within 'try' expression}} // expected-error@-2 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-3 {{force potentially-failing result with 'try!'}}{{5-9=try!}} } init(delegationBad2: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try? self.init(failableIUO: ()) // expected-warning@-1 {{no calls to throwing functions occur within 'try' expression}} // expected-error@-2 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-3 {{force potentially-failing result with 'try!'}}{{5-9=try!}} } init(delegationBad3: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try? self.init(throws: ()) // expected-error@-1 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-2 {{force potentially-failing result with 'try!'}}{{5-9=try!}} } init(delegationBad4: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try! try? self.init(throws: ()) // expected-warning@-1 {{no calls to throwing functions occur within 'try' expression}} // expected-error@-2 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-3 {{force potentially-failing result with 'try!'}}{{10-14=try!}} } init(delegationBad5: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try try? self.init(throws: ()) // expected-warning@-1 {{no calls to throwing functions occur within 'try' expression}} // expected-error@-2 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-3 {{force potentially-failing result with 'try!'}}{{9-13=try!}} } init(delegationBad6: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try? self.init(failableAndThrows: ())! // expected-error@-1 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-2 {{force potentially-failing result with 'try!'}}{{5-9=try!}} } init(delegationBad7: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try! self.init(failableAndThrows: ()) // expected-error@-1 {{a non-failable initializer cannot delegate to failable initializer 'init(failableAndThrows:)' written with 'init?'}} // expected-note@-2 {{force potentially-failing result with '!'}}{{42-42=!}} } init(delegationBad8: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} try? self.init(failableIUOAndThrows: ()) // expected-error@-1 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-2 {{force potentially-failing result with 'try!'}}{{5-9=try!}} } init(delegationBad9: Void) { // expected-note 2 {{propagate the failure with 'init?'}}{{7-7=?}} try? self.init(failableAndThrows: ()) // expected-error@-1 {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-error@-2 {{a non-failable initializer cannot delegate to failable initializer 'init(failableAndThrows:)' written with 'init?'}} // expected-note@-3 {{force potentially-failing result with '!'}}{{42-42=!}} // expected-note@-4 {{force potentially-failing result with 'try!'}}{{5-9=try!}} } } extension Optional { init(delegationOk1: Void) { self.init(nonFailable: ()) } init?(delegationOk2: Void) { self.init(nonFailable: ()) } init?(delegationOk3: Void) { self.init(failable: ()) } init(delegationBad1: Void) { // expected-note {{propagate the failure with 'init?'}}{{7-7=?}} self.init(failable: ()) // expected-error@-1 {{a non-failable initializer cannot delegate to failable initializer 'init(failable:)' written with 'init?'}} // expected-note@-2 {{force potentially-failing result with '!'}}{{28-28=!}} } init(nonFailable: Void) {} init?(failable: Void) {} } // ---------------------------------------------------------------------------- // Initializer overriding // ---------------------------------------------------------------------------- class Sub2 : Super { override init!(fail: String) { // okay to change ? to ! super.init(fail: fail) } override init?(failIUO: String) { // okay to change ! to ? super.init(failIUO: failIUO) } override init() { super.init() } // no change } // Dropping optionality class Sub3 : Super { override init(fail: String) { // okay, strengthened result type super.init() } override init(failIUO: String) { // okay, strengthened result type super.init() } override init() { } // no change } // Adding optionality class Sub4 : Super { override init?(fail: String) { super.init() } override init!(failIUO: String) { super.init() } override init?() { // expected-error{{failable initializer 'init()' cannot override a non-failable initializer}} super.init() } } class Sub5 : Super { override init?(fail: String) { super.init() } override init!(failIUO: String) { super.init() } override init!() { // expected-error{{failable initializer 'init()' cannot override a non-failable initializer}} super.init() } } // ---------------------------------------------------------------------------- // Initializer conformances // ---------------------------------------------------------------------------- protocol P1 { init(string: String) } @objc protocol P1_objc { init(string: String) } protocol P2 { init?(fail: String) } protocol P3 { init!(failIUO: String) } class C1a : P1 { required init?(string: String) { } // expected-error{{non-failable initializer requirement 'init(string:)' cannot be satisfied by a failable initializer ('init?')}} } class C1b : P1 { required init!(string: String) { } // okay } class C1b_objc : P1_objc { @objc required init!(string: String) { } // expected-error{{non-failable initializer requirement 'init(string:)' in Objective-C protocol cannot be satisfied by a failable initializer ('init!')}} } class C1c { required init?(string: String) { } // expected-note {{'init(string:)' declared here}} } extension C1c: P1 {} // expected-error{{non-failable initializer requirement 'init(string:)' cannot be satisfied by a failable initializer ('init?')}} class C2a : P2 { required init(fail: String) { } // okay to remove failability } class C2b : P2 { required init?(fail: String) { } // okay, ? matches } class C2c : P2 { required init!(fail: String) { } // okay to satisfy init? with init! } class C3a : P3 { required init(failIUO: String) { } // okay to remove failability } class C3b : P3 { required init?(failIUO: String) { } // okay to satisfy ! with ? } class C3c : P3 { required init!(failIUO: String) { } // okay, ! matches } // ---------------------------------------------------------------------------- // Initiating failure // ---------------------------------------------------------------------------- struct InitiateFailureS { init(string: String) { // expected-note{{use 'init?' to make the initializer 'init(string:)' failable}}{{7-7=?}} return (nil) // expected-error{{only a failable initializer can return 'nil'}} } init(int: Int) { return 0 // expected-error{{'nil' is the only return value permitted in an initializer}} } init?(double: Double) { return nil // ok } init!(char: Character) { return nil // ok } }
848823755e44720ab49d21adf06936b5
33.268734
196
0.625396
false
false
false
false
apple/swift-lldb
refs/heads/stable
packages/Python/lldbsuite/test/lang/swift/generic_class_arg/main.swift
apache-2.0
2
protocol P { func foo() -> Int32 } public class C: P { var x: Int32 = 11223344 public func foo() -> Int32 { return x } } public struct S : P { var x: Int32 = 44332211 public func foo() -> Int32 { return x } } func foo<T1: P, T2: P> (_ t1: T1, _ t2: T2) -> Int32 { return t1.foo() + t2.foo() //% self.expect('frame variable -d run -- t1', substrs=['11223344']) //% self.expect('frame variable -d run -- t2', substrs=['44332211']) //% self.expect('expression -d run -- t1', substrs=['11223344']) //% self.expect('expression -d run -- t2', substrs=['44332211']) } print(foo(C(), S()))
9e0309d25a3072ecc112eab8bf621267
22.884615
97
0.570048
false
false
false
false
theddnc/iPromise
refs/heads/master
iPromiseTests/iPromiseTests.swift
mit
1
// // PromiseTests.swift // iPromiseTests // // Created by jzaczek on 24.10.2015. // Copyright © 2015 jzaczek. All rights reserved. // import XCTest @testable import iPromise class PromiseTests: XCTestCase { enum Error: ErrorType { case Error } /** Tests promise fulfilling mechanisms */ func testFulfill() { let promise = Promise.fulfill(true) XCTAssertEqual(promise.state, State.Fulfilled, "Promise should be fulfilled.") expect { testExpectation in promise.success { result in XCTAssertEqual(result, true, "Promise's result should be equal to true.") testExpectation.fulfill() } promise.failure { error in XCTFail("Failure handler should not have run.") } } } func testReadmeTest() { enum Error: ErrorType { case FailureAndError } expect { testEx in async { return 0.5 }.then({ result in if result > 0.5 { print("This is quite a large number") } else { throw Error.FailureAndError } }).then({ result in // this won't be called }).then({ result in // this won't be called }).failure({ (error) -> Double in // but this will switch error as! Error { case .FailureAndError: print("Long computation has failed miserably :(") } // let's recover return 0.6 }).then ({ result -> Double in if result > 0.5 { print("This is quite a large number") testEx.fulfill() } return 0.1 }) } } /** Tests promise rejection mechanisms */ func testReject() { let promise = Promise<Any>.reject(PromiseError.NilReason) XCTAssertEqual(promise.state, State.Rejected, "Promise should be rejected.") expect { testExpectation in promise.failure { error in XCTAssert(error is PromiseError) testExpectation.fulfill() } promise.success { result in XCTFail("Success handler should not have run.") } } } /** Tests promise construction capabilities and state watchers */ func testFulfillFromExecutor() { let promise = Promise { fulfill, reject in fulfill(true) } expect { testExpectation in promise.success { result in XCTAssertEqual(result, true, "Promise's result should be equal to true") testExpectation.fulfill() } promise.failure { error in XCTFail("Failure handler should not have run") } } } /** Tests promise construction capabilities and state watchers */ func testRejectFromExecutor() { let promise = Promise<Any> { fulfill, reject in reject(PromiseError.NilReason) } expect { testExpectation in promise.failure { error in XCTAssert(error is PromiseError) testExpectation.fulfill() } promise.success { result in XCTFail("Sucess handler should not have run") } } } func testAsyncReturn() { expect { testExpectation in let promise = async { return true } promise.success { result in XCTAssertEqual(result, true, "Async result should be true") testExpectation.fulfill() } promise.failure { error in XCTFail("Failure handler should not have run") } } } func testAsyncThrow() { expect { testExpectation in let promise = async { throw Error.Error } promise.failure { reason in XCTAssertEqual(reason as? Error, Error.Error, "Async reason should be Error.Error") testExpectation.fulfill() } promise.success { result in XCTFail("Success handler should not have run") } } } func testRace() { let bigInt = 10000000 let promises: [Promise<Int>] = self.promiseArray(bigInt) expect { testExpectation in let promise = Promise<Int>.race(promises) promise.success { result -> Int in XCTAssertEqual(result, bigInt, "First promise should finish sooner") testExpectation.fulfill() return result } promise.failure { error in XCTFail("Failure handler should not have run") } } } func testRaceFailure() { let promises: [Promise<Int>] = [ Promise.reject(PromiseError.NilReason), Promise.reject(PromiseError.NilReason) ] expect { testExpectation in let promise = Promise<Int>.race(promises) promise.failure { error in if let error = error as? PromiseError { switch error { case .NilReason: testExpectation.fulfill() default: XCTFail() } } else { XCTFail() } } promise.success { result in XCTFail("Success handler should not have run") } } } func testAllWithFailure() { let bigInt = 10000000 let promises: [Promise<Int>] = self.promiseArray(bigInt, failing: true) expect { testExpectation in let promise = Promise<Any>.all(promises) promise.success { result in XCTAssertEqual(result[0].0, bigInt, "First promise should yield bigInt") XCTAssertEqual(result[1].0, 2*bigInt, "Second promise should yield 2*bigInt") XCTAssert(result[2].1 is PromiseError) testExpectation.fulfill() } promise.failure { error in XCTFail("Failure handler should not have run") } } } func testThrowingFromPromiseHandler() { expect { testExpectation in let promise = Promise<Bool> { fulfill, reject in for _ in 1...1000000 { continue } fulfill(true) } .success { result in throw Error.Error } promise.failure { error in XCTAssertEqual(error as? Error, Error.Error, "Promise's rejection reason should be Error.Error") promise.failure { error in XCTAssertEqual(error as? Error, Error.Error, "Promise's rejection reason should be Error.Error") testExpectation.fulfill() throw Error.Error } throw Error.Error } } } func testChainFailure() { let successTask: () -> Promise<String> = { return Promise.fulfill("shortSuccess") } expect { testExpectation in successTask() .then({ result in XCTAssertEqual(result, "shortSuccess") throw PromiseError.NilReason }) .then({ result in XCTFail("Expected skip to failure handler") }) .then({ result in XCTFail("Expected skip to failure handler") testExpectation.fulfill() }) .failure({ error -> String in XCTAssert(error is PromiseError) return "recovered" }) .success({ result in XCTAssertEqual(result, "recovered") testExpectation.fulfill() }) } } func testReturningPromiseFromSuccess() { expect { testExpectation in Promise { fulfill, reject in fulfill(10) }.then({ result in return Promise { fulfill, reject in fulfill(100) } }).then({ result in XCTAssertEqual(result, 100) testExpectation.fulfill() }) } } func testReturningPromiseFromFailure() { expect { testExpectation in Promise<Void>.reject(Error.Error).then(nil, onFailure: { error in return Promise { fulfill, reject in fulfill(100) } }).then({ result in XCTAssertEqual(result, 100) testExpectation.fulfill() }) } } private func promiseArray(bigInt: Int, failing: Bool = false) -> [Promise<Int>] { var promises: [Promise<Int>] = [ Promise { fulfill, reject in var ret = 0 for i in 1...bigInt { ret = i } fulfill(ret) }, Promise { fulfill, reject in var ret = 0 for i in 1...bigInt*2 { ret = i } fulfill(ret) } ] if failing { promises.append(Promise.reject(PromiseError.NilReason)) } return promises } private func expect(testClosure: (XCTestExpectation) -> Void) -> Void { let testExpectation = expectationWithDescription("Test expectation") testClosure(testExpectation) waitForExpectationsWithTimeout(10, handler: { error in XCTAssertNil(error, "Error") }) } }
73535ae8a7ad46fcb860bf3569c79ab2
28.957865
116
0.470605
false
true
false
false
narner/AudioKit
refs/heads/master
AudioKit/Common/Nodes/Effects/Filters/Low Pass Butterworth Filter/AKLowPassButterworthFilter.swift
mit
1
// // AKLowPassButterworthFilter.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// These filters are Butterworth second-order IIR filters. They offer an almost /// flat passband and very good precision and stopband attenuation. /// open class AKLowPassButterworthFilter: AKNode, AKToggleable, AKComponent, AKInput { public typealias AKAudioUnitType = AKLowPassButterworthFilterAudioUnit /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(effect: "btlp") // MARK: - Properties private var internalAU: AKAudioUnitType? private var token: AUParameterObserverToken? fileprivate var cutoffFrequencyParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change @objc open dynamic var rampTime: Double = AKSettings.rampTime { willSet { internalAU?.rampTime = newValue } } /// Cutoff frequency. (in Hertz) @objc open dynamic var cutoffFrequency: Double = 1_000.0 { willSet { if cutoffFrequency != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { cutoffFrequencyParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.cutoffFrequency = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) @objc open dynamic var isStarted: Bool { return internalAU?.isPlaying() ?? false } // MARK: - Initialization /// Initialize this filter node /// /// - Parameters: /// - input: Input node to process /// - cutoffFrequency: Cutoff frequency. (in Hertz) /// @objc public init( _ input: AKNode? = nil, cutoffFrequency: Double = 1_000.0) { self.cutoffFrequency = cutoffFrequency _Self.register() super.init() AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in self?.avAudioNode = avAudioUnit self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType input?.connect(to: self!) } guard let tree = internalAU?.parameterTree else { AKLog("Parameter Tree Failed") return } cutoffFrequencyParameter = tree["cutoffFrequency"] token = tree.token(byAddingParameterObserver: { [weak self] _, _ in guard let _ = self else { AKLog("Unable to create strong reference to self") return } // Replace _ with strongSelf if needed DispatchQueue.main.async { // This node does not change its own values so we won't add any // value observing, but if you need to, this is where that goes. } }) internalAU?.cutoffFrequency = Float(cutoffFrequency) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing @objc open func start() { internalAU?.start() } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { internalAU?.stop() } }
8961d436ad0dde887ee970eccd3a5091
30.743119
102
0.613006
false
false
false
false
yonasstephen/swift-of-airbnb
refs/heads/master
airbnb-main/airbnb-main/AirbnbHomeItemCell.swift
mit
1
// // AirbnbHomeItemCell.swift // airbnb-main // // Created by Yonas Stephen on 3/4/17. // Copyright © 2017 Yonas Stephen. All rights reserved. // import UIKit class AirbnbHomeItemCell: BaseCollectionCell { var home: AirbnbHome? { didSet { imageView.image = UIImage(named: home!.imageName) priceLabel.text = "$\(home!.price)" descriptionLabel.text = home?.homeDescription reviewCountLabel.text = "\(home!.reviewCount) Reviews" ratingView.rating = home!.rating } } var homeDescription: String? { didSet { descriptionLabel.text = homeDescription } } var imageView: UIImageView = { let view = UIImageView() view.translatesAutoresizingMaskIntoConstraints = false view.contentMode = .scaleAspectFill view.clipsToBounds = true return view }() var priceLabel: UILabel = { let view = UILabel() view.translatesAutoresizingMaskIntoConstraints = false view.font = UIFont.boldSystemFont(ofSize: 14) view.textColor = UIColor.black return view }() var descriptionLabel: UILabel = { let view = UILabel() view.translatesAutoresizingMaskIntoConstraints = false view.font = UIFont.systemFont(ofSize: 14) view.textColor = UIColor.gray return view }() var ratingView: AirbnbReview = { let view = AirbnbReview() view.translatesAutoresizingMaskIntoConstraints = false return view }() var reviewCountLabel: UILabel = { let view = UILabel() view.translatesAutoresizingMaskIntoConstraints = false view.font = UIFont.boldSystemFont(ofSize: 10) view.textColor = UIColor.darkGray return view }() override func setupViews() { addSubview(imageView) imageView.topAnchor.constraint(equalTo: topAnchor).isActive = true imageView.heightAnchor.constraint(equalToConstant: 180).isActive = true imageView.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true imageView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true addSubview(priceLabel) priceLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 10).isActive = true priceLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true priceLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true priceLabel.widthAnchor.constraint(equalToConstant: 50).isActive = true addSubview(descriptionLabel) descriptionLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 10).isActive = true descriptionLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true descriptionLabel.leftAnchor.constraint(equalTo: priceLabel.rightAnchor).isActive = true descriptionLabel.rightAnchor.constraint(equalTo: rightAnchor).isActive = true addSubview(ratingView) ratingView.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 0).isActive = true ratingView.heightAnchor.constraint(equalToConstant: 20).isActive = true ratingView.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true ratingView.widthAnchor.constraint(equalToConstant: ratingView.starSize * CGFloat(ratingView.stars.count)).isActive = true addSubview(reviewCountLabel) reviewCountLabel.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 0).isActive = true reviewCountLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true reviewCountLabel.leftAnchor.constraint(equalTo: ratingView.rightAnchor, constant: 5).isActive = true reviewCountLabel.rightAnchor.constraint(equalTo: rightAnchor).isActive = true } }
1ae974948bfc1873936e19883b63d156
37.238095
129
0.672478
false
false
false
false
shlyren/ONE-Swift
refs/heads/master
ONE_Swift/Classes/Movie-电影/Model/JENMovieItem.swift
mit
1
// // JENMovieItem.swift // ONE_Swift // // Created by 任玉祥 on 16/5/11. // Copyright © 2016年 任玉祥. All rights reserved. // import UIKit // MARK: - 电影列表模型 class JENMovieListItem: NSObject { /// id var detail_id: String? /// 标题 var title: String? /// 评分 var score: String? /// 图片url var cover: String? // var releasetime: String? // var scoretime: String? // var servertime: Int = 0 // var revisedscore: String? // var verse: String? // var verse_en: String? } // MARK: - 详情模型 class JENMovieDetailItem: JENMovieListItem { var detailcover: String? var keywords: String? var movie_id: String? var info: String? var charge_edt: String? var praisenum = 0 var sort: String? var maketime: String? var photo = [String]() var sharenum = 0 var commentnum = 0 var servertime = 0 // var indexcover: String? // var video: String? // var review: String? // var officialstory: String? // var web_url: String? // var releasetime: String? // var scoretime: String? // var last_update_date: String? // var read_num: String? // var push_id: String? } class JENMovieStroyResult: NSObject { var count = 0 var data = [JENMovieStoryItem]() } class JENMovieStoryItem: NSObject { /// id var story_id: String? var movie_id: String? var title: String? var content: String? var user_id: String? var sort: String? var praisenum = 0 var input_date: String? var story_type: String? var user = JENAuthorItem() }
0a6beb443c3c13c31a90c17b45aaa486
17.848837
47
0.595679
false
false
false
false
icapps/ios_objective_c_workshop
refs/heads/master
Students/Naomi/ObjcTextInput/ObjcTextInput/Modules/TextInput/TIITransitionManager.swift
mit
1
// // TIITransitionManager.swift // // // Created by Naomi De Leeuw on 16/11/2017. // import UIKit @objc class TIITransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { private var presenting = true func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)! let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)! let offScreenRight = CGAffineTransform(translationX: container.frame.width, y: 0) let offScreenLeft = CGAffineTransform(translationX: -container.frame.width, y: 0) if (self.presenting){ toView.transform = offScreenRight } else { toView.transform = offScreenLeft } container.addSubview(toView) container.addSubview(fromView) let duration = self.transitionDuration(using: transitionContext) UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.curveEaseIn, animations: { if (self.presenting){ fromView.transform = offScreenLeft } else { fromView.transform = offScreenRight } toView.transform = .identity }, completion: { finished in transitionContext.completeTransition(true) }) } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = false return self } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = true return self } }
b2e624a94b74e3602574bd79d4b8d80d
34.79661
174
0.696496
false
false
false
false
LbfAiYxx/douyuTV
refs/heads/master
DouYu/DouYu/Classes/Main/view/PageContentView.swift
mit
1
// // PageContentView.swift // DouYu // // Created by 刘冰峰 on 2016/12/15. // Copyright © 2016年 LBF. All rights reserved. // import UIKit protocol contentViewDelegate : class{ func contentView(progress: CGFloat,currentIndex: Int,oldIndex:Int) } class PageContentView: UIView { fileprivate var oldOffsetX :CGFloat = 0 fileprivate var currentOffsetX :CGFloat = 0 fileprivate var currentIndeX = 0 fileprivate var oldIndeX = 0 weak var delegate: contentViewDelegate? fileprivate var childVc: [UIViewController] //解除循环引用 fileprivate weak var parentcontroller: UIViewController? //懒加载collectionView fileprivate lazy var collectionView :UICollectionView = { [weak self] in //设置布局 let layout = UICollectionViewFlowLayout() layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 //强行解包 layout.itemSize = (self?.bounds.size)! layout.scrollDirection = .horizontal //创建collectionView let collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self as UICollectionViewDelegate? collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellID") return collectionView }() init(frame: CGRect,childVc: [UIViewController],parentcontroller: UIViewController?) { self.childVc = childVc self.parentcontroller = parentcontroller super.init(frame: frame) //添加scrollView setUpCollectionView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageContentView{ //添加collectionView fileprivate func setUpCollectionView(){ //添加子控制器到父控制器中 for childvc in childVc { parentcontroller?.addChildViewController(childvc) } addSubview(collectionView) collectionView.frame = bounds } } extension PageContentView : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVc.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) //移除循环利用里面的View for view in cell.contentView.subviews { view.removeFromSuperview() } //添加控制器视图在cell里面 childVc[indexPath.item].view.frame = cell.contentView.frame cell.contentView.addSubview(childVc[indexPath.item].view) return cell } } extension PageContentView{ //对外暴露方法,传值 func changeIndex(Index : Int){ //计算平移量 let offsetX = CGFloat(Index) * CscreenW collectionView.contentOffset.x = offsetX } } extension PageContentView : UICollectionViewDelegate{ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { oldOffsetX = scrollView.contentOffset.x } //监听滚动 func scrollViewDidScroll(_ scrollView: UIScrollView) { //动态偏移量 currentOffsetX = scrollView.contentOffset.x //设置进度条变量 var progress :CGFloat = 0 //左滑动、滚动进度 if currentOffsetX > oldOffsetX { progress = currentOffsetX/CscreenW - floor(currentOffsetX/CscreenW) oldIndeX = Int(currentOffsetX/CscreenW) if oldIndeX < 3 { currentIndeX = Int(currentOffsetX/CscreenW) + 1 } if currentOffsetX - oldOffsetX == CscreenW { progress = 1 currentIndeX = oldIndeX } } //右滑动、滚动进度 if currentOffsetX < oldOffsetX { progress = 1 - (currentOffsetX/CscreenW - floor(currentOffsetX/CscreenW)) if oldOffsetX - currentOffsetX == CscreenW { progress = 1 } currentIndeX = Int(currentOffsetX/CscreenW) oldIndeX = Int(currentOffsetX/CscreenW) + 1 } //通知代理 delegate?.contentView(progress: progress, currentIndex: currentIndeX, oldIndex: oldIndeX) } }
656068d2b85b5f158eb8681ca0f68272
29.295302
132
0.651086
false
false
false
false
Jnosh/swift
refs/heads/master
test/IDE/complete_enum_elements.swift
apache-2.0
3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_1 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=WITH_GLOBAL_RESULTS < %t.enum.txt // RUN: %FileCheck %s -check-prefix=FOO_ENUM_TYPE_CONTEXT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_2 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=WITH_GLOBAL_RESULTS < %t.enum.txt // RUN: %FileCheck %s -check-prefix=FOO_ENUM_TYPE_CONTEXT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_3 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=WITH_GLOBAL_RESULTS < %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAR_ENUM_TYPE_CONTEXT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_4 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=WITH_GLOBAL_RESULTS < %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAZ_ENUM_TYPE_CONTEXT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_5 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=WITH_GLOBAL_RESULTS < %t.enum.txt // RUN: %FileCheck %s -check-prefix=QUX_ENUM_TYPE_CONTEXT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_WITH_DOT_1 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=FOO_ENUM_DOT_ELEMENTS < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_WITH_QUAL_1 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=FOO_ENUM_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_EXPR_ERROR_1 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=FOO_ENUM_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_IN_PATTERN_1 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=WITH_GLOBAL_RESULTS < %t.enum.txt // RUN: %FileCheck %s -check-prefix=ENUM_SW_IN_PATTERN_1 < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_IN_PATTERN_2 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=ENUM_SW_IN_PATTERN_2 < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_NO_DOT_1 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=FOO_ENUM_NO_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_NO_DOT_2 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAR_ENUM_NO_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_NO_DOT_3 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAZ_INT_ENUM_NO_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_NO_DOT_4 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAZ_T_ENUM_NO_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_NO_DOT_5 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=QUX_ENUM_NO_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_DOT_1 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=FOO_ENUM_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_DOT_2 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAR_ENUM_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_DOT_3 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAZ_INT_ENUM_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_DOT_4 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAZ_T_ENUM_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_DOT_5 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=QUX_ENUM_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=WITH_INVALID_DOT_1 | %FileCheck %s -check-prefix=WITH_INVALID_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_1 | %FileCheck %s -check-prefix=UNRESOLVED_1 //===--- //===--- Test that we can complete enum elements. //===--- //===--- Helper types. enum FooEnum { case Foo1 case Foo2 } // FOO_ENUM_TYPE_CONTEXT: Begin completions // FOO_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Foo1[#FooEnum#]{{; name=.+$}} // FOO_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Foo2[#FooEnum#]{{; name=.+$}} // FOO_ENUM_TYPE_CONTEXT: End completions // FOO_ENUM_NO_DOT: Begin completions // FOO_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Foo1[#FooEnum#]{{; name=.+$}} // FOO_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Foo2[#FooEnum#]{{; name=.+$}} // FOO_ENUM_NO_DOT-NEXT: End completions // FOO_ENUM_DOT: Begin completions // FOO_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Foo1[#FooEnum#]{{; name=.+$}} // FOO_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Foo2[#FooEnum#]{{; name=.+$}} // FOO_ENUM_DOT-NEXT: End completions // FOO_ENUM_DOT_ELEMENTS: Begin completions, 2 items // FOO_ENUM_DOT_ELEMENTS-NEXT: Decl[EnumElement]/ExprSpecific: Foo1[#FooEnum#]{{; name=.+$}} // FOO_ENUM_DOT_ELEMENTS-NEXT: Decl[EnumElement]/ExprSpecific: Foo2[#FooEnum#]{{; name=.+$}} // FOO_ENUM_DOT_ELEMENTS-NEXT: End completions enum BarEnum { case Bar1 case Bar2() case Bar3(Int) case Bar4(a: Int, b: Float) case Bar5(a: Int, (Float)) case Bar6(a: Int, b: (Float)) case Bar7(a: Int, (b: Float, c: Double)) case Bar8(a: Int, b: (c: Float, d: Double)) case Bar9(Int) case Bar10(Int, Float) case Bar11(Int, (Float)) case Bar12(Int, (Float, Double)) mutating func barInstanceFunc() {} static var staticVar: Int = 12 static func barStaticFunc() {} } // BAR_ENUM_TYPE_CONTEXT: Begin completions // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar1[#BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar2()[#() -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar3({#Int#})[#(Int) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar4({#a: Int#}, {#b: Float#})[#(Int, Float) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar6({#a: Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar6({#a: Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar7({#a: Int#}, ({#b: Float#}, {#c: Double#}))[#(Int, (b: Float, c: Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar8({#a: Int#}, b: ({#c: Float#}, {#d: Double#}))[#(Int, (c: Float, d: Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar9({#Int#})[#(Int) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar10({#Int#}, {#Float#})[#(Int, Float) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar11({#Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar12({#Int#}, ({#Float#}, {#Double#}))[#(Int, (Float, Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT: End completions // BAR_ENUM_NO_DOT: Begin completions // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar1[#BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar2()[#() -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar3({#Int#})[#(Int) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar4({#a: Int#}, {#b: Float#})[#(Int, Float) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar5({#a: Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar6({#a: Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar7({#a: Int#}, ({#b: Float#}, {#c: Double#}))[#(Int, (b: Float, c: Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar8({#a: Int#}, b: ({#c: Float#}, {#d: Double#}))[#(Int, (c: Float, d: Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar9({#Int#})[#(Int) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar10({#Int#}, {#Float#})[#(Int, Float) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar11({#Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar12({#Int#}, ({#Float#}, {#Double#}))[#(Int, (Float, Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .barInstanceFunc({#self: &BarEnum#})[#() -> Void#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .staticVar[#Int#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .barStaticFunc()[#Void#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: End completions // BAR_ENUM_DOT: Begin completions // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar1[#BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar2()[#() -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar3({#Int#})[#(Int) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar4({#a: Int#}, {#b: Float#})[#(Int, Float) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar5({#a: Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar6({#a: Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar7({#a: Int#}, ({#b: Float#}, {#c: Double#}))[#(Int, (b: Float, c: Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar8({#a: Int#}, b: ({#c: Float#}, {#d: Double#}))[#(Int, (c: Float, d: Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar9({#Int#})[#(Int) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar10({#Int#}, {#Float#})[#(Int, Float) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar11({#Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar12({#Int#}, ({#Float#}, {#Double#}))[#(Int, (Float, Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: barInstanceFunc({#self: &BarEnum#})[#() -> Void#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[StaticVar]/CurrNominal: staticVar[#Int#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[StaticMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: barStaticFunc()[#Void#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: End completions enum BazEnum<T> { case Baz1 case Baz2(T) mutating func bazInstanceFunc() {} static var staticVar: Int = 12 static var staticVarT: T = 17 static func bazStaticFunc() {} } // BAZ_ENUM_TYPE_CONTEXT: Begin completions // BAZ_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Baz1[#BazEnum<T>#]{{; name=.+$}} // BAZ_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Baz2({#T#})[#(T) -> BazEnum<T>#]{{; name=.+$}} // BAZ_ENUM_TYPE_CONTEXT: End completions // BAZ_INT_ENUM_NO_DOT: Begin completions, 6 items // BAZ_INT_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Baz1[#BazEnum<T>#]{{; name=.+$}} // BAZ_INT_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Baz2({#T#})[#(T) -> BazEnum<T>#]{{; name=.+$}} // BAZ_INT_ENUM_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .bazInstanceFunc({#self: &BazEnum<Int>#})[#() -> Void#]{{; name=.+$}} // BAZ_INT_ENUM_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .staticVar[#Int#]{{; name=.+$}} // BAZ_INT_ENUM_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .staticVarT[#Int#]{{; name=.+$}} // BAZ_INT_ENUM_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .bazStaticFunc()[#Void#]{{; name=.+$}} // BAZ_INT_ENUM_NO_DOT-NEXT: End completions // BAZ_T_ENUM_NO_DOT: Begin completions // BAZ_T_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Baz1[#BazEnum<T>#]{{; name=.+$}} // BAZ_T_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Baz2({#T#})[#(T) -> BazEnum<T>#]{{; name=.+$}} // BAZ_T_ENUM_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .bazInstanceFunc({#self: &BazEnum<T>#})[#() -> Void#]{{; name=.+$}} // BAZ_T_ENUM_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .staticVar[#Int#]{{; name=.+$}} // BAZ_T_ENUM_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .staticVarT[#T#]{{; name=.+$}} // BAZ_T_ENUM_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .bazStaticFunc()[#Void#]{{; name=.+$}} // BAZ_T_ENUM_NO_DOT-NEXT: Decl[InfixOperatorFunction]/OtherModule[Swift]: == {#Any.Type?#}[#Bool#]; name=== Any.Type? // BAZ_T_ENUM_NO_DOT-NEXT: Decl[InfixOperatorFunction]/OtherModule[Swift]: != {#Any.Type?#}[#Bool#]; name=!= Any.Type? // BAZ_T_ENUM_NO_DOT-NEXT: End completions // BAZ_INT_ENUM_DOT: Begin completions, 6 items // BAZ_INT_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Baz1[#BazEnum<T>#]{{; name=.+$}} // BAZ_INT_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Baz2({#T#})[#(T) -> BazEnum<T>#]{{; name=.+$}} // BAZ_INT_ENUM_DOT-NEXT: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: bazInstanceFunc({#self: &BazEnum<Int>#})[#() -> Void#]{{; name=.+$}} // BAZ_INT_ENUM_DOT-NEXT: Decl[StaticVar]/CurrNominal: staticVar[#Int#]{{; name=.+$}} // BAZ_INT_ENUM_DOT-NEXT: Decl[StaticVar]/CurrNominal: staticVarT[#Int#]{{; name=.+$}} // BAZ_INT_ENUM_DOT-NEXT: Decl[StaticMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: bazStaticFunc()[#Void#]{{; name=.+$}} // BAZ_INT_ENUM_DOT-NEXT: End completions // BAZ_T_ENUM_DOT: Begin completions, 6 items // BAZ_T_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Baz1[#BazEnum<T>#]{{; name=.+$}} // BAZ_T_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Baz2({#T#})[#(T) -> BazEnum<T>#]{{; name=.+$}} // BAZ_T_ENUM_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: bazInstanceFunc({#self: &BazEnum<T>#})[#() -> Void#]{{; name=.+$}} // BAZ_T_ENUM_DOT-NEXT: Decl[StaticVar]/CurrNominal: staticVar[#Int#]{{; name=.+$}} // BAZ_T_ENUM_DOT-NEXT: Decl[StaticVar]/CurrNominal: staticVarT[#T#]{{; name=.+$}} // BAZ_T_ENUM_DOT-NEXT: Decl[StaticMethod]/CurrNominal: bazStaticFunc()[#Void#]{{; name=.+$}} // BAZ_T_ENUM_DOT-NEXT: End completions enum QuxEnum : Int { case Qux1 = 10 case Qux2 = 20 } // QUX_ENUM_TYPE_CONTEXT: Begin completions // QUX_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Qux1[#QuxEnum#]{{; name=.+$}} // QUX_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Qux2[#QuxEnum#]{{; name=.+$}} // QUX_ENUM_TYPE_CONTEXT: End completions // QUX_ENUM_NO_DOT: Begin completions, 4 items // QUX_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Qux1[#QuxEnum#]{{; name=.+$}} // QUX_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Qux2[#QuxEnum#]{{; name=.+$}} // QUX_ENUM_NO_DOT-NEXT: Decl[TypeAlias]/CurrNominal: .RawValue[#Int#]{{; name=.+$}} // QUX_ENUM_NO_DOT-NEXT: Decl[Constructor]/CurrNominal: ({#rawValue: Int#})[#QuxEnum?#]{{; name=.+$}} // QUX_ENUM_NO_DOT-NEXT: End completions // QUX_ENUM_DOT: Begin completions, 4 items // QUX_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Qux1[#QuxEnum#]{{; name=.+$}} // QUX_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Qux2[#QuxEnum#]{{; name=.+$}} // QUX_ENUM_DOT-NEXT: Decl[TypeAlias]/CurrNominal: RawValue[#Int#]{{; name=.+$}} // QUX_ENUM_DOT-NEXT: Decl[Constructor]/CurrNominal: init({#rawValue: Int#})[#QuxEnum?#]{{; name=.+$}} // QUX_ENUM_DOT-NEXT: End completions func freeFunc() {} // WITH_GLOBAL_RESULTS: Begin completions // WITH_GLOBAL_RESULTS: Decl[FreeFunction]/CurrModule: freeFunc()[#Void#]{{; name=.+$}} // WITH_GLOBAL_RESULTS: End completions //===--- Complete enum elements in 'switch'. func testSwitch1(e: FooEnum) { switch e { case #^ENUM_SW_1^# } } func testSwitch2(e: FooEnum) { switch e { case .Foo1: case #^ENUM_SW_2^# } } func testSwitch3(e: BarEnum) { switch e { case #^ENUM_SW_3^# } } func testSwitch4(e: BazEnum<Int>) { switch e { case #^ENUM_SW_4^# } } func testSwitch5(e: QuxEnum) { switch e { case #^ENUM_SW_5^# } } func testSwitchWithDot1(e: FooEnum) { switch e { case .#^ENUM_SW_WITH_DOT_1^# } } func testSwitchWithQualification1(e: FooEnum) { switch e { case FooEnum.#^ENUM_SW_WITH_QUAL_1^# } } func testSwitchExprError1() { switch unknown_var { case FooEnum.#^ENUM_SW_EXPR_ERROR_1^# } } // FIXME func testSwitchInPattern1(e: BazEnum<Int>) { switch e { case .Baz2(#^ENUM_SW_IN_PATTERN_1^# } } // ENUM_SW_IN_PATTERN_1-NOT: .Baz1 func testSwitchInPattern2(e: BazEnum<Int>) { switch e { case .Baz2(.#^ENUM_SW_IN_PATTERN_2^# } } // ENUM_SW_IN_PATTERN_2-NOT: .Baz1 //===--- Complete qualified references to enum elements. func testQualifiedNoDot1() { var e = FooEnum#^ENUM_QUAL_NO_DOT_1^# } func testQualifiedNoDot2() { var e = BarEnum#^ENUM_QUAL_NO_DOT_2^# } func testQualifiedNoDot3() { var e = BazEnum<Int>#^ENUM_QUAL_NO_DOT_3^# } func testQualifiedNoDot4() { var e = BazEnum#^ENUM_QUAL_NO_DOT_4^# } func testQualifiedNoDot5() { var e = QuxEnum#^ENUM_QUAL_NO_DOT_5^# } func testQualifiedDot1() { var e = FooEnum.#^ENUM_QUAL_DOT_1^# } func testQualifiedDot2() { var e = BarEnum.#^ENUM_QUAL_DOT_2^# } func testQualifiedDot3() { var e = BazEnum<Int>.#^ENUM_QUAL_DOT_3^# } func testQualifiedDot4() { var e = BazEnum.#^ENUM_QUAL_DOT_4^# } func testQualifiedDot5() { var e = QuxEnum.#^ENUM_QUAL_DOT_5^# } // ===--- Complete in the presence of invalid enum elements. enum WithInvalid { case Okay case NotOkay. case .AlsoNotOkay case case JustFine } func testWithInvalid1() { let x = WithInvalid.#^WITH_INVALID_DOT_1^# // WITH_INVALID_DOT: Begin completions // WITH_INVALID_DOT-DAG: Decl[EnumElement]/CurrNominal: Okay[#WithInvalid#]; name=Okay // WITH_INVALID_DOT-DAG: Decl[EnumElement]/CurrNominal: NotOkay[#WithInvalid#]; name=NotOkay // WITH_INVALID_DOT-DAG: Decl[EnumElement]/CurrNominal: AlsoNotOkay[#WithInvalid#]; name=AlsoNotOkay // WITH_INVALID_DOT-DAG: Decl[EnumElement]/CurrNominal: JustFine[#WithInvalid#]; name=JustFine // WITH_INVALID_DOT: End completions var y : QuxEnum y = .#^UNRESOLVED_1^# // FIXME: Only contains resolvable ones. // UNRESOLVED_1: Begin completions // UNRESOLVED_1-NOT: Baz // UNRESOLVED_1-NOT: Bar // UNRESOLVED_1-DAG: Decl[EnumElement]/ExprSpecific: Qux1[#QuxEnum#]; name=Qux1 // UNRESOLVED_1-DAG: Decl[EnumElement]/ExprSpecific: Qux2[#QuxEnum#]; name=Qux2 // UNRESOLVED_1-NOT: Okay }
d77f3e029391753cbc9f54dfd69635ec
50.370079
170
0.653638
false
true
false
false
movabletype/smartphone-app
refs/heads/master
MT_iOS/MT_iOS/Classes/Model/UploadItem.swift
mit
1
// // UploadItem.swift // MT_iOS // // Created by CHEEBOW on 2016/02/08. // Copyright © 2016年 Six Apart, Ltd. All rights reserved. // import UIKit import SwiftyJSON class UploadItem: NSObject { internal(set) var data: NSData! = nil var blogID = "" var uploadPath = "" var uploaded = false var progress: Float = 0.0 internal(set) var _filename: String = "" var filename: String { get { if self._filename.isEmpty { return self.makeFilename() } return _filename } } func setup(completion: (() -> Void)) { completion() } func clear() { self.data = nil } internal func makeFilename()->String { return self._filename } func upload(progress progress: ((Int64!, Int64!, Int64!) -> Void)? = nil, success: (JSON! -> Void)!, failure: (JSON! -> Void)!) { let api = DataAPI.sharedInstance let app = UIApplication.sharedApplication().delegate as! AppDelegate let authInfo = app.authInfo api.authenticationV2(authInfo.username, password: authInfo.password, remember: true, success:{_ in let filename = self.makeFilename() api.uploadAssetForSite(self.blogID, assetData: self.data, fileName: filename, options: ["path":self.uploadPath, "autoRenameIfExists":"true"], progress: progress, success: success, failure: failure) }, failure: failure ) } func thumbnail(size: CGSize, completion: (UIImage->Void)) { completion(UIImage()) } }
95a5cc9683789cfc441a8cd6779bb7d1
27.293103
214
0.577697
false
false
false
false
ccrama/Slide-iOS
refs/heads/master
Slide for Reddit/ColorPicker.swift
apache-2.0
1
import UIKit class ColorPicker: UIView { var hueValueForPreview: CGFloat = 1.0 { didSet { setNeedsDisplay() } } var accent = false func setAccent(accent: Bool) { self.accent = true } var allColors: [CGColor] { return accent ? GMPalette.allAccentCGColor() : GMPalette.allCGColor() } private var lastTouchLocation: CGPoint? private var decelerateTimer: Timer? private var decelerationSpeed: CGFloat = 0.0 { didSet { if let timer = decelerateTimer { if timer.isValid { timer.invalidate() } } decelerateTimer = Timer.scheduledTimer(timeInterval: 0.025, target: self, selector: #selector(decelerate), userInfo: nil, repeats: true) } } private lazy var panGesture: UIPanGestureRecognizer = { return UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:))) }() private(set) var value: CGFloat = 0.5 { didSet { if Int(self.value * CGFloat(allColors.count)) > allColors.count - 1 { self.value -= 1 } else if self.value < 0 { self.value += 1 } else { setNeedsDisplay() } // delegate?.valueChanged(self.value, accent: accent) } } private func colors(for value: Int) -> [CGColor] { var result = [CGColor]() let i = value - 2 var index = 0 for val in i...(i + 4) { if val < 0 { index = val + (allColors.count - 1) } else if val > (allColors.count - 1) { index = val - (allColors.count - 1) } else { index = val } result.append(allColors[index]) } return result } @objc private func handlePan(_ gesture: UIPanGestureRecognizer) { if gesture.state == .began { lastTouchLocation = gesture.location(in: self) } else if gesture.state == .changed { if let location = lastTouchLocation { value += ((gesture.location(in: self).x - location.x) / frame.width) * 0.1 } lastTouchLocation = gesture.location(in: self) } else if gesture.state == .ended || gesture.state == .cancelled { decelerationSpeed = gesture.velocity(in: self).x } } @objc private func decelerate() { decelerationSpeed *= 0.7255 if abs(decelerationSpeed) <= 0.001 { if let decelerateTimer = decelerateTimer { decelerateTimer.invalidate() } return } value += ((decelerationSpeed * 0.025) / 100) * 0.2 } private func commonInit() { addGestureRecognizer(panGesture) layer.cornerRadius = 5.0 clipsToBounds = true } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override func draw(_ rect: CGRect) { let ctx = UIGraphicsGetCurrentContext() if let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors(for: Int(value * CGFloat(allColors.count))) as CFArray, locations: [0, 0.25, 0.50, 0.75, 1]) { ctx?.drawLinearGradient(gradient, start: CGPoint(x: rect.size.width, y: 0), end: CGPoint.zero, options: .drawsBeforeStartLocation) } let selectionPath = CGMutablePath() let verticalPadding = rect.height * 0.4 let horizontalPosition = rect.midX selectionPath.move(to: CGPoint(x: horizontalPosition, y: verticalPadding * 0.5)) selectionPath.addLine(to: CGPoint(x: horizontalPosition, y: rect.height - (verticalPadding * 0.5))) ctx?.addPath(selectionPath) ctx?.setLineWidth(1.0) ctx?.setStrokeColor(UIColor(white: 0, alpha: 0.5).cgColor) ctx?.strokePath() } }
8635697ce0a78a70da8d2b1a8a06d4d4
30.977273
190
0.544184
false
false
false
false
danielgindi/Charts
refs/heads/master
Source/Charts/Renderers/BarLineScatterCandleBubbleRenderer.swift
apache-2.0
2
// // BarLineScatterCandleBubbleRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc(BarLineScatterCandleBubbleChartRenderer) open class BarLineScatterCandleBubbleRenderer: NSObject, DataRenderer { public let viewPortHandler: ViewPortHandler public final var accessibleChartElements: [NSUIAccessibilityElement] = [] public let animator: Animator internal var _xBounds = XBounds() // Reusable XBounds object public init(animator: Animator, viewPortHandler: ViewPortHandler) { self.viewPortHandler = viewPortHandler self.animator = animator super.init() } open func drawData(context: CGContext) { } open func drawValues(context: CGContext) { } open func drawExtras(context: CGContext) { } open func drawHighlighted(context: CGContext, indices: [Highlight]) { } /// Checks if the provided entry object is in bounds for drawing considering the current animation phase. internal func isInBoundsX(entry e: ChartDataEntry, dataSet: BarLineScatterCandleBubbleChartDataSetProtocol) -> Bool { let entryIndex = dataSet.entryIndex(entry: e) return Double(entryIndex) < Double(dataSet.entryCount) * animator.phaseX } /// Calculates and returns the x-bounds for the given DataSet in terms of index in their values array. /// This includes minimum and maximum visible x, as well as range. internal func xBounds(chart: BarLineScatterCandleBubbleChartDataProvider, dataSet: BarLineScatterCandleBubbleChartDataSetProtocol, animator: Animator?) -> XBounds { return XBounds(chart: chart, dataSet: dataSet, animator: animator) } /// - Returns: `true` if the DataSet values should be drawn, `false` if not. internal func shouldDrawValues(forDataSet set: ChartDataSetProtocol) -> Bool { return set.isVisible && (set.isDrawValuesEnabled || set.isDrawIconsEnabled) } open func initBuffers() { } open func isDrawingValuesAllowed(dataProvider: ChartDataProvider?) -> Bool { guard let data = dataProvider?.data else { return false } return data.entryCount < Int(CGFloat(dataProvider?.maxVisibleCount ?? 0) * viewPortHandler.scaleX) } /// Class representing the bounds of the current viewport in terms of indices in the values array of a DataSet. open class XBounds { /// minimum visible entry index open var min: Int = 0 /// maximum visible entry index open var max: Int = 0 /// range of visible entry indices open var range: Int = 0 public init() { } public init(chart: BarLineScatterCandleBubbleChartDataProvider, dataSet: BarLineScatterCandleBubbleChartDataSetProtocol, animator: Animator?) { self.set(chart: chart, dataSet: dataSet, animator: animator) } /// Calculates the minimum and maximum x values as well as the range between them. open func set(chart: BarLineScatterCandleBubbleChartDataProvider, dataSet: BarLineScatterCandleBubbleChartDataSetProtocol, animator: Animator?) { let phaseX = Swift.max(0.0, Swift.min(1.0, animator?.phaseX ?? 1.0)) let low = chart.lowestVisibleX let high = chart.highestVisibleX let entryFrom = dataSet.entryForXValue(low, closestToY: .nan, rounding: .down) let entryTo = dataSet.entryForXValue(high, closestToY: .nan, rounding: .up) self.min = entryFrom == nil ? 0 : dataSet.entryIndex(entry: entryFrom!) self.max = entryTo == nil ? 0 : dataSet.entryIndex(entry: entryTo!) range = Int(Double(self.max - self.min) * phaseX) } } public func createAccessibleHeader(usingChart chart: ChartViewBase, andData data: ChartData, withDefaultDescription defaultDescription: String) -> NSUIAccessibilityElement { return AccessibleHeader.create(usingChart: chart, andData: data, withDefaultDescription: defaultDescription) } } extension BarLineScatterCandleBubbleRenderer.XBounds: RangeExpression { public func relative<C>(to collection: C) -> Swift.Range<Int> where C : Collection, Bound == C.Index { return Swift.Range<Int>(min...min + range) } public func contains(_ element: Int) -> Bool { return (min...min + range).contains(element) } } extension BarLineScatterCandleBubbleRenderer.XBounds: Sequence { public struct Iterator: IteratorProtocol { private var iterator: IndexingIterator<ClosedRange<Int>> fileprivate init(min: Int, max: Int) { self.iterator = (min...max).makeIterator() } public mutating func next() -> Int? { return self.iterator.next() } } public func makeIterator() -> Iterator { return Iterator(min: self.min, max: self.min + self.range) } } extension BarLineScatterCandleBubbleRenderer.XBounds: CustomDebugStringConvertible { public var debugDescription: String { return "min:\(self.min), max:\(self.max), range:\(self.range)" } }
3c2556d366af89d7ce864adeebdc57b9
34.429487
177
0.65768
false
false
false
false
EngrAhsanAli/AAFragmentManager
refs/heads/master
AAFragmentManager/Classes/AAFragmentManager+UIKit.swift
mit
1
// // AAFragmentManager+UIKit.swift // AAFragmentManager // // Created by MacBook Pro on 20/09/2018. // import UIKit // MARK: - UIView extension UIView { /// Add subview and for according to height /// /// - Parameters: /// - subview: Fragment to be added currently in the parent view /// - insets: Insets for current fragment func addAndFitSubview(_ subview: UIView, insets: UIEdgeInsets = .zero) { addSubview(subview) subview.fitInSuperview(with: insets) } /// Fits the given view in its superview fileprivate func fitInSuperview(with insets: UIEdgeInsets = .zero) { guard let superview = superview else { assertionFailure("AAFragmentManager: added fragment was not in a view hierarchy.") return } let applyInset: (NSLayoutConstraint.Attribute, UIEdgeInsets) -> CGFloat = { switch $0 { case .top: return $1.top case .bottom: return -$1.bottom case .left: return $1.left case .right: return -$1.right default: return 0 } } translatesAutoresizingMaskIntoConstraints = false let attributes = [NSLayoutConstraint.Attribute.top, .left, .right, .bottom] superview.addConstraints(attributes.map { return NSLayoutConstraint(item: self, attribute: $0, relatedBy: .equal, toItem: superview, attribute: $0, multiplier: 1, constant: applyInset($0, insets)) }) } } // MARK: - Array Collection extension Collection { // Checks if index exists in the given array subscript(optional i: Index) -> Iterator.Element? { return self.indices.contains(i) ? self[i] : nil } }
b5cc544d472b0bae10535a0030a292a7
30.296875
94
0.540689
false
false
false
false
Esri/arcgis-runtime-samples-ios
refs/heads/main
arcgis-ios-sdk-samples/Scenes/Create terrain surface from a local raster/CreateTerrainSurfaceFromLocalRasterViewController.swift
apache-2.0
1
// Copyright 2019 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class CreateTerrainSurfaceFromLocalRasterViewController: UIViewController { @IBOutlet weak var sceneView: AGSSceneView! { didSet { // Initialize a scene. sceneView.scene = makeScene() // Set scene's viewpoint. let camera = AGSCamera(latitude: 36.525, longitude: -121.80, altitude: 300.0, heading: 180, pitch: 80, roll: 0) sceneView.setViewpointCamera(camera) } } func makeScene() -> AGSScene { let scene = AGSScene(basemapStyle: .arcGISImagery) let surface = AGSSurface() // Create raster elevation source. let rasterURL = Bundle.main.url(forResource: "MontereyElevation", withExtension: "dt2")! let rasterElevationSource = AGSRasterElevationSource(fileURLs: [rasterURL]) // Add a raster source to the surface. surface.elevationSources.append(rasterElevationSource) scene.baseSurface = surface return scene } override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["CreateTerrainSurfaceFromLocalRasterViewController"] } }
7f7b9bfe613b37406f2c7278870493df
36.823529
142
0.674443
false
false
false
false
amleszk/RxPasscode
refs/heads/master
RxPasscode/PasscodeNumberButton.swift
mit
1
import UIKit class PasscodeNumberButton: UIButton, PasscodeStyleView { var borderColor: UIColor = UIColor.whiteColor() var highlightBackgroundColor: UIColor = UIColor(white: 0.9, alpha: 0.8) var defaultBackgroundColor = UIColor.clearColor() let borderRadius: CGFloat let intrinsicSize: CGSize var displayedState: PasscodeStyleViewState = .Inactive init(buttonSize: CGFloat) { self.intrinsicSize = CGSizeMake(buttonSize, buttonSize) self.borderRadius = floor(buttonSize/2) super.init(frame: CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize)) setupViewBorder() setupActions() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func intrinsicContentSize() -> CGSize { return intrinsicSize } private func setupActions() { addTarget(self, action: #selector(PasscodeNumberButton.handleTouchDown), forControlEvents: .TouchDown) addTarget(self, action: #selector(PasscodeNumberButton.handleTouchUp), forControlEvents: [.TouchUpInside, .TouchDragOutside, .TouchCancel]) } internal func handleTouchDown() { animateToState(.Active) } internal func handleTouchUp() { let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.07 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.animateToState(.Inactive) } } }
6d04d78d1dbff7363d07d03d416f3c1e
33.568182
147
0.675214
false
false
false
false
billdonner/sheetcheats9
refs/heads/master
sc9/TilesViewController.swift
apache-2.0
1
// // TilesViewController.swift // import UIKit final class TileCell: UICollectionViewCell { @IBOutlet var alphabetLabel: UILabel! @IBOutlet weak var track: UILabel! @IBOutlet weak var notes: UILabel! @IBOutlet weak var key: UILabel! @IBOutlet weak var bpm: UILabel! func configureCellFromTile(_ t:Tyle,invert:Bool = false) { let name = t.tyleTitle self.alphabetLabel.text = name self.track.text = "\(t.tyleID)" self.key.text = t.tyleKey self.bpm.text = t.tyleBpm self.notes.text = t.tyleNote let bc = t.tyleBackColor let fc = Corpus.findFast(name) ? t.tyleTextColor :Col.r(.collectionSectionHeaderAltText) // if the title isnt found make the label a plain gray let frontcolor = invert ? bc : fc let backcolor = invert ? fc : bc self.contentView.backgroundColor = backcolor self.backgroundColor = backcolor self.alphabetLabel.textColor = frontcolor self.key.textColor = frontcolor self.bpm.textColor = frontcolor self.notes.textColor = frontcolor } } final class TilesViewController: UIViewController , ModelData,UserInteractionSignalDelegate , UICollectionViewDelegate,UICollectionViewDataSource { let backColor = Col.r(.collectionBackground) @IBAction func choseMore(_ sender: AnyObject) { self.presentMore(self) } func backToModalMenu () {// can go directly back self.presentingViewController?.dismiss(animated: true, completion: nil) } @IBAction func backAction(_ sender: AnyObject) { backToModalMenu() } @IBOutlet weak var collectionView: UICollectionView! var longPressOneShot = false var observer0 : NSObjectProtocol? // emsure ots retained var observer1 : NSObjectProtocol? // emsure ots retained var av = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) var lastTapped : IndexPath? deinit{ // NotificationCenter.default.removeObserver(observer0!) // NotificationCenter.default.removeObserver(observer1!) self.cleanupFontSizeAware(self) } func refresh() { self.collectionView?.backgroundColor = backColor self.view.backgroundColor = backColor self.collectionView?.reloadData() longPressOneShot = false // now listen to longPressAgain self.av.removeFromSuperview() } // total surrender to storyboards, everything is done thru performSegue and unwindtoVC @IBAction func unwindToTilesViewController( _ segue:// unwindToVC(segue: UIStoryboardSegue) { } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.collectionView?.reloadData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) longPressOneShot = false } func noItemsSimulatePress() { self.performSegue(withIdentifier: "nogigfileseque", sender: self) } @objc func pressedLong() { // ensure not getting double hit let pvd = self.presentedViewController if pvd == nil { if longPressOneShot == false { //print ("Long Press Presenting Modal Menu ....") longPressOneShot = true self.presentingViewController?.dismiss(animated: true, completion: nil) } } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = Col.r(.helpBackground) //self.clearsSelectionOnViewWillAppear = false self.collectionView.dataSource = self self.collectionView.delegate = self self.collectionView?.backgroundColor = Col.r(.collectionBackground) // self.view.backgroundColor = .darkGray // choseMoreButton.isEnabled = !performanceMode if performanceMode { // self.navigationItem.rightBarButtonItem = nil } self.setupFontSizeAware(self) // observer0 = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: kSurfaceRestorationCompleteSignal), object: nil, queue: OperationQueue.main) { _ in // NSLog ("Restoration Complete, tilesviewController reacting....") // self.refresh() // if self.noTiles() { // no items // Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(TilesViewController.noItemsSimulatePress), userInfo: nil, repeats: false) // } // } // observer1 = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: kSurfaceUpdatedSignal), object: nil, queue: OperationQueue.main) { _ in // print ("Surface was updated, tilesviewController reacting....") // self.refresh() // } refresh() if noTiles() { noItemsSimulatePress() } } func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool { return false } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { var indexPaths:[IndexPath] indexPaths = [] // change colorization if a different cell than las if lastTapped != nil { indexPaths.append(lastTapped!) // record path of old cell } if indexPath != lastTapped { // if tapping new cell // now change this cell lastTapped = indexPath indexPaths.append(indexPath) if indexPaths.count != 0 { collectionView.reloadItems(at: indexPaths) } } // ok show the document showDoc(self,named:self.tileData(indexPath).tyleTitle) } } extension TilesViewController { //: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return self.tileSectionCount() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.tileCountInSection(section) } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { //1 switch kind { //2 case UICollectionElementKindSectionHeader: //3 if let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionheaderid", for: indexPath) as? TilesSectionHeaderView { headerView.headerLabel.text = self.sectHeader((indexPath as NSIndexPath).section)[SectionProperties.NameKey] headerView.headerLabel.textColor = Col.r(.collectionSectionHeaderText) headerView.headerLabel.backgroundColor = .clear // headerView.headerLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) let tgr = UITapGestureRecognizer(//UILongPressGestureRecognizer target: self, action: #selector(TilesViewController.pressedLong)) headerView.addGestureRecognizer(tgr) return headerView } default: //4 fatalError("Unexpected element kind") } fatalError("Unexpected element kind") } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 3 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TileCellID", for: indexPath) as! TileCell let invert = lastTapped != nil && (indexPath as NSIndexPath).section == lastTapped!.section && (indexPath as NSIndexPath).item == lastTapped!.item // Configure the cell cell.configureCellFromTile(self.tileData(indexPath),invert:invert) return cell } } extension TilesViewController:SegueHelpers { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "nogigfileseque" { if let nav = segue.destination as? UINavigationController{ if let uivc = nav.topViewController as? NoGigsViewController { uivc.delegate = self } } } else if segue.identifier == nil { // unwinding self.refresh() } else { self.prepForSegue(segue , sender: sender) } longPressOneShot = false } } extension TilesViewController: FontSizeAware { func refreshFontSizeAware(_ vc: TilesViewController) { vc.collectionView?.reloadData() } } extension TilesViewController: ShowContentDelegate { func userDidDismiss() { // print("user dismissed Content View Controller") } } extension TilesViewController { //: UIScrollViewDelegate func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { DispatchQueue.main.async(execute: { // get section from first visible cell let paths = self.collectionView?.indexPathsForVisibleItems if (paths != nil) { let path = paths![0] let section = (path as NSIndexPath).section let sectionHead = self.sectHeader(section) let sectionTitle = sectionHead[SectionProperties.NameKey] self.title = sectionTitle } }) } } ///////////////////////////////////////////////
120a6b4c80acdcf515801e047b636502
36.911538
184
0.62656
false
false
false
false
ppraveentr/MobileCore
refs/heads/master
Sources/CoreComponents/Contollers/ScrollViewControllerProtocol.swift
mit
1
// // ScrollViewControllerProtocol.swift // MobileCore-CoreComponents // // Created by Praveen Prabhakar on 18/08/17. // Copyright © 2017 Praveen Prabhakar. All rights reserved. // #if canImport(CoreUtility) import CoreUtility #endif import Foundation import UIKit private var kAOScrollVC = "k.FT.AO.ScrollViewController" public protocol ScrollViewControllerProtocol: ViewControllerProtocol { var scrollView: UIScrollView { get } } public extension ScrollViewControllerProtocol { var scrollView: UIScrollView { get { guard let scroll = AssociatedObject<UIScrollView>.getAssociated(self, key: &kAOScrollVC) else { return self.setupScrollView() } return scroll } set { setupScrollView(newValue) } } } private extension ScrollViewControllerProtocol { @discardableResult func setupScrollView(_ local: UIScrollView = UIScrollView() ) -> UIScrollView { // Load Base view setupCoreView() if let scroll: UIScrollView = AssociatedObject<UIScrollView>.getAssociated(self, key: &kAOScrollVC) { scroll.removeSubviews() AssociatedObject<Any>.resetAssociated(self, key: &kAOScrollVC) } if local.superview == nil { self.mainView?.pin(view: local, edgeOffsets: .zero) local.setupContentView(local.contentView) } AssociatedObject<UIScrollView>.setAssociated(self, value: local, key: &kAOScrollVC) return local } }
280eb9b79c7c75ca49cdc8a23204f502
26.465517
109
0.647207
false
false
false
false
mokemokechicken/ObjectJsonMapperGenerator
refs/heads/master
tmp/entity_common.swift
mit
1
import Foundation private func encode(obj: AnyObject?) -> AnyObject { switch obj { case nil: return NSNull() case let ojmObject as EntityBase: return ojmObject.toJsonDictionary() default: return obj! } } private func decodeOptional(obj: AnyObject?) -> AnyObject? { switch obj { case let x as NSNull: return nil default: return obj } } private func JsonGenObjectFromJsonData(data: NSData!) -> AnyObject? { if data == nil { return nil } return NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: nil) } public class EntityBase { public init() { } public func toJsonDictionary() -> NSDictionary { return NSDictionary() } public class func toJsonArray(entityList: [EntityBase]) -> NSArray { return entityList.map {x in encode(x)} } public class func toJsonData(entityList: [EntityBase], pretty: Bool = false) -> NSData { var obj = toJsonArray(entityList) return toJson(obj, pretty: pretty) } public func toJsonData(pretty: Bool = false) -> NSData { var obj = toJsonDictionary() return EntityBase.toJson(obj, pretty: pretty) } public class func toJsonString(entityList: [EntityBase], pretty: Bool = false) -> NSString { return NSString(data: toJsonData(entityList, pretty: pretty), encoding: NSUTF8StringEncoding)! } public func toJsonString(pretty: Bool = false) -> NSString { return NSString(data: toJsonData(pretty: pretty), encoding: NSUTF8StringEncoding)! } public class func fromData(data: NSData!) -> AnyObject? { var object:AnyObject? = JsonGenObjectFromJsonData(data) switch object { case let hash as NSDictionary: return fromJsonDictionary(hash) case let array as NSArray: return fromJsonArray(array) default: return object } } public class func fromJsonDictionary(hash: NSDictionary?) -> EntityBase? { return nil } public class func fromJsonArray(array: NSArray?) -> [EntityBase]? { if array == nil { return nil } var ret = [EntityBase]() if let xx = array as? [NSDictionary] { for x in xx { if let obj = fromJsonDictionary(x) { ret.append(obj) } else { return nil } } } else { return nil } return ret } private class func toJson(obj: NSObject, pretty: Bool = false) -> NSData { let options = pretty ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions.allZeros return NSJSONSerialization.dataWithJSONObject(obj, options: options, error: nil)! } }
2da1f857e2818c3a054637a2878cb43c
26.846154
115
0.605318
false
false
false
false
omaralbeik/SwifterSwift
refs/heads/master
Tests/UIKitTests/UIStackViewExtensionsTest.swift
mit
1
// // UIStackViewExtensionsTest.swift // SwifterSwift // // Created by Benjamin Meyer on 2/18/18. // Copyright © 2018 SwifterSwift // import XCTest @testable import SwifterSwift #if canImport(UIKit) && !os(watchOS) import UIKit final class UIStackViewExtensionsTest: XCTestCase { // MARK: - Initializers func testInitWithViews() { let view1 = UIView() let view2 = UIView() var stack = UIStackView(arrangedSubviews: [view1, view2], axis: .horizontal) XCTAssertEqual(stack.arrangedSubviews.count, 2) XCTAssertTrue(stack.arrangedSubviews[0] === view1) XCTAssertTrue(stack.arrangedSubviews[1] === view2) XCTAssertEqual(stack.axis, .horizontal) XCTAssertEqual(stack.alignment, .fill) XCTAssertEqual(stack.distribution, .fill) XCTAssertEqual(stack.spacing, 0.0) XCTAssertEqual(UIStackView(arrangedSubviews: [view1, view2], axis: .vertical).axis, .vertical) XCTAssertEqual(UIStackView(arrangedSubviews: [view1, view2], axis: .vertical, alignment: .center).alignment, .center) XCTAssertEqual(UIStackView(arrangedSubviews: [view1, view2], axis: .vertical, distribution: .fillEqually).distribution, .fillEqually) XCTAssertEqual(UIStackView(arrangedSubviews: [view1, view2], axis: .vertical, spacing: 16.0).spacing, 16.0) stack = UIStackView(arrangedSubviews: [view1, view2], axis: .vertical, spacing: 16.0, alignment: .center, distribution: .fillEqually) XCTAssertEqual(stack.axis, .vertical) XCTAssertEqual(stack.alignment, .center) XCTAssertEqual(stack.distribution, .fillEqually) XCTAssertEqual(stack.spacing, 16.0) } func testAddArrangedSubviews() { let view1 = UIView() let view2 = UIView() let stack = UIStackView() stack.addArrangedSubviews([view1, view2]) XCTAssertEqual(stack.arrangedSubviews.count, 2) } func testRemoveArrangedSubviews() { let view1 = UIView() let view2 = UIView() let stack = UIStackView() stack.addArrangedSubview(view1) stack.addArrangedSubview(view2) stack.removeArrangedSubviews() XCTAssert(stack.arrangedSubviews.isEmpty) } } #endif
ba782d15ecf7d60af14558f1d18a11d7
32.855072
116
0.657962
false
true
false
false
wibosco/CoalescingOperations-Example
refs/heads/master
CoalescingOperations-Example/Coalescing/CoalescingExampleManager.swift
mit
1
// // CoalescingExampleManager.swift // CoalescingOperations-Example // // Created by Boles on 28/02/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit /** An example manager that handles queuing operations. It exists as we don't really want our VCs to know anything about coalescing or the queue. */ class CoalescingExampleManager: NSObject { // MARK: - Add class func addExampleCoalescingOperation(queueManager: QueueManager = QueueManager.sharedInstance, completion: (QueueManager.CompletionClosure)?) { let coalescingOperationExampleIdentifier = "coalescingOperationExampleIdentifier" if let completion = completion { queueManager.addNewCompletionClosure(completion, identifier: coalescingOperationExampleIdentifier) } if !queueManager.operationIdentifierExistsOnQueue(coalescingOperationExampleIdentifier) { let operation = CoalescingExampleOperation() operation.identifier = coalescingOperationExampleIdentifier operation.completion = {(successful) in let closures = queueManager.completionClosures(coalescingOperationExampleIdentifier) if let closures = closures { for closure in closures { closure(successful: successful) } queueManager.clearClosures(coalescingOperationExampleIdentifier) } } queueManager.enqueue(operation) } } }
d60dc4b1d6e23986557a86ea45a14fc6
34.644444
151
0.650249
false
false
false
false
thedreamer979/Calvinus
refs/heads/master
Calvin/AppDelegate.swift
gpl-3.0
1
// // AppDelegate.swift // Calvin // // Created by Arion Zimmermann on 27.01.17. // Copyright © 2017 AZEntreprise. All rights reserved. // import UIKit import UserNotifications @UIApplicationMain class AppDelegate : UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { @available(iOS 10.0, *) static let center = UNUserNotificationCenter.current() var window: UIWindow? var completionHandler : ((UIBackgroundFetchResult) -> Void)? = nil func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum) if #available(iOS 10.0, *) { AppDelegate.center.delegate = self let options: UNAuthorizationOptions = [.alert, .badge, .sound] AppDelegate.center.requestAuthorization(options: options) { (granted, error) in if !granted { print(error ?? "Undefined") } } } else { UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)) }; AZEntrepriseServer.login(controller: window?.rootViewController, userHash: UserDefaults.standard.string(forKey: "user-hash"), onResponse: loginResponse) return true } func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { self.completionHandler = completionHandler AZEntrepriseServer.login(controller: nil, userHash: UserDefaults.standard.string(forKey: "user-hash"), onResponse: handle) } func handle(dummy : Bool) { if self.completionHandler != nil { self.completionHandler!(.newData) self.completionHandler = nil } } func loginResponse(success : Bool) { if !success { DispatchQueue.main.async { let storyboard = UIStoryboard(name: "Main", bundle: nil) self.window?.rootViewController?.present(storyboard.instantiateViewController(withIdentifier: "tutorial"), animated: true, completion: nil) } } else { AZEntrepriseServer.dummyOnResponse(dummy: true) } } @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert, .badge, .sound]) } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
a4d38c017dee5e8bacf9adb5596f74ae
45.541667
285
0.69897
false
false
false
false
narner/AudioKit
refs/heads/master
Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Costello Reverb.xcplaygroundpage/Contents.swift
mit
1
//: ## Sean Costello Reverb //: This is a great sounding reverb that we just love. import AudioKitPlaygrounds import AudioKit let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true var reverb = AKCostelloReverb(player) reverb.cutoffFrequency = 9_900 // Hz reverb.feedback = 0.92 AudioKit.output = reverb AudioKit.start() player.play() //: User Interface Set up import AudioKitUI class LiveView: AKLiveViewController { var cutoffFrequencySlider: AKSlider! var feedbackSlider: AKSlider! override func viewDidLoad() { addTitle("Sean Costello Reverb") addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles)) cutoffFrequencySlider = AKSlider(property: "Cutoff Frequency", value: reverb.cutoffFrequency, range: 20 ... 5_000, format: "%0.1f Hz" ) { sliderValue in reverb.cutoffFrequency = sliderValue } addView(cutoffFrequencySlider) feedbackSlider = AKSlider(property: "Feedback", value: reverb.feedback) { sliderValue in reverb.feedback = sliderValue } addView(feedbackSlider) let presets = ["Short Tail", "Low Ringing Tail"] addView(AKPresetLoaderView(presets: presets) { preset in switch preset { case "Short Tail": reverb.presetShortTailCostelloReverb() case "Low Ringing Tail": reverb.presetLowRingingLongTailCostelloReverb() default: break } self.updateUI() }) } func updateUI() { cutoffFrequencySlider?.value = reverb.cutoffFrequency feedbackSlider?.value = reverb.feedback } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
9117ac5ec4b5157c75e92bc38237c090
28.028571
96
0.632874
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/VerticalSpacerView.swift
mit
1
import UIKit /// A vertical spacer (conceptually similar to SwiftUI's `Spacer`) class VerticalSpacerView: SetupView { // MARK: - Properties var space: CGFloat = 0 { didSet { spaceHeightAnchor?.constant = space } } fileprivate var spaceHeightAnchor: NSLayoutConstraint? // MARK: - Setup override func setup() { spaceHeightAnchor = heightAnchor.constraint(equalToConstant: space) spaceHeightAnchor?.isActive = true } // MARK: - Factory static func spacerWith(space: CGFloat) -> VerticalSpacerView { let spacer = VerticalSpacerView() spacer.space = space return spacer } }
fcb081cee571cb7422fa9c9397009daa
18.548387
69
0.722772
false
false
false
false
jhurray/SelectableTextView
refs/heads/master
Source/TextViewLayout.swift
mit
1
// // TextViewLayout.swift // SelectableTextView // // Created by Jeff Hurray on 2/4/17. // Copyright © 2017 jhurray. All rights reserved. // import UIKit internal protocol TextViewLayoutDataSource: class { func lineSpacing(forLayout layout: TextViewLayout) -> CGFloat func numberOfLines(forLayout layout: TextViewLayout) -> Int func numberOfTextModels(forLayout layout: TextViewLayout) -> Int func truncationMode(forLayout layout: TextViewLayout) -> TruncationMode func textAlignment(forLayout layout: TextViewLayout) -> TextAlignment func cellModel(atIndex index:Int, layout: TextViewLayout) -> TextCellModel func expansionButtonModel(layout: TextViewLayout) -> TextExpansionButtonModel? } fileprivate struct AttributeKey: Hashable { var indexPath: IndexPath var kind: String fileprivate var hashValue: Int { return kind.hashValue ^ indexPath.hashValue } } fileprivate func ==(left: AttributeKey, right: AttributeKey) -> Bool { return left.hashValue == right.hashValue } internal struct TruncationContext { let indexOfCellModelNeedingTruncation: Int let transformedText: String } internal struct MalformedTextCellContext { let indicesOfMalformedCells: [Int] } internal final class TextViewLayout: UICollectionViewLayout { weak internal var dataSource: TextViewLayoutDataSource? = nil internal var truncationContext: TruncationContext? = nil internal var malformedTextCellContext: MalformedTextCellContext? = nil internal var onLayout: () -> () = {} fileprivate var contentHeight: CGFloat = 0 fileprivate var contentWidth: CGFloat = 0 fileprivate var cellAttributes: [AttributeKey:UICollectionViewLayoutAttributes] = [:] override func prepare() { super.prepare() guard let dataSource = dataSource else { return } if cellAttributes.isEmpty { contentWidth = collectionView!.bounds.width - collectionView!.contentInset.left - collectionView!.contentInset.right let numberOfLines = dataSource.numberOfLines(forLayout: self) let numberOfModels = dataSource.numberOfTextModels(forLayout: self) let lineSpacing = dataSource.lineSpacing(forLayout: self) var line: Int = 0 var item: Int = 0 var lineWidth: CGFloat = 0 let lineHeight: CGFloat = maxLineHeight() if numberOfModels > 0 { contentHeight = lineHeight } var attributeKeysForCurrentLine: [AttributeKey] = [] func alignCurrentLine() { var shiftValue = floor(contentWidth - lineWidth) switch dataSource.textAlignment(forLayout: self) { case .center: shiftValue /= 2 break case .right: // do nothing break case .left: shiftValue = 0 break } if shiftValue > 0 { for key: AttributeKey in attributeKeysForCurrentLine { adjustLayoutAttributesFrameForKey(key: key, frameAdjustment: { (frame) -> (CGRect) in var frame = frame frame.origin.x += shiftValue return frame }) } } attributeKeysForCurrentLine.removeAll(keepingCapacity: true) } func isLastLine() -> Bool { return numberOfLines != 0 && line == numberOfLines } var indicesOfMalformedCells: [Int] = [] while (numberOfLines == 0 || line < numberOfLines) && item < numberOfModels { var xOrigin: CGFloat = lineWidth var width: CGFloat = 0 func newLine(additionalWidth: CGFloat) { line += 1 let isLastLine: Bool = (numberOfLines != 0 && line == numberOfLines) if (!isLastLine) { alignCurrentLine() // Start new line xOrigin = 0 lineWidth = additionalWidth contentHeight += lineHeight + lineSpacing } else { // Truncation let truncationMode = dataSource.truncationMode(forLayout: self) switch truncationMode { case .clipping: width = additionalWidth lineWidth += additionalWidth break case .truncateTail: let remainingWidth = contentWidth - lineWidth width = remainingWidth break } } } let model = dataSource.cellModel(atIndex: item, layout: self) switch model.type { case .newLine: newLine(additionalWidth: 0) default: let attributedText = model.attributedText width = attributedText.width // If this word will take up a whole line and not be the last line if width > contentWidth && line < numberOfLines - 2 { indicesOfMalformedCells.append(item) } if (lineWidth + width) > contentWidth { newLine(additionalWidth: width) } else { lineWidth += width } } if numberOfLines == 0 || line < numberOfLines || item == 0 { let indexPath = IndexPath(item: item, section: 0) let (attributes, key) = registerCell(cellType: TextCell.self, indexPath: indexPath) attributes.frame = CGRect(x: xOrigin, y: contentHeight - lineHeight, width: max(0, min(width, contentWidth)), height: lineHeight) attributeKeysForCurrentLine.append(key) item += 1 } } // Clean up the end of the text if expansionButtonNeedsNewLine() { // Expansion button needs a new line // Truncation for current line truncationContext = nil if let newLineWidth = adjustForTruncationIfNecessary(numberOfCellsHiddenByExpansion: 0, expansionOnNewLine: true) { lineWidth = newLineWidth } // Align current line of text alignCurrentLine() // Add new linew contentHeight += lineHeight lineWidth = 0 // Put expansion button on new line let (_, expansionButtonKey) = adjustForExpansionButton(lineHeight: lineHeight, onNewLine: true) // Move Expansion Button if let key = expansionButtonKey { attributeKeysForCurrentLine.append(key) if let attributes = cellAttributes[key] { lineWidth += attributes.frame.width } } // Align last line of text alignCurrentLine() } else { // Expansion let (numberOfCellsHiddenByExpansion, expansionButtonKey) = adjustForExpansionButton(lineHeight: lineHeight, onNewLine: false) // Truncation truncationContext = nil if let newLineWidth = adjustForTruncationIfNecessary(numberOfCellsHiddenByExpansion: numberOfCellsHiddenByExpansion, expansionOnNewLine:false) { lineWidth = newLineWidth } // Move Expansion Button if let key = expansionButtonKey { attributeKeysForCurrentLine.append(key) if lineWidth < contentWidth - widthForExpansionButtonCell() { adjustLayoutAttributesFrameForKey(key: key, frameAdjustment: { (frame) -> (CGRect) in var frame = frame frame.origin.x = lineWidth lineWidth += frame.width return frame }) } } // Align last line of text alignCurrentLine() } malformedTextCellContext = indicesOfMalformedCells.isEmpty ? nil : MalformedTextCellContext(indicesOfMalformedCells: indicesOfMalformedCells) } onLayout() } fileprivate func expansionButtonNeedsNewLine() -> Bool { guard let dataSource = dataSource else { return false } let numberOfLines = dataSource.numberOfLines(forLayout: self) guard numberOfLines == 0 else { return false } let numberOfModels = dataSource.numberOfTextModels(forLayout: self) let (lastAttributes, _, _) = layoutInformationAtIndex(index: numberOfModels - 1) let remainingWidth = contentWidth - lastAttributes.frame.maxX let expansionButtonWidth = widthForExpansionButtonCell() return remainingWidth < expansionButtonWidth } fileprivate func widthForExpansionButtonCell() -> CGFloat { guard let expansionButtonModel = dataSource?.expansionButtonModel(layout: self) else { return 0 } let padding: CGFloat = TextExpansionButtonConfig.horizontalPadding return expansionButtonModel.attributedText.width + 2 * padding } fileprivate func layoutInformationAtIndex(index: Int) -> (UICollectionViewLayoutAttributes, TextCellModel, AttributeKey) { let indexPath = IndexPath(item: index, section: 0) let key = AttributeKey(indexPath: indexPath, kind: TextCell.kind) guard let attributes = cellAttributes[key] else { fatalError("Attributes should not be nil") } guard let dataSource = dataSource else { fatalError("DataSource should not be nil") } let model = dataSource.cellModel(atIndex: index, layout: self) return (attributes, model, key) } // Returns he number of cells hidden, the key for the button attributes, and whether or not a new line was added fileprivate func adjustForExpansionButton(lineHeight: CGFloat, onNewLine: Bool) -> (Int, AttributeKey?) { guard let dataSource = dataSource else { return (0, nil) } guard (dataSource.expansionButtonModel(layout: self)) != nil else { return (0, nil) } let numberOfModels = dataSource.numberOfTextModels(forLayout: self) let expansionButtonWidth: CGFloat = widthForExpansionButtonCell() let indexPath = IndexPath(item: numberOfModels, section: 0) let (expansionButtonAttributes, expansionButtonKey) = registerCell(cellType: TextExpansionButtonCell.self, indexPath: indexPath) let xOrigin: CGFloat = onNewLine ? 0 : contentWidth - expansionButtonWidth expansionButtonAttributes.frame = CGRect(x: xOrigin, y: contentHeight - lineHeight, width: expansionButtonWidth, height: lineHeight) guard !onNewLine else { return (0, expansionButtonKey) } guard let attributeCollection = layoutAttributesForElements(in: expansionButtonAttributes.frame) else { return (0, expansionButtonKey) } var numberOfCellsHiddenByExpansion = 0 for attributes in attributeCollection { let index = attributes.indexPath.item guard index != numberOfModels else { continue } let (_, _, key) = layoutInformationAtIndex(index: index) let expansionButtonFrame = expansionButtonAttributes.frame if expansionButtonFrame.contains(attributes.frame) { hideCellForKey(key: key) numberOfCellsHiddenByExpansion += 1 } else { adjustLayoutAttributesFrameForKey(key: key, frameAdjustment: { (frame) -> (CGRect) in assert(frame.height == expansionButtonFrame.height) assert(frame.minY == expansionButtonFrame.minY) assert(frame.minX <= expansionButtonFrame.minX) var frame = frame let intersection = expansionButtonFrame.intersection(frame) frame.size.width -= intersection.width return frame }) } } return (numberOfCellsHiddenByExpansion, expansionButtonKey) } // Returns new value of line width fileprivate func adjustForTruncationIfNecessary(numberOfCellsHiddenByExpansion: Int, expansionOnNewLine: Bool) -> CGFloat? { guard let dataSource = dataSource else { return nil } let truncationMode = dataSource.truncationMode(forLayout: self) guard truncationMode != .clipping else { return nil } let numberOfLines = dataSource.numberOfLines(forLayout: self) guard numberOfLines > 0 else { return nil } let numberOfModels = dataSource.numberOfTextModels(forLayout: self) var numberOfCells = cellAttributes.count - numberOfCellsHiddenByExpansion if (dataSource.expansionButtonModel(layout: self)) != nil { numberOfCells -= 1 } let expansionButtonWidth = expansionOnNewLine ? 0 : widthForExpansionButtonCell() guard numberOfCells > 0 else { return nil } // the last visible cell not covered by expansion let (lastCellAttributes, lastCellModel, lastKey) = layoutInformationAtIndex(index: numberOfCells - 1) let remainingWidth = contentWidth - lastCellAttributes.frame.minX - expansionButtonWidth let lastCellModelIsWordThatDoesntFit = (lastCellModel is Word) && (lastCellModel.attributedText.width > lastCellAttributes.frame.width) && (lastCellModel.text.truncatedString(fittingWidth: remainingWidth, attributes: lastCellModel.attributes) == nil) let needsTruncation: Bool = numberOfCells < numberOfModels || lastCellModelIsWordThatDoesntFit guard needsTruncation else { return nil } let isOnlyCell: Bool = (numberOfCells == 1) if lastCellModelIsWordThatDoesntFit { if isOnlyCell { return lastCellAttributes.frame.width } else { // hide last cell hideCellForKey(key: lastKey) numberOfCells -= 1 } } // get the last visible word and create truncation context for cellIndex in (0..<numberOfCells).reversed() { let (attributes, model, key) = layoutInformationAtIndex(index: cellIndex) if let word = model as? Word, !attributes.isHidden { let availableWidthForTruncatedText: CGFloat = floor(contentWidth - attributes.frame.minX - expansionButtonWidth) let text = word.displayText ?? word.text guard let truncatedString = text.truncatedString(fittingWidth: availableWidthForTruncatedText, attributes: word.attributes) else { // JHTODO assert? should ever happen? return nil } let truncatedStringWidth = truncatedString.width(withAttributes: word.attributes) let newMaxX = attributes.frame.minX + truncatedStringWidth adjustLayoutAttributesFrameForKey(key: key, frameAdjustment: { (frame) -> (CGRect) in var frame = frame frame.size.width = truncatedStringWidth return frame }) truncationContext = TruncationContext(indexOfCellModelNeedingTruncation: cellIndex, transformedText: truncatedString) return newMaxX } else { hideCellForKey(key: key) } } return nil } fileprivate func hideCellForKey(key: AttributeKey) { adjustLayoutAttributesForKey(key: key, adjustment: { (attributes) -> (UICollectionViewLayoutAttributes) in attributes.isHidden = true return attributes }) } fileprivate func adjustLayoutAttributesFrameForKey(key: AttributeKey, frameAdjustment: (CGRect) -> (CGRect)) { adjustLayoutAttributesForKey(key: key) { (attributes) -> (UICollectionViewLayoutAttributes) in let frame = frameAdjustment(attributes.frame) attributes.frame = frame return attributes } } fileprivate func adjustLayoutAttributesForKey(key: AttributeKey, adjustment: (UICollectionViewLayoutAttributes) -> (UICollectionViewLayoutAttributes)) { guard let attributes = cellAttributes[key] else { return } cellAttributes[key] = adjustment(attributes) } func maxLineHeight() -> CGFloat { guard let dataSource = dataSource else { return 0 } var maxHeight: CGFloat = 0 let numberOfModels = dataSource.numberOfTextModels(forLayout: self) var item = 0 while item < numberOfModels { let model = dataSource.cellModel(atIndex: item, layout: self) let attributedString = model.attributedText maxHeight = max(maxHeight, attributedString.size().height) item += 1 } return ceil(maxHeight) } override func invalidateLayout() { super.invalidateLayout() cellAttributes = [AttributeKey:UICollectionViewLayoutAttributes]() contentWidth = 0 contentHeight = 0 } override var collectionViewContentSize: CGSize { return CGSize(width: contentWidth, height: contentHeight) } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return cellAttributes.values.filter { return $0.frame.intersects(rect) } } open override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let key = AttributeKey(indexPath: indexPath, kind: TextCell.kind) return self.cellAttributes[key] } open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return false } fileprivate func registerCell(cellType: UICollectionViewCell.Type, indexPath: IndexPath) -> (UICollectionViewLayoutAttributes, AttributeKey) { let key = AttributeKey(indexPath: indexPath, kind: cellType.kind) let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) cellAttributes[key] = attributes return (attributes, key) } }
d70756cc46083733339d42aed3aed624
42
160
0.582005
false
false
false
false
EstefaniaGilVaquero/ciceIOS
refs/heads/master
App_VolksWagenFinal-/App_VolksWagenFinal-/VWUsersParseTableViewController.swift
apache-2.0
1
// // VWUsersParseTableViewController.swift // App_VolksWagenFinal_CICE // // Created by Formador on 19/10/16. // Copyright © 2016 icologic. All rights reserved. // import UIKit import Parse class VWUsersParseTableViewController: UITableViewController { //MARK: - VARIABLES LOCALES GLOBALES var usersFromParse = [String]() var usersFollowing = [Bool]() //MARK: - LIFE VC override func viewDidLoad() { super.viewDidLoad() actualizarDatosUsuariosSeguidos() //consultaUsuariosParse() self.title = PFUser.currentUser()?.username } func actualizarDatosUsuariosSeguidos(){ //1. Consulta a Followers let queryFollowers = PFQuery(className: "Followers") queryFollowers.whereKey("follower", equalTo: (PFUser.currentUser()?.username)!) queryFollowers.findObjectsInBackgroundWithBlock { (objectFollowers, errorFollowers) in if errorFollowers == nil{ if let followingPersonas = objectFollowers{ //2. consulta de PFQuey let queryUsuariosFromParse = PFUser.query() queryUsuariosFromParse?.findObjectsInBackgroundWithBlock({ (objectsUsuarios, errorUsuarios) in self.usersFromParse.removeAll() self.usersFollowing.removeAll() for objectsData in objectsUsuarios!{ //3. Consulta let userData = objectsData as! PFUser if userData.username != PFUser.currentUser()?.username{ self.usersFromParse.append(userData.username!) var isFollowing = false for followingPersonaje in followingPersonas{ if followingPersonaje["following"] as? String == userData.username{ isFollowing = true } } self.usersFollowing.append(isFollowing) } } self.tableView.reloadData() }) } }else{ print("Error: \(errorFollowers?.userInfo)") } } } //TODO: - METODO DE CONSULTA DE USUARIOS DE PARSE func consultaUsuariosParse(){ let queryUsuariosFromParse = PFUser.query() queryUsuariosFromParse?.findObjectsInBackgroundWithBlock({ (objectsUsuarios, errorUsuarios) in self.usersFromParse.removeAll() for objectsData in objectsUsuarios!{ let userData = objectsData as! PFUser if userData.username != PFUser.currentUser()?.username{ self.usersFromParse.append(userData.username!) } } self.tableView.reloadData() }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return usersFromParse.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let modelData = usersFromParse[indexPath.row] let followingData = usersFollowing[indexPath.row] cell.textLabel?.text = modelData if followingData{ cell.accessoryType = UITableViewCellAccessoryType.Checkmark }else{ cell.accessoryType = UITableViewCellAccessoryType.None } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) if cell?.accessoryType == UITableViewCellAccessoryType.Checkmark{ cell?.accessoryType = UITableViewCellAccessoryType.None let queryFollowing = PFQuery(className: "Followers") queryFollowing.whereKey("follower", equalTo: (PFUser.currentUser()?.username)!) queryFollowing.whereKey("following", equalTo: (cell?.textLabel?.text)!) queryFollowing.findObjectsInBackgroundWithBlock({ (objectFollowers, errorFollowers) in if errorFollowers == nil{ if let objectFollowersData = objectFollowers{ for object in objectFollowersData{ object.deleteInBackgroundWithBlock(nil) } } }else{ print("Error: \(errorFollowers?.userInfo)") } }) }else{ cell?.accessoryType = UITableViewCellAccessoryType.Checkmark let following = PFObject(className: "Followers") following["following"] = cell?.textLabel?.text following["follower"] = PFUser.currentUser()?.username following.saveInBackgroundWithBlock(nil) } } }
0447c9dccb3b6f880ba30a7ec6301bfe
35.771242
118
0.584963
false
false
false
false
giaunv/cookiecrunch-swift-spritekit-ios
refs/heads/master
cookiecrunch/GameViewController.swift
mit
1
// // GameViewController.swift // cookiecrunch // // Created by giaunv on 3/8/15. // Copyright (c) 2015 366. All rights reserved. // import UIKit import SpriteKit import AVFoundation class GameViewController: UIViewController{ var scene: GameScene! var level: Level! var movesLeft = 0 var score = 0 var tapGestureRecognizer: UITapGestureRecognizer! @IBOutlet weak var targetLabel: UILabel! @IBOutlet weak var movesLabel: UILabel! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var gameOverPanel: UIImageView! @IBOutlet weak var shuffleButton: UIButton! @IBAction func shuffleButtonPressed(AnyObject){ shuffle() decrementMoves() } lazy var backgroundMusic: AVAudioPlayer = { let url = NSBundle.mainBundle().URLForResource("Mining by Moonlight", withExtension: "mp3") let player = AVAudioPlayer(contentsOfURL: url, error: nil) player.numberOfLoops = -1 return player }() override func prefersStatusBarHidden() -> Bool { return true } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } override func viewDidLoad() { super.viewDidLoad() // Configure the view let skView = view as SKView skView.multipleTouchEnabled = false // Create and configure the scene scene = GameScene(size: skView.bounds.size) scene.scaleMode = .AspectFill level = Level(filename: "Level_3") scene.level = level scene.addTiles() scene.swipeHandler = handleSwipe gameOverPanel.hidden = true shuffleButton.hidden = true // Present the scene skView.presentScene(scene) backgroundMusic.play() beginGame() } func beginGame(){ movesLeft = level.maximumMoves score = 0 updateLabels() level.resetComboMultiplier() scene.animateBeginGame(){ self.shuffleButton.hidden = false } shuffle() } func shuffle(){ scene.removeAllCookieSprites() let newCookies = level.shuffle() scene.addSpritesForCookies(newCookies) } func handleSwipe(swap: Swap){ view.userInteractionEnabled = false if level.isPossibleSwap(swap){ level.performSwap(swap) scene.animateSwap(swap, completion: handleMatches) } else{ scene.animateInvalidSwap(swap){ self.view.userInteractionEnabled = true } } } func handleMatches(){ let chains = level.removeMatches() if chains.count == 0{ beginNextTurn() return } scene.animateMatchedCookies(chains){ for chain in chains{ self.score += chain.score } self.updateLabels() let columns = self.level.fillHoles() self.scene.animateFallingCookies(columns){ let columns = self.level.topUpCookies() self.scene.animateNewCookies(columns){ self.handleMatches() } } } } func beginNextTurn(){ level.resetComboMultiplier() level.detectPossibleSwaps() view.userInteractionEnabled = true decrementMoves() } func updateLabels(){ targetLabel.text = NSString(format: "%ld", level.targetScore) movesLabel.text = NSString(format: "%ld", movesLeft) scoreLabel.text = NSString(format: "%ld", score) } func decrementMoves(){ --movesLeft updateLabels() if score >= level.targetScore{ gameOverPanel.image = UIImage(named: "LevelComplete") showGameOver() } else if movesLeft == 0{ gameOverPanel.image = UIImage(named: "GameOver") showGameOver() } } func showGameOver(){ shuffleButton.hidden = true gameOverPanel.hidden = false scene.userInteractionEnabled = false scene.animateGameOver(){ self.tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "hideGameOver") self.view.addGestureRecognizer(self.tapGestureRecognizer) } } func hideGameOver(){ view.removeGestureRecognizer(tapGestureRecognizer) tapGestureRecognizer = nil gameOverPanel.hidden = true scene.userInteractionEnabled = true beginGame() } }
90b580fde05f5c4b4b79f9b7eb44e690
26.144444
100
0.580143
false
false
false
false
klundberg/sweep
refs/heads/master
Sources/grift/DependenciesCommand.swift
mit
1
// // DependenciesCommand.swift // Grift // // Created by Kevin Lundberg on 3/23/17. // Copyright © 2017 Kevin Lundberg. All rights reserved. // import Commandant import GriftKit import Result import SourceKittenFramework import SwiftGraph struct GriftError: Error, CustomStringConvertible { var message: String var description: String { return message } } struct DependenciesCommand: CommandProtocol { let verb: String = "dependencies" let function: String = "Generates a dependency graph from swift files in the given directory" func run(_ options: DependenciesOptions) -> Result<(), GriftError> { do { let structures = try GriftKit.structures(at: options.path) let graph = GraphBuilder.build(structures: structures) let dot = graph.graphviz() print(dot.description) return .success(()) } catch { return .failure(GriftError(message: "\(error)")) } } } struct DependenciesOptions: OptionsProtocol { let path: String static func create(_ path: String) -> DependenciesOptions { return DependenciesOptions(path: path) } static func evaluate(_ m: CommandMode) -> Result<DependenciesOptions, CommandantError<GriftError>> { return create <*> m <| Option(key: "path", defaultValue: ".", usage: "The path to generate a dependency graph from") } }
503d7101fef0acafb7f33dd969f91460
26.056604
114
0.658298
false
false
false
false
willpowell8/LocalizationKit_iOS
refs/heads/master
Tests/KeyParseTest.swift
mit
1
// // KeyParseTest.swift // LocalizationKit // // Created by Will Powell on 28/12/2017. // Copyright © 2017 willpowell8. All rights reserved. // import XCTest import LocalizationKit class KeyParseTest: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testParseSuccess() { XCTAssert(Localization.parse(str: "com.test") == "com.test") } func testParseSpace() { XCTAssert(Localization.parse(str: "com. test") == "com.test") } func testParsePunctuation() { XCTAssert(Localization.parse(str: "com.#?/<>,test") == "com.test") } }
a43b6d6384c3f6fe9d9a0447dd5dda31
24.472222
111
0.624864
false
true
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureInterest/Sources/FeatureInterestUI/Accessibility+InterestUIKit.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformUIKit extension Accessibility.Identifier { public enum Interest { enum Dashboard { enum Announcement { private static let prefix = "InterestAccountAnnouncementScreen." static let rateLineItem = "\(prefix)rateLineItem" static let paymentIntervalLineItem = "\(prefix)paymentIntervalLineItem" static let footerCell = "\(prefix)footerCell" } enum InterestDetails { private static let prefix = "InterestAccoundDetailsScreen." static let view = "\(prefix)view" static let balanceCellTitle = "\(prefix)balanceCellTitle" static let balanceCellDescription = "\(prefix)balanceCellDescription" static let balanceCellFiatAmount = "\(prefix)balanceCellFiatAmount" static let balanceCellCryptoAmount = "\(prefix)balanceCellCryptoAmount" static let balanceCellPending = "\(prefix)balanceCellPending" static let lineItem = "\(prefix)lineItem" static let footerCellTitle = "\(prefix)footerCellTitle" } } } }
c6629d722628a362d9d60e8a1d7ec832
42.206897
87
0.621708
false
false
false
false
rafaelGuerreiro/swift-websocket
refs/heads/master
Sources/App/WebSocketSession.swift
mit
1
import Vapor class WebSocketSession: Equatable, Hashable, CustomStringConvertible { let id: String let username: String let socket: WebSocket init(id: String, username: String, socket: WebSocket) { self.id = id self.username = username self.socket = socket } var description: String { return "\(id) -> \(username)" } var hashValue: Int { return id.hashValue } static func == (lhs: WebSocketSession, rhs: WebSocketSession) -> Bool { return lhs.id == rhs.id } func send(_ message: String) { send(MessageOutputData(message: message, sent: Date.currentTimestamp(), received: Date.currentTimestamp())) } func send(_ output: MessageOutputData) { if let json = try? output.makeJSON(), let bytes = try? json.makeBytes() { print("Sending to \(id)") try? socket.send(bytes.makeString()) } } }
fc4266ca10be63d8032b4ef2f49d872d
24.236842
115
0.596455
false
false
false
false
infinitedg/SwiftDDP
refs/heads/master
Examples/CoreData/SwiftTodos/AppDelegate.swift
mit
1
import UIKit import SwiftDDP import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? let todos = MeteorCoreDataCollection(collectionName: "Todos", entityName: "Todo") let lists = MeteorCoreDataCollection(collectionName: "Lists", entityName: "List") func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let splitViewController = self.window!.rootViewController as! UISplitViewController splitViewController.preferredDisplayMode = .AllVisible splitViewController.delegate = self // let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController // let listViewController = masterNavigationController.topViewController as! Lists Meteor.client.logLevel = .Debug let url = "ws://localhost:3000/websocket" // let url = "wss://meteor-ios-todos.meteor.com/websocket" Meteor.connect(url) { Meteor.subscribe("lists.public") Meteor.subscribe("lists.private") } print("Application Did Finish Launching") return true } func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { if let todosViewController = (secondaryViewController as? UINavigationController)?.topViewController as? Todos { if todosViewController.listId == nil { return true } } return false } // MARK: - Core Data Saving support /* func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } }*/ }
c160cb26e51d9bc529dcc849f1e88c7a
37.53125
222
0.660989
false
false
false
false
Bunn/firefox-ios
refs/heads/master
Extensions/ShareTo/SendToDevice.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage class SendToDevice: DevicePickerViewControllerDelegate, InstructionsViewControllerDelegate { var sharedItem: ShareItem? weak var delegate: ShareControllerDelegate? func initialViewController() -> UIViewController { if !hasAccount() { let instructionsViewController = InstructionsViewController() instructionsViewController.delegate = self return instructionsViewController } let devicePickerViewController = DevicePickerViewController() devicePickerViewController.pickerDelegate = self devicePickerViewController.profile = nil // This means the picker will open and close the default profile return devicePickerViewController } func finish() { delegate?.finish(afterDelay: 0) } func devicePickerViewController(_ devicePickerViewController: DevicePickerViewController, didPickDevices devices: [RemoteDevice]) { guard let item = sharedItem else { return finish() } let profile = BrowserProfile(localName: "profile") profile.sendItem(item, toDevices: devices).uponQueue(.main) { _ in profile._shutdown() self.finish() addAppExtensionTelemetryEvent(forMethod: "send-to-device") } } func devicePickerViewControllerDidCancel(_ devicePickerViewController: DevicePickerViewController) { finish() } func instructionsViewControllerDidClose(_ instructionsViewController: InstructionsViewController) { finish() } private func hasAccount() -> Bool { let profile = BrowserProfile(localName: "profile") defer { profile._shutdown() } return profile.hasAccount() } }
7c347cdc8a1e9c6b5a2d7372975d7ffa
32.966102
135
0.686627
false
false
false
false
ripventura/VCUIKit
refs/heads/master
VCUIKit/Classes/VCTheme/View Controller/Collection View/VCCollectionViewController.swift
mit
1
// // VCCollectionViewController.swift // FCAlertView // // Created by Vitor Cesco on 26/02/18. // import UIKit open class VCCollectionViewController: UICollectionViewController, RefreshControlManagerDelegate, SearchControlManagerDelegate { /** Whether the appearance is being set manually on Storyboard */ @IBInspectable var storyboardAppearance: Bool = false /** Whether the CollectionView should have a RefreshControl */ @IBInspectable open var includesRefreshControl: Bool = false /** Whether the CollectionView should have a RefreshControl */ @IBInspectable open var includesSearchControl: Bool = false /** Whether the CollectionView should disable the RefreshControl when searching */ @IBInspectable open var disablesRefreshWhenSearching: Bool = true open var refreshControlManager: RefreshControlManager = RefreshControlManager() open var searchControlManager: SearchControlManager = SearchControlManager() // MARK: - Lifecycle open override func viewDidLoad() { super.viewDidLoad() self.refreshControlManager.delegate = self if self.includesRefreshControl { self.refreshControlManager.setupRefreshControl(scrollView: self.collectionView) } self.searchControlManager.delegate = self if self.includesSearchControl { self.searchControlManager.setupSearchControl(viewController: self) } self.updateBackButtonStyle() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.applyAppearance() } // MARK: - Styling /** Override this if you want to change the Default Styles for this particular View Controller */ open func willSetDefaultStyles() { sharedAppearanceManager.initializeDefaultAppearance?() sharedAppearanceManager.appearance = defaultAppearance } override open func applyAppearance() -> Void { self.willSetDefaultStyles() super.applyAppearance() self.collectionView?.backgroundColor = sharedAppearanceManager.appearance.collectionViewBackgroundColor //Updates StatusBar Style UIApplication.shared.statusBarStyle = sharedAppearanceManager.appearance.applicationStatusBarStyle //Updates NavigationBar appearance self.navigationController?.applyAppearance() if !storyboardAppearance { self.view.tintColor = sharedAppearanceManager.appearance.viewControllerViewTintColor self.view.backgroundColor = sharedAppearanceManager.appearance.collectionViewBackgroundColor } //Updates TabBar colors self.tabBarController?.applyAppearance() } // MARK: - RefreshControlManagerDelegate open func refreshControlDidRefresh(manager: RefreshControlManager) { } // MARK: - SearchControlManagerDelegate open func searchControlDidBeginEditing(manager: SearchControlManager) { if self.disablesRefreshWhenSearching { // Disables the RefreshControl when searching self.collectionView?.bounces = false self.collectionView?.alwaysBounceVertical = false } } open func searchControlCancelButtonPressed(manager: SearchControlManager) { if self.disablesRefreshWhenSearching { // Enables back the RefreshControl self.collectionView?.bounces = true self.collectionView?.alwaysBounceVertical = true } } open func searchControl(manager: SearchControlManager, didSearch text: String?) { } }
31f07d38247b25c8a788015a7723d94f
36.876289
128
0.704682
false
false
false
false
15cm/AMM
refs/heads/master
AMM/Preferences/AboutViewController.swift
gpl-3.0
1
// // AboutViewÇontroller.swift // AMM // // Created by Sinkerine on 19/02/2017. // Copyright © 2017 sinkerine. All rights reserved. // import Cocoa class AboutViewController: NSViewController { let infoDictionary = Bundle.main.infoDictionary! @IBOutlet weak var appName: NSTextField! { didSet { appName.stringValue = infoDictionary["CFBundleName"] as! String } } @IBOutlet weak var appVersionBuild: NSTextField! { didSet { let version = infoDictionary["CFBundleShortVersionString"] as! String let build = infoDictionary["CFBundleVersion"] as! String appVersionBuild.stringValue = "v\(version) (Build \(build))" } } @IBOutlet weak var appSource: NSTextField! { didSet { let sourceRTFPath = Bundle.main.path(forResource: "Source", ofType: "rtf") do { if let path = sourceRTFPath { let data = try Data(contentsOf: URL(fileURLWithPath: path)) appSource.attributedStringValue = NSAttributedString(rtf: data, documentAttributes: nil)! } } catch { print(error) } } } @IBOutlet weak var contactMe: NSTextField! { didSet { do { let contactRTFPath = Bundle.main.path(forResource: "Contact", ofType: "rtf") if let path = contactRTFPath { let data = try Data(contentsOf: URL(fileURLWithPath: path)) contactMe.attributedStringValue = NSAttributedString(rtf: data, documentAttributes: nil)! } } catch { print(error) } } } @IBOutlet weak var copyright: NSTextField! { didSet { copyright.stringValue = infoDictionary["NSHumanReadableCopyright"] as! String } } override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } }
2f6edf1267e7af3c61f30c41774d6bbc
31.548387
109
0.570367
false
false
false
false
SASAbus/SASAbus-ios
refs/heads/master
SASAbus/Controller/Departure/BusStopViewController.swift
gpl-3.0
1
import UIKit import RxSwift import RxCocoa import Realm import RealmSwift import Alamofire import StatefulViewController class BusStopViewController: MasterViewController, UITabBarDelegate, StatefulViewController { let dateFormat = "HH:mm" @IBOutlet weak var timeField: UITextField! @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var tabBar: UITabBar! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var autoCompleteTableView: UITableView! var selectedBusStop: BBusStop? var foundBusStations: [BBusStop] = [] var datePicker: UIDatePicker! var allDepartures: [Departure] = [] var disabledDepartures: [Departure] = [] var searchDate: Date! var refreshControl: UIRefreshControl! var working: Bool! = false var realm = Realm.busStops() init(busStop: BBusStop? = nil) { super.init(nibName: "BusStopViewController", title: L10n.Departures.title) self.selectedBusStop = busStop } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.register(UINib(nibName: "DepartureViewCell", bundle: nil), forCellReuseIdentifier: "DepartureViewCell") tableView.delegate = self tableView.dataSource = self tableView.tableFooterView = UIView() refreshControl = UIRefreshControl() refreshControl.tintColor = Theme.lightOrange refreshControl.addTarget(self, action: #selector(parseData), for: .valueChanged) refreshControl.attributedTitle = NSAttributedString( string: L10n.General.pullToRefresh, attributes: [NSForegroundColorAttributeName: Theme.darkGrey] ) tableView.refreshControl = refreshControl setupSearchDate() view.backgroundColor = Theme.darkGrey searchBar.barTintColor = .darkGray searchBar.tintColor = Theme.white searchBar.backgroundImage = UIImage() searchBar.setImage(Asset.icNavigationBus.image, for: UISearchBarIcon.search, state: UIControlState()) (searchBar.value(forKey: "searchField") as! UITextField).textColor = Theme.darkGrey (searchBar.value(forKey: "searchField") as! UITextField).clearButtonMode = UITextFieldViewMode.never navigationItem.rightBarButtonItem = getFilterButton() tabBar.items![0].title = L10n.Departures.Header.gps tabBar.items![1].title = L10n.Departures.Header.map tabBar.items![2].title = L10n.Departures.Header.favorites datePicker = UIDatePicker(frame: CGRect.zero) datePicker.datePickerMode = .dateAndTime datePicker.backgroundColor = Theme.darkGrey datePicker.tintColor = Theme.white datePicker.setValue(Theme.white, forKey: "textColor") timeField.textColor = Theme.white timeField.tintColor = Theme.transparent timeField.inputView = datePicker loadingView = LoadingView(frame: view.frame) emptyView = NoDeparturesView(frame: tableView.frame) errorView = ErrorView(frame: view.frame, target: self, action: #selector(parseData)) setupAutoCompleteTableView() setupBusStopSearchDate() if let stop = selectedBusStop { let tempStop = stop selectedBusStop = nil setBusStop(tempStop) } } override func leftDrawerButtonPress(_ sender: AnyObject?) { self.searchBar.endEditing(true) self.timeField.endEditing(true) super.leftDrawerButtonPress(sender) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let view = emptyView { view.frame = CGRect( x: view.frame.origin.x, y: view.frame.origin.y + tabBar.frame.size.height, width: view.frame.size.width, height: view.frame.size.height - 2 * tabBar.frame.size.height ) (view as? NoDeparturesView)?.setupView() } } override func viewDidAppear(_ animated: Bool) { tabBar.selectedItem = nil } fileprivate func setupAutoCompleteTableView() { self.autoCompleteTableView!.isHidden = true self.updateFoundBusStations("") self.view.addSubview(self.autoCompleteTableView!) self.autoCompleteTableView!.register(UINib(nibName: "DepartureAutoCompleteCell", bundle: nil), forCellReuseIdentifier: "DepartureAutoCompleteCell") } fileprivate func updateFoundBusStations(_ searchText: String) { let busStops: Results<BusStop> if searchText.isEmpty { busStops = realm.objects(BusStop.self) } else { busStops = realm.objects(BusStop.self) .filter("nameDe CONTAINS[c] %@ OR nameIt CONTAINS[c] %@ OR municDe CONTAINS[c] %@ OR municIt CONTAINS[c] %@", searchText, searchText, searchText, searchText) } let mapped = busStops.map { BBusStop(fromRealm: $0) } foundBusStations = Array(Set(mapped)) self.foundBusStations = foundBusStations.sorted(by: { $0.name(locale: Locales.get()) < $1.name(locale: Locales.get()) }) self.autoCompleteTableView.reloadData() } func setBusStationFromCurrentLocation() { // TODO /*if UserDefaultHelper.instance.isBeaconStationDetectionEnabled() { let currentBusStop = UserDefaultHelper.instance.getCurrentBusStop() if let stop = currentBusStop != nil { Log.info("Current bus stop: \(stop)") if let busStop = realm.objects(BusStop.self).filter("id == \(stop)").first { setBusStop(BBusStop(fromRealm: busStop)) setupBusStopSearchDate() autoCompleteTableView.isHidden = true tabBar.selectedItem = nil } } }*/ } func setupBusStopSearchDate() { setupSearchDate() datePicker.date = searchDate as Date let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat timeField.text = dateFormatter.string(from: searchDate as Date) } func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { if item.tag == 0 { let busStopGpsViewController = BusStopGpsViewController() navigationController!.pushViewController(busStopGpsViewController, animated: true) } else if item.tag == 1 { let busStopMapViewController = BusStopMapViewController() navigationController!.pushViewController(busStopMapViewController, animated: true) } else if item.tag == 2 { let busStopFavoritesViewController = BusStopFavoritesViewController(busStop: self.selectedBusStop) navigationController!.pushViewController(busStopFavoritesViewController, animated: true) } } func goToFilter() { let busStopFilterViewController = BusStopFilterViewController() navigationController!.pushViewController(busStopFilterViewController, animated: true) } func setBusStop(_ busStop: BBusStop) { if selectedBusStop != nil && selectedBusStop!.family == busStop.family { // Don't reload same bus stop return } Log.info("Setting bus stop '\(busStop.id)'") selectedBusStop = busStop autoCompleteTableView.isHidden = true searchBar.text = selectedBusStop?.name() searchBar.endEditing(true) searchBar.resignFirstResponder() allDepartures.removeAll() disabledDepartures.removeAll() tableView.reloadData() parseData() } func parseData() { guard selectedBusStop != nil else { Log.error("No bus stop is currently selected") return } startLoading() _ = self.getDepartures() .subscribeOn(MainScheduler.background) .observeOn(MainScheduler.instance) .subscribe(onNext: { items in self.allDepartures.removeAll() self.allDepartures.append(contentsOf: items) self.updateFilter() self.tableView.reloadData() self.tableView.refreshControl?.endRefreshing() self.endLoading(animated: false) self.loadDelays() }, onError: { error in ErrorHelper.log(error, message: "Could not fetch departures") self.allDepartures.removeAll() self.tableView.reloadData() self.tableView.refreshControl?.endRefreshing() self.endLoading(animated: false, error: error) }) } func loadDelays() { _ = RealtimeApi.delays() .subscribeOn(MainScheduler.background) .observeOn(MainScheduler.instance) .subscribe(onNext: { buses in for bus in buses { for item in self.allDepartures { if item.trip == bus.trip { item.delay = bus.delay item.vehicle = bus.vehicle item.currentBusStop = bus.busStop break } } } self.allDepartures.filter { $0.delay == Config.BUS_STOP_DETAILS_OPERATION_RUNNING }.forEach { $0.delay = Config.BUS_STOP_DETAILS_NO_DELAY } if !self.allDepartures.isEmpty { self.tableView.reloadData() } }, onError: { error in ErrorHelper.log(error, message: "Could not load delays") self.allDepartures.filter { $0.delay == Config.BUS_STOP_DETAILS_OPERATION_RUNNING }.forEach { $0.delay = Config.BUS_STOP_DETAILS_NO_DELAY } if !self.allDepartures.isEmpty { self.tableView.reloadData() } }) } func updateFilter() { let disabledLines: [Int] = UserRealmHelper.getDisabledDepartures() disabledDepartures.removeAll() if disabledLines.isEmpty { disabledDepartures.append(contentsOf: allDepartures) } else { disabledDepartures.append(contentsOf: allDepartures.filter { !disabledLines.contains($0.lineId) }) } self.refreshControl.endRefreshing() self.tableView.reloadData() self.enableSearching() } func hasContent() -> Bool { return !allDepartures.isEmpty } func getDepartures() -> Observable<[Departure]> { return Observable.create { observer in let departures = DepartureMonitor() .atBusStopFamily(family: self.selectedBusStop?.family ?? 0) .at(date: self.searchDate) .collect() let mapped = departures.map { $0.asDeparture(busStopId: self.selectedBusStop?.id ?? 0) } observer.on(.next(mapped)) return Disposables.create() } } } extension BusStopViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.autoCompleteTableView != nil && tableView.isEqual(self.autoCompleteTableView) { return self.foundBusStations.count } else { return disabledDepartures.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if self.autoCompleteTableView != nil && tableView.isEqual(self.autoCompleteTableView) { let busStation = self.foundBusStations[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "DepartureAutoCompleteCell", for: indexPath) as! DepartureAutoCompleteCell cell.label.text = busStation.name() return cell } let departure = disabledDepartures[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "DepartureViewCell", for: indexPath) as! DepartureViewCell cell.timeLabel.text = departure.time if departure.delay == Departure.OPERATION_RUNNING { cell.delayLabel.text = L10n.Departures.Cell.loading cell.delayColor = Theme.darkGrey } else if departure.delay == Departure.NO_DELAY { cell.delayLabel.text = L10n.Departures.Cell.noData cell.delayColor = Theme.darkGrey } if departure.vehicle != 0 { cell.delayColor = Color.delay(departure.delay) if departure.delay == 0 { cell.delayLabel.text = L10n.General.delayPunctual } else if departure.delay < 0 { cell.delayLabel.text = L10n.General.delayEarly(abs(departure.delay)) } else { cell.delayLabel.text = L10n.General.delayDelayed(departure.delay) } } cell.infoLabel.text = Lines.line(id: departure.lineId) cell.directionLabel.text = departure.destination return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if autoCompleteTableView != nil && tableView.isEqual(autoCompleteTableView) { navigationItem.rightBarButtonItem = getFilterButton() let busStop = foundBusStations[indexPath.row] // Is this the right place to put this? UserRealmHelper.addRecentDeparture(group: busStop.family) setBusStop(busStop) } else { let item = disabledDepartures[indexPath.row] let busStopTripViewController = LineCourseViewController( tripId: item.trip, lineId: item.lineId, vehicle: item.vehicle, currentBusStop: item.currentBusStop, busStopGroup: item.busStopGroup, date: searchDate ) self.navigationController!.pushViewController(busStopTripViewController, animated: true) } } } extension BusStopViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { return false } func textFieldDidBeginEditing(_ textField: UITextField) { let datePickerDoneButton = UIBarButtonItem( title: L10n.Departures.Button.done, style: UIBarButtonItemStyle.done, target: self, action: #selector(setSearchDate) ) navigationItem.rightBarButtonItem = datePickerDoneButton } func textFieldDidEndEditing(_ textField: UITextField) { navigationItem.rightBarButtonItem = nil allDepartures.removeAll() tableView.reloadData() textField.resignFirstResponder() } } extension BusStopViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if selectedBusStop != nil { selectedBusStop = nil } updateFoundBusStations(searchText) } func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { return !working } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { navigationItem.rightBarButtonItem = UIBarButtonItem( barButtonSystemItem: .cancel, target: self, action: #selector(searchBarCancel) ) searchBar.text = "" updateFoundBusStations(searchBar.text!) autoCompleteTableView.isHidden = false errorView?.isHidden = true loadingView?.isHidden = true emptyView?.isHidden = true } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { foundBusStations = [] autoCompleteTableView.isHidden = true autoCompleteTableView.reloadData() startLoading(animated: false) endLoading(animated: false) errorView?.isHidden = false loadingView?.isHidden = false emptyView?.isHidden = false } } extension BusStopViewController { internal func disableSearching() { self.working = true (self.searchBar.value(forKey: "searchField") as! UITextField).textColor = Theme.grey self.timeField.isUserInteractionEnabled = false self.searchBar.alpha = 0.7 self.timeField.alpha = 0.7 let items = self.tabBar.items for item in items! { item.isEnabled = false } self.tabBar.setItems(items, animated: false) } internal func enableSearching() { working = false (searchBar.value(forKey: "searchField") as! UITextField).textColor = Theme.darkGrey timeField.isUserInteractionEnabled = true searchBar.alpha = 1.0 timeField.alpha = 1.0 let items = tabBar.items for item in items! { item.isEnabled = true } tabBar.setItems(items, animated: false) } func searchBarCancel() { searchBar.endEditing(true) searchBar.resignFirstResponder() navigationItem.rightBarButtonItem = getFilterButton() } func setSearchDate() { let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat searchDate = datePicker.date timeField.text = dateFormatter.string(from: searchDate as Date) timeField.endEditing(true) navigationItem.rightBarButtonItem = getFilterButton() allDepartures.removeAll() disabledDepartures.removeAll() tableView.reloadData() parseData() } func setupSearchDate() { self.searchDate = Date() let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat } func getFilterButton() -> UIBarButtonItem { return UIBarButtonItem( image: Asset.filterIcon.image.withRenderingMode(UIImageRenderingMode.alwaysTemplate), style: .plain, target: self, action: #selector(goToFilter) ) } }
9622cb486f7a62beeccb02272bec941e
30.735
129
0.604695
false
false
false
false