repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Eccelor/material-components-ios
components/Collections/examples/CollectionsSimpleSwiftDemo.swift
2
2061
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MaterialComponents.MaterialCollections class CollectionsSimpleSwiftDemo: MDCCollectionViewController { let reusableIdentifierItem = "itemCellIdentifier" let colors = [ "red", "blue", "green", "black", "yellow", "purple" ] override func viewDidLoad() { super.viewDidLoad() // Register cell class. self.collectionView?.register(MDCCollectionViewTextCell.self, forCellWithReuseIdentifier: reusableIdentifierItem) // Customize collection view settings. self.styler.cellStyle = .card } // MARK: UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return colors.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reusableIdentifierItem, for: indexPath) if let cell = cell as? MDCCollectionViewTextCell { cell.textLabel?.text = colors[indexPath.item] } return cell } } // MARK: Catalog by convention extension CollectionsSimpleSwiftDemo { class func catalogBreadcrumbs() -> [String] { return [ "Collections", "Simple Swift Demo"] } }
apache-2.0
03dd7a7c7a51347be6aeb2bec70c98ca
32.786885
94
0.69869
5.381201
false
false
false
false
shushutochako/CircleSlider
Example/CircleSlider/ViewController.swift
1
8115
// // ViewController.swift // CircleSlider // // Created by shushutochako on 11/17/2015. // Copyright (c) 2015 shushutochako. All rights reserved. // import UIKit import CircleSlider class ViewController: UIViewController { @IBOutlet weak var sliderArea: UIView! @IBOutlet weak var tapProgressButton: UIButton! @IBOutlet weak var valueLabel: UILabel! @IBOutlet weak var delegateLabel: UILabel! @IBOutlet weak var statusLabel: UILabel! private var circleSlider: CircleSlider! private var timer: Timer? private var minValue: Float = 20 private var maxValue: Float = 100 private var sliderOptions: [CircleSliderOption] { return [ CircleSliderOption.barColor(UIColor(red: 127 / 255, green: 244 / 255, blue: 23 / 255, alpha: 1)), CircleSliderOption.thumbColor(UIColor(red: 127 / 255, green: 185 / 255, blue: 204 / 255, alpha: 1)), CircleSliderOption.trackingColor(UIColor(red: 78 / 255, green: 136 / 255, blue: 185 / 255, alpha: 1)), CircleSliderOption.barWidth(20), CircleSliderOption.startAngle(0), CircleSliderOption.maxValue(self.maxValue), CircleSliderOption.minValue(self.minValue), CircleSliderOption.thumbImage(UIImage(named: "thumb_image_1")!) ] } private var progressOptions: [CircleSliderOption] { return [ .barColor(UIColor(red: 255 / 255, green: 190 / 255, blue: 190 / 255, alpha: 1)), .trackingColor(UIColor(red: 159 / 255, green: 0 / 255, blue: 0 / 255, alpha: 1)), .barWidth(30), .sliderEnabled(false) ] } override func viewDidLoad() { super.viewDidLoad() buildCircleSlider() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() circleSlider.frame = sliderArea.bounds } private func buildCircleSlider() { circleSlider = CircleSlider(frame: sliderArea.bounds, options: sliderOptions) circleSlider?.addTarget(self, action: #selector(valueChange(sender:)), for: .valueChanged) sliderArea.addSubview(circleSlider!) circleSlider.delegate = self } @objc func valueChange(sender: CircleSlider) { valueLabel.text = "\(Int(sender.value))" changeButtonImage(circleSlider.status) } @IBAction func tapProgress(_: AnyObject) { switch circleSlider.status { case CircleSliderStatus.noChangeMinValue: timer = Timer.scheduledTimer(timeInterval: 0.02, target: self, selector: #selector(fire(timer:)), userInfo: nil, repeats: true) case CircleSliderStatus.reachedMaxValue: tapProgressButton.setImage(UIImage(named: "button_start"), for: UIControlState.normal) circleSlider.value = minValue timer = Timer.scheduledTimer(timeInterval: 0.02, target: self, selector: #selector(fire(timer:)), userInfo: nil, repeats: true) case CircleSliderStatus.inProgressChangeValue: if (timer?.isValid)! { tapProgressButton.setImage(UIImage(named: "button_start"), for: UIControlState.normal) timer?.invalidate() } else { tapProgressButton.setImage(UIImage(named: "button_stop"), for: UIControlState.normal) timer = Timer.scheduledTimer(timeInterval: 0.02, target: self, selector: #selector(fire(timer:)), userInfo: nil, repeats: true) } } } @objc func fire(timer _: Timer) { circleSlider.value += 0.5 changeButtonImage(circleSlider.status) } private func changeButtonImage(_ status: CircleSliderStatus) { switch status { case CircleSliderStatus.noChangeMinValue: tapProgressButton.setImage(UIImage(named: "button_start"), for: UIControlState.normal) statusLabel.text = "noChangeMinValue" case CircleSliderStatus.inProgressChangeValue: tapProgressButton.setImage(UIImage(named: "button_stop"), for: UIControlState.normal) statusLabel.text = "inProgressChangeValue" case CircleSliderStatus.reachedMaxValue: tapProgressButton.setImage(UIImage(named: "button_end"), for: UIControlState.normal) statusLabel.text = "reachedMaxValue" timer?.invalidate() timer = nil } } @IBAction func enableSwitchChanged(_ sender: Any) { let lastValue = circleSlider.value circleSlider.changeOptions([.sliderEnabled((sender as! UISwitch).isOn)]) circleSlider.value = lastValue } @IBAction func trackingColorChanged(_ sender: AnyObject) { let redValue = CGFloat((sender as! UISlider).value) / 255 let newColor = UIColor(red: redValue, green: 136 / 255, blue: 185 / 255, alpha: 1) let lastValue = circleSlider.value circleSlider.changeOptions([.trackingColor(newColor)]) circleSlider.value = lastValue } @IBAction func barColorChanged(_ sender: Any) { let redValue = CGFloat((sender as! UISlider).value) / 255 let newColor = UIColor(red: redValue, green: 244 / 255, blue: 23 / 255, alpha: 1) let lastValue = circleSlider.value circleSlider.changeOptions([.barColor(newColor)]) circleSlider.value = lastValue } @IBAction func thumbColorChanged(_ sender: Any) { let redValue = CGFloat((sender as! UISlider).value) / 255 let newColor = UIColor(red: redValue, green: 185 / 255, blue: 204 / 255, alpha: 1) let lastValue = circleSlider.value circleSlider.changeOptions([.thumbColor(newColor)]) circleSlider.value = lastValue } @IBAction func barWidthChanged(_ sender: AnyObject) { let lastValue = circleSlider.value circleSlider.changeOptions([.barWidth(CGFloat((sender as! UISlider).value))]) circleSlider.value = lastValue } @IBAction func thumbWidthChanged(_ sender: AnyObject) { let lastValue = circleSlider.value circleSlider.changeOptions([.thumbWidth(CGFloat((sender as! UISlider).value))]) circleSlider.value = lastValue } @IBAction func viewInsetChanged(_ sender: AnyObject) { let lastValue = circleSlider.value circleSlider.changeOptions([.viewInset(CGFloat((sender as! UISlider).value))]) circleSlider.value = lastValue } @IBAction func startAngle(_ sender: Any) { let lastValue = circleSlider.value circleSlider.changeOptions([.startAngle(Double((sender as! UISlider).value))]) circleSlider.value = lastValue } @IBAction func thumbImage1BtnTapped(_: Any) { let lastValue = circleSlider.value circleSlider.changeOptions([.thumbImage(UIImage(named: "thumb_image_1")!)]) circleSlider.value = lastValue } @IBAction func thumbImage2BtnTapped(_: Any) { let lastValue = circleSlider.value circleSlider.changeOptions([.thumbImage(UIImage(named: "thumb_image_2")!)]) circleSlider.value = lastValue } @IBAction func thumbImage3BtnTapped(_: Any) { let lastValue = circleSlider.value circleSlider.changeOptions([.thumbImage(UIImage(named: "thumb_image_3")!)]) circleSlider.value = lastValue } @IBAction func thumbNoImageBtnTapped(_: Any) { let lastValue = circleSlider.value circleSlider.changeOptions([.thumbImage(nil)]) circleSlider.value = lastValue } @IBAction func thumbPositionChanged(_ sender: Any) { let lastValue = circleSlider.value circleSlider.changeOptions([.thumbPosition(Float((sender as! UISlider).value))]) circleSlider.value = lastValue } } extension ViewController: CircleSliderDelegate { func didStartChangeValue() { delegateLabel.text = "didStartChangeValue" } func didReachedMaxValue() { delegateLabel.text = "didReachedMaxValue" } }
mit
70f18511431d5ee914f2726d9d7ab71b
38.393204
143
0.645718
4.608177
false
false
false
false
leancloud/objc-sdk
main.swift
1
23993
#!/usr/bin/swift import Foundation struct TaskError: Error, CustomStringConvertible { var description: String { return self._description } let _description: String init(description: String = "", _ file: String = #file, _ function: String = #function, _ line: Int = #line) { self._description = """ ------ Error ------ file: \(file) function: \(function) line: \(line) description: \(description) ------ End -------- """ } } class Task { let task: Process = Process() init(launchPath: String, arguments: [String] = []) { self.task.launchPath = launchPath if !arguments.isEmpty { self.task.arguments = arguments } self.task.standardOutput = Pipe() self.task.standardError = Pipe() } func excute( printOutput: Bool = true, _ completion: ((Process) -> Void)? = nil) -> Bool { var success: Bool = false let group = DispatchGroup() group.enter() do { self.task.terminationHandler = { success = ($0.terminationStatus == 0) if let error = String( data: ($0.standardError as! Pipe).fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) { print(error) } if printOutput, let output = String( data: ($0.standardOutput as! Pipe).fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) { print(output) } completion?($0) group.leave() } print("Run Task: \(self.task.arguments?[0] ?? "") \(self.task.arguments?[1] ?? "") ...") try self.task.run() self.task.waitUntilExit() } catch { print(error) group.leave() } group.wait() return success } } class OpenTask: Task { convenience init(arguments: [String] = []) { self.init( launchPath: "/usr/bin/env", arguments: ["open"] + arguments) } static func url(_ urlString: String) throws { guard let _ = URL(string: urlString), OpenTask(arguments: [urlString]).excute() else { throw TaskError() } } } class XcodebuildTask: Task { static let projectPath = "./AVOS/AVOS.xcodeproj" convenience init(arguments: [String] = []) { self.init( launchPath: "/usr/bin/xcrun", arguments: ["xcodebuild"] + arguments) } static func version() throws { guard XcodebuildTask(arguments: ["-version"]).excute() else { throw TaskError() } } struct Xcodeproj: Decodable { let project: Project struct Project: Decodable { let configurations: [String] let name: String let schemes: [String] let targets: [String] } } static func getXcodeproj(name: String) throws -> Xcodeproj { var project: Xcodeproj! var taskError: Error? _ = XcodebuildTask(arguments: ["-list", "-project", name, "-json"]) .excute(printOutput: false, { do { let data = ($0.standardOutput as! Pipe).fileHandleForReading.readDataToEndOfFile() project = try JSONDecoder().decode(Xcodeproj.self, from: data) } catch { taskError = error } }) if let error = taskError { throw error } else { return project } } static func building( project: String, scheme: String, configuration: String, destination: String? = nil) throws { var arguments: [String] = [ "-project", project, "-scheme", scheme, "-configuration", configuration] if let destination = destination { arguments += ["-destination", destination] } arguments += ["clean", "build", "-quiet"] let success = XcodebuildTask(arguments: arguments).excute { let argumentsString = String( data: try! JSONSerialization.data( withJSONObject: ($0.arguments ?? []), options: [.prettyPrinted]), encoding: .utf8) print(""" ------ Build Task ------ Completion Status: \($0.terminationStatus == 0 ? "Complete Success 🎉" : "\($0.terminationStatus)") Launch Path: \($0.launchPath ?? "") Arguments: \(argumentsString ?? "") ------ End ------------- """) } if !success { throw TaskError() } } enum Platform: String { case iOS case macOS case tvOS case watchOS } static func building( project: String = XcodebuildTask.projectPath, platforms: [Platform] = [.iOS, .macOS, .tvOS]) throws { try version() let xcodeproj = try getXcodeproj(name: project) let start = Date() try platforms.forEach { (platform) in try xcodeproj.project.configurations.forEach { (configuration) in try building( project: project, scheme: "LeanCloudObjc", configuration: configuration, destination: platform == .macOS ? "platform=\(platform.rawValue)" : "generic/platform=\(platform.rawValue)") } } print("\nBuilding Time Cost: \(Date().timeIntervalSince(start) / 60.0) minutes.\n") } } class GitTask: Task { convenience init(arguments: [String] = []) { self.init( launchPath: "/usr/bin/env", arguments: ["git"] + arguments) } static func commitAll(with message: String) throws { guard GitTask(arguments: ["commit", "-a", "-m", message]).excute() else { throw TaskError() } } static func lastReleasableMessage() -> String? { var message: String? _ = GitTask( arguments: ["log", "-16", "--pretty=%B|cat"]) .excute(printOutput: false) { let data = ($0.standardOutput as! Pipe).fileHandleForReading.readDataToEndOfFile() message = String(data: data, encoding: .utf8)? .components(separatedBy: .newlines) .map({ s in s.trimmingCharacters(in: .whitespacesAndNewlines) }) .first(where: { (s) -> Bool in s.hasPrefix("release") || s.hasPrefix("feat") || s.hasPrefix("fix") || s.hasPrefix("refactor") || s.hasPrefix("docs") }) } return message } } class HubTask: Task { convenience init(arguments: [String] = []) { self.init( launchPath: "/usr/bin/env", arguments: ["hub"] + arguments) } static func version() throws { guard HubTask(arguments: ["version"]).excute() else { throw TaskError() } } enum ReleaseDrafterLabel: String { case breakingChanges = "feat!" case newFeatures = "feat" case bugFixes = "fix" case maintenanceRefactor = "refactor" case maintenanceDocs = "docs" } static func pullRequest(with message: String) throws { try version() var label: String? if message.hasPrefix(ReleaseDrafterLabel.breakingChanges.rawValue) { label = ReleaseDrafterLabel.breakingChanges.rawValue } else if message.hasPrefix(ReleaseDrafterLabel.newFeatures.rawValue) { label = ReleaseDrafterLabel.newFeatures.rawValue } else if message.hasPrefix(ReleaseDrafterLabel.bugFixes.rawValue) { label = ReleaseDrafterLabel.bugFixes.rawValue } else if message.hasPrefix(ReleaseDrafterLabel.maintenanceRefactor.rawValue) { label = ReleaseDrafterLabel.maintenanceRefactor.rawValue } else if message.hasPrefix(ReleaseDrafterLabel.maintenanceDocs.rawValue) { label = ReleaseDrafterLabel.maintenanceDocs.rawValue } guard HubTask(arguments: [ "pull-request", "--base", "leancloud:master", "--message", message, "--force", "--push", "--browse"] + (label != nil ? ["--labels", label!] : [])) .excute() else { throw TaskError() } } } class PodTask: Task { convenience init(arguments: [String] = []) { self.init( launchPath: "/usr/bin/env", arguments: ["pod"] + arguments) } static func version() throws { guard PodTask(arguments: ["--version"]).excute() else { throw TaskError() } } static func trunkPush( path: String, repoUpdate: Bool, wait: Bool) throws { if repoUpdate { _ = PodTask(arguments: ["repo", "update"]).excute() } if PodTask(arguments: ["trunk", "push", path, "--allow-warnings"]).excute() { if wait { let minutes: UInt32 = 31 print("wait for \(minutes) minutes ...") sleep(60 * minutes) } } else { print("[?] try pod trunk push \(path) again? [yes/no]") if let input = readLine()?.trimmingCharacters(in: .whitespaces).lowercased(), ["y", "ye", "yes"].contains(input) { try PodTask.trunkPush( path: path, repoUpdate: repoUpdate, wait: wait) } else { throw TaskError() } } } static func trunkPush(paths: [String]) throws { try version() for (index, path) in paths.enumerated() { try PodTask.trunkPush( path: path, repoUpdate: (index != 0), wait: (index != (paths.count - 1))) } } } class VersionUpdater { static let userAgentFilePath: String = "./AVOS/Sources/Foundation/UserAgent.h" static let LeanCloudObjcFilePath: String = "./LeanCloudObjc.podspec" static func checkFileExists(path: String) throws { guard FileManager.default.fileExists(atPath: path) else { throw TaskError(description: "\(path) not found.") } } struct Version { let major: Int let minor: Int let revision: Int let tag: (category: String, number: Int)? var versionString: String { var string = "\(major).\(minor).\(revision)" if let tag = tag { string = "\(string)-\(tag.category).\(tag.number)" } return string } init(string: String) throws { var versionString: String = string var tag: (String, Int)? if versionString.contains("-") { let components = versionString.components(separatedBy: "-") guard components.count == 2 else { throw TaskError(description: "invalid semantic version: \(string).") } versionString = components[0] let tagComponents = components[1].components(separatedBy: ".") guard tagComponents.count == 2, let tagNumber = Int(tagComponents[1]) else { throw TaskError(description: "invalid semantic version: \(string).") } tag = (tagComponents[0], tagNumber) } let numbers = versionString.components(separatedBy: ".") guard numbers.count == 3, let major = Int(numbers[0]), let minor = Int(numbers[1]), let revision = Int(numbers[2]) else { throw TaskError(description: "invalid semantic version: \(string).") } self.major = major self.minor = minor self.revision = revision self.tag = tag } } static func currentVersion() throws -> Version { let path = userAgentFilePath try checkFileExists(path: path) return try Version(string: String((try String(contentsOfFile: path)) .trimmingCharacters(in: .whitespacesAndNewlines) .dropFirst(#"#define SDK_VERSION @""#.count) .dropLast())) } static func newVersion(_ newVersion: Version, replace oldVersion: Version) throws { let paths = [userAgentFilePath, LeanCloudObjcFilePath] for path in paths { try checkFileExists(path: path) try (try String(contentsOfFile: path)) .replacingOccurrences(of: oldVersion.versionString, with: newVersion.versionString) .write(toFile: path, atomically: true, encoding: .utf8) } } } class JazzyTask: Task { static let APIDocsRepoObjcDirectory = "../api-docs/api/iOS" static let APIDocsTempDirectory = "./api-docs" convenience init(arguments: [String] = []) { self.init( launchPath: "/usr/bin/env", arguments: ["jazzy"] + arguments) } static func version() throws { guard JazzyTask(arguments: ["--version"]).excute() else { throw TaskError() } } static func checkAPIDocsRepoObjcDirectory() throws { var isDirectory: ObjCBool = false guard FileManager.default.fileExists(atPath: APIDocsRepoObjcDirectory, isDirectory: &isDirectory), isDirectory.boolValue else { throw TaskError() } } static func checkAPIDocsTempDirectory() throws { var isDirectory: ObjCBool = false guard FileManager.default.fileExists(atPath: APIDocsTempDirectory, isDirectory: &isDirectory), isDirectory.boolValue else { throw TaskError() } } static func generateDocumentation(currentVersion: VersionUpdater.Version) throws { _ = JazzyTask(arguments: [ "--objc", "--output", APIDocsTempDirectory, "--author", "LeanCloud", "--author_url", "https://leancloud.cn", "--module", "LeanCloudObjc", "--module-version", currentVersion.versionString, "--github_url", "https://github.com/leancloud/objc-sdk", "--github-file-prefix", "https://github.com/leancloud/objc-sdk/tree/\(currentVersion.versionString)", "--root-url", "https://leancloud.cn/api-docs/iOS/", "--umbrella-header", "./AVOS/LeanCloudObjc/LeanCloudObjc.h", "--framework-root", "./AVOS", "--sdk", "iphonesimulator", ] + (FileManager.default.fileExists(atPath: APIDocsTempDirectory) ? ["--clean"] : []) ).excute() try checkAPIDocsTempDirectory() } static func moveGeneratedDocumentationToRepo() throws { try FileManager.default.removeItem(atPath: APIDocsRepoObjcDirectory) try FileManager.default.moveItem( atPath: APIDocsTempDirectory, toPath: APIDocsRepoObjcDirectory) } static func commitPull() throws { guard GitTask(arguments: [ "-C", APIDocsRepoObjcDirectory, "pull"]) .excute() else { throw TaskError() } } static func commitPush() throws { guard GitTask(arguments: [ "-C", APIDocsRepoObjcDirectory, "add", "-A"]) .excute() else { throw TaskError() } guard GitTask(arguments: [ "-C", APIDocsRepoObjcDirectory, "commit", "-a", "-m", "update objc sdk docs"]) .excute() else { throw TaskError() } guard GitTask(arguments: [ "-C", APIDocsRepoObjcDirectory, "push"]) .excute() else { throw TaskError() } } static func update(currentVersion: VersionUpdater.Version) throws { try version() try checkAPIDocsRepoObjcDirectory() try commitPull() try generateDocumentation(currentVersion: currentVersion) try moveGeneratedDocumentationToRepo() try commitPush() try OpenTask.url("https://jenkins.leancloud.cn/job/cn-api-doc-prod-ucloud/build") } } class ThirdPartyLibraryUpgrader { static let protobufObjcDirectoryPath = "../protobuf/objectivec/" static let lcProtobufObjcDirectoryPath = "./AVOS/Sources/Realtime/IM/Protobuf/" static func checkDirectoryExists(path: String) throws { var isDirectory: ObjCBool = false guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue else { throw TaskError(description: "\(path) not found.") } } static func replacingFiles( srcDirectory: String, dstDirectory: String, originNamespace: String, lcNamespace: String, excludeFiles: [String] = []) throws { let srcDirectoryURL = URL(fileURLWithPath: srcDirectory, isDirectory: true) let dstDirectoryURL = URL(fileURLWithPath: dstDirectory, isDirectory: true) let enumerator = FileManager.default.enumerator( at: srcDirectoryURL, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles, .skipsPackageDescendants, .skipsSubdirectoryDescendants]) while let srcUrl = enumerator?.nextObject() as? URL { let srcFileName = srcUrl.lastPathComponent if !excludeFiles.contains(srcFileName), srcFileName.hasPrefix(originNamespace) { let dstFileName = srcFileName.replacingOccurrences(of: originNamespace, with: lcNamespace, options: [.anchored]) let dstFileURL = dstDirectoryURL.appendingPathComponent(dstFileName) if FileManager.default.fileExists(atPath: dstFileURL.path) { try FileManager.default.removeItem(at: dstFileURL) } else { print("[!] New File: `\(dstFileURL.path)`\n") } try FileManager.default.copyItem(at: srcUrl, to: dstFileURL) try (try String(contentsOfFile: dstFileURL.path)) .replacingOccurrences(of: originNamespace, with: lcNamespace) .write(toFile: dstFileURL.path, atomically: true, encoding: .utf8) } } } static func updateProtobuf() throws { try checkDirectoryExists(path: protobufObjcDirectoryPath) try checkDirectoryExists(path: lcProtobufObjcDirectoryPath) try replacingFiles( srcDirectory: protobufObjcDirectoryPath, dstDirectory: lcProtobufObjcDirectoryPath, originNamespace: "GPB", lcNamespace: "LCGPB", // reason: https://github.com/protocolbuffers/protobuf/blob/v3.15.6/Protobuf.podspec#L31 excludeFiles: ["GPBProtocolBuffers.m"]) } } class CLI { static func help() { print(""" Actions Docs: b, build Building all schemes vu, version-update Updating SDK version pr, pull-request New pull request from current head to base master pt, pod-trunk Publish all podspecs adu, api-docs-update Update API Docs tplu, third-party-library-upgrade Upgrade third party library h, help Show help info """) } static func tpluHelp() { print(""" Action `third-party-library-upgrade` Docs: PARAMETERS protobuf Upgrade `protobuf` library """) } static func build() throws { try XcodebuildTask.building() } static func versionUpdate() throws { let currentVersion = try VersionUpdater.currentVersion() print(""" Current Version is \(currentVersion.versionString) [?] do you want to update it ? [<new-semantic-version>/no] """) if let input = readLine()?.trimmingCharacters(in: .whitespaces).lowercased() { if !["n", "no", "not"].contains(input.lowercased()) { let newVersion = try VersionUpdater.Version(string: input) guard newVersion.versionString != currentVersion.versionString else { throw TaskError(description: "[!] Version no change") } try VersionUpdater.newVersion(newVersion, replace: currentVersion) try GitTask.commitAll(with: "release: \(newVersion.versionString)") } } } static func pullRequest() throws { if let message = GitTask.lastReleasableMessage() { try HubTask.pullRequest(with: message) } else { throw TaskError(description: "Not get a releasable Message.") } } static func podTrunk() throws { try PodTask.trunkPush(paths: ["LeanCloudObjc.podspec"]) } static func apiDocsUpdate() throws { try JazzyTask.update( currentVersion: try VersionUpdater.currentVersion()) } static func thirdPartyLibraryUpgrade(with library: String) throws { switch library { case "protobuf": try ThirdPartyLibraryUpgrader.updateProtobuf() default: print("[!] Unknown Library: `\(library)`\n") tpluHelp() } } static func read() -> [String] { var args = CommandLine.arguments args.removeFirst() return args } static func process(action: String) throws { switch action { case "b", "build": try build() case "vu", "version-update": try versionUpdate() case "pr", "pull-request": try pullRequest() case "pt", "pod-trunk": try podTrunk() case "adu", "api-docs-update": try apiDocsUpdate() case "tplu", "third-party-library-upgrade": print("[!] This Action need one parameter\n") tpluHelp() case "h", "help": help() default: print("[!] Unknown Action: `\(action)`\n") help() } } static func process(action: String, parameter: String) throws { switch action { case "tplu", "third-party-library-upgrade": switch parameter { case "h", "help": tpluHelp() default: try thirdPartyLibraryUpgrade(with: parameter) } default: print("[!] Unknown Action: `\(action)`\n") help() } } static func run() throws { let args = read() switch args.count { case 1: try process(action: args[0]) case 2: try process(action: args[0], parameter: args[1]) default: print("[!] Unknown Command: `\(args.joined(separator: " "))`\n") help() } } } func main() { do { try CLI.run() } catch { print(error) } } main()
apache-2.0
8b9196761fb378e96d97fed604542eb9
32.69382
128
0.53514
4.904927
false
false
false
false
cfraz89/RxSwift
RxExample/RxExample/Examples/GitHubSearchRepositories/UINavigationController+Extensions.swift
2
996
// // UINavigationController+Extensions.swift // RxExample // // Created by Krunoslav Zaher on 12/13/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif struct Colors { static let OfflineColor = UIColor(red: 1.0, green: 0.6, blue: 0.6, alpha: 1.0) static let OnlineColor = nil as UIColor? } extension Reactive where Base: UINavigationController { var serviceState: UIBindingObserver<Base, ServiceState?> { return UIBindingObserver(UIElement: base) { navigationController, maybeServiceState in // if nil is being bound, then don't change color, it's not perfect, but :) if let serviceState = maybeServiceState { let isOffline = serviceState == .offline navigationController.navigationBar.backgroundColor = isOffline ? Colors.OfflineColor : Colors.OnlineColor } } } }
mit
507b0669a7182640c54994abcf72c7dd
29.151515
94
0.655276
4.502262
false
false
false
false
jonasman/TeslaSwift
Sources/TeslaSwift/Model/NearbyChargingSites.swift
1
3204
// // NearbyChargingSites.swift // TeslaSwift // // Created by Jordan Owens on 7/4/19. // Copyright © 2019 Jordan Owens. All rights reserved. // import Foundation import CoreLocation public protocol Charger { var name: String? { get } var type: String? { get } var distance: Distance? { get } var location: NearbyChargingSites.ChargerLocation? { get } } open class NearbyChargingSites: Codable { open var congestionSyncTimeUTCSecs: Int? open var destinationChargers: [DestinationCharger]? open var superchargers: [Supercharger]? open var timestamp: Double? enum CodingKeys: String, CodingKey { case congestionSyncTimeUTCSecs = "congestion_sync_time_utc_secs" case destinationChargers = "destination_charging" case superchargers = "superchargers" case timestamp = "timestamp" } required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) congestionSyncTimeUTCSecs = try? container.decode(Int.self, forKey: .congestionSyncTimeUTCSecs) destinationChargers = try? container.decode([DestinationCharger].self, forKey: .destinationChargers) superchargers = try? container.decode([Supercharger].self, forKey: .superchargers) timestamp = try? container.decode(Double.self, forKey: .timestamp) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(congestionSyncTimeUTCSecs, forKey: .congestionSyncTimeUTCSecs) try container.encodeIfPresent(destinationChargers, forKey: .destinationChargers) try container.encodeIfPresent(superchargers, forKey: .superchargers) try container.encodeIfPresent(timestamp, forKey: .timestamp) } public struct DestinationCharger: Codable, Charger { public var distance: Distance? public var location: ChargerLocation? public var name: String? public var type: String? enum CodingKeys: String, CodingKey { case distance = "distance_miles" case name = "name" case location = "location" case type = "type" } } public struct Supercharger: Codable, Charger { public var availableStalls: Int? public var distance: Distance? public var location: ChargerLocation? public var name: String? public var siteClosed: Bool? public var totalStalls: Int? public var type: String? enum CodingKeys: String, CodingKey { case availableStalls = "available_stalls" case distance = "distance_miles" case location = "location" case name = "name" case siteClosed = "site_closed" case totalStalls = "total_stalls" case type = "type" } } public struct ChargerLocation: Codable { public var latitude: CLLocationDegrees? public var longitude: CLLocationDegrees? enum CodingKeys: String, CodingKey { case latitude = "lat" case longitude = "long" } } }
mit
9859c85f6e821e960ee1aa8cb9f80f54
33.815217
108
0.661879
4.424033
false
false
false
false
PomTTcat/SourceCodeGuideRead_JEFF
RxSwiftGuideRead/RxSwift-master/RxExample/RxExample/Examples/macOS simple example/IntroductionExampleViewController.swift
5
3020
// // IntroductionExampleViewController.swift // RxExample // // Created by Krunoslav Zaher on 5/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift import RxCocoa import Cocoa import AppKit class IntroductionExampleViewController : ViewController { @IBOutlet var a: NSTextField! @IBOutlet var b: NSTextField! @IBOutlet var c: NSTextField! @IBOutlet var leftTextView: NSTextView! @IBOutlet var rightTextView: NSTextView! @IBOutlet var speechEnabled: NSButton! @IBOutlet var slider: NSSlider! @IBOutlet var sliderValue: NSTextField! @IBOutlet var disposeButton: NSButton! override func viewDidLoad() { super.viewDidLoad() // c = a + b let sum = Observable.combineLatest(a.rx.text.orEmpty, b.rx.text.orEmpty) { (a: String, b: String) -> (a: Int, b: Int) in return (Int(a) ?? 0, Int(b) ?? 0) } // bind result to UI sum .map { pair in return "\(pair.a + pair.b)" } .bind(to: c.rx.text) .disposed(by: disposeBag) // Also, tell it out loud let speech = NSSpeechSynthesizer() Observable.combineLatest(sum, speechEnabled.rx.state) { (operands: $0, state: $1) } .flatMapLatest { pair -> Observable<String> in let (a, b) = pair.operands if pair.state == NSControl.StateValue.off { return .empty() } return .just("\(a) + \(b) = \(a + b)") } .subscribe(onNext: { result in if speech.isSpeaking { speech.stopSpeaking() } speech.startSpeaking(result) }) .disposed(by: disposeBag) slider.rx.value .subscribe(onNext: { value in self.sliderValue.stringValue = "\(Int(value))" }) .disposed(by: disposeBag) sliderValue.rx.text.orEmpty .subscribe(onNext: { value in let doubleValue = value.toDouble() ?? 0.0 self.slider.doubleValue = doubleValue self.sliderValue.stringValue = "\(Int(doubleValue))" }) .disposed(by: disposeBag) // Synchronize text in two different textviews. let textViewValue = BehaviorRelay(value: "System Truth") _ = leftTextView.rx.string <-> textViewValue _ = rightTextView.rx.string <-> textViewValue textViewValue.asObservable() .subscribe(onNext: { value in print("Text: \(value)") }) .disposed(by: disposeBag) disposeButton.rx.tap .subscribe(onNext: { [weak self] _ in print("Unbind everything") self?.disposeBag = DisposeBag() }) .disposed(by: disposeBag) } }
mit
00d2e597900274c6f495a778d2d596c2
30.123711
128
0.532958
4.709828
false
false
false
false
sora0077/RelayoutKit
RelayoutKit/TableView/TableController.swift
1
7240
// // TableController.swift // RelayoutKit // // Created by 林達也 on 2015/09/09. // Copyright © 2015年 jp.sora0077. All rights reserved. // import Foundation final class TableController: NSObject { var sections: [TableSection] = [] weak var tableView: UITableView! { didSet { if let tableView = oldValue { detachTableView(tableView) } if let tableView = tableView { attachTableView(tableView) } } } weak var altDelegate: UITableViewDelegate? weak var altDataSource: UITableViewDataSource? var registeredCells: Set<String> = [] private var transactionQueue: [() -> [TableTransaction]] = [] weak var nextResponder: UIResponder? init(responder: UIResponder?, sections: [TableSection]) { self.nextResponder = responder self.sections = sections super.init() } } extension TableController { func flush() { while tableUpdate() {} } func transaction(block: () -> [TableTransaction]) { transactionQueue.append(block) tableUpdate() } } private extension TableController { func tableUpdate() -> Bool { if transactionQueue.count == 0 { return false } let transactions = transactionQueue.removeFirst()() func insertRow(row: TableRowProtocol, atIndex index: Int, section: Int, animation: UITableViewRowAnimation) { sections[section].insert(row, atIndex: index) tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: section)], withRowAnimation: animation) } func extendRows(rows: [TableRowProtocol], section: Int, animation: UITableViewRowAnimation) { let index = sections[section].rows.count let indexPaths = (index..<(rows.count + index)).map { NSIndexPath(forRow: $0, inSection: section) } sections[section].extend(rows) tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: animation) } func reloadRow(row: TableRowProtocol, atIndex index: Int, section: Int, animation: UITableViewRowAnimation) { sections[section][index] = row tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: section)], withRowAnimation: animation) } func deleteRow(index: Int, section: Int, animation: UITableViewRowAnimation) { sections[section].removeAtIndex(index) tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: section)], withRowAnimation: animation) } func deleteRows(section section: Int?, animation: UITableViewRowAnimation) { if let section = section { sections.removeAtIndex(section) tableView.deleteSections(NSIndexSet(index: section), withRowAnimation: animation) } else { let num = sections.count sections.removeAll() let indexSet = NSMutableIndexSet() for i in 0..<num { indexSet.addIndex(i) } tableView.deleteSections(indexSet, withRowAnimation: animation == .Automatic ? .Top : animation) sections.append(TableSection()) tableView.insertSections(NSIndexSet(index: 0), withRowAnimation: .None) } } self.tableView.beginUpdates() for t in transactions { switch t { case let .Insert(row, atIndex: index, section: section, with: animation): insertRow(row, atIndex: index, section: section, animation: animation) case let .InsertLast(row, section: section, with: animation): let index = self.sections[section].rows.count insertRow(row, atIndex: index, section: section, animation: animation) case let .Replacement(row, atIndex: index, section: section, with: animation): reloadRow(row, atIndex: index, section: section, animation: animation) case let .ReplacementLast(row, section: section, with: animation): let index = self.sections[section].rows.count reloadRow(row, atIndex: index, section: section, animation: animation) case let .RemoveIndex(index, section: section, with: animation): let row = self.sections[section].internalRows[safe: index] deleteRow(index, section: section, animation: animation) row?.setOutdated(true) case let .Remove(row, with: animation): if let indexPath = row.indexPath { deleteRow(indexPath.row, section: indexPath.section, animation: animation) let row = row as! TableRowProtocolInternal row.setOutdated(true) } case let .RemoveLast(section: section, with: animation): let row = self.sections[section].rows.last if let indexPath = row?.indexPath { deleteRow(indexPath.row, section: indexPath.section, animation: animation) let row = row as! TableRowProtocolInternal row.setOutdated(true) } case let .RemoveAll(section: section, with: animation): deleteRows(section: section, animation: animation) case let .Setting(rows, section: section, removal: removal, insertion: insertion): for idx in 0..<self.sections[section].rows.count { deleteRow(idx, section: section, animation: removal) } for (index, row) in rows.enumerate() { insertRow(row, atIndex: index, section: section, animation: insertion) } } } self.tableView.endUpdates() dispatch_async(dispatch_get_main_queue()) { } return true } } extension TableController: UITableViewDelegate, UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sections.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].internalRows.count } } private extension TableController { func attachTableView(tableView: UITableView) { altDelegate = tableView.delegate altDataSource = tableView.dataSource tableView.delegate = self tableView.dataSource = self } func detachTableView(tableView: UITableView) { registeredCells.removeAll() // self.registeredHeaderFooterViews.removeAll(keepCapacity: true) tableView.delegate = altDelegate tableView.dataSource = altDataSource self.tableView = nil } }
mit
6f1509ece3bb81439c918333c115e0f3
35.155
123
0.585535
5.449133
false
false
false
false
tjw/swift
stdlib/public/core/Sequence.swift
2
53908
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A type that supplies the values of a sequence one at a time. /// /// The `IteratorProtocol` protocol is tightly linked with the `Sequence` /// protocol. Sequences provide access to their elements by creating an /// iterator, which keeps track of its iteration process and returns one /// element at a time as it advances through the sequence. /// /// Whenever you use a `for`-`in` loop with an array, set, or any other /// collection or sequence, you're using that type's iterator. Swift uses a /// sequence's or collection's iterator internally to enable the `for`-`in` /// loop language construct. /// /// Using a sequence's iterator directly gives you access to the same elements /// in the same order as iterating over that sequence using a `for`-`in` loop. /// For example, you might typically use a `for`-`in` loop to print each of /// the elements in an array. /// /// let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"] /// for animal in animals { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// Behind the scenes, Swift uses the `animals` array's iterator to loop over /// the contents of the array. /// /// var animalIterator = animals.makeIterator() /// while let animal = animalIterator.next() { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// The call to `animals.makeIterator()` returns an instance of the array's /// iterator. Next, the `while` loop calls the iterator's `next()` method /// repeatedly, binding each element that is returned to `animal` and exiting /// when the `next()` method returns `nil`. /// /// Using Iterators Directly /// ======================== /// /// You rarely need to use iterators directly, because a `for`-`in` loop is the /// more idiomatic approach to traversing a sequence in Swift. Some /// algorithms, however, may call for direct iterator use. /// /// One example is the `reduce1(_:)` method. Similar to the `reduce(_:_:)` /// method defined in the standard library, which takes an initial value and a /// combining closure, `reduce1(_:)` uses the first element of the sequence as /// the initial value. /// /// Here's an implementation of the `reduce1(_:)` method. The sequence's /// iterator is used directly to retrieve the initial value before looping /// over the rest of the sequence. /// /// extension Sequence { /// func reduce1( /// _ nextPartialResult: (Element, Element) -> Element /// ) -> Element? /// { /// var i = makeIterator() /// guard var accumulated = i.next() else { /// return nil /// } /// /// while let element = i.next() { /// accumulated = nextPartialResult(accumulated, element) /// } /// return accumulated /// } /// } /// /// The `reduce1(_:)` method makes certain kinds of sequence operations /// simpler. Here's how to find the longest string in a sequence, using the /// `animals` array introduced earlier as an example: /// /// let longestAnimal = animals.reduce1 { current, element in /// if current.count > element.count { /// return current /// } else { /// return element /// } /// } /// print(longestAnimal) /// // Prints "Butterfly" /// /// Using Multiple Iterators /// ======================== /// /// Whenever you use multiple iterators (or `for`-`in` loops) over a single /// sequence, be sure you know that the specific sequence supports repeated /// iteration, either because you know its concrete type or because the /// sequence is also constrained to the `Collection` protocol. /// /// Obtain each separate iterator from separate calls to the sequence's /// `makeIterator()` method rather than by copying. Copying an iterator is /// safe, but advancing one copy of an iterator by calling its `next()` method /// may invalidate other copies of that iterator. `for`-`in` loops are safe in /// this regard. /// /// Adding IteratorProtocol Conformance to Your Type /// ================================================ /// /// Implementing an iterator that conforms to `IteratorProtocol` is simple. /// Declare a `next()` method that advances one step in the related sequence /// and returns the current element. When the sequence has been exhausted, the /// `next()` method returns `nil`. /// /// For example, consider a custom `Countdown` sequence. You can initialize the /// `Countdown` sequence with a starting integer and then iterate over the /// count down to zero. The `Countdown` structure's definition is short: It /// contains only the starting count and the `makeIterator()` method required /// by the `Sequence` protocol. /// /// struct Countdown: Sequence { /// let start: Int /// /// func makeIterator() -> CountdownIterator { /// return CountdownIterator(self) /// } /// } /// /// The `makeIterator()` method returns another custom type, an iterator named /// `CountdownIterator`. The `CountdownIterator` type keeps track of both the /// `Countdown` sequence that it's iterating and the number of times it has /// returned a value. /// /// struct CountdownIterator: IteratorProtocol { /// let countdown: Countdown /// var times = 0 /// /// init(_ countdown: Countdown) { /// self.countdown = countdown /// } /// /// mutating func next() -> Int? { /// let nextNumber = countdown.start - times /// guard nextNumber > 0 /// else { return nil } /// /// times += 1 /// return nextNumber /// } /// } /// /// Each time the `next()` method is called on a `CountdownIterator` instance, /// it calculates the new next value, checks to see whether it has reached /// zero, and then returns either the number, or `nil` if the iterator is /// finished returning elements of the sequence. /// /// Creating and iterating over a `Countdown` sequence uses a /// `CountdownIterator` to handle the iteration. /// /// let threeTwoOne = Countdown(start: 3) /// for count in threeTwoOne { /// print("\(count)...") /// } /// // Prints "3..." /// // Prints "2..." /// // Prints "1..." public protocol IteratorProtocol { /// The type of element traversed by the iterator. associatedtype Element /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Repeatedly calling this method returns, in order, all the elements of the /// underlying sequence. As soon as the sequence has run out of elements, all /// subsequent calls return `nil`. /// /// You must not call this method if any other copy of this iterator has been /// advanced with a call to its `next()` method. /// /// The following example shows how an iterator can be used explicitly to /// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and /// then call the iterator's `next()` method until it returns `nil`. /// /// let numbers = [2, 3, 5, 7] /// var numbersIterator = numbers.makeIterator() /// /// while let num = numbersIterator.next() { /// print(num) /// } /// // Prints "2" /// // Prints "3" /// // Prints "5" /// // Prints "7" /// /// - Returns: The next element in the underlying sequence, if a next element /// exists; otherwise, `nil`. mutating func next() -> Element? } /// A type that provides sequential, iterated access to its elements. /// /// A sequence is a list of values that you can step through one at a time. The /// most common way to iterate over the elements of a sequence is to use a /// `for`-`in` loop: /// /// let oneTwoThree = 1...3 /// for number in oneTwoThree { /// print(number) /// } /// // Prints "1" /// // Prints "2" /// // Prints "3" /// /// While seemingly simple, this capability gives you access to a large number /// of operations that you can perform on any sequence. As an example, to /// check whether a sequence includes a particular value, you can test each /// value sequentially until you've found a match or reached the end of the /// sequence. This example checks to see whether a particular insect is in an /// array. /// /// let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// var hasMosquito = false /// for bug in bugs { /// if bug == "Mosquito" { /// hasMosquito = true /// break /// } /// } /// print("'bugs' has a mosquito: \(hasMosquito)") /// // Prints "'bugs' has a mosquito: false" /// /// The `Sequence` protocol provides default implementations for many common /// operations that depend on sequential access to a sequence's values. For /// clearer, more concise code, the example above could use the array's /// `contains(_:)` method, which every sequence inherits from `Sequence`, /// instead of iterating manually: /// /// if bugs.contains("Mosquito") { /// print("Break out the bug spray.") /// } else { /// print("Whew, no mosquitos!") /// } /// // Prints "Whew, no mosquitos!" /// /// Repeated Access /// =============== /// /// The `Sequence` protocol makes no requirement on conforming types regarding /// whether they will be destructively consumed by iteration. As a /// consequence, don't assume that multiple `for`-`in` loops on a sequence /// will either resume iteration or restart from the beginning: /// /// for element in sequence { /// if ... some condition { break } /// } /// /// for element in sequence { /// // No defined behavior /// } /// /// In this case, you cannot assume either that a sequence will be consumable /// and will resume iteration, or that a sequence is a collection and will /// restart iteration from the first element. A conforming sequence that is /// not a collection is allowed to produce an arbitrary sequence of elements /// in the second `for`-`in` loop. /// /// To establish that a type you've created supports nondestructive iteration, /// add conformance to the `Collection` protocol. /// /// Conforming to the Sequence Protocol /// =================================== /// /// Making your own custom types conform to `Sequence` enables many useful /// operations, like `for`-`in` looping and the `contains` method, without /// much effort. To add `Sequence` conformance to your own custom type, add a /// `makeIterator()` method that returns an iterator. /// /// Alternatively, if your type can act as its own iterator, implementing the /// requirements of the `IteratorProtocol` protocol and declaring conformance /// to both `Sequence` and `IteratorProtocol` are sufficient. /// /// Here's a definition of a `Countdown` sequence that serves as its own /// iterator. The `makeIterator()` method is provided as a default /// implementation. /// /// struct Countdown: Sequence, IteratorProtocol { /// var count: Int /// /// mutating func next() -> Int? { /// if count == 0 { /// return nil /// } else { /// defer { count -= 1 } /// return count /// } /// } /// } /// /// let threeToGo = Countdown(count: 3) /// for i in threeToGo { /// print(i) /// } /// // Prints "3" /// // Prints "2" /// // Prints "1" /// /// Expected Performance /// ==================== /// /// A sequence should provide its iterator in O(1). The `Sequence` protocol /// makes no other requirements about element access, so routines that /// traverse a sequence should be considered O(*n*) unless documented /// otherwise. public protocol Sequence { /// A type representing the sequence's elements. associatedtype Element /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. associatedtype Iterator : IteratorProtocol where Iterator.Element == Element /// A type that represents a subsequence of some of the sequence's elements. associatedtype SubSequence : Sequence = AnySequence<Element> where Element == SubSequence.Element, SubSequence.SubSequence == SubSequence /// Returns an iterator over the elements of this sequence. func makeIterator() -> Iterator /// A value less than or equal to the number of elements in the sequence, /// calculated nondestructively. /// /// The default implementation returns 0. If you provide your own /// implementation, make sure to compute the value nondestructively. /// /// - Complexity: O(1), except if the sequence also conforms to `Collection`. /// In this case, see the documentation of `Collection.underestimatedCount`. var underestimatedCount: Int { get } /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercased() } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. func map<T>( _ transform: (Element) throws -> T ) rethrows -> [T] /// Returns an array containing, in order, the elements of the sequence /// that satisfy the given predicate. /// /// In this example, `filter(_:)` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `isIncluded` allowed. func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Element] /// Calls the given closure on each element in the sequence in the same order /// as a `for`-`in` loop. /// /// The two loops in the following example produce the same output: /// /// let numberWords = ["one", "two", "three"] /// for word in numberWords { /// print(word) /// } /// // Prints "one" /// // Prints "two" /// // Prints "three" /// /// numberWords.forEach { word in /// print(word) /// } /// // Same as above /// /// Using the `forEach` method is distinct from a `for`-`in` loop in two /// important ways: /// /// 1. You cannot use a `break` or `continue` statement to exit the current /// call of the `body` closure or skip subsequent calls. /// 2. Using the `return` statement in the `body` closure will exit only from /// the current call to `body`, not from any outer scope, and won't skip /// subsequent calls. /// /// - Parameter body: A closure that takes an element of the sequence as a /// parameter. func forEach(_ body: (Element) throws -> Void) rethrows // Note: The complexity of Sequence.dropFirst(_:) requirement // is documented as O(n) because Collection.dropFirst(_:) is // implemented in O(n), even though the default // implementation for Sequence.dropFirst(_:) is O(1). /// Returns a subsequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the sequence, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of /// the sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence starting after the specified number of /// elements. /// /// - Complexity: O(*n*), where *n* is the number of elements to drop from /// the beginning of the sequence. func dropFirst(_ n: Int) -> SubSequence /// Returns a subsequence containing all but the specified number of final /// elements. /// /// The sequence must be finite. If the number of elements to drop exceeds /// the number of elements in the sequence, the result is an empty /// subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence leaving off the specified number of elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. func dropLast(_ n: Int) -> SubSequence /// Returns a subsequence by skipping elements while `predicate` returns /// `true` and returning the remaining elements. /// /// - Parameter predicate: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element is a match. /// /// - Complexity: O(*n*), where *n* is the length of the collection. func drop( while predicate: (Element) throws -> Bool ) rethrows -> SubSequence /// Returns a subsequence, up to the specified maximum length, containing /// the initial elements of the sequence. /// /// If the maximum length exceeds the number of elements in the sequence, /// the result contains all the elements in the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. /// `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence starting at the beginning of this sequence /// with at most `maxLength` elements. func prefix(_ maxLength: Int) -> SubSequence /// Returns a subsequence containing the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `prefix(while:)` method to find the /// positive numbers at the beginning of the `numbers` array. Every element /// of `numbers` up to, but not including, the first negative value is /// included in the result. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let positivePrefix = numbers.prefix(while: { $0 > 0 }) /// // positivePrefix == [3, 7, 4] /// /// If `predicate` matches every element in the sequence, the resulting /// sequence contains every element of the sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A subsequence of the initial, consecutive elements that /// satisfy `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. func prefix( while predicate: (Element) throws -> Bool ) rethrows -> SubSequence /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the sequence. /// /// The sequence must be finite. If the maximum length exceeds the number /// of elements in the sequence, the result contains all the elements in /// the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence terminating at the end of this sequence with /// at most `maxLength` elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. func suffix(_ maxLength: Int) -> SubSequence /// Returns the longest possible subsequences of the sequence, in order, that /// don't contain elements satisfying the given predicate. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print( /// line.split(maxSplits: 1, whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.split(omittingEmptySubsequences: false, /// whereSeparator: { $0 == " " }) /// ).map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the sequence satisfying the `isSeparator` predicate. /// If `true`, only nonempty subsequences are returned. The default /// value is `true`. /// - isSeparator: A closure that returns `true` if its argument should be /// used to split the sequence; otherwise, `false`. /// - Returns: An array of subsequences, split from this sequence's elements. func split( maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator isSeparator: (Element) throws -> Bool ) rethrows -> [SubSequence] func _customContainsEquatableElement( _ element: Element ) -> Bool? /// If `self` is multi-pass (i.e., a `Collection`), invoke `preprocess` and /// return its result. Otherwise, return `nil`. func _preprocessingPass<R>( _ preprocess: () throws -> R ) rethrows -> R? /// Create a native array buffer containing the elements of `self`, /// in the same order. func _copyToContiguousArray() -> ContiguousArray<Element> /// Copy `self` into an unsafe buffer, returning a partially-consumed /// iterator with any elements that didn't fit remaining. func _copyContents( initializing ptr: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) } // Provides a default associated type witness for Iterator when the // Self type is both a Sequence and an Iterator. extension Sequence where Self: IteratorProtocol { // @_implements(Sequence, Iterator) public typealias _Default_Iterator = Self } /// A default makeIterator() function for `IteratorProtocol` instances that /// are declared to conform to `Sequence` extension Sequence where Self.Iterator == Self { /// Returns an iterator over the elements of this sequence. @inlinable public func makeIterator() -> Self { return self } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. @usableFromInline @_fixed_layout internal struct _DropFirstSequence<Base : IteratorProtocol> : Sequence, IteratorProtocol { @usableFromInline internal var _iterator: Base @usableFromInline internal let _limit: Int @usableFromInline internal var _dropped: Int @inlinable internal init(_iterator: Base, limit: Int, dropped: Int = 0) { self._iterator = _iterator self._limit = limit self._dropped = dropped } @inlinable internal func makeIterator() -> _DropFirstSequence<Base> { return self } @inlinable internal mutating func next() -> Base.Element? { while _dropped < _limit { if _iterator.next() == nil { _dropped = _limit return nil } _dropped += 1 } return _iterator.next() } @inlinable internal func dropFirst(_ n: Int) -> AnySequence<Base.Element> { // If this is already a _DropFirstSequence, we need to fold in // the current drop count and drop limit so no data is lost. // // i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to // [1,2,3,4].dropFirst(2). return AnySequence( _DropFirstSequence( _iterator: _iterator, limit: _limit + n, dropped: _dropped)) } } /// A sequence that only consumes up to `n` elements from an underlying /// `Base` iterator. /// /// The underlying iterator's sequence may be infinite. @_fixed_layout @usableFromInline internal struct _PrefixSequence<Base : IteratorProtocol> : Sequence, IteratorProtocol { @usableFromInline internal let _maxLength: Int @usableFromInline internal var _iterator: Base @usableFromInline internal var _taken: Int @inlinable internal init(_iterator: Base, maxLength: Int, taken: Int = 0) { self._iterator = _iterator self._maxLength = maxLength self._taken = taken } @inlinable internal func makeIterator() -> _PrefixSequence<Base> { return self } @inlinable internal mutating func next() -> Base.Element? { if _taken >= _maxLength { return nil } _taken += 1 if let next = _iterator.next() { return next } _taken = _maxLength return nil } @inlinable internal func prefix(_ maxLength: Int) -> AnySequence<Base.Element> { return AnySequence( _PrefixSequence( _iterator: _iterator, maxLength: Swift.min(maxLength, self._maxLength), taken: _taken)) } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. @_fixed_layout @usableFromInline internal struct _DropWhileSequence<Base : IteratorProtocol> : Sequence, IteratorProtocol { typealias Element = Base.Element @usableFromInline internal var _iterator: Base @usableFromInline internal var _nextElement: Base.Element? @inlinable internal init( iterator: Base, nextElement: Base.Element?, predicate: (Base.Element) throws -> Bool ) rethrows { self._iterator = iterator self._nextElement = nextElement ?? _iterator.next() while try _nextElement.flatMap(predicate) == true { _nextElement = _iterator.next() } } @inlinable internal func makeIterator() -> _DropWhileSequence<Base> { return self } @inlinable internal mutating func next() -> Element? { guard _nextElement != nil else { return _iterator.next() } let next = _nextElement _nextElement = nil return next } @inlinable internal func drop( while predicate: (Element) throws -> Bool ) rethrows -> AnySequence<Element> { // If this is already a _DropWhileSequence, avoid multiple // layers of wrapping and keep the same iterator. return try AnySequence( _DropWhileSequence( iterator: _iterator, nextElement: _nextElement, predicate: predicate)) } } //===----------------------------------------------------------------------===// // Default implementations for Sequence //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercased() } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. @inlinable public func map<T>( _ transform: (Element) throws -> T ) rethrows -> [T] { let initialCapacity = underestimatedCount var result = ContiguousArray<T>() result.reserveCapacity(initialCapacity) var iterator = self.makeIterator() // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { result.append(try transform(iterator.next()!)) } // Add remaining elements, if any. while let element = iterator.next() { result.append(try transform(element)) } return Array(result) } /// Returns an array containing, in order, the elements of the sequence /// that satisfy the given predicate. /// /// In this example, `filter(_:)` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `isIncluded` allowed. @inlinable public func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Element] { return try _filter(isIncluded) } @_transparent public func _filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Element] { var result = ContiguousArray<Element>() var iterator = self.makeIterator() while let element = iterator.next() { if try isIncluded(element) { result.append(element) } } return Array(result) } /// A value less than or equal to the number of elements in the sequence, /// calculated nondestructively. /// /// The default implementation returns 0. If you provide your own /// implementation, make sure to compute the value nondestructively. /// /// - Complexity: O(1), except if the sequence also conforms to `Collection`. /// In this case, see the documentation of `Collection.underestimatedCount`. @inlinable public var underestimatedCount: Int { return 0 } @inlinable public func _preprocessingPass<R>( _ preprocess: () throws -> R ) rethrows -> R? { return nil } @inlinable public func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? { return nil } /// Calls the given closure on each element in the sequence in the same order /// as a `for`-`in` loop. /// /// The two loops in the following example produce the same output: /// /// let numberWords = ["one", "two", "three"] /// for word in numberWords { /// print(word) /// } /// // Prints "one" /// // Prints "two" /// // Prints "three" /// /// numberWords.forEach { word in /// print(word) /// } /// // Same as above /// /// Using the `forEach` method is distinct from a `for`-`in` loop in two /// important ways: /// /// 1. You cannot use a `break` or `continue` statement to exit the current /// call of the `body` closure or skip subsequent calls. /// 2. Using the `return` statement in the `body` closure will exit only from /// the current call to `body`, not from any outer scope, and won't skip /// subsequent calls. /// /// - Parameter body: A closure that takes an element of the sequence as a /// parameter. @inlinable public func forEach( _ body: (Element) throws -> Void ) rethrows { for element in self { try body(element) } } } @usableFromInline @_frozen internal enum _StopIteration : Error { case stop } extension Sequence { /// Returns the first element of the sequence that satisfies the given /// predicate. /// /// The following example uses the `first(where:)` method to find the first /// negative number in an array of integers: /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// if let firstNegative = numbers.first(where: { $0 < 0 }) { /// print("The first negative number is \(firstNegative).") /// } /// // Prints "The first negative number is -2." /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element is a match. /// - Returns: The first element of the sequence that satisfies `predicate`, /// or `nil` if there is no element that satisfies `predicate`. @inlinable public func first( where predicate: (Element) throws -> Bool ) rethrows -> Element? { var foundElement: Element? do { try self.forEach { if try predicate($0) { foundElement = $0 throw _StopIteration.stop } } } catch is _StopIteration { } return foundElement } } extension Sequence where Element : Equatable { /// Returns the longest possible subsequences of the sequence, in order, /// around elements equal to the given element. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string at each /// space character (" "). The first use of `split` returns each word that /// was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(separator: " ") /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print(line.split(separator: " ", maxSplits: 1) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.split(separator: " ", omittingEmptySubsequences: false) /// .map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - separator: The element that should be split upon. /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each consecutive pair of `separator` /// elements in the sequence and for each instance of `separator` at the /// start or end of the sequence. If `true`, only nonempty subsequences /// are returned. The default value is `true`. /// - Returns: An array of subsequences, split from this sequence's elements. @inlinable public func split( separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true ) -> [SubSequence] { return split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: { $0 == separator }) } } extension Sequence where SubSequence == AnySequence<Element> { /// Returns the longest possible subsequences of the sequence, in order, that /// don't contain elements satisfying the given predicate. Elements that are /// used to split the sequence are not returned as part of any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print( /// line.split(maxSplits: 1, whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `true` for the `allowEmptySlices` parameter, so /// the returned array contains empty strings where spaces were repeated. /// /// print( /// line.split( /// omittingEmptySubsequences: false, /// whereSeparator: { $0 == " " } /// ).map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the sequence satisfying the `isSeparator` predicate. /// If `true`, only nonempty subsequences are returned. The default /// value is `true`. /// - isSeparator: A closure that returns `true` if its argument should be /// used to split the sequence; otherwise, `false`. /// - Returns: An array of subsequences, split from this sequence's elements. @inlinable public func split( maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Element) throws -> Bool ) rethrows -> [AnySequence<Element>] { _precondition(maxSplits >= 0, "Must take zero or more splits") var result: [AnySequence<Element>] = [] var subSequence: [Element] = [] @discardableResult func appendSubsequence() -> Bool { if subSequence.isEmpty && omittingEmptySubsequences { return false } result.append(AnySequence(subSequence)) subSequence = [] return true } if maxSplits == 0 { // We aren't really splitting the sequence. Convert `self` into an // `Array` using a fast entry point. subSequence = Array(self) appendSubsequence() return result } var iterator = self.makeIterator() while let element = iterator.next() { if try isSeparator(element) { if !appendSubsequence() { continue } if result.count == maxSplits { break } } else { subSequence.append(element) } } while let element = iterator.next() { subSequence.append(element) } appendSubsequence() return result } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the sequence. /// /// The sequence must be finite. If the maximum length exceeds the number of /// elements in the sequence, the result contains all the elements in the /// sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func suffix(_ maxLength: Int) -> AnySequence<Element> { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence") if maxLength == 0 { return AnySequence([]) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements into a ring buffer to save space. Once all // elements are consumed, reorder the ring buffer into an `Array` // and return it. This saves memory for sequences particularly longer // than `maxLength`. var ringBuffer: [Element] = [] ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount)) var i = ringBuffer.startIndex for element in self { if ringBuffer.count < maxLength { ringBuffer.append(element) } else { ringBuffer[i] = element i += 1 i %= maxLength } } if i != ringBuffer.startIndex { let s0 = ringBuffer[i..<ringBuffer.endIndex] let s1 = ringBuffer[0..<i] return AnySequence([s0, s1].joined()) } return AnySequence(ringBuffer) } /// Returns a subsequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the sequence, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of /// the sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence starting after the specified number of /// elements. /// /// - Complexity: O(1). @inlinable public func dropFirst(_ n: Int) -> AnySequence<Element> { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } return AnySequence(_DropFirstSequence(_iterator: makeIterator(), limit: n)) } /// Returns a subsequence containing all but the given number of final /// elements. /// /// The sequence must be finite. If the number of elements to drop exceeds /// the number of elements in the sequence, the result is an empty /// subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence leaving off the specified number of elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func dropLast(_ n: Int) -> AnySequence<Element> { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements from this sequence in a holding tank, a ring buffer // of size <= n. If more elements keep coming in, pull them out of the // holding tank into the result, an `Array`. This saves // `n` * sizeof(Element) of memory, because slices keep the entire // memory of an `Array` alive. var result: [Element] = [] var ringBuffer: [Element] = [] var i = ringBuffer.startIndex for element in self { if ringBuffer.count < n { ringBuffer.append(element) } else { result.append(ringBuffer[i]) ringBuffer[i] = element i = ringBuffer.index(after: i) % n } } return AnySequence(result) } /// Returns a subsequence by skipping the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `drop(while:)` method to skip over the /// positive numbers at the beginning of the `numbers` array. The result /// begins with the first element of `numbers` that does not satisfy /// `predicate`. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let startingWithNegative = numbers.drop(while: { $0 > 0 }) /// // startingWithNegative == [-2, 9, -6, 10, 1] /// /// If `predicate` matches every element in the sequence, the result is an /// empty sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A subsequence starting after the initial, consecutive elements /// that satisfy `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public func drop( while predicate: (Element) throws -> Bool ) rethrows -> AnySequence<Element> { return try AnySequence( _DropWhileSequence( iterator: makeIterator(), nextElement: nil, predicate: predicate)) } /// Returns a subsequence, up to the specified maximum length, containing the /// initial elements of the sequence. /// /// If the maximum length exceeds the number of elements in the sequence, /// the result contains all the elements in the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence starting at the beginning of this sequence /// with at most `maxLength` elements. /// /// - Complexity: O(1) @inlinable public func prefix(_ maxLength: Int) -> AnySequence<Element> { _precondition(maxLength >= 0, "Can't take a prefix of negative length from a sequence") if maxLength == 0 { return AnySequence(EmptyCollection<Element>()) } return AnySequence( _PrefixSequence(_iterator: makeIterator(), maxLength: maxLength)) } /// Returns a subsequence containing the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `prefix(while:)` method to find the /// positive numbers at the beginning of the `numbers` array. Every element /// of `numbers` up to, but not including, the first negative value is /// included in the result. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let positivePrefix = numbers.prefix(while: { $0 > 0 }) /// // positivePrefix == [3, 7, 4] /// /// If `predicate` matches every element in the sequence, the resulting /// sequence contains every element of the sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A subsequence of the initial, consecutive elements that /// satisfy `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public func prefix( while predicate: (Element) throws -> Bool ) rethrows -> AnySequence<Element> { var result: [Element] = [] for element in self { guard try predicate(element) else { break } result.append(element) } return AnySequence(result) } } extension Sequence { /// Returns a subsequence containing all but the first element of the /// sequence. /// /// The following example drops the first element from an array of integers. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst()) /// // Prints "[2, 3, 4, 5]" /// /// If the sequence has no elements, the result is an empty subsequence. /// /// let empty: [Int] = [] /// print(empty.dropFirst()) /// // Prints "[]" /// /// - Returns: A subsequence starting after the first element of the /// sequence. /// /// - Complexity: O(1) @inlinable public func dropFirst() -> SubSequence { return dropFirst(1) } /// Returns a subsequence containing all but the last element of the /// sequence. /// /// The sequence must be finite. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast()) /// // Prints "[1, 2, 3, 4]" /// /// If the sequence has no elements, the result is an empty subsequence. /// /// let empty: [Int] = [] /// print(empty.dropLast()) /// // Prints "[]" /// /// - Returns: A subsequence leaving off the last element of the sequence. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func dropLast() -> SubSequence { return dropLast(1) } } extension Sequence { /// Copies `self` into the supplied buffer. /// /// - Precondition: The memory in `self` is uninitialized. The buffer must /// contain sufficient uninitialized memory to accommodate `source.underestimatedCount`. /// /// - Postcondition: The `Pointee`s at `buffer[startIndex..<returned index]` are /// initialized. @inlinable public func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { var it = self.makeIterator() guard var ptr = buffer.baseAddress else { return (it,buffer.startIndex) } for idx in buffer.startIndex..<buffer.count { guard let x = it.next() else { return (it, idx) } ptr.initialize(to: x) ptr += 1 } return (it,buffer.endIndex) } } // FIXME(ABI)#182 // Pending <rdar://problem/14011860> and <rdar://problem/14396120>, // pass an IteratorProtocol through IteratorSequence to give it "Sequence-ness" /// A sequence built around an iterator of type `Base`. /// /// Useful mostly to recover the ability to use `for`...`in`, /// given just an iterator `i`: /// /// for x in IteratorSequence(i) { ... } @_fixed_layout public struct IteratorSequence<Base : IteratorProtocol> { @usableFromInline internal var _base: Base /// Creates an instance whose iterator is a copy of `base`. @inlinable public init(_ base: Base) { _base = base } } extension IteratorSequence: IteratorProtocol, Sequence { /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. @inlinable public mutating func next() -> Base.Element? { return _base.next() } }
apache-2.0
0511d76762922512b594aa75bd3b75da
35.898015
100
0.630444
4.274681
false
false
false
false
tjw/swift
test/Interpreter/repl.swift
4
4620
// RUN: %target-repl-run-simple-swift | %FileCheck %s // REQUIRES: swift_repl :print_decl String // CHECK: struct String // CHECK: extension String : _ExpressibleByStringInterpolation false // CHECK: Bool = false (1,2) // CHECK: (Int, Int) = (1, 2) print(10) print(10) // CHECK: 10 // CHECK-NEXT: 10 func f() { print("Hello") } f() // CHECK: Hello 102 // CHECK: Int = 102 var x = 1 // CHECK: x : Int = 1 (x, 2) // CHECK: (Int, Int) = (1, 2) var (_, y) = (x,2) // CHECK: (_, y) : (Int, Int) = (1, 2) var aString = String() // CHECK: aString : String = "" "\n\r\t\"' abcd\u{45}\u{01}" // CHECK: "\n\r\t\"\' abcdE\u{01}" String(-1) // CHECK: String = "-1" String(-112312312) // CHECK: String = "-112312312" String(4.0) // CHECK: String = "4.0" 1 + 44 // CHECK: Int = 45{{$}} 123 . hashValue // CHECK: Int = {{-?[0-9]+$}} // Check that we handle unmatched parentheses in REPL. 1+1) var z = 44 +z // CHECK: Int = 44{{$}} +44 // CHECK: Int = 44{{$}} typealias Foo = Int var f1 : Foo = 1 var f44 : Foo = 44 f1 + f44 // CHECK: Foo = 45{{$}} +(f44) // CHECK: Foo = 44{{$}} 1.5 // CHECK: Double = 1.5{{$}} 1.5+2.25 // CHECK: Double = 3.75{{$}} +1.75 // CHECK: Double = 1.75{{$}} -1.75 // CHECK: Double = -1.75{{$}} func r13792487(_ x: Float64) -> Float64 { return x } r13792487(1234.0) // CHECK: Float64 = 1234.0{{$}} r13792487(1234) // CHECK: Float64 = 1234.0{{$}} var ab = (1, 2) // CHECK: (Int, Int) = (1, 2) var ba = (y:1, x:2) var f2 : Foo = 2 var xy = (f1, f2) // CHECK: (Foo, Foo) = (1, 2) var yx = (y:f1, x:f2) func sub(x x: Int, y: Int) -> Int { return x - y } sub(x:1, y:2) // CHECK: Int = -1 sub(x:f1, y:f2) // CHECK: Foo = -1 var array = [1, 2, 3, 4, 5] // CHECK: array : [Int] = [1, 2, 3, 4, 5] var dict = [ "Hello" : 1.5 ] // CHECK: dict : [String : Double] = ["Hello": 1.5] 0..<10 // FIXME: Disabled CHECK for Range<Int> = 0...10 until we get general printing going // FIXME: Disabled CHECK for 0...10 pending <rdar://problem/11510876> // (Implement overload resolution) // Don't crash on this. rdar://14912363 -2...-1 -2 ... -1 // r2 : Range<Int> = -2...-1 String(0) // CHECK: "0" for i in 0..<10 { print(i); } // CHECK: 0 // CHECK-NEXT: 1 // CHECK-NEXT: 2 // CHECK-NEXT: 3 // CHECK-NEXT: 4 // CHECK-NEXT: 5 // CHECK-NEXT: 6 // CHECK-NEXT: 7 // CHECK-NEXT: 8 // CHECK-NEXT: 9 for i in 0..<10 { print(i); } // CHECK: 0 // CHECK-NEXT: 1 // CHECK-NEXT: 2 // CHECK-NEXT: 3 // CHECK-NEXT: 4 // CHECK-NEXT: 5 // CHECK-NEXT: 6 // CHECK-NEXT: 7 // CHECK-NEXT: 8 // CHECK-NEXT: 9 for c in "foobar".unicodeScalars { print(c) } // CHECK: f // CHECK-NEXT: o // CHECK-NEXT: o // CHECK-NEXT: b // CHECK-NEXT: a // CHECK-NEXT: r var vec = Array<String>() // CHECK: vec : [String] = [] // Error recovery var a : [int] var a = [Int]() var b = a.slice[3..<5] struct Inner<T> {} struct Outer<T> { var inner : Inner<T> } Outer<Int>(inner: Inner()) // CHECK: Outer<Int> = REPL.Outer struct ContainsSlice { var slice : [Int] } ContainsSlice(slice: [1, 2, 3]) // CHECK: ContainsSlice = REPL.ContainsSlice struct ContainsGenericSlice<T> { var slice : [T] } ContainsGenericSlice(slice: [1, 2, 3]) // CHECK: ContainsGenericSlice<Int> = REPL.ContainsGenericSlice ContainsGenericSlice(slice: [(1, 2), (3, 4)]) // CHECK: ContainsGenericSlice<(Int, Int)> = REPL.ContainsGenericSlice struct ContainsContainsSlice { var containsSlice : ContainsSlice } ContainsContainsSlice(containsSlice: ContainsSlice(slice: [1, 2, 3])) // CHECK: ContainsContainsSlice = REPL.ContainsContainsSlice protocol Proto { func foo() } extension Double : Proto { func foo() { print("Double: \(self)\n", terminator: "") } } var pr : Proto = 3.14159 // CHECK: Double: 3.14159 pr.foo() // erroneous; we'll try again after adding the conformance pr = "foo" extension String : Proto { func foo() { print("String: \(self)\n", terminator: "") } } pr = "foo" // CHECK: String: foo pr.foo() var _ : ([Int]).Type = type(of: [4]) // CHECK: : ([Int]).Type var _ : ((Int) -> Int)? = .none // CHECK: : ((Int) -> Int)? func chained(f f: @escaping (Int) -> ()) -> Int { return 0 } chained // CHECK: : (@escaping (Int) -> ()) -> Int [chained] // CHECK: : [(@escaping (Int) -> ()) -> Int] ({97210}()) // CHECK: = 97210 true && true // CHECK: = true if ({true}()) { print("yeah1") } // CHECK: yeah1 if true && true { print("yeah2") } // CHECK: yeah2 if true && true { if true && true { print("yeah3") } } // CHECK: yeah3 if true && (true && true) { if true && (true && true) { print("yeah4") } } // CHECK: yeah4 if true && true { if true && true { print(true && true) } } // CHECK: true "ok" // CHECK: = "ok"
apache-2.0
9200a7c517c4cf1491382c63498e58c2
19.625
130
0.580519
2.638492
false
false
false
false
allsome/LSYEvernote
evernote/CollectionViewController.swift
1
3787
// // CollectionViewController.swift // evernote // // Created by 梁树元 on 10/12/15. // Copyright © 2015 com. All rights reserved. // import UIKit private let reuseIdentifier = "Cell" private let topPadding:CGFloat = 20 public let BGColor = UIColor(red: 56.0/255.0, green: 51/255.0, blue: 76/255.0, alpha: 1.0) class CollectionViewController: UIViewController,UICollectionViewDelegate, UICollectionViewDataSource { private let colorArray = NSMutableArray() private let rowNumber = 15 private let customTransition = EvernoteTransition() private let collectionView = UICollectionView(frame: CGRect(x: 0, y: topPadding, width: screenWidth, height: screenHeight - topPadding), collectionViewLayout: CollectionViewLayout()) override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = BGColor collectionView.backgroundColor = BGColor collectionView.dataSource = self collectionView.delegate = self collectionView.alwaysBounceVertical = false collectionView.contentInset = UIEdgeInsetsMake(0, 0, verticallyPadding, 0); self.view.addSubview(collectionView) let nib = UINib(nibName: "CollectionViewCell", bundle: nil) collectionView.register(nib, forCellWithReuseIdentifier: reuseIdentifier) let random = arc4random() % 360 // 160 arc4random() % 360 for index in 0 ..< rowNumber { let color = UIColor(hue: CGFloat((Int(random) + index * 6)).truncatingRemainder(dividingBy: 360.0) / 360.0, saturation: 0.8, brightness: 1.0, alpha: 1.0) colorArray.add(color) } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } func numberOfSections(in collectionView: UICollectionView) -> Int { return colorArray.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell cell.backgroundColor = colorArray.object(at: colorArray.count - 1 - (indexPath as NSIndexPath).section) as? UIColor cell.titleLabel.text = "Notebook + " + String((indexPath as NSIndexPath).section + 1) cell.titleLine.alpha = 0.0 cell.textView.alpha = 0.0 cell.backButton.alpha = 0.0 cell.tag = (indexPath as NSIndexPath).section return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! CollectionViewCell let visibleCells = collectionView.visibleCells as! [CollectionViewCell] let storyBoard = UIStoryboard(name: "evernote", bundle: nil) let viewController = storyBoard.instantiateViewController(withIdentifier: "Note") as! NoteViewController viewController.titleName = cell.titleLabel.text! viewController.domainColor = cell.backgroundColor! let finalFrame = CGRect(x: 10, y: collectionView.contentOffset.y + 10, width: screenWidth - 20, height: screenHeight - 40) self.customTransition.EvernoteTransitionWith(selectCell: cell, visibleCells: visibleCells, originFrame: cell.frame, finalFrame: finalFrame, panViewController:viewController, listViewController: self) viewController.transitioningDelegate = self.customTransition viewController.delegate = self.customTransition self.present(viewController, animated: true) { () -> Void in } } }
mit
8a8e5ed5808d75cd05aa334936366b94
45.097561
207
0.707143
5.09434
false
false
false
false
psharanda/Atributika
Sources/AttributedText.swift
1
8671
/** * Atributika * * Copyright (c) 2017 Pavel Sharanda. Licensed under the MIT license, as follows: * * 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 enum DetectionType { case tag(Tag) case hashtag(String) case mention(String) case regex(String) case phoneNumber(String) case link(URL) case textCheckingType(String, NSTextCheckingResult.CheckingType) case range } public struct Detection { public let type: DetectionType public let style: Style public let range: Range<String.Index> let level: Int } public protocol AttributedTextProtocol { var string: String {get} var detections: [Detection] {get} var baseStyle: Style {get} } extension AttributedTextProtocol { fileprivate func makeAttributedString(getAttributes: (Style)-> [AttributedStringKey: Any]) -> NSAttributedString { let attributedString = NSMutableAttributedString(string: string, attributes: getAttributes(baseStyle)) let sortedDetections = detections.sorted { $0.level < $1.level } for d in sortedDetections { let attrs = getAttributes(d.style) if attrs.count > 0 { attributedString.addAttributes(attrs, range: NSRange(d.range, in: string)) } } return attributedString } } public final class AttributedText: AttributedTextProtocol { public let string: String public let detections: [Detection] public let baseStyle: Style init(string: String, detections: [Detection], baseStyle: Style) { self.string = string self.detections = detections self.baseStyle = baseStyle } public lazy private(set) var attributedString: NSAttributedString = { makeAttributedString { $0.attributes } }() public lazy private(set) var disabledAttributedString: NSAttributedString = { makeAttributedString { $0.disabledAttributes } }() } extension AttributedTextProtocol { /// style the whole string public func styleAll(_ style: Style) -> AttributedText { return AttributedText(string: string, detections: detections, baseStyle: baseStyle.merged(with: style)) } /// style things like #xcode #mentions public func styleHashtags(_ style: Style) -> AttributedText { let ranges = string.detectHashTags() let ds = ranges.map { Detection(type: .hashtag(String(string[(string.index($0.lowerBound, offsetBy: 1))..<$0.upperBound])), style: style, range: $0, level: Int.max) } return AttributedText(string: string, detections: detections + ds, baseStyle: baseStyle) } /// style things like @John @all public func styleMentions(_ style: Style) -> AttributedText { let ranges = string.detectMentions() let ds = ranges.map { Detection(type: .mention(String(string[(string.index($0.lowerBound, offsetBy: 1))..<$0.upperBound])), style: style, range: $0, level: Int.max) } return AttributedText(string: string, detections: detections + ds, baseStyle: baseStyle) } public func style(regex: String, options: NSRegularExpression.Options = [], style: Style) -> AttributedText { let ranges = string.detect(regex: regex, options: options) let ds = ranges.map { Detection(type: .regex(regex), style: style, range: $0, level: Int.max) } return AttributedText(string: string, detections: detections + ds, baseStyle: baseStyle) } public func style(textCheckingTypes: NSTextCheckingResult.CheckingType, style: Style) -> AttributedText { let ranges = string.detect(textCheckingTypes: textCheckingTypes) let ds = ranges.map { Detection(type: .textCheckingType(String(string[$0]), textCheckingTypes), style: style, range: $0, level: Int.max) } return AttributedText(string: string, detections: detections + ds, baseStyle: baseStyle) } public func stylePhoneNumbers(_ style: Style) -> AttributedText { let ranges = string.detect(textCheckingTypes: [.phoneNumber]) let ds = ranges.map { Detection(type: .phoneNumber(String(string[$0])), style: style, range: $0, level: Int.max) } return AttributedText(string: string, detections: detections + ds, baseStyle: baseStyle) } public func styleLinks(_ style: Style) -> AttributedText { let ranges = string.detect(textCheckingTypes: [.link]) #if swift(>=4.1) let ds = ranges.compactMap { range in URL(string: String(string[range])).map { Detection(type: .link($0), style: style, range: range, level: Int.max) } } #else let ds = ranges.flatMap { range in URL(string: String(string[range])).map { Detection(type: .link($0), style: style, range: range) } } #endif return AttributedText(string: string, detections: detections + ds, baseStyle: baseStyle) } public func style(range: Range<String.Index>, style: Style) -> AttributedText { let d = Detection(type: .range, style: style, range: range, level: Int.max) return AttributedText(string: string, detections: detections + [d], baseStyle: baseStyle) } } extension String: AttributedTextProtocol { public var string: String { return self } public var detections: [Detection] { return [] } public var baseStyle: Style { return Style() } public func style(tags: [Style], transformers: [TagTransformer] = [TagTransformer.brTransformer], tuner: (Style, Tag) -> Style = { s, _ in return s}) -> AttributedText { let (string, tagsInfo) = detectTags(transformers: transformers) var ds: [Detection] = [] tagsInfo.forEach { t in if let style = (tags.first { style in style.name.lowercased() == t.tag.name.lowercased() }) { ds.append(Detection(type: .tag(t.tag), style: tuner(style, t.tag), range: t.range, level: t.level)) } else { ds.append(Detection(type: .tag(t.tag), style: Style(), range: t.range, level: t.level)) } } return AttributedText(string: string, detections: ds, baseStyle: baseStyle) } public func style(tags: Style..., transformers: [TagTransformer] = [TagTransformer.brTransformer], tuner: (Style, Tag) -> Style = { s, _ in return s}) -> AttributedText { return style(tags: tags, transformers: transformers, tuner: tuner) } public var attributedString: NSAttributedString { return makeAttributedString { $0.attributes } } public var disabledAttributedString: NSAttributedString { return makeAttributedString { $0.disabledAttributes } } } extension NSAttributedString: AttributedTextProtocol { public var detections: [Detection] { var ds: [Detection] = [] enumerateAttributes(in: NSMakeRange(0, length), options: []) { (attributes, range, _) in if let range = Range(range, in: self.string) { ds.append(Detection(type: .range, style: Style("", attributes), range: range, level: Int.max)) } } return ds } public var baseStyle: Style { return Style() } public var attributedString: NSAttributedString { return makeAttributedString { $0.attributes } } public var disabledAttributedString: NSAttributedString { return makeAttributedString { $0.disabledAttributes } } }
mit
7bf28386fcbb08e2ad8798302f5e4e5d
37.883408
175
0.655749
4.469588
false
false
false
false
malcommac/Hydra
Sources/Hydra/Promise+Then.swift
1
5961
/* * Hydra * Fullfeatured lightweight Promise & Await Library for Swift * * Created by: Daniele Margutti * Email: [email protected] * Web: http://www.danielemargutti.com * Twitter: @danielemargutti * * Copyright © 2017 Daniele Margutti * * * 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 extension Promise { /// This `then` allows to execute a block which return a value; this value is used to get a chainable /// Promise already resolved with that value. /// Executed body can also reject the chain if throws. /// /// - Parameters: /// - context: context in which the body is executed (if not specified `main` is used) /// - body: block to execute /// - Returns: a chainable promise @discardableResult func then<N>(in context: Context? = nil, _ body: @escaping ( (Value) throws -> N) ) -> Promise<N> { let ctx = context ?? .main return self.then(in: ctx, { value in do { // get the value from body (or throws) and // create a resolved Promise with that which is returned // as output of the then as chainable promise. let transformedValue = try body(value) return Promise<N>(resolved: transformedValue) } catch let error { // if body throws a rejected promise with catched error is generated return Promise<N>(rejected: error) } }) } /// This `then` allows to execute a block of code which can transform the result of the promise in another /// promise. /// It's also possible to use it in order to send the output of a promise an input of another one and use it: /// `asyncFunc1().then(asyncFunc2).then...` /// Executed body can also reject the chain if throws. /// /// - Parameters: /// - context: context in which the body is executed (if not specified `main` is used) /// - body: body to execute /// - Returns: chainable promise @discardableResult func then<N>(in context: Context? = nil, _ body: @escaping ( (Value) throws -> (Promise<N>) )) -> Promise<N> { let ctx = context ?? .main let nextPromise = Promise<N>(in: ctx, token: self.invalidationToken, { resolve, reject, operation in // Observe the resolve of the self promise let onResolve = Observer.onResolve(ctx, { value in do { // Pass the value to the body and get back a new promise // with another value let chainedPromise = try body(value) // execute the promise's body and get the result of it let pResolve = Promise<N>.Observer.onResolve(ctx, resolve) let pReject = Promise<N>.Observer.onReject(ctx, reject) chainedPromise.add(observers: pResolve, pReject) chainedPromise.runBody() } catch let error { reject(error) } }) // Observe the reject of the self promise let onReject = Observer.onReject(ctx, reject) let onCancel = Observer.onCancel(ctx, operation.cancel) self.add(observers: onResolve, onReject, onCancel) }) nextPromise.runBody() self.runBody() return nextPromise } /// This `then` variant allows to catch the resolved value of the promise and execute a block of code /// without returning anything. /// Defined body can also reject the next promise if throw. /// Returned object is a promise which is able to dispatch both error or resolved value of the promise. /// /// - Parameters: /// - context: context in which the body is executed (if not specified `main` is used) /// - body: code block to execute /// - Returns: a chainable promise @discardableResult func then(in context: Context? = nil, _ body: @escaping ( (Value) throws -> () ) ) -> Promise<Value> { let ctx = context ?? .main // This is the simplest `then` is possible to create; it simply execute the body of the // promise, get the value and allows to execute a body. Body can also throw and reject // next chained promise. let nextPromise = Promise<Value>(in: ctx, token: self.invalidationToken, { resolve, reject, operation in let onResolve = Observer.onResolve(ctx, { value in do { // execute body and resolve this promise with the same value // no transformations are allowed in this `then` except the throw. // if body throw nextPromise is rejected. try body(value) resolve(value) } catch let error { // body throws, this nextPromise reject with given error reject(error) } }) // this promise rejects so nextPromise also rejects with the error let onReject = Observer.onReject(ctx, reject) let onCancel = Observer.onCancel(ctx, operation.cancel) self.add(observers: onResolve, onReject, onCancel) }) // execute the body of nextPromise so we can register observer // to this promise and get back value/error once its resolved/rejected. nextPromise.runBody() // run the body of the self promise. Body is executed only one time; if this // promise is the main promise it simply execute the core of the promsie functions. self.runBody() return nextPromise } }
mit
5e10e79288f67be97df75db353acad54
38.210526
111
0.705705
3.85511
false
false
false
false
swifteiro/NeonTransfer
Pods/JSONHelper/JSONHelper/Extensions/Float.swift
1
596
// // Copyright © 2016 Baris Sencan. All rights reserved. // import Foundation extension Float: Convertible { public static func convertFromValue<T>(value: T?) throws -> Float? { guard let value = value else { return nil } if let floatValue = value as? Float { return floatValue } else if let stringValue = value as? String { return Float(stringValue) } else if let doubleValue = value as? Double { return Float(doubleValue) } else if let intValue = value as? Int { return Float(intValue) } throw ConversionError.UnsupportedType } }
mit
b8e76aa253fea6c66179d847a932781b
23.791667
70
0.667227
4.375
false
false
false
false
Darr758/Swift-Algorithms-and-Data-Structures
Data Structures/LinkedList.playground/Contents.swift
1
1873
public class Node<T>{ var value:T init(value:T){ self.value = value } var next:Node? weak var prev:Node? } public class LinkedList<T>{ private var head:Node<T>? private var tail:Node<T>? func isEmpty() -> Bool{ return self.head == nil } func getHead() -> Node<T>?{ return self.head } func getTail() -> Node<T>?{ return self.tail } func append(value:T) -> T{ let newNode = Node(value:value) if let tail = self.tail{ tail.next = newNode newNode.prev = tail }else{ head = newNode } self.tail = newNode return value } func removeAll(){ self.head = nil self.tail = nil } func delete(node:Node<T>) -> T{ let next = node.next let prev = node.prev if let prev = prev{ prev.next = next }else{ head = next } next?.prev = prev if next == nil{ tail = prev } node.prev = nil node.next = nil return node.value } func nodeAt(index:Int) -> Node<T>? { if index >= 0{ var node = head var i = index while node != nil{ if i == 0{ return node} node = node?.next i -= 1 } } return nil } } extension LinkedList:CustomStringConvertible{ public var description: String{ var text = "(" var node = self.getHead() while node != nil{ text += node?.value as! String node = node?.next if node != nil{ text += ", " } } text += ")" return text } }
mit
3668cc62dacbd2203969ec609abf9ee6
19.139785
45
0.431927
4.376168
false
false
false
false
kinyong/KYWeiboDemo-Swfit
AYWeibo/AYWeibo/classes/Home/ImageBrowserCell.swift
1
5534
// // ImageBrowserCell.swift // AYWeibo // // Created by Kinyong on 16/7/11. // Copyright © 2016年 Ayong. All rights reserved. // import UIKit import SDWebImage class ImageBrowserCell: UICollectionViewCell { let width = UIScreen.mainScreen().bounds.width let height = UIScreen.mainScreen().bounds.height /// 缩略小图片 var thumbnailImageView = UIImageView() /// 缩略小图url var thumbnail_url: NSURL? // MARK: - 懒加载 lazy var scrollView: UIScrollView = { let sc = UIScrollView() sc.delegate = self sc.maximumZoomScale = 2.0 sc.minimumZoomScale = 0.5 return sc }() /// 显示大图片 lazy var imageView: KYProgressImgView = KYProgressImgView(frame: CGRectZero) var bmiddle_url: NSURL? { didSet { // 重置所有数据 resetView() // 设置图片 SDWebImageManager.sharedManager().downloadImageWithURL(bmiddle_url, options: SDWebImageOptions(rawValue: 0), progress: { (current, total) in self.imageView.sd_setImageWithURL(self.thumbnail_url) // 1.计算当前图片的宽高比 self.thumbnailImageView.sizeToFit() let scale = self.thumbnailImageView.bounds.height / self.thumbnailImageView.bounds.width // 2.利用宽高比乘以屏幕宽度,等比缩放图片 let imageHeight = scale * self.width // 3.设置图片frame self.imageView.frame = CGRect(origin: CGPointZero, size: CGSize(width: self.width, height: imageHeight)) // 4.计算滚动视图的顶部和底部的内边距 let offsetY = (self.height - imageHeight) * 0.5 // 5.设置内边距 if imageHeight < self.height { // 小图 self.scrollView.contentInset = UIEdgeInsets(top: offsetY, left: 0, bottom: offsetY, right: 0) } else if imageHeight > self.height { // 大图 self.scrollView.contentSize = CGSizeMake(self.width, imageHeight) } self.imageView.setProgressHidden(false) self.imageView.progress = CGFloat(current) / CGFloat(total) }) { (image, error, _, _, _) in // 1.计算当前图片的宽高比 let scale = image.size.height / image.size.width // 2.利用宽高比乘以屏幕宽度,等比缩放图片 let imageHeight = scale * self.width // 3.设置图片frame self.imageView.frame = CGRect(origin: CGPointZero, size: CGSize(width: self.width, height: imageHeight)) // 4.计算滚动视图的顶部和底部的内边距 let offsetY = (self.height - imageHeight) * 0.5 // 5.设置内边距 if imageHeight < self.height { // 小图 self.scrollView.contentInset = UIEdgeInsets(top: offsetY, left: 0, bottom: offsetY, right: 0) } else if imageHeight > self.height { // 大图 self.scrollView.contentSize = CGSizeMake(self.width, imageHeight) } // 6.设置图片 self.imageView.image = image } } } // MARK: - 系统内部方法 override init(frame: CGRect) { super.init(frame: frame) // 初始化UI setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - 内部方法 private func setupUI() { // 1.添加子控件 self.contentView.addSubview(scrollView) scrollView.addSubview(imageView) // 2.布局子控件 scrollView.frame = self.bounds } // 重置视图 private func resetView() { scrollView.contentInset = UIEdgeInsetsZero scrollView.contentOffset = CGPointZero scrollView.contentSize = CGSizeZero imageView.transform = CGAffineTransformIdentity self.imageView.setProgressHidden(true) } } // MARK: - UIScrollViewDelegate extension ImageBrowserCell: UIScrollViewDelegate { func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(scrollView: UIScrollView) { // 1. 计算UIScrollView的内边距 var offsetX = (width - imageView.frame.width) * 0.5 var offsetY = (height - imageView.frame.height) * 0.5 // 2. 如果内边距超出屏幕范围,就设为0 offsetX = offsetX < 0 ? 0 : offsetX offsetY = offsetY < 0 ? 0 : offsetY // 3. 设置内边距 scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: offsetY, right: offsetX) } }
apache-2.0
6cdd701456e90f787d5ee8884fd78670
31.09375
152
0.509056
5.181635
false
false
false
false
calebkleveter/Ether
Sources/Ether/New.swift
1
4105
// The MIT License (MIT) // // Copyright (c) 2017 Caleb Kleveter // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import Manifest import Helpers import Command public final class New: Command { public var arguments: [CommandArgument] = [ CommandArgument.argument(name: "name", help: ["The name of the new project"]) ] public var options: [CommandOption] = [ CommandOption.flag(name: "executable", short: "e", help: ["Creates an executable SPM project"]), CommandOption.flag(name: "package", short: "p", help: ["(default) Creates an SPM package"]), CommandOption.value(name: "template", help: ["Creates a project with a previously saved template"]) ] public var help: [String] = ["Creates a new project"] public init() {} public func run(using context: CommandContext) throws -> EventLoopFuture<Void> { let newProject = context.console.loadingBar(title: "Generating Project") _ = newProject.start(on: context.container) let executable = try newExecutable(from: context) let template = try newFromTemplate(using: context) if !executable && !template { try newPackage(from: context) } newProject.succeed() let config = try Configuration.get() let name = try context.argument("name") try config.commit(with: config.newCommit, on: context, replacements: [name]) return context.container.future() } func newExecutable(from context: CommandContext) throws -> Bool { if let _ = context.options["executable"] { let name = try context.argument("name") let script = "mkdir \(name); cd \(name); swift package init --type=executable" _ = try Process.execute("bash", ["-c", script]) let currentDir = try Process.execute("pwd") try Manifest(path: "file:\(currentDir)/\(name)/Package.swift").reset() return true } return false } func newFromTemplate(using context: CommandContext) throws -> Bool { if let template = context.options["template"] { let name = try context.argument("name") let manager = FileManager.default let directoryName = try Process.execute("echo", "$HOME") let templatePath = String("\(directoryName)Library/Application Support/Ether/Templates/\(template)".dropFirst(7)) let current = manager.currentDirectoryPath _ = try Process.execute("cp", ["-a", "\(templatePath)", "\(current)/\(name)"]) return true } return false } func newPackage(from context: CommandContext) throws { let name = try context.argument("name") let script = "mkdir \(name); cd \(name); swift package init" _ = try Process.execute("bash", ["-c", script]) let currentDir = try Process.execute("pwd") try Manifest(path: "file:\(currentDir)/\(name)/Package.swift").reset() } }
mit
76baabd7dc380a391c4e6470da18d67f
41.319588
125
0.65067
4.617548
false
false
false
false
zmeyc/GRDB.swift
Tests/Performance/InsertNamedValuesTests.swift
1
5383
import XCTest import GRDB import SQLite private let insertedRowCount = 20_000 // Here we insert rows, referencing statement arguments by name. class InsertNamedValuesTests: XCTestCase { func testFMDB() { let databaseFileName = "GRDBPerformanceTests-\(ProcessInfo.processInfo.globallyUniqueString).sqlite" let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName) defer { let dbQueue = try! DatabaseQueue(path: databasePath) try! dbQueue.inDatabase { db in XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, insertedRowCount) XCTAssertEqual(try Int.fetchOne(db, "SELECT MIN(i0) FROM items")!, 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT MAX(i9) FROM items")!, insertedRowCount - 1) } try! FileManager.default.removeItem(atPath: databasePath) } measure { _ = try? FileManager.default.removeItem(atPath: databasePath) let dbQueue = FMDatabaseQueue(path: databasePath)! dbQueue.inDatabase { db in db!.executeStatements("CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)") } dbQueue.inTransaction { (db, rollback) -> Void in db!.setShouldCacheStatements(true) for i in 0..<insertedRowCount { db!.executeUpdate("INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (:i0, :i1, :i2, :i3, :i4, :i5, :i6, :i7, :i8, :i9)", withParameterDictionary: ["i0": i, "i1": i, "i2": i, "i3": i, "i4": i, "i5": i, "i6": i, "i7": i, "i8": i, "i9": i]) } } } } func testGRDB() { let databaseFileName = "GRDBPerformanceTests-\(ProcessInfo.processInfo.globallyUniqueString).sqlite" let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName) defer { let dbQueue = try! DatabaseQueue(path: databasePath) try! dbQueue.inDatabase { db in XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, insertedRowCount) XCTAssertEqual(try Int.fetchOne(db, "SELECT MIN(i0) FROM items")!, 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT MAX(i9) FROM items")!, insertedRowCount - 1) } try! FileManager.default.removeItem(atPath: databasePath) } measure { _ = try? FileManager.default.removeItem(atPath: databasePath) let dbQueue = try! DatabaseQueue(path: databasePath) try! dbQueue.inDatabase { db in try db.execute("CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)") } try! dbQueue.inTransaction { db in let statement = try! db.makeUpdateStatement("INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (:i0, :i1, :i2, :i3, :i4, :i5, :i6, :i7, :i8, :i9)") for i in 0..<insertedRowCount { try statement.execute(arguments: ["i0": i, "i1": i, "i2": i, "i3": i, "i4": i, "i5": i, "i6": i, "i7": i, "i8": i, "i9": i]) } return .commit } } } func testSQLiteSwift() { let databaseFileName = "GRDBPerformanceTests-\(ProcessInfo.processInfo.globallyUniqueString).sqlite" let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName) defer { let dbQueue = try! DatabaseQueue(path: databasePath) try! dbQueue.inDatabase { db in XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, insertedRowCount) XCTAssertEqual(try Int.fetchOne(db, "SELECT MIN(i0) FROM items")!, 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT MAX(i9) FROM items")!, insertedRowCount - 1) } try! FileManager.default.removeItem(atPath: databasePath) } measure { _ = try? FileManager.default.removeItem(atPath: databasePath) let db = try! Connection(databasePath) try! db.run(itemsTable.create { t in t.column(i0Column) t.column(i1Column) t.column(i2Column) t.column(i3Column) t.column(i4Column) t.column(i5Column) t.column(i6Column) t.column(i7Column) t.column(i8Column) t.column(i9Column) }) try! db.transaction { for i in 0..<insertedRowCount { _ = try db.run(itemsTable.insert( i0Column <- i, i1Column <- i, i2Column <- i, i3Column <- i, i4Column <- i, i5Column <- i, i6Column <- i, i7Column <- i, i8Column <- i, i9Column <- i)) } } } } }
mit
398db4500c999c7012f515f67f289053
44.235294
274
0.533531
4.241923
false
true
false
false
uasys/swift
test/SILGen/foreach.swift
1
23356
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s ////////////////// // Declarations // ////////////////// class C {} @_silgen_name("loopBodyEnd") func loopBodyEnd() -> () @_silgen_name("condition") func condition() -> Bool @_silgen_name("loopContinueEnd") func loopContinueEnd() -> () @_silgen_name("loopBreakEnd") func loopBreakEnd() -> () @_silgen_name("funcEnd") func funcEnd() -> () struct TrivialStruct { var value: Int32 } struct NonTrivialStruct { var value: C } struct GenericStruct<T> { var value: T var value2: C } protocol P {} protocol ClassP : class {} protocol GenericCollection : Collection { } /////////// // Tests // /////////// //===----------------------------------------------------------------------===// // Trivial Struct //===----------------------------------------------------------------------===// // CHECK-LABEL: sil hidden @_T07foreach13trivialStructySaySiGF : $@convention(thin) (@owned Array<Int>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @owned $Array<Int>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<Int>> }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: switch_enum [[IND_VAR:%.*]] : $Optional<Int>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[VAR:%.*]] : @trivial $Int): // CHECK: [[LOOP_END_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_END_FUNC]]() // CHECK: br [[LOOP_DEST]] // // CHECK: [[CONT_BLOCK]]: // CHECK: destroy_value [[ITERATOR_BOX]] // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: destroy_value [[ARRAY]] // CHECK: } // end sil function '_T07foreach13trivialStructySaySiGF' func trivialStruct(_ xx: [Int]) { for x in xx { loopBodyEnd() } funcEnd() } // TODO: Write this test func trivialStructContinue(_ xx: [Int]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } // TODO: Write this test func trivialStructBreak(_ xx: [Int]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden @_T07foreach26trivialStructContinueBreakySaySiGF : $@convention(thin) (@owned Array<Int>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @owned $Array<Int>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<Int>> }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = function_ref @_T0s10CollectionPssAARzs16IndexingIteratorVyxG0C0RtzlE04makeC0AEyF : $@convention(method) <τ_0_0 where τ_0_0 : Collection, τ_0_0.Iterator == IndexingIterator<τ_0_0>> (@in_guaranteed τ_0_0) -> @out IndexingIterator<τ_0_0> // CHECK: [[BORROWED_ARRAY:%.*]] = begin_borrow [[ARRAY]] // CHECK: [[BORROWED_ARRAY_STACK:%.*]] = alloc_stack $Array<Int> // CHECK: store_borrow [[BORROWED_ARRAY]] to [[BORROWED_ARRAY_STACK]] // CHECK: apply [[MAKE_ITERATOR_FUNC]]<[Int]>([[PROJECT_ITERATOR_BOX]], [[BORROWED_ARRAY_STACK]]) // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[FUNC_REF:%.*]] = function_ref @_T0s16IndexingIteratorV4next7ElementQzSgyF : $@convention(method) // CHECK: [[GET_ELT_STACK:%.*]] = alloc_stack $Optional<Int> // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*IndexingIterator<Array<Int>> // CHECK: apply [[FUNC_REF]]<[Int]>([[GET_ELT_STACK]], [[WRITE]]) // CHECK: [[IND_VAR:%.*]] = load [trivial] [[GET_ELT_STACK]] // CHECK: switch_enum [[IND_VAR]] : $Optional<Int>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK_JUMP:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[VAR:%.*]] : @trivial $Int): // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: br [[LOOP_DEST]] // // CHECK: [[CONT_BLOCK_JUMP]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: destroy_value [[ITERATOR_BOX]] : ${ var IndexingIterator<Array<Int>> } // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: destroy_value [[ARRAY]] // CHECK: } // end sil function '_T07foreach26trivialStructContinueBreakySaySiGF' func trivialStructContinueBreak(_ xx: [Int]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Existential //===----------------------------------------------------------------------===// func existential(_ xx: [P]) { for x in xx { loopBodyEnd() } funcEnd() } func existentialContinue(_ xx: [P]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func existentialBreak(_ xx: [P]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden @_T07foreach24existentialContinueBreakySayAA1P_pGF : $@convention(thin) (@owned Array<P>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @owned $Array<P>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<P>> }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = function_ref @_T0s10CollectionPssAARzs16IndexingIteratorVyxG0C0RtzlE04makeC0AEyF : $@convention(method) <τ_0_0 where τ_0_0 : Collection, τ_0_0.Iterator == IndexingIterator<τ_0_0>> (@in_guaranteed τ_0_0) -> @out IndexingIterator<τ_0_0> // CHECK: [[BORROWED_ARRAY:%.*]] = begin_borrow [[ARRAY]] // CHECK: [[BORROWED_ARRAY_STACK:%.*]] = alloc_stack $Array<P> // CHECK: store_borrow [[BORROWED_ARRAY]] to [[BORROWED_ARRAY_STACK]] // CHECK: apply [[MAKE_ITERATOR_FUNC]]<[P]>([[PROJECT_ITERATOR_BOX]], [[BORROWED_ARRAY_STACK]]) // CHECK: [[ELT_STACK:%.*]] = alloc_stack $Optional<P> // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[FUNC_REF:%.*]] = function_ref @_T0s16IndexingIteratorV4next7ElementQzSgyF : $@convention(method) // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*IndexingIterator<Array<P>> // users: %16, %15 // CHECK: apply [[FUNC_REF]]<[P]>([[ELT_STACK]], [[WRITE]]) // CHECK: switch_enum_addr [[ELT_STACK]] : $*Optional<P>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK_JUMP:bb[0-9]+]] // // CHECK: [[SOME_BB]]: // CHECK: [[T0:%.*]] = alloc_stack $P, let, name "x" // CHECK: [[ELT_STACK_TAKE:%.*]] = unchecked_take_enum_data_addr [[ELT_STACK]] : $*Optional<P>, #Optional.some!enumelt.1 // CHECK: copy_addr [take] [[ELT_STACK_TAKE]] to [initialization] [[T0]] // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[CONT_BLOCK_JUMP]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: dealloc_stack [[ELT_STACK]] // CHECK: destroy_value [[ITERATOR_BOX]] : ${ var IndexingIterator<Array<P>> } // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: destroy_value [[ARRAY]] // CHECK: } // end sil function '_T07foreach24existentialContinueBreakySayAA1P_pGF' func existentialContinueBreak(_ xx: [P]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Class Constrainted Existential //===----------------------------------------------------------------------===// func existentialClass(_ xx: [ClassP]) { for x in xx { loopBodyEnd() } funcEnd() } func existentialClassContinue(_ xx: [ClassP]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func existentialClassBreak(_ xx: [ClassP]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } func existentialClassContinueBreak(_ xx: [ClassP]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Generic Struct //===----------------------------------------------------------------------===// func genericStruct<T>(_ xx: [GenericStruct<T>]) { for x in xx { loopBodyEnd() } funcEnd() } func genericStructContinue<T>(_ xx: [GenericStruct<T>]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func genericStructBreak<T>(_ xx: [GenericStruct<T>]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden @_T07foreach26genericStructContinueBreakySayAA07GenericC0VyxGGlF : $@convention(thin) <T> (@owned Array<GenericStruct<T>>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @owned $Array<GenericStruct<T>>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box $<τ_0_0> { var IndexingIterator<Array<GenericStruct<τ_0_0>>> } <T>, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = function_ref @_T0s10CollectionPssAARzs16IndexingIteratorVyxG0C0RtzlE04makeC0AEyF : $@convention(method) <τ_0_0 where τ_0_0 : Collection, τ_0_0.Iterator == IndexingIterator<τ_0_0>> (@in_guaranteed τ_0_0) -> @out IndexingIterator<τ_0_0> // CHECK: [[BORROWED_ARRAY:%.*]] = begin_borrow [[ARRAY]] // CHECK: [[BORROWED_ARRAY_STACK:%.*]] = alloc_stack $Array<GenericStruct<T>> // CHECK: store_borrow [[BORROWED_ARRAY]] to [[BORROWED_ARRAY_STACK]] // CHECK: apply [[MAKE_ITERATOR_FUNC]]<[GenericStruct<T>]>([[PROJECT_ITERATOR_BOX]], [[BORROWED_ARRAY_STACK]]) // CHECK: [[ELT_STACK:%.*]] = alloc_stack $Optional<GenericStruct<T>> // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[FUNC_REF:%.*]] = function_ref @_T0s16IndexingIteratorV4next7ElementQzSgyF : $@convention(method) // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*IndexingIterator<Array<GenericStruct<T>>> // CHECK: apply [[FUNC_REF]]<[GenericStruct<T>]>([[ELT_STACK]], [[WRITE]]) // CHECK: switch_enum_addr [[ELT_STACK]] : $*Optional<GenericStruct<T>>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK_JUMP:bb[0-9]+]] // // CHECK: [[SOME_BB]]: // CHECK: [[T0:%.*]] = alloc_stack $GenericStruct<T>, let, name "x" // CHECK: [[ELT_STACK_TAKE:%.*]] = unchecked_take_enum_data_addr [[ELT_STACK]] : $*Optional<GenericStruct<T>>, #Optional.some!enumelt.1 // CHECK: copy_addr [take] [[ELT_STACK_TAKE]] to [initialization] [[T0]] // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[CONT_BLOCK_JUMP]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: dealloc_stack [[ELT_STACK]] // CHECK: destroy_value [[ITERATOR_BOX]] // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: destroy_value [[ARRAY]] // CHECK: } // end sil function '_T07foreach26genericStructContinueBreakySayAA07GenericC0VyxGGlF' func genericStructContinueBreak<T>(_ xx: [GenericStruct<T>]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Fully Generic Collection //===----------------------------------------------------------------------===// func genericCollection<T : Collection>(_ xx: T) { for x in xx { loopBodyEnd() } funcEnd() } func genericCollectionContinue<T : Collection>(_ xx: T) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func genericCollectionBreak<T : Collection>(_ xx: T) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden @_T07foreach30genericCollectionContinueBreakyxs0C0RzlF : $@convention(thin) <T where T : Collection> (@in T) -> () { // CHECK: bb0([[COLLECTION:%.*]] : @trivial $*T): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : Collection> { var τ_0_0.Iterator } <T>, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = witness_method $T, #Sequence.makeIterator!1 : <Self where Self : Sequence> (Self) -> () -> Self.Iterator : $@convention(witness_method) <τ_0_0 where τ_0_0 : Sequence> (@in_guaranteed τ_0_0) -> @out τ_0_0.Iterator // CHECK: apply [[MAKE_ITERATOR_FUNC]]<T>([[PROJECT_ITERATOR_BOX]], [[COLLECTION]]) // CHECK: [[ELT_STACK:%.*]] = alloc_stack $Optional<T.Element> // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[GET_NEXT_FUNC:%.*]] = witness_method $T.Iterator, #IteratorProtocol.next!1 : <Self where Self : IteratorProtocol> (inout Self) -> () -> Self.Element? : $@convention(witness_method) <τ_0_0 where τ_0_0 : IteratorProtocol> (@inout τ_0_0) -> @out Optional<τ_0_0.Element> // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*T.Iterator // CHECK: apply [[GET_NEXT_FUNC]]<T.Iterator>([[ELT_STACK]], [[WRITE]]) // CHECK: switch_enum_addr [[ELT_STACK]] : $*Optional<T.Element>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK_JUMP:bb[0-9]+]] // // CHECK: [[SOME_BB]]: // CHECK: [[T0:%.*]] = alloc_stack $T.Element, let, name "x" // CHECK: [[ELT_STACK_TAKE:%.*]] = unchecked_take_enum_data_addr [[ELT_STACK]] : $*Optional<T.Element>, #Optional.some!enumelt.1 // CHECK: copy_addr [take] [[ELT_STACK_TAKE]] to [initialization] [[T0]] // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[CONT_BLOCK_JUMP]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: dealloc_stack [[ELT_STACK]] // CHECK: destroy_value [[ITERATOR_BOX]] // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: destroy_addr [[COLLECTION]] // CHECK: } // end sil function '_T07foreach30genericCollectionContinueBreakyxs0C0RzlF' func genericCollectionContinueBreak<T : Collection>(_ xx: T) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Pattern Match Tests //===----------------------------------------------------------------------===// // CHECK-LABEL: sil hidden @_T07foreach13tupleElementsySayAA1CC_ADtGF func tupleElements(_ xx: [(C, C)]) { // CHECK: bb3([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: [[BORROWED_PAYLOAD:%.*]] = begin_borrow [[PAYLOAD]] // CHECK: [[A:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 0 // CHECK: [[COPY_A:%.*]] = copy_value [[A]] // CHECK: [[B:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 1 // CHECK: [[COPY_B:%.*]] = copy_value [[B]] // CHECK: end_borrow [[BORROWED_PAYLOAD]] from [[PAYLOAD]] // CHECK: destroy_value [[COPY_B]] // CHECK: destroy_value [[COPY_A]] // CHECK: destroy_value [[PAYLOAD]] for (a, b) in xx {} // CHECK: bb7([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: [[BORROWED_PAYLOAD:%.*]] = begin_borrow [[PAYLOAD]] // CHECK: [[A:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 0 // CHECK: [[COPY_A:%.*]] = copy_value [[A]] // CHECK: [[B:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 1 // CHECK: [[COPY_B:%.*]] = copy_value [[B]] // CHECK: destroy_value [[COPY_B]] // CHECK: end_borrow [[BORROWED_PAYLOAD]] from [[PAYLOAD]] // CHECK: destroy_value [[COPY_A]] // CHECK: destroy_value [[PAYLOAD]] for (a, _) in xx {} // CHECK: bb11([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: [[BORROWED_PAYLOAD:%.*]] = begin_borrow [[PAYLOAD]] // CHECK: [[A:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 0 // CHECK: [[COPY_A:%.*]] = copy_value [[A]] // CHECK: [[B:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 1 // CHECK: [[COPY_B:%.*]] = copy_value [[B]] // CHECK: destroy_value [[COPY_A]] // CHECK: end_borrow [[BORROWED_PAYLOAD]] from [[PAYLOAD]] // CHECK: destroy_value [[COPY_B]] // CHECK: destroy_value [[PAYLOAD]] for (_, b) in xx {} // CHECK: bb15([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: [[BORROWED_PAYLOAD:%.*]] = begin_borrow [[PAYLOAD]] // CHECK: [[A:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 0 // CHECK: [[COPY_A:%.*]] = copy_value [[A]] // CHECK: [[B:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 1 // CHECK: [[COPY_B:%.*]] = copy_value [[B]] // CHECK: destroy_value [[COPY_B]] // CHECK: destroy_value [[COPY_A]] // CHECK: end_borrow [[BORROWED_PAYLOAD]] from [[PAYLOAD]] // CHECK: destroy_value [[PAYLOAD]] for (_, _) in xx {} // CHECK: bb19([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: [[BORROWED_PAYLOAD:%.*]] = begin_borrow [[PAYLOAD]] // CHECK: [[A:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 0 // CHECK: [[COPY_A:%.*]] = copy_value [[A]] // CHECK: [[B:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 1 // CHECK: [[COPY_B:%.*]] = copy_value [[B]] // CHECK: destroy_value [[COPY_B]] // CHECK: destroy_value [[COPY_A]] // CHECK: end_borrow [[BORROWED_PAYLOAD]] from [[PAYLOAD]] // CHECK: destroy_value [[PAYLOAD]] for _ in xx {} } // Make sure that when we have an unused value, we properly iterate over the // loop rather than run through the loop once. // // CHECK-LABEL: sil hidden @_T07foreach16unusedArgPatternySaySiGF : $@convention(thin) (@owned Array<Int>) -> () { // CHECK: bb0([[ARG:%.*]] : @owned $Array<Int>): // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: switch_enum [[OPT_VAL:%.*]] : $Optional<Int>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[VAL:%.*]] : @trivial $Int): // CHECK: [[LOOP_END_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_END_FUNC]] func unusedArgPattern(_ xx: [Int]) { for _ in xx { loopBodyEnd() } }
apache-2.0
0d875d0d549d5f631f4b83e39ebca2ab
34.939908
280
0.564416
3.275983
false
false
false
false
itssofluffy/NanoMessage
Sources/NanoMessage/Core/TransportMechanism.swift
1
3118
/* TransportMechanism.swift Copyright (c) 2016, 2017 Stephen Whittle All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import CNanoMessage import Foundation /// Transport mechanism. public enum TransportMechanism: CInt { case TCP // Transmission Control Protocol transport. case InProcess // In-process transport. case InterProcess // Inter-process communication transport. case WebSocket // Web socket transport. case UnSupported // Unsupported transport. public var rawValue: CInt { switch self { case .TCP: return NN_TCP case .InProcess: return NN_INPROC case .InterProcess: return NN_IPC case .WebSocket: return NN_WS case .UnSupported: return CInt.max } } public init(rawValue: CInt) { switch rawValue { case NN_TCP: self = .TCP case NN_INPROC: self = .InProcess case NN_IPC: self = .InterProcess case NN_WS: self = .WebSocket default: self = .UnSupported } } public init(url: URL) { switch url.scheme! { case "tcp": self = .TCP case "inproc": self = .InProcess case "ipc": self = .InterProcess case "ws": self = .WebSocket default: self = .UnSupported } } } extension TransportMechanism: CustomStringConvertible { public var description: String { switch self { case .TCP: return "tcp" case .InProcess: return "in-process" case .InterProcess: return "ipc" case .WebSocket: return "web-socket" case .UnSupported: return "unsupported" } } }
mit
ea37da403d1020598ec119a9ff38cdda
31.821053
80
0.583066
5.170813
false
false
false
false
seaburg/IGIdenticon
Identicon/JenkinsHash.swift
1
619
// // JenkinsHash.swift // Identicon // // Created by Evgeniy Yurtaev on 21/11/2016. // Copyright © 2016 Evgeniy Yurtaev. All rights reserved. // import Foundation func jenkinsHash(from data: Data) -> UInt32 { return data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> UInt32 in var hash: UInt32 = 0 for i in 0..<data.count { hash = hash &+ UInt32(bytes[i]) hash = hash &+ (hash << 10); hash ^= (hash >> 6); } hash = hash &+ (hash << 3); hash ^= (hash >> 11); hash = hash &+ (hash << 15); return hash } }
mit
b31f3470854eeb4265cc5e42704acd8e
23.72
78
0.535599
3.678571
false
false
false
false
playstones/NEKit
src/Crypto/CryptoHelper.swift
1
1845
import Foundation public struct CryptoHelper { public static let infoDictionary: [CryptoAlgorithm:(Int, Int)] = [ .AES128CFB: (16, 16), .AES192CFB: (24, 16), .AES256CFB: (32, 16), .CHACHA20: (32, 8), .SALSA20: (32, 8), .RC4MD5: (16, 16) ] public static func getKeyLength(_ methodType: CryptoAlgorithm) -> Int { return infoDictionary[methodType]!.0 } public static func getIVLength(_ methodType: CryptoAlgorithm) -> Int { return infoDictionary[methodType]!.1 } public static func getIV(_ methodType: CryptoAlgorithm) -> Data { var IV = Data(count: getIVLength(methodType)) _ = IV.withUnsafeMutableBytes { SecRandomCopyBytes(kSecRandomDefault, IV.count, $0) } return IV } public static func getKey(_ password: String, methodType: CryptoAlgorithm) -> Data { var result = Data(count: getIVLength(methodType) + getKeyLength(methodType)) let passwordData = password.data(using: String.Encoding.utf8)! var md5result = MD5Hash.final(password) var extendPasswordData = Data(count: passwordData.count + md5result.count) extendPasswordData.replaceSubrange(md5result.count..<extendPasswordData.count, with: passwordData) var length = 0 repeat { let copyLength = min(result.count - length, md5result.count) result.withUnsafeMutableBytes { md5result.copyBytes(to: $0.advanced(by: length), count: copyLength) } extendPasswordData.replaceSubrange(0..<md5result.count, with: md5result) md5result = MD5Hash.final(extendPasswordData) length += copyLength } while length < result.count return result.subdata(in: 0..<getKeyLength(methodType)) } }
bsd-3-clause
8f6c8a24671c10c3ae20c72fbf0ece85
36.653061
106
0.635772
4.174208
false
false
false
false
HTWDD/HTWDresden-iOS
HTWDD/Components/Grades/Models/Grade.swift
1
4726
// // Grade.swift // HTWDD // // Created by Mustafa Karademir on 27.09.19. // Copyright © 2019 HTW Dresden. All rights reserved. // import Foundation // MARK: - Codable struct Grade: Codable { let tries: Int let remark: Remark? let examNumber: Int let examDate: String? let typeOfExamination: String let credits: Double let grade: Int? let semester: Int let examination: String let state: State let id: Int // MARK: - Coding-Keys enum CodingKeys: String, CodingKey { case tries = "tries" case remark = "note" case examNumber = "nr" case examDate = "examDate" case typeOfExamination = "form" case credits = "credits" case grade = "grade" case semester = "semester" case examination = "text" case state = "state" case id = "id" } // MARK: - State enum State: String, Codable { case enrolled = "AN" case passed = "BE" case failed = "NB" case finalFailed = "EN" case unkown var localizedDescription: String { switch self { case .enrolled: return R.string.localizable.gradesStatusSignedUp() case .passed: return R.string.localizable.gradesStatusPassed() case .failed: return R.string.localizable.gradesStatusFailed() case .finalFailed: return R.string.localizable.gradesStatusUltimatelyFailed() default: return R.string.localizable.scheduleLectureTypeUnknown() } } } enum Remark: String, Codable { case recognised = "a" case unsubscribed = "e" case blocked = "g" case ill = "k" case notPermitted = "nz" case missedWithoutExcuse = "5ue" case notEntered = "5na" case notSecondRequested = "kA" case freeTrail = "PFV" case successfully = "mE" case failed = "N" case prepraticalOpen = "VPo" case volutaryDateNotMet = "f" case conditionally = "uV" case cheated = "TA" case unkown var localizedDescription: String { switch self { case .recognised: return R.string.localizable.gradesRemarkRecognized() case .unsubscribed: return R.string.localizable.gradesRemarkSignOff() case .blocked: return R.string.localizable.gradesRemarkBlocked() case .ill: return R.string.localizable.gradesRemarkIll() case .notPermitted: return R.string.localizable.gradesRemarkNotAllowed() case .missedWithoutExcuse: return R.string.localizable.gradesRemarkUnexcusedMissing() case .notEntered: return R.string.localizable.gradesRemarkNotStarted() case .notSecondRequested: return R.string.localizable.gradesRemarkNoRetest() case .freeTrail: return R.string.localizable.gradesRemarkFreeTry() case .successfully: return R.string.localizable.gradesRemarkWithSuccess() case .failed: return R.string.localizable.gradesRemarkFailed() case .prepraticalOpen: return R.string.localizable.gradesRemarkPrePlacement() case .volutaryDateNotMet: return R.string.localizable.gradesRemarkVoluntaryAppointment() case .conditionally: return R.string.localizable.gradesRemarkConditional() case .cheated: return R.string.localizable.gradesRemarkAttempt() default: return R.string.localizable.gradesRemarkUnkown() } } } } // MARK: - Equatable extension Grade: Equatable { static func ==(lhs: Grade, rhs: Grade) -> Bool { return lhs.id == rhs.id && lhs.tries == rhs.tries && lhs.examNumber == rhs.examNumber && lhs.credits == rhs.credits && lhs.state == rhs.state } } // MARK: - Comparable extension Grade: Comparable { static func < (lhs: Grade, rhs: Grade) -> Bool { guard let lhsDate = lhs.examDate else { return false } guard let rhsDate = rhs.examDate else { return false } return lhsDate < rhsDate } }
gpl-2.0
3970f6cd157571159b16b295d18fef98
33.23913
89
0.543915
4.678218
false
false
false
false
WSDOT/wsdot-ios-app
wsdot/BridgeAlertsRealmStore.swift
2
4895
// // BridgeAlertsRealmStore.swift // WSDOT // // Copyright (c) 2021 Washington State Department of Transportation // // 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 RealmSwift import Alamofire import SwiftyJSON class BridgeAlertsStore { typealias UpdateBridgeAlertsCompletion = (_ error: Error?) -> () static func findBridgeAlert(withId: Int) -> BridgeAlertItem? { let realm = try! Realm() let alertItem = realm.object(ofType: BridgeAlertItem.self, forPrimaryKey: withId) return alertItem } static func getAllBridgeAlerts() -> [BridgeAlertItem]{ let realm = try! Realm() let alertItems = realm.objects(BridgeAlertItem.self).filter("delete == false") return Array(alertItems) } static func updateBridgeAlerts(_ force: Bool, completion: @escaping UpdateBridgeAlertsCompletion) { DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { var delta = CachesStore.updateTime let deltaUpdated = (Calendar.current as NSCalendar).components(.second, from: CachesStore.getUpdatedTime(CachedData.bridgeAlerts), to: Date(), options: []).second if let deltaValue = deltaUpdated { delta = deltaValue } if ((delta > CachesStore.bridgeCacheTime) || force) { let request = NetworkUtils.getJSONRequestNoLocalCache(forUrl: "https://data.wsdot.wa.gov/mobile/BridgeOpenings.js") AF.request(request).validate().responseJSON { response in switch response.result { case .success: if let value = response.data { DispatchQueue.global().async { let json = JSON(value) self.saveBridgeAlerts(json) CachesStore.updateTime(CachedData.bridgeAlerts, updated: Date()) completion(nil) } } case .failure(let error): print("error") print(error) completion(error) } } } else { completion(nil) } } } fileprivate static func saveBridgeAlerts(_ json: JSON){ let realm = try! Realm() let newAlerts = List<BridgeAlertItem>() for (_, alertJson):(String, JSON) in json { let alert = BridgeAlertItem() alert.alertId = alertJson["BridgeOpeningId"].intValue alert.bridge = alertJson["BridgeLocation"]["Description"].stringValue alert.descText = alertJson["EventText"].stringValue alert.latitude = alertJson["BridgeLocation"]["Latitude"].doubleValue alert.longitude = alertJson["BridgeLocation"]["Longitude"].doubleValue if let timeJsonStringValue = alertJson["OpeningTime"].string { do { alert.openingTime = try TimeUtils.formatTimeStamp(timeJsonStringValue, dateFormat: "yyyy-MM-dd'T'HH:mm:ss") //ex. 2021-04-06T22:00:00 } catch { print("error formatting date") } } alert.localCacheDate = Date() newAlerts.append(alert) } let oldAlerts = getAllBridgeAlerts() do { try realm.write{ for alert in oldAlerts { alert.delete = true } realm.add(newAlerts, update: .all) } }catch{ print("BridgeAlertsStore.saveAlerts: Realm write error") } } static func flushOldData() { let realm = try! Realm() let alerts = realm.objects(BridgeAlertItem.self).filter("delete == true") do { try realm.write{ realm.delete(alerts) } }catch{ print("BridgeAlertsStore.flushOldData: Realm write error") } } }
gpl-3.0
7ccded854e09449d2b6c2728b71559ea
34.992647
174
0.557712
5.109603
false
false
false
false
nwspeete-ibm/openwhisk
mobile/iOS/starterapp/OpenWhiskStarterApp/Utils.swift
1
1816
/* * Copyright 2015-2016 IBM Corporation * * 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 func convertReply(input: [String:AnyObject]) -> [String:Any] { var output = [String:Any]() for (key, value) in input { if let value = value as? [[String: AnyObject]] { var newValue = [[String:Any]]() for dict in value { var newDict = [String:Any]() for (key2, value2) in dict { newDict[key2] = value2 } newValue.append(newDict) } output[key] = newValue } } return output } func filterForecast(args:[String:Any]) -> [String:Any] { let NumDays = 2 var filteredForecasts = [[String:Any]]() if let forecasts = args["forecasts"] as? [[String:Any]] { for day in 0...(NumDays - 1) { let forecast = forecasts[day] as [String:Any] var terse = [String:Any]() terse["dow"] = forecast["dow"] terse["narrative"] = forecast["narrative"] terse["min_temp"] = forecast["min_temp"] terse["max_temp"] = forecast["max_temp"] filteredForecasts.append(terse) } } return [ "forecasts": filteredForecasts ] }
apache-2.0
0e879d1878a5375758596dd53665cc63
30.310345
75
0.586454
4.099323
false
false
false
false
PGSSoft/AutoMate
AutoMate/XCTest extensions/XCUIElementQuery+Locator.swift
1
9228
// // XCUIElementQuery+Locator.swift // AutoMate // // Created by Bartosz Janda on 31.03.2017. // Copyright © 2017 PGS Software. All rights reserved. // import Foundation import XCTest public extension XCUIElementQuery { // MARK: Locator methods /// Returns `XCUIElement` that matches the type and locator. /// /// **Example:** /// /// ```swift /// let button = app.buttons[Locators.ok] /// ``` /// /// - Parameter locator: `Locator` used to find element subscript(locator: Locator) -> XCUIElement { return self[locator.identifier] } /// Returns element with label matching provided string. /// /// - note: /// String matching is customizable with operators available in `NSPredicate` specification. /// Check the `StringComparisonOperator` for available options. /// /// **Example:** /// /// ```swift /// let text = app.staticTexts.element(withLabelMatchingLocator: Locators.john, comparisonOperator: .like) /// XCTAssertTrue(text.exists) /// ``` /// /// - Parameters: /// - locator: Locator to search for. /// - comparisonOperator: Operation to use when performing comparison. /// - Returns: `XCUIElement` that label matches given locator. func element(withLabelMatchingLocator locator: Locator, comparisonOperator: StringComparisonOperator = .equals) -> XCUIElement { return element(withLabelMatching: locator.identifier, comparisonOperator: comparisonOperator) } /// Returns element with identifier and label matching provided values. /// /// Can be used to find a cell which `UILabel`, with provided `identifier`, contains text provided by `label`. /// /// - note: /// String matching is customizable with operators available in `NSPredicate` specification. /// Check the `StringComparisonOperator` for available options. /// /// **Example:** /// /// ```swift /// let label = app.staticTexts.element(withLocator: Locators.title, label: Locators.madeWithLove) /// ``` /// /// - Parameters: /// - locator: Identifier of element to search for. /// - label: Label of element to search for. /// - labelComparisonOperator: Operation to use when performing comparison. /// - Returns: `XCUIElement` that identifier and label match to given locators. func element(withLocator locator: Locator, label: Locator, labelComparisonOperator: StringComparisonOperator = .equals) -> XCUIElement { return element(withLocator: locator, label: label.identifier, labelComparisonOperator: labelComparisonOperator) } /// Returns element with identifier and label matching provided values. /// /// Can be used to find a cell which `UILabel`, with provided `identifier`, contains text provided by `label`. /// /// - note: /// String matching is customizable with operators available in `NSPredicate` specification. /// Check the `StringComparisonOperator` for available options. /// /// **Example:** /// /// ```swift /// let label = app.staticTexts.element(withLocator: Locators.title, label: "Made with love") /// ``` /// /// - Parameters: /// - locator: Identifier of element to search for. /// - label: Label of element to search for. /// - labelComparisonOperator: Operation to use when performing comparison. /// - Returns: `XCUIElement` that identifier and label match to given locator and text. func element(withLocator locator: Locator, label: String, labelComparisonOperator: StringComparisonOperator = .equals) -> XCUIElement { return element(withIdentifier: locator.identifier, label: label, labelComparisonOperator: labelComparisonOperator) } /// Returns element with identifier and label matching one of provided values. /// /// Can be used to find a `UILabel` with given identifier and localized labels. /// Localized texts are provided in the `labels` parameter. /// /// - note: /// String matching is customizable with operators available in `NSPredicate` specification. /// Check the `StringComparisonOperator` for available options. /// /// **Example:** /// /// ```swift /// let label = app.staticTexts.element(withLocator: Locators.title, labels: ["Z miłością przez", "Made with love by"]) /// ``` /// /// - Parameters: /// - locator: Identifier of element to search for. /// - labels: Labels of element to search for. /// - labelComparisonOperator: Operation to use when performing comparison. /// - Returns: `XCUIElement` that identifier and label match given texts. func element(withLocator locator: Locator, labels: [String], labelComparisonOperator: StringComparisonOperator = .equals) -> XCUIElement { return element(withIdentifier: locator.identifier, labels: labels, labelComparisonOperator: labelComparisonOperator) } /// Returns element that contains children matching provided locator-label dictionary. /// /// Searches for element that has sub-elements matching provided "locator:label" pairs. /// Especially useful for table views and collection views where cells will have the same identifier. /// /// - note: /// String matching is customizable with operators available in `NSPredicate` specification. /// Check the `StringComparisonOperator` for available options. /// /// - note: This method is intended to be used with table and collection views, where cells have to be identified by their contents. /// /// **Example:** /// /// ```swift /// let tableView = app.tables.element /// let cell = tableView.cells.element(containingLabels: [Locators.name: "John*", Locators.email: "*.com"], labelsComparisonOperator: .like) /// XCTAssertTrue(cell.exists) /// ``` /// /// - Parameters: /// - dictionary: Dictionary of locators and labels to search for. /// - labelsComparisonOperator: Operation to use when performing comparison. /// - Returns: `XCUIElement` that identifiers and labels match to given locators and texts. func element <LocatorItem: Locator> (containingLabels dictionary: [LocatorItem: String], labelsComparisonOperator: StringComparisonOperator = .equals) -> XCUIElement { let dict = dictionary.reduce([:]) { $0.union([$1.key.identifier: $1.value]) } return element(containingLabels: dict, labelsComparisonOperator: labelsComparisonOperator) } /// Returns element that contains children matching provided locator-label dictionary. /// /// Searches for element that has sub-elements matching provided "locator:label" pairs. /// Especially useful for table views and collection views where cells will have the same identifier. /// /// - note: /// String matching is customizable with operators available in `NSPredicate` specification. /// Check the `StringComparisonOperator` for available options. /// /// - note: This method is intended to be used with table and collection views, where cells have to be identified by their contents. /// /// **Example:** /// /// ```swift /// let tableView = app.tables.element /// let cell = tableView.cells.element(containingLabels: [Locators.name: ["John*", "Jan*"], Locators.email: ["Free*", "Wolny*"]], labelsComparisonOperator: .like) /// XCTAssertTrue(cell.exists) /// ``` /// /// - Parameters: /// - dictionary: Dictionary of locators and labels to search for. /// - labelsComparisonOperator: Operation to use when performing comparison. /// - Returns: `XCUIElement` that identifiers and labels match to given locators and texts. func element <LocatorItem: Locator> (containingLabels dictionary: [LocatorItem: [String]], labelsComparisonOperator: StringComparisonOperator = .equals) -> XCUIElement { let dict = dictionary.reduce([:]) { $0.union([$1.key.identifier: $1.value]) } return element(containingLabels: dict, labelsComparisonOperator: labelsComparisonOperator) } // MARK: Locator shorted methods /// Returns element with label which begins with provided Locator. /// /// **Example:** /// /// ```swift /// let text = app.staticTexts.element(withLabelPrefixed: Locators.john) /// XCTAssertTrue(text.exists) /// ``` /// /// - Parameter locator: Object conforming to Locator. /// - Returns: `XCUIElement` that label begins with given locator. func element(withLabelPrefixed locator: Locator) -> XCUIElement { return element(withLabelPrefixed: locator.identifier) } /// Returns element with label which contains provided Locator. /// /// **Example:** /// /// ```swift /// let text = app.staticTexts.element(withLabelContaining: Locators.john) /// XCTAssertTrue(text.exists) /// ``` /// /// - Parameter locator: Object conforming to Locator. /// - Returns: `XCUIElement` that label contains given locator. func element(withLabelContaining locator: Locator) -> XCUIElement { return element(withLabelContaining: locator.identifier) } }
mit
58a764fe54153fa0d1f5d4ffb574acad
44.215686
173
0.673135
4.749743
false
false
false
false
yonadev/yona-app-ios
Yona/Yona/NewDeviceRequestManager.swift
1
7840
// // NewDeviceRequestManager.swift // Yona // // Created by Ben Smith on 28/04/16. // Copyright © 2016 Yona. All rights reserved. // import Foundation //MARK: - New Device Requests APIService class NewDeviceRequestManager { let APIService = APIServiceManager.sharedInstance let APIUserRequestManager = UserRequestManager.sharedInstance static let sharedInstance = NewDeviceRequestManager() fileprivate init() {} func genericHelper(_ httpMethod: httpMethods, addDeviceCode: String?, mobileNumber: String?, onCompletion: @escaping APIUserResponse) { switch httpMethod { case httpMethods.put: UserRequestManager.sharedInstance.getUser(GetUserRequest.notAllowed) { (success, message, code, user) in //success so get the user? if success { if let path = user?.newDeviceRequestsLink{ var bodyNewDevice: BodyDataDictionary? if let password = addDeviceCode { bodyNewDevice = ["newDeviceRequestPassword": password] as BodyDataDictionary } self.APIService.callRequestWithAPIServiceResponse(bodyNewDevice, path: path, httpMethod: httpMethods.put, onCompletion: { (success, json, error) in onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error), nil) }) } else { onCompletion(false, YonaConstants.serverMessages.FailedToGetDeviceRequestLink, String(responseCodes.internalErrorCode.rawValue), nil) } } // else { // onCompletion(false , YonaConstants.serverMessages.FailedToRetrieveGetUserDetails, String(responseCodes.internalErrorCode), nil) // } } case httpMethods.get: let langId = (Locale.current as NSLocale).object(forKey: NSLocale.Key.languageCode) as! String let countryId = (Locale.current as NSLocale).object(forKey: NSLocale.Key.countryCode) as! String let language = "\(langId)-\(countryId)" //need to call manager directly because of different response header if let password = addDeviceCode { let httpHeader = ["Content-Type": "application/json", "Accept-Language": language, "Yona-NewDeviceRequestPassword": password] //need to create the new device request URL on the other device as we only have the mobile number to get the device request, also user needs to enter password that appears on their other device if let mobileNumber = mobileNumber { let path = YonaConstants.commands.newDeviceRequests + mobileNumber.replacePlusSign() //non are optional here so you cannot put in check (the if let bit) Manager.sharedInstance.makeRequest(path, body: nil, httpMethod: httpMethod, httpHeader: httpHeader, onCompletion: { success, dict, error in guard success == true else { onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error),nil) return } //Update user details locally if let json = dict { self.APIUserRequestManager.newUser = Users.init(userData: json) } //send back user object onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error), self.APIUserRequestManager.newUser) }) } } case httpMethods.delete: UserRequestManager.sharedInstance.getUser(GetUserRequest.allowed) { (success, message, code, user) in //success so get the user? if success { if let path = user?.newDeviceRequestsLink { self.APIService.callRequestWithAPIServiceResponse(nil, path: path, httpMethod: httpMethod, onCompletion: { (success, json, error) in onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error), nil) }) } else { onCompletion(false, YonaConstants.serverMessages.FailedToGetDeviceRequestLink, String(responseCodes.internalErrorCode.rawValue), nil) } } else { onCompletion(false , YonaConstants.serverMessages.FailedToRetrieveGetUserDetails, String(responseCodes.internalErrorCode.rawValue), nil) } } default: break } } /** Add a new device from device A by calling this, password generated randomly, will be sent to device B - parameter onCompletion: APIResponse, returns success or fail of the method and server messages - return none */ func putNewDevice(_ onCompletion: @escaping APIGetDeviceResponse) { let addDevicePassCode = String().randomAlphaNumericString() //generate random alphanumeric code self.genericHelper(httpMethods.put, addDeviceCode: addDevicePassCode, mobileNumber: nil) { (success, message, code, nil) in if success { onCompletion(true, message, code, addDevicePassCode) } else { onCompletion(false, message, code, addDevicePassCode) } } } /** Device B gets the password, user enters password, UI calls this method passing in password, response is the user info generated from the already created account...used to get more user info when requested as the SELF link is tored - parameter password: String Password sent from device A to this device B - parameter onCompletion: APIResponse, returns success or fail of the method and server messages - return none */ func getNewDevice(_ password: String, mobileNumber: String, onCompletion: @escaping APIUserResponse) { //create a password for the user self.genericHelper(httpMethods.get, addDeviceCode: password, mobileNumber: mobileNumber) { (success, message, code, user) in if success { onCompletion(true, message, code, user) } else { onCompletion(false, message, code, nil) } } } /** Used to delete new device request after it has been verified, passes back success or fail - parameter onCompletion: APIResponse, returns success or fail of the method and server messages - return none */ func deleteNewDevice(_ onCompletion: @escaping APIResponse) { self.genericHelper(httpMethods.delete, addDeviceCode: nil, mobileNumber: nil) { (success, message, code, nil) in if success { onCompletion(true, message, code) } else { onCompletion(false, message, code) } } } }
mpl-2.0
3191cedcbbe92007997a578cc43231cd
55.395683
235
0.575966
6.048611
false
false
false
false
eduarenas/GithubClient
Sources/GitHubClient/Models/Response/Organization.swift
1
2645
// // Organization.swift // GitHubClient // // Created by Eduardo Arenas on 4/23/18. // import Foundation public struct Organization: Decodable { public let id: Int public let login: String public let url: String public let reposUrl: String public let eventsUrl: String public let hooksUrl: String public let issuesUrl: String public let membersUrl: String public let publicMembersUrl: String public let avatarUrl: String public let description: String? public let name: String? public let company: String? public let blog: String? public let location: String? public let email: String? public let hasOrganizationProjects: Bool? public let hasRepositoryProjects: Bool? public let publicRepos: Int? public let publicGists: Int? public let followers: Int? public let following: Int? public let htmlUrl: String? public let createdAt: Date? public let updatedAt: Date? public let type: String? // TODO: strong type public let totalPrivateRepos: Int? public let ownedPrivateRepos: Int? public let privateGists: Int? public let diskUsage: Int? public let collaborators: Int? public let billingEmail: String? public let plan: Plan? public let defaultRepositoryPermission: String? // TODO: strong type public let membersCanCreateRepositories: Bool? public let twoFactorRequirementEnabled: Bool? } extension Organization { enum CodingKeys: String, CodingKey { case id case login case url case reposUrl = "repos_url" case eventsUrl = "events_url" case hooksUrl = "hooks_url" case issuesUrl = "issues_url" case membersUrl = "members_url" case publicMembersUrl = "public_members_url" case avatarUrl = "avatar_url" case description case name case company case blog case location case email case hasOrganizationProjects = "has_organization_projects" case hasRepositoryProjects = "has_repository_projects" case publicRepos = "public_repos" case publicGists = "public_gists" case followers case following case htmlUrl = "html_url" case createdAt = "created_at" case updatedAt = "updated_at" case type case totalPrivateRepos = "total_private_repos" case ownedPrivateRepos = "owned_private_repos" case privateGists = "private_gists" case diskUsage = "disk_usage" case collaborators case billingEmail = "billing_email" case plan case defaultRepositoryPermission = "default_repository_permission" case membersCanCreateRepositories = "members_can_create_repositories" case twoFactorRequirementEnabled = "two_factor_requirement_enabled" } }
mit
1a7133195cb9e975aff2a2ba61dc471a
29.056818
73
0.728922
4.211783
false
false
false
false
SonnyBrooks/ProjectEulerSwift
ProjectEulerSwift/Problem21.swift
1
1600
// // Problem21.swift // ProjectEulerSwift // https://projecteuler.net/problem=21 // // Created by Andrew Budziszek on 12/22/16. // Copyright © 2016 Andrew Budziszek. All rights reserved. // //Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). //If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. // //For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. // //Evaluate the sum of all the amicable numbers under 10000. // import Foundation class Problem21 { var sumOfAmicableNumbers = 0 var alreadyObserved : [Int] = [] func AmicableNumbers() -> Int{ var count = 2 while count <= 10000 { let a = sumOfDivisors(count) let b = sumOfDivisors(a) if b == count && a != b && !alreadyObserved.contains(count) { alreadyObserved.append(a) alreadyObserved.append(b) sumOfAmicableNumbers += a + b } count += 1 } return sumOfAmicableNumbers } func sumOfDivisors(_ n: Int) -> Int { var sum = 0 if n / 2 > 0 { for i in 1...n / 2 { if n % i == 0 { sum += i } } } else { return 0 } return sum } }
mit
e70a476afed3f919225684bd713d63ab
26.534483
182
0.522229
3.671264
false
false
false
false
benlangmuir/swift
test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-enum-1argument-1distinct_use.swift
14
3027
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main9NamespaceO5ValueOySS_SiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main9NamespaceO5ValueOySS_SiGWV", i32 0, i32 0) // CHECK-SAME: [[INT]] 513, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main9NamespaceO5ValueOMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ), // CHECK-SAME: %swift.type* @"$sSSN", // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] enum Namespace<Arg> { enum Value<First> { case first(First) } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"( // CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}}, // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main9NamespaceO5ValueOySS_SiGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ) // CHECK-SAME: ) // CHECK: } func doit() { consume( Namespace<String>.Value.first(13) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceO5ValueOMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( // CHECK-SAME: [[INT]] %0, // CHECK-SAME: i8* [[ERASED_TYPE_1]], // CHECK-SAME: i8* [[ERASED_TYPE_2]], // CHECK-SAME: i8* undef, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main9NamespaceO5ValueOMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ) // CHECK-SAME: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
a59df55ec8dfb74c3f361f34a87e04ba
37.316456
157
0.595309
3.008946
false
false
false
false
ealeksandrov/SomaFM-miniplayer
Source/ViewControllers/PreferencesViewController.swift
1
1014
// // PreferencesViewController.swift // // Copyright © 2017 Evgeny Aleksandrov. All rights reserved. import Cocoa class PreferencesViewController: NSViewController { @IBOutlet weak var startAtLoginButton: NSButton! @IBOutlet weak var versionLabel: NSTextField! override func viewDidLoad() { super.viewDidLoad() startAtLoginButton.state = StartAtLogin.isEnabled ? .on : .off if let shortVersionString: String = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String, let buildVersionString: String = Bundle.main.infoDictionary?["CFBundleVersion"] as? String { versionLabel.stringValue = "Version \(shortVersionString) (\(buildVersionString))" } } @IBAction func tapStartAtLogin(_ sender: NSButton) { StartAtLogin.isEnabled = sender.state == .on } @IBAction func updateSortOrder(_ sender: NSPopUpButton) { NotificationCenter.default.post(name: .somaApiChannelsUpdated, object: nil) } }
mit
6b88ba3b71ef85851c2daf0dcb5f3c8b
31.677419
113
0.70385
4.990148
false
false
false
false
LawrenceHan/Games
CapNap/CapNap/BedNode.swift
1
548
// // BedNode.swift // CapNap // // Created by Hanguang on 6/6/16. // Copyright © 2016 Hanguang. All rights reserved. // import SpriteKit class BedNode: SKSpriteNode, CustomNodeEvents { func didMoveToScene() { print("bed added to scene") let bedBodySize = CGSize(width: 40.0, height: 30.0) physicsBody = SKPhysicsBody(rectangleOfSize: bedBodySize) physicsBody!.dynamic = false physicsBody!.categoryBitMask = PhysicsCategory.Bed physicsBody!.collisionBitMask = PhysicsCategory.None } }
mit
9c14b79c023bb822e38462118f6c2fea
26.35
65
0.680073
4.175573
false
false
false
false
OscarSwanros/swift
test/SILGen/guaranteed_closure_context.swift
2
3224
// RUN: %target-swift-frontend -parse-as-library -emit-silgen -enable-guaranteed-closure-contexts %s | %FileCheck %s func use<T>(_: T) {} func escape(_ f: () -> ()) {} protocol P {} class C: P {} struct S {} // CHECK-LABEL: sil hidden @_T026guaranteed_closure_context0A9_capturesyyF func guaranteed_captures() { // CHECK: [[MUTABLE_TRIVIAL_BOX:%.*]] = alloc_box ${ var S } var mutableTrivial = S() // CHECK: [[MUTABLE_RETAINABLE_BOX:%.*]] = alloc_box ${ var C } var mutableRetainable = C() // CHECK: [[MUTABLE_ADDRESS_ONLY_BOX:%.*]] = alloc_box ${ var P } var mutableAddressOnly: P = C() // CHECK: [[IMMUTABLE_TRIVIAL:%.*]] = apply {{.*}} -> S let immutableTrivial = S() // CHECK: [[IMMUTABLE_RETAINABLE:%.*]] = apply {{.*}} -> @owned C let immutableRetainable = C() // CHECK: [[IMMUTABLE_ADDRESS_ONLY:%.*]] = alloc_stack $P let immutableAddressOnly: P = C() func captureEverything() { use((mutableTrivial, mutableRetainable, mutableAddressOnly, immutableTrivial, immutableRetainable, immutableAddressOnly)) } // CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]] // CHECK: [[IMMUTABLE_AO_BOX:%.*]] = alloc_box ${ var P } // CHECK: [[FN:%.*]] = function_ref [[FN_NAME:@_T026guaranteed_closure_context0A9_capturesyyF17captureEverythingL_yyF]] // CHECK: apply [[FN]]([[MUTABLE_TRIVIAL_BOX]], [[MUTABLE_RETAINABLE_BOX]], [[MUTABLE_ADDRESS_ONLY_BOX]], [[IMMUTABLE_TRIVIAL]], [[IMMUTABLE_RETAINABLE]], [[IMMUTABLE_AO_BOX]]) captureEverything() // CHECK: destroy_value [[IMMUTABLE_AO_BOX]] // CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]] // -- partial_apply still takes ownership of its arguments. // CHECK: [[FN:%.*]] = function_ref [[FN_NAME]] // CHECK: [[MUTABLE_TRIVIAL_BOX_COPY:%.*]] = copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK: [[MUTABLE_RETAINABLE_BOX_COPY:%.*]] = copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK: [[MUTABLE_ADDRESS_ONLY_BOX_COPY:%.*]] = copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK: [[IMMUTABLE_RETAINABLE_COPY:%.*]] = copy_value [[IMMUTABLE_RETAINABLE]] // CHECK: [[IMMUTABLE_AO_BOX:%.*]] = alloc_box ${ var P } // CHECK: [[CLOSURE:%.*]] = partial_apply {{.*}}([[MUTABLE_TRIVIAL_BOX_COPY]], [[MUTABLE_RETAINABLE_BOX_COPY]], [[MUTABLE_ADDRESS_ONLY_BOX_COPY]], [[IMMUTABLE_TRIVIAL]], [[IMMUTABLE_RETAINABLE_COPY]], [[IMMUTABLE_AO_BOX]]) // CHECK: [[CONVERT:%.*]] = convert_function [[CLOSURE]] // CHECK: apply {{.*}}[[CONVERT]] // CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]] // CHECK-NOT: destroy_value [[IMMUTABLE_AO_BOX]] escape(captureEverything) } // CHECK: sil private [[FN_NAME]] : $@convention(thin) (@guaranteed { var S }, @guaranteed { var C }, @guaranteed { var P }, S, @guaranteed C, @guaranteed { var P })
apache-2.0
f445b5ff0fa9357739540aea6b651c45
45.057143
224
0.646712
3.586207
false
false
false
false
qvik/HelsinkiOS-IBD-Demo
HelsinkiOS-Demo/Views/Article/ArticleMeta.swift
1
872
// // ArticleMeta.swift // HelsinkiOS-Demo // // Created by Jerry Jalava on 29/09/15. // Copyright © 2015 Qvik. All rights reserved. // import UIKit @IBDesignable class ArticleMeta: DesignableXib { @IBOutlet weak var sourceLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var categoryLabel: UILabel! var article: Article? { didSet { setupView() } } @IBInspectable var showCategory: Bool = false { didSet { setupView() } } // MARK: Lifecycle override func setupView() { categoryLabel.hidden = !showCategory if let article = article { sourceLabel.text = article.source timeLabel.text = article.createdAt categoryLabel.text = article.category.uppercaseString } } }
mit
819fb3d065faf6b2dfb13e0fea61ca13
20.775
65
0.591274
4.632979
false
false
false
false
lyle-luan/firefox-ios
FxAClient/Frontend/SignIn/FxASignInWebViewController.swift
2
6684
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Snappy import UIKit import WebKit protocol FxASignInWebViewControllerDelegate { func signInWebViewControllerDidCancel(vc: FxASignInWebViewController) -> Void func signInWebViewControllerDidLoad(vc: FxASignInWebViewController) -> Void func signInWebViewControllerDidSignIn(vc: FxASignInWebViewController, data: JSON) -> Void func signInWebViewControllerDidFailProvisionalNavigation (vc: FxASignInWebViewController, withError error: NSError!) -> Void func signInWebViewControllerDidFailNavigation (vc: FxASignInWebViewController, withError error: NSError!) -> Void } /** * A controller that manages a single web view connected to the Firefox * Accounts (Desktop) Sync postMessage interface. * * The postMessage interface is not really documented, but it is simple * enough. I reverse engineered it from the Desktop Firefox code and the * fxa-content-server git repository. */ class FxASignInWebViewController: UIViewController, WKScriptMessageHandler, WKNavigationDelegate { private enum RemoteCommand: String { case CanLinkAccount = "can_link_account" case Loaded = "loaded" case Login = "login" case SessionStatus = "session_status" case SignOut = "sign_out" } var delegate: FxASignInWebViewControllerDelegate? var url: NSURL? private var webView: WKWebView! override func loadView() { super.loadView() } func startLoad(url: NSURL) { self.url = url loadWebView(url) } override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "SELdidCancel") view.addSubview(webView!) // Web content fills view. webView.snp_makeConstraints { make in make.edges.equalTo(self.view) return } } private func loadWebView(url: NSURL) { // Inject our setup code after the page loads. let source = getJS() let userScript = WKUserScript( source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true ) // Handle messages from the content server (via our user script). let contentController = WKUserContentController() contentController.addUserScript(userScript) contentController.addScriptMessageHandler( self, name: "accountsCommandHandler" ) let config = WKWebViewConfiguration() config.userContentController = contentController webView = WKWebView( frame: CGRectMake(0, 0, 0, 0), configuration: config ) webView.navigationDelegate = self webView.loadRequest(NSURLRequest(URL: url)) // Don't allow overscrolling. webView.scrollView.bounces = false } func SELdidCancel() { delegate?.signInWebViewControllerDidCancel(self) } // Send a message to the content server. func injectData(type: String, content: [String: AnyObject]) { let data = [ "type": type, "content": content, ] let json = JSON(data).toString(pretty: false) let script = "window.postMessage(\(json), '\(self.url)');" webView.evaluateJavaScript(script, completionHandler: nil) } private func onCanLinkAccount(data: JSON) { // // We need to confirm a relink - see shouldAllowRelink for more // let ok = shouldAllowRelink(accountData.email); let ok = true injectData("message", content: ["status": "can_link_account", "data": ["ok": ok]]); } // We're not signed in to a Firefox Account at this time, which we signal by returning an error. private func onSessionStatus(data: JSON) { injectData("message", content: ["status": "error"]) } // We're not signed in to a Firefox Account at this time. We should never get a sign out message! private func onSignOut(data: JSON) { injectData("message", content: ["status": "error"]) } // The user has signed in to a Firefox Account. We're done! private func onLogin(data: JSON) { injectData("message", content: ["status": "login"]) dismissViewControllerAnimated(true, completion: nil) self.delegate?.signInWebViewControllerDidSignIn(self, data: data) } // The content server page is ready to be shown. private func onLoaded(data: JSON) { delegate?.signInWebViewControllerDidLoad(self) } // Handle a message coming from the content server. func handleRemoteCommand(command: String, data: JSON) { if let command = RemoteCommand(rawValue: command) { switch (command) { case .Loaded: onLoaded(data) case .Login: onLogin(data) case .CanLinkAccount: onCanLinkAccount(data) case .SessionStatus: onSessionStatus(data) case .SignOut: onSignOut(data) } } else { NSLog("Unknown remote command '\(command)'; ignoring."); } } // Dispatch webkit messages originating from our child webview. func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if (message.name == "accountsCommandHandler") { let body = JSON(message.body) let detail = body["detail"] handleRemoteCommand(detail["command"].asString!, data: detail["data"]) } else { NSLog("Got unrecognized message \(message)") } } private func getJS() -> String { let fileRoot = NSBundle.mainBundle().pathForResource("FxASignIn", ofType: "js") return NSString(contentsOfFile: fileRoot!, encoding: NSUTF8StringEncoding, error: nil)! } func webView(webView: WKWebView!, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError!) { delegate?.signInWebViewControllerDidFailProvisionalNavigation(self, withError: error) } func webView(webView: WKWebView!, didFailNavigation navigation: WKNavigation!, withError error: NSError!) { delegate?.signInWebViewControllerDidFailNavigation(self, withError: error) } }
mpl-2.0
96e8406c9c46f2e4d6000fe1edf984fc
35.12973
147
0.654249
4.947446
false
false
false
false
bravelocation/yeltzland-ios
YeltzlandWidget/Views/InProgressView.swift
1
4122
// // InProgressView.swift // YeltzlandWidgetExtension // // Created by John Pollard on 12/06/2022. // Copyright © 2022 John Pollard. All rights reserved. // import WidgetKit import SwiftUI struct InProgressView: View { var data: WidgetTimelineData @Environment(\.widgetFamily) var widgetFamily var body: some View { VStack { Group { if data.first != nil { if widgetFamily == .systemSmall { TimelineFixtureView(fixture: data.first!) } else { InProgressGameView(fixture: data.first!) } } else { Text("No data available") } } if data.table != nil && widgetFamily == .systemLarge { Divider().background(Color("light-blue")) TableWidgetView(table: data.table!) Spacer() } }.padding() .foregroundColor(Color("light-blue")) .background(ContainerRelativeShape().fill(Color("yeltz-blue"))) } } #if DEBUG struct InProgressView_Previews: PreviewProvider { static var previews: some View { InProgressView(data: WidgetTimelineData( date: Date(), first: PreviewTimelineManager.buildPlaceholder(opponent: "Barnet (FAT QF)", home: false, date: "2020-02-29 15:00", teamScore: 2, opponentScore: 1, status: .inProgress), second: PreviewTimelineManager.buildPlaceholder(opponent: "Concord Rangers (FAT SF)", home: false, date: "2020-09-05 15:00", teamScore: nil, opponentScore: nil, status: .fixture), table: LeagueTableDataProvider.shared.table )).previewContext(WidgetPreviewContext(family: .systemSmall)) InProgressView(data: WidgetTimelineData( date: Date(), first: PreviewTimelineManager.buildPlaceholder(opponent: "Barnet (FAT QF)", home: false, date: "2020-02-29 15:00", teamScore: 0, opponentScore: 1, status: .inProgress), second: PreviewTimelineManager.buildPlaceholder(opponent: "Concord Rangers (FAT SF)", home: false, date: "2020-09-05 15:00", teamScore: nil, opponentScore: nil, status: .fixture), table: LeagueTableDataProvider.shared.table )).previewContext(WidgetPreviewContext(family: .systemMedium)) InProgressView(data: WidgetTimelineData( date: Date(), first: PreviewTimelineManager.buildPlaceholder(opponent: "Barnet (FAT QF)", home: false, date: "2020-02-29 15:00", teamScore: 0, opponentScore: 1, status: .inProgress), second: PreviewTimelineManager.buildPlaceholder(opponent: "Concord Rangers (FAT SF)", home: false, date: "2020-09-05 15:00", teamScore: nil, opponentScore: nil, status: .fixture), table: LeagueTableDataProvider.shared.table )).previewContext(WidgetPreviewContext(family: .systemLarge)) } } #endif
mit
85bcd95d6b63ba2d3e4527885df04b16
41.05102
97
0.449891
5.796062
false
false
false
false
bravelocation/yeltzland-ios
yeltzland/GameTimeTweetsViewController.swift
1
1510
// // GameTimeTweetsViewController.swift // Yeltzland // // Created by John Pollard on 01/11/2020. // Copyright © 2020 John Pollard. All rights reserved. // import UIKit class GameTimeTweetsViewController: UIViewController { let firebaseNotifications = FirebaseNotifications() @IBOutlet weak var enableButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.title = "Game Time Tweet Notifications" self.setButtonLayout() } @IBAction func enableButtonTouchUp(_ sender: Any) { self.firebaseNotifications.enabled.toggle() self.setButtonLayout() } private func setButtonLayout() { #if !targetEnvironment(macCatalyst) self.enableButton.backgroundColor = self.firebaseNotifications.enabled ? UIColor.systemRed : UIColor.systemGreen var buttonTextColor = UIColor.white if #available(iOS 13.0, *) { buttonTextColor = UIColor.systemBackground } self.enableButton.setTitleColor(buttonTextColor, for: .normal) self.enableButton.setTitleColor(buttonTextColor, for: .highlighted) self.enableButton.setTitleColor(buttonTextColor, for: .selected) self.enableButton.setTitleColor(buttonTextColor, for: .focused) #endif self.enableButton.layer.cornerRadius = 4.0 self.enableButton.setTitle(self.firebaseNotifications.enabled ? "Turn Off" : "Turn On", for: .normal) } }
mit
6243912b8f55489afe0231cf3f22865c
30.4375
120
0.675282
4.745283
false
false
false
false
Fenrikur/ef-app_ios
Eurofurence/Modules/Maps/Presenter/MapsPresenter.swift
1
1294
import Foundation class MapsPresenter: MapsSceneDelegate { private struct Binder: MapsBinder { var viewModel: MapsViewModel func bind(_ component: MapComponent, at index: Int) { let map = viewModel.mapViewModel(at: index) component.setMapName(map.mapName) map.fetchMapPreviewPNGData(completionHandler: component.setMapPreviewImagePNGData) } } private let scene: MapsScene private let interactor: MapsInteractor private let delegate: MapsModuleDelegate private var viewModel: MapsViewModel? init(scene: MapsScene, interactor: MapsInteractor, delegate: MapsModuleDelegate) { self.scene = scene self.interactor = interactor self.delegate = delegate scene.setMapsTitle(.maps) scene.setDelegate(self) } func mapsSceneDidLoad() { interactor.makeMapsViewModel { (viewModel) in self.viewModel = viewModel self.scene.bind(numberOfMaps: viewModel.numberOfMaps, using: Binder(viewModel: viewModel)) } } func simulateSceneDidSelectMap(at index: Int) { guard let identifier = viewModel?.identifierForMap(at: index) else { return } delegate.mapsModuleDidSelectMap(identifier: identifier) } }
mit
67f3159dfad4e21143a0f9f576a006e8
28.409091
102
0.680062
4.883019
false
false
false
false
SwiftOnTheServer/DrinkChooser
lib/Redis/Redis+List.swift
1
21209
/** * Copyright IBM Corporation 2016 * * 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 /// Extend Redis by adding the List operations extension Redis { // // MARK: List API functions // /// Retrieve an element from one of many lists, potentially blocking until one of /// the lists has an element /// /// - Parameter keys: The keys of the lists to check for an element. /// - Parameter timeout: The amount of time to wait or zero to wait forever. /// - Parameter callback: The callback function, when a time out didn't occur, the /// Array<RedisString> will contain two entries, the first one /// is the key of the list that had an element and the second /// entry is the value of that element. /// NSError will be non-nil if an error occurred. public func blpop(_ keys: String..., timeout: TimeInterval, callback: ([RedisString?]?, NSError?) -> Void) { var command = ["BLPOP"] for key in keys { command.append(key) } command.append(String(Int(timeout))) issueCommandInArray(command) {(response: RedisResponse) in self.redisStringArrayResponseHandler(response, callback: callback) } } /// Retrieve an element from the end of one of many lists, potentially blocking until /// one of the lists has an element /// /// - Parameter keys: The keys of the lists to check for an element. /// - Parameter timeout: The amount of time to wait or zero to wait forever. /// - Parameter callback: The callback function, when a time out didn't occur, the /// Array<RedisString> will contain two entries, the first one /// is the key of the list that had an element and the second /// entry is the value of that element. /// NSError will be non-nil if an error occurred. public func brpop(_ keys: String..., timeout: TimeInterval, callback: ([RedisString?]?, NSError?) -> Void) { var command = ["BRPOP"] for key in keys { command.append(key) } command.append(String(Int(timeout))) issueCommandInArray(command) {(response: RedisResponse) in self.redisStringArrayResponseHandler(response, callback: callback) } } /// Remove and return the last value of a list and push it onto another list, /// blocking until there is an element to pop /// /// - Parameter source: The list to pop an item from. /// - Parameter destination: The list to push the poped item onto. /// - Parameter timeout: The amount of time to wait or zero to wait forever. /// - Parameter callback: The callback function, when a time out didn't occur, the /// `RedisString` will contain the value of the element that /// was poped. NSError will be non-nil if an error occurred. public func brpoplpush(_ source: String, destination: String, timeout: TimeInterval, callback: (RedisString?, NSError?) -> Void) { issueCommand("BRPOPLPUSH", source, destination, String(Int(timeout))) {(response: RedisResponse) in self.redisStringResponseHandler(response, callback: callback) } } /// Retrieve an element from a list by index /// /// - Parameter key: The key. /// - Parameter index: The index of the element to retrieve. /// - Parameter callback: The callback function, the `RedisString` will contain the /// value of the element at the index. /// NSError will be non-nil if an error occurred. public func lindex(_ key: String, index: Int, callback: (RedisString?, NSError?) -> Void) { issueCommand("LINDEX", key, String(index)) {(response: RedisResponse) in self.redisStringResponseHandler(response, callback: callback) } } /// Insert a value into a list before or after a pivot /// /// - Parameter key: The key. /// - Parameter before: If true, the value is inserted before the pivot. /// - Parameter pivot: The pivot around which the value will be inserted. /// - Parameter value: The value to be inserted. /// - Parameter callback: The callback function, the Int will contain the length of /// the list after the insert or -1 if the pivot wasn't found. /// NSError will be non-nil if an error occurred. public func linsert(_ key: String, before: Bool, pivot: String, value: String, callback: (Int?, NSError?) -> Void) { issueCommand("LINSERT", key, (before ? "BEFORE" : "AFTER"), pivot, value) {(response: RedisResponse) in self.redisIntegerResponseHandler(response, callback: callback) } } /// Insert a value into a list before or after a pivot /// /// - Parameter key: The key. /// - Parameter before: If true, the value is inserted before the pivot. /// - Parameter pivot: The pivot, in the form of a `RedisString`, around which /// the value will be inserted. /// - Parameter value: The value, in the form of a `RedisString`, to be inserted. /// - Parameter callback: The callback function, the Int will contain the length of /// the list after the insert or -1 if the pivot wasn't found. /// NSError will be non-nil if an error occurred. public func linsert(_ key: String, before: Bool, pivot: RedisString, value: RedisString, callback: (Int?, NSError?) -> Void) { issueCommand(RedisString("LINSERT"), RedisString(key), RedisString(before ? "BEFORE" : "AFTER"), pivot, value) {(response: RedisResponse) in self.redisIntegerResponseHandler(response, callback: callback) } } /// Get the length of a list /// /// - Parameter key: The key. /// - Parameter callback: The callback function, the Int will contain the length of /// the list. NSError will be non-nil if an error occurred. public func llen(_ key: String, callback: (Int?, NSError?) -> Void) { issueCommand("LLEN", key) {(response: RedisResponse) in self.redisIntegerResponseHandler(response, callback: callback) } } /// Pop a value from a list /// /// - Parameter key: The key. /// - Parameter callback: The callback function, the RedisString will contain the value /// poped from the list. NSError will be non-nil if an error occurred. public func lpop(_ key: String, callback: (RedisString?, NSError?) -> Void) { issueCommand("LPOP", key) {(response: RedisResponse) in self.redisStringResponseHandler(response, callback: callback) } } /// Push a set of values on to a list /// /// - Parameter key: The key. /// - Parameter values: The set of the values to be pushed on to the list. /// - Parameter callback: The callback function, the Int will contain the /// length of the list after push. /// NSError will be non-nil if an error occurred. public func lpush(_ key: String, values: String..., callback: (Int?, NSError?) -> Void) { lpushArrayOfValues(key, values: values, callback: callback) } /// Push a set of values on to a list /// /// - Parameter key: The key. /// - Parameter values: An array of values to be pushed on to the list. /// - Parameter callback: The callback function, the Int will contain the /// length of the list after push. /// NSError will be non-nil if an error occurred. public func lpushArrayOfValues(_ key: String, values: [String], callback: (Int?, NSError?) -> Void) { var command = ["LPUSH", key] for value in values { command.append(value) } issueCommandInArray(command) {(response: RedisResponse) in self.redisIntegerResponseHandler(response, callback: callback) } } /// Push a set of values on to a list /// /// - Parameter key: The key. /// - Parameter values: The set of values, in the form of `RedisString`s, to be /// pushed on to the list. /// - Parameter callback: The callback function, the Int will contain the /// length of the list after push. /// NSError will be non-nil if an error occurred. public func lpush(_ key: String, values: RedisString..., callback: (Int?, NSError?) -> Void) { lpushArrayOfValues(key, values: values, callback: callback) } /// Push a set of values on to a list /// /// - Parameter key: The key. /// - Parameter values: The array of the values, in the form of `RedisString`s, /// to be pushed on to the list. /// - Parameter callback: The callback function, the Int will contain the /// length of the list after push. /// NSError will be non-nil if an error occurred. public func lpushArrayOfValues(_ key: String, values: [RedisString], callback: (Int?, NSError?) -> Void) { var command = [RedisString("LPUSH"), RedisString(key)] for value in values { command.append(value) } issueCommandInArray(command) {(response: RedisResponse) in self.redisIntegerResponseHandler(response, callback: callback) } } /// Push a value on to a list, only if the list exists /// /// - Parameter key: The key. /// - Parameter value: The value to be pushed on to the list. /// - Parameter callback: The callback function, the Int will contain the /// length of the list after push. /// NSError will be non-nil if an error occurred. public func lpushx(_ key: String, value: String, callback: (Int?, NSError?) -> Void) { issueCommand("LPUSHX", key, value) {(response: RedisResponse) in self.redisIntegerResponseHandler(response, callback: callback) } } /// Push a value on to a list, only if the list exists /// /// - Parameter key: The key. /// - Parameter values: The value, in the form of `RedisString`, to be pushed on to the list. /// - Parameter callback: The callback function, the Int will contain the /// length of the list after push. /// NSError will be non-nil if an error occurred. public func lpushx(_ key: String, value: RedisString, callback: (Int?, NSError?) -> Void) { issueCommand(RedisString("LPUSHX"), RedisString(key), value) {(response: RedisResponse) in self.redisIntegerResponseHandler(response, callback: callback) } } /// Retrieve a group of elements from a list as specified by a range /// /// - Parameter key: The key. /// - Parameter start: The index to start retrieving from. /// - Parameter end: The index to stop retrieving at. /// - Parameter callback: The callback function, the Array<RedisString> will contain the /// group of elements retrieved. /// NSError will be non-nil if an error occurred. public func lrange(_ key: String, start: Int, end: Int, callback: ([RedisString?]?, NSError?) -> Void) { issueCommand("LRANGE", key, String(start), String(end)) {(response: RedisResponse) in self.redisStringArrayResponseHandler(response, callback: callback) } } /// Remove a number of elements that match the supplied value from the list /// /// - Parameter key: The key. /// - Parameter count: The number of elements to remove. /// - Parameter value: The value of the elements to remove. /// - Parameter callback: The callback function, the Int will contain the /// number of elements that were removed. /// NSError will be non-nil if an error occurred. public func lrem(_ key: String, count: Int, value: String, callback: (Int?, NSError?) -> Void) { issueCommand("LREM", key, String(count), value) {(response: RedisResponse) in self.redisIntegerResponseHandler(response, callback: callback) } } /// Remove a number of elements that match the supplied value from the list /// /// - Parameter key: The key. /// - Parameter count: The number of elements to remove. /// - Parameter value: The value of the elemnts to remove in the form of a `RedisString`. /// - Parameter callback: The callback function, the Int will contain the /// number of elements that were removed. /// NSError will be non-nil if an error occurred. public func lrem(_ key: String, count: Int, value: RedisString, callback: (Int?, NSError?) -> Void) { issueCommand(RedisString("LREM"), RedisString(key), RedisString(count), value) {(response: RedisResponse) in self.redisIntegerResponseHandler(response, callback: callback) } } /// Set a value in a list to a new value /// /// - Parameter key: The key. /// - Parameter index: The index of the value in the list to be updated. /// - Parameter value: The new value for the element of the list. /// - Parameter callback: The callback function, the Bool will contain true /// if the list element was updated. /// NSError will be non-nil if an error occurred. public func lset(_ key: String, index: Int, value: String, callback: (Bool, NSError?) -> Void) { issueCommand("LSET", key, String(index), value) {(response: RedisResponse) in let (ok, error) = self.redisOkResponseHandler(response) callback(ok, _: error) } } /// Set a value in a list to a new value /// /// - Parameter key: The key. /// - Parameter index: The index of the value in the list to be updated. /// - Parameter value: The new value for the element of the list in the form of a `RedisString`. /// - Parameter callback: The callback function, the Bool will contain true /// if the list element was updated. /// NSError will be non-nil if an error occurred. public func lset(_ key: String, index: Int, value: RedisString, callback: (Bool, NSError?) -> Void) { issueCommand(RedisString("LSET"), RedisString(key), RedisString(index), value) {(response: RedisResponse) in let (ok, error) = self.redisOkResponseHandler(response) callback(ok, _: error) } } /// Trim a list to a new size /// /// - Parameter key: The key. /// - Parameter start: The index of the first element of the list to keep. /// - Parameter end: The index of the last element of the list to keep. /// - Parameter callback: The callback function, the Bool will contain true /// if the list was trimmed. /// NSError will be non-nil if an error occurred. public func ltrim(_ key: String, start: Int, end: Int, callback: (Bool, NSError?) -> Void) { issueCommand("LTRIM", key, String(start), String(end)) {(response: RedisResponse) in let (ok, error) = self.redisOkResponseHandler(response) callback(ok, _: error) } } /// Remove and return the last value of a list /// /// - Parameter key: The key. /// - Parameter callback: The callback function, the RedisString will contain the /// value poped from the list. /// NSError will be non-nil if an error occurred. public func rpop(_ key: String, callback: (RedisString?, NSError?) -> Void) { issueCommand("RPOP", key) {(response: RedisResponse) in self.redisStringResponseHandler(response, callback: callback) } } /// Remove and return the last value of a list and push it onto the front of another list /// /// - Parameter source: The list to pop an item from. /// - Parameter destination: The list to push the poped item onto. /// - Parameter callback: The callback function, the RedisString will contain the /// value poped from the source list. /// NSError will be non-nil if an error occurred. public func rpoplpush(_ source: String, destination: String, callback: (RedisString?, NSError?) -> Void) { issueCommand("RPOPLPUSH", source, destination) {(response: RedisResponse) in self.redisStringResponseHandler(response, callback: callback) } } /// Append a set of values to end of a list /// /// - Parameter key: The key. /// - Parameter values: The list of values to be pushed on to the list. /// - Parameter callback: The callback function, the Int will contain the /// length of the list after push. /// NSError will be non-nil if an error occurred. public func rpush(_ key: String, values: String..., callback: (Int?, NSError?) -> Void) { rpushArrayOfValues(key, values: values, callback: callback) } /// Append a set of values to a list /// /// - Parameter key: The key. /// - Parameter values: An array of values to be pushed on to the list. /// - Parameter callback: The callback function, the Int will contain the /// length of the list after push. /// NSError will be non-nil if an error occurred. public func rpushArrayOfValues(_ key: String, values: [String], callback: (Int?, NSError?) -> Void) { var command = ["RPUSH", key] for value in values { command.append(value) } issueCommandInArray(command) {(response: RedisResponse) in self.redisIntegerResponseHandler(response, callback: callback) } } /// Append a set of values to a list /// /// - Parameter key: The key. /// - Parameter values: The list of `RedisString` values to be pushed on to the list. /// - Parameter callback: The callback function, the Int will contain the /// length of the list after push. /// NSError will be non-nil if an error occurred. public func rpush(_ key: String, values: RedisString..., callback: (Int?, NSError?) -> Void) { rpushArrayOfValues(key, values: values, callback: callback) } /// Append a set of values to a list /// /// - Parameter key: The key. /// - Parameter values: An array of `RedisString` values to be pushed on to the list public func rpushArrayOfValues(_ key: String, values: [RedisString], callback: (Int?, NSError?) -> Void) { var command = [RedisString("RPUSH"), RedisString(key)] for value in values { command.append(value) } issueCommandInArray(command) {(response: RedisResponse) in self.redisIntegerResponseHandler(response, callback: callback) } } /// Append a value to a list, only if the list exists /// /// - Parameter key: The key. /// - Parameter values: The value to be pushed on to the list. /// - Parameter callback: The callback function, the Int will contain the /// length of the list after push. /// NSError will be non-nil if an error occurred. public func rpushx(_ key: String, value: String, callback: (Int?, NSError?) -> Void) { issueCommand("RPUSHX", key, value) {(response: RedisResponse) in self.redisIntegerResponseHandler(response, callback: callback) } } /// Append a value to a list, only if the list exists /// /// - Parameter key: The key. /// - Parameter values: The `RedisString` value to be pushed on to the list. /// - Parameter callback: The callback function, the Int will contain the /// length of the list after push. /// NSError will be non-nil if an error occurred. public func rpushx(_ key: String, value: RedisString, callback: (Int?, NSError?) -> Void) { issueCommand(RedisString("RPUSHX"), RedisString(key), value) {(response: RedisResponse) in self.redisIntegerResponseHandler(response, callback: callback) } } }
mit
eeaf2b83ec3263d92b8ed1571269fd14
48.903529
148
0.609175
4.547384
false
false
false
false
strivingboy/CocoaChinaPlus
Code/CocoaChinaPlus/Application/Business/Util/Helper/HTMLModel/Model/CCArticleModel.swift
1
2459
// // CCArticleModel.swift // CocoaChinaPlus // // Created by user on 15/10/30. // Copyright © 2015年 zixun. All rights reserved. // import Foundation class CCArticleModel: NSObject { //标题 var title : String? //发表时间 var postTime : String? { get { return _postTime } set { var str = newValue if (str != nil) { str = str!.stringByReplacingOccurrencesOfString("\t", withString: "") str = str!.stringByReplacingOccurrencesOfString("\r", withString: "") str = str!.stringByReplacingOccurrencesOfString("\n", withString: "") str = str!.stringByReplacingOccurrencesOfString("\n", withString: "") str = str!.stringByReplacingOccurrencesOfString("\n", withString: "") str = str!.stringByReplacingOccurrencesOfString(" ", withString: "") } _postTime = str } } //阅读次数 var viewed: String? //图片链接 var imageURL: String? //文章唯一标识 var identity: String! //文章链接 var linkURL : String { get { return _linkURL } set { _linkURL = CCURLHelper.generateWapURLFromURL(newValue) self.identity = CCURLHelper.generateIdentity(newValue) } } //数据库用字段 //文章收藏时间 var dateOfCollection:String? //文章阅读时间 var dateOfRead:String? //文章类型 var type:Int? private var _linkURL : String = "http://www.cocoachina.com" private var _postTime : String? } class CCPOptionModel: NSObject { var urlString: String var title: String = "" init(href: String, title:String) { self.urlString = "http://www.cocoachina.com\(href)" if title == "App Store研究" { self.title = "App Store" }else { self.title = title } super.init() } } class CCPHomeModel: NSObject { var page:[CCArticleModel]! var banners:[CCArticleModel] = [] var options:[CCPOptionModel] = [] convenience init(options:[CCPOptionModel], banners:[CCArticleModel], page:[CCArticleModel]) { self.init() self.options = options self.banners = banners self.page = page } }
mit
0e3752a7dc8d6c1552d51bdffa3ae25d
22.6
97
0.544915
4.486692
false
false
false
false
charlesvinette/FlickManager
Pod/Classes/FlickManager.swift
1
4580
// // FlickManager.swift // Pods // // Created by Charles Vinette on 2016-03-28. // // import UIKit class FlickManager: UIViewController, UIGestureRecognizerDelegate { // MARK:Constants let throwingThreshold: CGFloat = 1000 let throwingVelocityPadding: CGFloat = 10 //MARK Variables var leftButtonSize: Int = 120 var rightButtonSize: Int = 120 var tap: UIGestureRecognizer! var receivedView: UIView! var animator: UIDynamicAnimator! var originalBounds: CGRect! var originalCenter: CGPoint! var attachmentBehavior: UIAttachmentBehavior! var push: UIPushBehavior! var itemBehavior: UIDynamicItemBehavior! var popupMovedVertically:Bool! var leftButton:UIButton! var rightButton:UIButton! var didDragToLeft = false var didDragToRight = false //MARK: Initialization init(view:UIView){ super.init(nibName: nil, bundle: nil) self.view = view self.createWithView(view) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func createWithView(view:UIView){ let animator = UIDynamicAnimator(referenceView: self.view) self.animator = animator self.originalBounds = self.view.bounds self.originalCenter = self.view.center let panGesture = UIPanGestureRecognizer() panGesture.addTarget(self, action: "handleAttachmentGesture:") self.view.addGestureRecognizer(panGesture) //Right and Left Button let leftButton = UIButton() self.leftButton = leftButton leftButton.alpha = 0 self.view.addSubview(leftButton) let rightButton = UIButton() self.rightButton = rightButton self.view.addSubview(rightButton) } func handleAttachmentGesture(panGesture: UIPanGestureRecognizer) { let location = panGesture.locationInView(self.view) let boxLocation = panGesture.locationInView(self.view) let initialMidX = CGRectGetMidX(self.view.bounds) if panGesture.state == .Began { self.animator.removeAllBehaviors() let centerOffset = UIOffsetMake(boxLocation.x - CGRectGetMidX(self.view.bounds), boxLocation.y - CGRectGetMidY(self.view.bounds)) self.attachmentBehavior = UIAttachmentBehavior(item: self.view, offsetFromCenter: centerOffset, attachedToAnchor: location) self.animator.addBehavior(attachmentBehavior) } if panGesture.state == .Changed{ if self.view.frame.midX > initialMidX + 150{ //Right self.leftButton.alpha = (self.view.frame.midX - (initialMidX + 150)) * 0.03 if self.leftButton.alpha >= 1{ self.leftButton.alpha = 1 self.didDragToRight = true } }else if self.view.frame.midX < initialMidX - 150{ //Left self.rightButton.alpha = ((initialMidX - 150) - self.view.frame.midX) * 0.03 if self.rightButton.alpha >= 1{ self.rightButton.alpha = 1 self.didDragToLeft = true } } } if panGesture.state == .Ended { if self.view.frame.midX > initialMidX + 100{ //Right popupMovedVertically = false }else if self.view.frame.midX < initialMidX - 100{ //Left popupMovedVertically = false }else{ popupMovedVertically = true } UIView.animateWithDuration(0.3, animations: { self.leftButton.alpha = 0 self.rightButton.alpha = 0 }) self.animator.removeAllBehaviors() let velocity = panGesture.velocityInView(self.view) let magnitude: CGFloat = sqrt((CGFloat(velocity.x * velocity.x) + CGFloat(velocity.y * velocity.y))) if magnitude > throwingThreshold && popupMovedVertically { let push = UIPushBehavior(items: [self.view], mode: .Instantaneous) push.pushDirection = CGVectorMake((velocity.x / 10), (velocity.y / 10)) push.magnitude = magnitude / throwingVelocityPadding self.push = push self.animator.addBehavior(push) // self.performSelector("recenterView", withObject: nil, afterDelay: 0.4) self.dismissViewControllerAnimated(true, completion: nil) } else { // AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) self.recenterView() if didDragToLeft{ didDragToLeft = false rightButton.sendActionsForControlEvents(.TouchUpInside) } if didDragToRight{ didDragToRight = false leftButton.sendActionsForControlEvents(.TouchUpInside) } } } else { self.attachmentBehavior.anchorPoint = panGesture.locationInView(self.view) } } func recenterView() { self.animator.removeAllBehaviors() UIView.animateWithDuration(0.5) { () -> Void in self.view.bounds = self.view.bounds self.view.center = self.view.center self.view.transform = CGAffineTransformIdentity } } }
mit
3cfc6959bb097162a45e3ee326291c93
26.926829
132
0.718559
3.797678
false
false
false
false
icapps/ios-delirium
Example/Example for Delirium/Modules/Pie Chart/PieChartViewController.swift
1
1738
// // PieChartViewController.swift // Delirium // // Created by Jelle Vandebeeck on 23/08/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import Delirium class Slice: PieChartSlice { @objc var value: Float @objc var color: UIColor init(value: Float, color: UIColor) { self.value = value self.color = color } } class PieChartViewController: UIViewController { // MARK: - Outlets @IBOutlet var constraints: [NSLayoutConstraint]! @IBOutlet var chart: PieChartView! // MARK: - View flow override func viewDidLoad() { super.viewDidLoad() title = "Pie Chart" chart.overlayPadding = 25.0 chart.overlayColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.5) // Add slices to the chart. chart.add(slice: Slice(value: 5.46, color: UIColor(red:0.16,green:0.55,blue:0.55,alpha:1.00))) chart.add(slice: Slice(value: 12.41, color: UIColor(red:0.44,green:0.81,blue:0.80,alpha:1.00))) chart.add(slice: Slice(value: 16.71, color: UIColor(red:0.98,green:0.90,blue:0.40,alpha:1.00))) chart.add(slice: Slice(value: 4.02, color: UIColor(red:0.93,green:0.45,blue:0.20,alpha:1.00))) chart.add(slice: Slice(value: 23.72, color: UIColor(red:0.57,green:0.86,blue:0.63,alpha:1.00))) chart.add(slice: Slice(value: 37.67, color: UIColor(red:0.28,green:0.24,blue:0.25,alpha:1.00))) } // MARK: - Actions @IBAction func toggleSize(_ sender: AnyObject) { for constraint in constraints { constraint.priority = UILayoutPriority(rawValue: constraint.priority.rawValue == 800 ? 700 : 800) } } }
mit
b4b9a957e97e7abd33b0b33d58ecc790
30.017857
109
0.620035
3.340385
false
false
false
false
eface2face/cordova-plugin-iosrtc
src/PluginRTCRtpSender.swift
2
2371
import Foundation class PluginRTCRtpSender : NSObject { var rtpSender: RTCRtpSender var id: Int init(_ rtpSender: RTCRtpSender, _ id: Int) { self.rtpSender = rtpSender self.id = id != 0 ? id : Int.random(in: 0...10000) } func setParameters(_ params: [String : NSObject], _ callback: @escaping (_ data: NSDictionary) -> Void, _ errback: @escaping (_ error: Error) -> Void ) { let oldParameters : RTCRtpParameters! = rtpSender.parameters let newParameters : RTCRtpParameters! = RTCRtpParameters() newParameters.transactionId = oldParameters.transactionId let encodings = params["encodings"] as? [[String:Any]] if encodings != nil { for e in encodings! { let p : RTCRtpEncodingParameters = RTCRtpEncodingParameters() if e["maxBitrate"] as? NSNumber != nil { p.maxBitrateBps = e["maxBitrate"] as? NSNumber } if e["scaleResolutionDownBy"] as? NSNumber != nil { p.scaleResolutionDownBy = e["scaleResolutionDownBy"] as? NSNumber } newParameters.encodings.append(p) } } rtpSender.parameters = newParameters var newCodecs : [NSDictionary] = [] for c in newParameters.codecs { let codec = PluginRTCRtpCodecParameters(c) newCodecs.append(codec.getJSON()) } var newEncodings : [NSDictionary] = [] for e in newParameters.encodings { let encoding = PluginRTCRtpEncodingParameters(e) newEncodings.append(encoding.getJSON()) } let newHeaderExtensions : [NSDictionary] = [] let result : [String : Any] = [ "codecs": newCodecs, "encodings": newEncodings, "headerExtensions": newHeaderExtensions ] callback(result as NSDictionary) } func replaceTrack(_ pluginMediaStreamTrack: PluginMediaStreamTrack?) { let rtcMediaStreamTrack = pluginMediaStreamTrack?.rtcMediaStreamTrack self.rtpSender.track = rtcMediaStreamTrack } func getJSON() -> NSDictionary { let track = self.rtpSender.track != nil ? [ "id": self.rtpSender.track!.trackId, "kind": self.rtpSender.track!.kind, "readyState": self.rtpSender.track!.readyState == RTCMediaStreamTrackState.live ? "live" : "ended", "enabled": self.rtpSender.track!.isEnabled, "label": self.rtpSender.track!.trackId ] : nil return [ "id": self.id, "senderId": self.rtpSender.senderId, "params": PluginRTCRtpParameters(self.rtpSender.parameters).getJSON(), "track": track ] } }
mit
dc9a30d357c2e1ac5b39923a0028836c
29.397436
105
0.698018
3.471449
false
false
false
false
velvetroom/columbus
Source/View/Create/VCreateStatusReadyBar+Constants.swift
1
343
import UIKit extension VCreateStatusReadyBar { struct Constants { static let minTop:CGFloat = -260 static let height:CGFloat = 280 static let contentTop:CGFloat = 20 static let contentBottom:CGFloat = -20 static let loaderHeight:CGFloat = 19 static let travelWidth:CGFloat = 50 } }
mit
a4481d18a5b1ed98d14345473d37d246
23.5
46
0.653061
4.573333
false
true
false
false
ephread/Instructions
Examples/Example/Sources/Core/Custom Views/CustomCoachMarkArrowView.swift
1
2366
// Copyright (c) 2015-present Frédéric Maquin <[email protected]> and contributors. // Licensed under the terms of the MIT License. import UIKit import Instructions // Custom coach mark body (with the secret-like arrow) internal class CustomCoachMarkArrowView: UIView, CoachMarkArrowView { // MARK: - Internal properties var topPlateImage = UIImage(named: "coach-mark-top-plate") var bottomPlateImage = UIImage(named: "coach-mark-bottom-plate") var plate = UIImageView() var isHighlighted: Bool = false // MARK: - Private properties private var column = UIView() // MARK: - Initialization init(orientation: CoachMarkArrowOrientation) { super.init(frame: CGRect.zero) if orientation == .top { self.plate.image = topPlateImage } else { self.plate.image = bottomPlateImage } self.translatesAutoresizingMaskIntoConstraints = false self.column.translatesAutoresizingMaskIntoConstraints = false self.plate.translatesAutoresizingMaskIntoConstraints = false self.addSubview(plate) self.addSubview(column) plate.backgroundColor = UIColor.clear column.backgroundColor = UIColor.white plate.fillSuperviewHorizontally() NSLayoutConstraint.activate([ column.widthAnchor.constraint(equalToConstant: 3), column.centerXAnchor.constraint(equalTo: centerXAnchor) ]) if orientation == .top { NSLayoutConstraint.activate( NSLayoutConstraint.constraints( withVisualFormat: "V:|[plate(==5)][column(==10)]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["plate": plate, "column": column] ) ) } else { NSLayoutConstraint.activate( NSLayoutConstraint.constraints( withVisualFormat: "V:|[column(==10)][plate(==5)]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["plate": plate, "column": column] ) ) } } required init(coder aDecoder: NSCoder) { fatalError("This class does not support NSCoding.") } }
mit
3c655782dd3e7cc4754add418ccecd30
33.26087
82
0.60956
5.409611
false
false
false
false
mwildeboer/Axis
Source/UIView+Axis.swift
1
551
// // UIView+Axis.swift // Axis // // Created by Menno Wildeboer on 17/02/16. // Copyright © 2016 Menno Wideboer. All rights reserved. // import UIKit public extension UIView { public func fillSuperview(insets: UIEdgeInsets = UIEdgeInsetsZero) { if let superview = self.superview { var frame = superview.bounds frame.origin.x += insets.left frame.origin.y += insets.top frame.size.width -= (insets.left + insets.right) frame.size.height -= (insets.top + insets.bottom) self.frame = frame } } }
bsd-2-clause
96e992a6acc114f457d6e8e148b7d274
22.956522
70
0.654545
3.571429
false
false
false
false
giorgia/shopify-ios
shopify-ios/ProductsViewController.swift
1
4505
// // ProductsViewController.swift // shopify-ios // // Created by Giorgia Marenda on 2/27/16. // Copyright © 2016 Giorgia Marenda. All rights reserved. // import Buy import UIKit import Haneke import SnapKit class ProductsViewController: UIViewController { var products = [BUYProduct]() var currentPage: UInt = 1 var reachedEnd = false var collectionView: UICollectionView? override func viewDidLoad() { super.viewDidLoad() setupViews() fetchProducts() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupViews() { let layout = UICollectionViewFlowLayout() setupFlowLayout(layout) collectionView = UICollectionView(frame: view.frame, collectionViewLayout: layout) collectionView?.dataSource = self collectionView?.delegate = self collectionView?.registerClass(ProductCell.self, forCellWithReuseIdentifier: ProductCell.reuseCellIdentifier) collectionView?.backgroundColor = UIColor.whiteColor() view.addSubview(collectionView!) setupConstaints() } func setupFlowLayout(flowLayout: UICollectionViewFlowLayout) { let dim = view.frame.size.width < 415 ? view.frame.size.width - 1 : (view.frame.size.width - 2) / 2 flowLayout.estimatedItemSize = CGSize(width: dim, height: dim) flowLayout.scrollDirection = .Vertical flowLayout.sectionInset = UIEdgeInsetsZero flowLayout.minimumInteritemSpacing = 0 flowLayout.minimumLineSpacing = 1 flowLayout.invalidateLayout() } func setupConstaints() { collectionView?.snp_makeConstraints { (make) -> Void in make.edges.equalTo(view) } } func fetchProducts() { Shopify.client?.getProductsPage(currentPage) { (products, page, reachedEnd, error) -> Void in self.currentPage = page self.reachedEnd = reachedEnd guard let buyProducts = products as? [BUYProduct] else { return } self.products.appendContentsOf(buyProducts) self.collectionView?.reloadData() } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() guard let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout else { return } setupFlowLayout(flowLayout) } } extension ProductsViewController: UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return products.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ProductCell.reuseCellIdentifier, forIndexPath: indexPath) as? ProductCell let product = products[indexPath.row] if let image = product.images.first, imageURL = NSURL(string: image.src) { cell?.imageView.hnk_setImageFromURL(imageURL) } cell?.titleLabel.text = product.title return cell ?? UICollectionViewCell() } func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { if indexPath.row == products.count - 1 { currentPage++ fetchProducts() } } } extension ProductsViewController: UICollectionViewDelegate { func productViewController() -> BUYProductViewController { let theme = BUYTheme() theme.style = .Light theme.tintColor = UIColor(red: 124.0/255.0, green: 162.0/255.0, blue: 142.0/255.0, alpha:1.0) theme.showsProductImageBackground = false let productDetailController = BUYProductViewController(client: Shopify.client, theme: theme) return productDetailController } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let product = products[indexPath.row] let controller = productViewController() controller.loadWithProduct(product) { (success, error) -> Void in controller.presentPortraitInViewController(self) } } }
apache-2.0
b08acd9bf32017cac9346b153d05b1dd
34.1875
146
0.670293
5.452785
false
false
false
false
dbaldwin/DronePan
DronePan/Utils/ActiveAwareDispatchGroup.swift
1
1167
import Foundation import CocoaLumberjackSwift class ActiveAwareDispatchGroup { let group = dispatch_group_create() let name: String var active: Bool = false init(name: String) { self.name = name } func enter() { DDLogDebug("Entering dispatch group \(name)") active = true dispatch_group_enter(group) } func leave() -> Bool { DDLogDebug("Leaving dispatch group \(name)") var result = true if !active { DDLogError("Warning - leaving dispatch group \(name) while not active") result = false } active = false dispatch_group_leave(group) return result } func leaveIfActive() -> Bool { DDLogDebug("Leaving dispatch group if active: \(active) - \(name)") var result = false if active { self.leave() result = true } return result } func wait() { DDLogDebug("Waiting for dispatch group \(name)") dispatch_group_wait(group, DISPATCH_TIME_FOREVER) DDLogDebug("Waiting complete for dispatch group \(name)") } }
gpl-3.0
1a1b40c36e73db5da97bc3c5da4ad257
19.491228
83
0.569837
4.882845
false
false
false
false
mcrollin/safecaster
safecaster/SCRUploadViewModel.swift
1
6884
// // SCRUploadViewModel.swift // safecaster // // Created by Marc Rollin on 4/12/15. // Copyright (c) 2015 safecast. All rights reserved. // import Foundation import ReactiveCocoa import Alamofire import ObjectMapper class SCRUploadViewModel: SCRViewModel { dynamic private(set) var allMeasurements:[SCRMeasurement] = [] dynamic private(set) var validMeasurements:[SCRMeasurement] = [] dynamic private(set) var totalMeasurementsCount:String! dynamic private(set) var totalDuration:String! dynamic private(set) var totalDistance:String! dynamic private(set) var distanceUnit:String! dynamic private(set) var mapCenterCoordinate:String! dynamic private(set) var usvh:String! dynamic private(set) var cpm:String! var selectedMeasurement:SCRMeasurement? { didSet { if let measurement = selectedMeasurement { usvh = String(format: "%.3f", measurement.usvh) cpm = "\(measurement.cpm)" } } } } // MARK: - Reactive signals extension SCRUploadViewModel { func uploadSignal() -> RACSignal! { return RACSignal.createSignal { subscriber in let measurements = SCRMeasurement.findAll() let measurementsData: [String] = measurements.map { return $0.data } let logs = measurementsData.reduce("", combine: { $0 + "\r\n" + $1 }) let key = SCRUserManager.sharedManager.user!.token! let fileData = logs.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) let boundaryConstant = "Boundary-" + NSUUID().UUIDString let uploadData = self.generateUploadData(fileData!, parameters: ["api_key": key], boundaryConstant: boundaryConstant) Alamofire.upload(SCRSafecastAPIRouter.CreateImport(boundaryConstant), data: uploadData) .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in log("\(totalBytesWritten) / \(totalBytesExpectedToWrite)") subscriber.sendNext(Float(totalBytesWritten / totalBytesExpectedToWrite)) }.responseJSON { _, _, result in log("RESULT \(result)") if result.isFailure { subscriber.sendError(result.error as! NSError) } else { let logImport = Mapper<SCRImport>().map(result.value) log("IMPORT \(logImport)") subscriber.sendNext(logImport) subscriber.sendCompleted() } } Alamofire.upload(SCRSafecastAPIRouter.CreateImport(boundaryConstant), data: uploadData) .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in log("\(totalBytesWritten) / \(totalBytesExpectedToWrite)") subscriber.sendNext(Float(totalBytesWritten / totalBytesExpectedToWrite)) }.responseJSON { _, _, result in log("RESULT \(result)") if result.isFailure { subscriber.sendError(result.error as! NSError) } else { let logImport = Mapper<SCRImport>().map(result.value) log("IMPORT \(logImport)") subscriber.sendNext(logImport) subscriber.sendCompleted() } } return nil } } } // MARK: - Public methods extension SCRUploadViewModel { func updateMeasurements() { allMeasurements = SCRMeasurement.findAll() validMeasurements = SCRMeasurement.findAll(true, onlyValid: true) } func deleteAllMeasurements() { SCRMeasurement.deleteAll() updateMeasurements() } func updateTotalMeasurementCount() { totalMeasurementsCount = "\(SCRMeasurement.count())" } func updateDurationsAndDistance() { let totalDuration = SCRMeasurement.totalDuration() let totalDistance = SCRMeasurement.totalDistance() self.totalDuration = getTime(totalDuration) self.totalDistance = getDistance(totalDistance) self.distanceUnit = getDistanceUnit() } } // MARK: - Private methods extension SCRUploadViewModel { private func getDistanceUnit() -> String { let metric:Bool = NSLocale.currentLocale().objectForKey(NSLocaleUsesMetricSystem)!.boolValue return "Distance (" + (metric ? "km" : "mi") + ")" } private func getDistance(distance:CLLocationDistance) -> String { let metric:Bool = NSLocale.currentLocale().objectForKey(NSLocaleUsesMetricSystem)!.boolValue let distance = distance / (metric ? 1000 : 1609.34) if distance >= 100 { return String(format:"%.0f", distance) } return String(format:"%.01f", distance) } private func getTime(interval:NSTimeInterval) -> String { let calendar = NSCalendar.currentCalendar() let referenceDate = NSDate() let date = NSDate(timeInterval: interval, sinceDate:referenceDate) let flags: NSCalendarUnit = [NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second] let components = calendar.components(flags, fromDate: referenceDate, toDate: date, options:[]) return String(format: "%02d:%02d:%02d", components.hour, components.minute, components.second) } private func generateUploadData(data:NSData, parameters:Dictionary<String, String>, boundaryConstant:String) -> NSData { let filename = NSUUID().UUIDString + ".LOG" let uploadData = NSMutableData() uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) uploadData.appendData("Content-Disposition: form-data; name=\"bgeigie_import[source]\"; filename=\"\(filename)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) uploadData.appendData("Content-Type: application/octet-stream\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) uploadData.appendData(data) for (key, value) in parameters { uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!) } uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) return uploadData } }
cc0-1.0
b96020068407c1309efdf5b6099602ad
40.475904
167
0.609675
5.31583
false
false
false
false
klaus01/Centipede
Centipede/StoreKit/CE_SKProductsRequest.swift
1
2209
// // CE_SKProductsRequest.swift // Centipede // // Created by kelei on 2016/9/15. // Copyright (c) 2016年 kelei. All rights reserved. // import StoreKit extension SKProductsRequest { private struct Static { static var AssociationKey: UInt8 = 0 } private var _delegate: SKProductsRequest_Delegate? { get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? SKProductsRequest_Delegate } set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } private var ce: SKProductsRequest_Delegate { if let obj = _delegate { return obj } if let obj: AnyObject = self.delegate { if obj is SKProductsRequest_Delegate { return obj as! SKProductsRequest_Delegate } } let obj = getDelegateInstance() _delegate = obj return obj } private func rebindingDelegate() { let delegate = ce self.delegate = nil self.delegate = delegate } internal override func getDelegateInstance() -> SKProductsRequest_Delegate { return SKProductsRequest_Delegate() } @discardableResult public func ce_productsRequest_didReceive(handle: @escaping (SKProductsRequest, SKProductsResponse) -> Void) -> Self { ce._productsRequest_didReceive = handle rebindingDelegate() return self } } internal class SKProductsRequest_Delegate: SKRequest_Delegate, SKProductsRequestDelegate { var _productsRequest_didReceive: ((SKProductsRequest, SKProductsResponse) -> Void)? override func responds(to aSelector: Selector!) -> Bool { let funcDic1: [Selector : Any?] = [ #selector(productsRequest(_:didReceive:)) : _productsRequest_didReceive, ] if let f = funcDic1[aSelector] { return f != nil } return super.responds(to: aSelector) } @objc func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { _productsRequest_didReceive!(request, response) } }
mit
d8979588bf4e82f8377d00c21cb10f09
29.232877
128
0.638423
5.004535
false
false
false
false
argon/WordPress-iOS
WordPress/Classes/Services/PushAuthenticationService.swift
1
2260
import Foundation /** * @class PushAuthenticationService * @brief The purpose of this service is to encapsulate the Restful API that performs Mobile 2FA * Code Verification. */ @objc public class PushAuthenticationService : NSObject, LocalCoreDataService { var authenticationServiceRemote:PushAuthenticationServiceRemote? /** * @details Designated Initializer * @param managedObjectContext A Reference to the MOC that should be used to interact with * the Core Data Persistent Store. */ public required init(managedObjectContext: NSManagedObjectContext) { super.init() self.managedObjectContext = managedObjectContext self.authenticationServiceRemote = PushAuthenticationServiceRemote(remoteApi: apiForRequest()) } /** * @details Authorizes a WordPress.com Login Attempt (2FA Protected Accounts) * @param token The Token sent over by the backend, via Push Notifications. * @param completion The completion block to be executed when the remote call finishes. */ public func authorizeLogin(token: String, completion: ((Bool) -> ())) { if self.authenticationServiceRemote == nil { return } self.authenticationServiceRemote!.authorizeLogin(token, success: { completion(true) }, failure: { completion(false) }) } /** * @details Helper method to get the WordPress.com REST Api, if any * @returns WordPressComApi instance, if applicable, or nil. */ private func apiForRequest() -> WordPressComApi? { let accountService = AccountService(managedObjectContext: managedObjectContext) if let unwrappedRestApi = accountService.defaultWordPressComAccount()?.restApi { if unwrappedRestApi.hasCredentials() { return unwrappedRestApi } } return nil } // MARK: - Private Internal Properties private var managedObjectContext : NSManagedObjectContext! }
gpl-2.0
acd3f45a56450bec209cf4fde00fce4e
34.873016
106
0.613274
5.765306
false
false
false
false
guidomb/Portal
Portal/View/Components/Collection.swift
1
6968
// // CollectionView.swift // PortalView // // Created by Argentino Ducret on 4/4/17. // Copyright © 2017 Guido Marucci Blas. All rights reserved. // import Foundation import UIKit public class SectionInset: AutoEquatable { public static let zero = SectionInset(top: 0, left: 0, bottom: 0, right: 0) public var bottom: UInt public var top: UInt public var left: UInt public var right: UInt public init(top: UInt, left: UInt, bottom: UInt, right: UInt) { self.bottom = bottom self.top = top self.left = left self.right = right } } public enum CollectionScrollDirection { case horizontal case vertical } public struct CollectionProperties<MessageType>: AutoPropertyDiffable { // sourcery: skipDiff public var items: [CollectionItemProperties<MessageType>] public var showsVerticalScrollIndicator: Bool public var showsHorizontalScrollIndicator: Bool // sourcery: skipDiff public var refresh: RefreshProperties<MessageType>? // Layout properties public var itemsSize: Size public var minimumInteritemSpacing: UInt public var minimumLineSpacing: UInt public var scrollDirection: CollectionScrollDirection public var sectionInset: SectionInset public var paging: Bool fileprivate init( items: [CollectionItemProperties<MessageType>] = [], showsVerticalScrollIndicator: Bool = false, showsHorizontalScrollIndicator: Bool = false, itemsSize: Size, refresh: RefreshProperties<MessageType>? = .none, minimumInteritemSpacing: UInt = 0, minimumLineSpacing: UInt = 0, scrollDirection: CollectionScrollDirection = .vertical, sectionInset: SectionInset = .zero, paging: Bool = false) { self.items = items self.showsVerticalScrollIndicator = showsVerticalScrollIndicator self.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator self.itemsSize = itemsSize self.refresh = refresh self.minimumLineSpacing = minimumLineSpacing self.minimumInteritemSpacing = minimumInteritemSpacing self.sectionInset = sectionInset self.scrollDirection = scrollDirection self.paging = paging } public func map<NewMessageType>( _ transform: @escaping (MessageType) -> NewMessageType) -> CollectionProperties<NewMessageType> { return CollectionProperties<NewMessageType>( items: self.items.map { $0.map(transform) }, showsVerticalScrollIndicator: self.showsVerticalScrollIndicator, showsHorizontalScrollIndicator: self.showsHorizontalScrollIndicator, itemsSize: self.itemsSize, refresh: self.refresh.map { $0.map(transform) }, minimumInteritemSpacing: self.minimumInteritemSpacing, minimumLineSpacing: self.minimumLineSpacing, scrollDirection: self.scrollDirection, sectionInset: self.sectionInset) } } public struct CollectionItemProperties<MessageType> { public typealias Renderer = () -> Component<MessageType> public let onTap: MessageType? public let renderer: Renderer public let identifier: String fileprivate init( onTap: MessageType?, identifier: String, renderer: @escaping Renderer) { self.onTap = onTap self.renderer = renderer self.identifier = identifier } } extension CollectionItemProperties { public func map<NewMessageType>( _ transform: @escaping (MessageType) -> NewMessageType) -> CollectionItemProperties<NewMessageType> { return CollectionItemProperties<NewMessageType>( onTap: self.onTap.map(transform), identifier: self.identifier, renderer: { self.renderer().map(transform) } ) } } public func collection<MessageType>( properties: CollectionProperties<MessageType>, style: StyleSheet<CollectionStyleSheet> = CollectionStyleSheet.default, layout: Layout = layout()) -> Component<MessageType> { return .collection(properties, style, layout) } public func collectionItem<MessageType>( onTap: MessageType? = .none, identifier: String, renderer: @escaping CollectionItemProperties<MessageType>.Renderer) -> CollectionItemProperties<MessageType> { return CollectionItemProperties(onTap: onTap, identifier: identifier, renderer: renderer) } public func properties<MessageType>( itemsWidth: UInt, itemsHeight: UInt, configure: (inout CollectionProperties<MessageType>) -> Void) -> CollectionProperties<MessageType> { var properties = CollectionProperties<MessageType>( itemsSize: Size(width: itemsWidth, height: itemsHeight) ) configure(&properties) return properties } // MARK: - Style sheet public struct CollectionStyleSheet: AutoPropertyDiffable { public static let `default` = StyleSheet<CollectionStyleSheet>(component: CollectionStyleSheet()) public var refreshTintColor: Color fileprivate init(refreshTintColor: Color = .gray) { self.refreshTintColor = refreshTintColor } } public func collectionStyleSheet( configure: (inout BaseStyleSheet, inout CollectionStyleSheet) -> Void = { _, _ in }) -> StyleSheet<CollectionStyleSheet> { var base = BaseStyleSheet() var component = CollectionStyleSheet() configure(&base, &component) return StyleSheet(component: component, base: base) } // MARK: - ChangeSet public struct CollectionChangeSet<MessageType> { static func fullChangeSet( properties: CollectionProperties<MessageType>, style: StyleSheet<CollectionStyleSheet>, layout: Layout) -> CollectionChangeSet<MessageType> { return CollectionChangeSet( properties: properties.fullChangeSet, baseStyleSheet: style.base.fullChangeSet, collectionStyleSheet: style.component.fullChangeSet, layout: layout.fullChangeSet ) } let properties: [CollectionProperties<MessageType>.Property] let baseStyleSheet: [BaseStyleSheet.Property] let collectionStyleSheet: [CollectionStyleSheet.Property] let layout: [Layout.Property] var isEmpty: Bool { return properties.isEmpty && baseStyleSheet.isEmpty && collectionStyleSheet.isEmpty && layout.isEmpty } init( properties: [CollectionProperties<MessageType>.Property] = [], baseStyleSheet: [BaseStyleSheet.Property] = [], collectionStyleSheet: [CollectionStyleSheet.Property] = [], layout: [Layout.Property] = []) { self.properties = properties self.baseStyleSheet = baseStyleSheet self.collectionStyleSheet = collectionStyleSheet self.layout = layout } }
mit
9859a75eb23408509f5b4407f6c28c3b
32.334928
114
0.683651
5.250188
false
false
false
false
GabrielGhe/SwiftProjects
App11Happinesss/FaceView.swift
1
2986
// // File.swift // App11Happinesss // // Created by Gabriel on 2014-07-22. // Copyright (c) 2014 Gabriel. All rights reserved. // import UIKit protocol FaceViewDelegate { func smileForFaceView(requestor:FaceView) -> Float } class FaceView: UIView { var delegate:FaceViewDelegate? init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } func drawCircleAtPoint(p:CGPoint, withRadius radius:CGFloat, context:CGContextRef){ UIGraphicsPushContext(context) CGContextBeginPath(context) CGContextAddArc(context, p.x, p.y, radius, 0, CGFloat(2*M_PI), TRUE) CGContextStrokePath(context) UIGraphicsPopContext() } override func drawRect(rect: CGRect) { var midPoint: CGPoint = CGPoint( x: (self.bounds.origin.x + self.bounds.size.width/2), y: (self.bounds.origin.y + self.bounds.size.height/2)) var size:CGFloat = self.bounds.size.width/2 if self.bounds.size.height < self.bounds.size.width { size = self.bounds.size.height / 2 } var context = UIGraphicsGetCurrentContext() drawCircleAtPoint(midPoint, withRadius:size, context:context) //EYES let EYE_WIDTH:Float = 0.35 let EYE_HEIGHT:Float = 0.35 let EYE_RADIUS:Float = 0.1 var eyePoint:CGPoint = CGPoint() eyePoint.x = midPoint.x - size * EYE_WIDTH eyePoint.y = midPoint.y - size * EYE_HEIGHT //Eyes Drawing drawCircleAtPoint(eyePoint, withRadius:(size * EYE_RADIUS), context: context) eyePoint.x += size * EYE_WIDTH * 2 drawCircleAtPoint(eyePoint, withRadius:(size * EYE_RADIUS), context: context) //Mouth let MOUTH_WIDTH:Float = 0.45 let MOUTH_HEIGHT:Float = 0.4 let MOUTH_SMILE:Float = 0.25 var mouthStart:CGPoint = CGPoint() mouthStart.x = midPoint.x - MOUTH_WIDTH * size mouthStart.y = midPoint.y + MOUTH_HEIGHT * size var mouthEnd:CGPoint = mouthStart mouthEnd.x += MOUTH_WIDTH * size * 2 var mouthP1:CGPoint = mouthStart mouthP1.x += MOUTH_WIDTH * size * 2/3 var mouthP2:CGPoint = mouthEnd mouthP2.x -= MOUTH_WIDTH * size * 2/3 //Mouth Drawing var smile:Float = 0 // [-1.0, 1.0] if let smileValue = delegate?.smileForFaceView(self){ smile = smileValue } if smile < -1.0 { smile = -1.0 } if smile > 1.0 { smile = 1.0 } var smileOffset:CGFloat = MOUTH_SMILE * size * smile mouthP1.y += smileOffset mouthP2.y += smileOffset CGContextBeginPath(context); CGContextMoveToPoint(context, mouthStart.x, mouthStart.y) CGContextAddCurveToPoint(context, mouthP1.x, mouthP1.y, mouthP2.x, mouthP2.y, mouthEnd.x, mouthEnd.y) CGContextStrokePath(context) } }
mit
72aa89890dfc58fb8f73eb3b62daf67c
32.188889
109
0.601808
3.857881
false
false
false
false
grandima/DMUtilities
DMUtilities/Classes/Classes/TableViewDataSource.swift
1
2781
// // TableViewDataSource.swift // Series // // Created by Dima Medynsky on 2/26/16. // Copyright © 2016 Dima Medynsky. All rights reserved. // import UIKit class TableViewDataSource<Delegate: DataSourceDelegate, Data: AugmentedDataProvider, Cell: UITableViewCell>: NSObject, UITableViewDataSource where Delegate.Item == Data.Item, Cell: ConfigurableCell, Cell.Entity == Data.Item { required init(tableView: UITableView, dataProvider: Data, delegate: Delegate) { self.tableView = tableView self.dataProvider = dataProvider self.delegate = delegate super.init() tableView.dataSource = self tableView.reloadData() } private let tableView: UITableView private let dataProvider: Data! private weak var delegate: Delegate! // MARK: UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return dataProvider.numberOfSections } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return dataProvider.titleForHeader(in: section) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataProvider.numberOfItems(in: section) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let object = dataProvider.object(at: indexPath) let identifier = delegate.cellIdentifier(for: object) guard let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as? Cell else { fatalError("Unexpected cell type at \(indexPath)") } cell.configure(for: object) return cell } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return dataProvider.numberOfSections } func processUpdates(updates: [DataProviderUpdate<Data.Item>]?) { guard let updates = updates else { return tableView.reloadData() } tableView.beginUpdates() for update in updates { switch update { case .Insert(let indexPath): tableView.insertRows(at: [indexPath], with: .fade) case .Update(let indexPath, let object): guard let cell = tableView.cellForRow(at: indexPath) as? Cell else { break } cell.configure(for: object) case .Move(let indexPath, let newIndexPath): tableView.deleteRows(at: [indexPath], with: .fade) tableView.insertRows(at: [newIndexPath], with: .fade) case .Delete(let indexPath): tableView.deleteRows(at: [indexPath], with: .fade) } } tableView.endUpdates() } }
mit
31f4325d8a30beb44e5512d8b381710b
35.578947
225
0.652158
5.148148
false
false
false
false
RBevilacqua/oauthSwift1.1
OAuthSwift/NSURL+OAuthSwift.swift
1
741
// // NSURL+OAuthSwift.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation extension NSURL { func URLByAppendingQueryString(queryString: String) -> NSURL { if countElements(queryString.utf16) == 0 { return self } var absoluteURLString = self.absoluteString! if absoluteURLString.hasSuffix("?") { absoluteURLString = (absoluteURLString as NSString).substringToIndex(countElements(absoluteURLString.utf16) - 1) } let URLString = absoluteURLString + (absoluteURLString.rangeOfString("?") != nil ? "&" : "?") + queryString return NSURL(string: URLString)! } }
mit
06a643fd1d64473bad302a6642025b3a
23.7
124
0.646424
4.689873
false
false
false
false
imxieyi/iosu
iosu/ViewControllers/GameViewController.swift
1
4744
// // GameViewController.swift // iosu // // Created by xieyi on 2017/3/28. // Copyright © 2017年 xieyi. All rights reserved. // import UIKit import SpriteKit import GameplayKit class GameViewController: UIViewController { let screenWidth=UIScreen.main.bounds.width*UIScreen.main.scale let screenHeight=UIScreen.main.bounds.height*UIScreen.main.scale static var showgame = true static var showvideo = true static var showsb = true var alert:UIAlertController! let runtestscene=false @IBOutlet weak var backBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() var maxfps: Int if #available(iOS 10.3, *) { maxfps = UIScreen.main.maximumFramesPerSecond } else { maxfps = 60 } debugPrint("Max FPS: \(maxfps)") view?.autoresizesSubviews=true view.backgroundColor = .black if runtestscene { let scene=TestScene(size: CGSize(width: screenWidth, height: screenHeight)) let skView=self.view as! SKView skView.preferredFramesPerSecond = maxfps skView.showsFPS=true skView.showsNodeCount=true skView.showsDrawCount=true skView.showsQuadCount=true skView.ignoresSiblingOrder=true skView.allowsTransparency=true scene.scaleMode = .aspectFit scene.backgroundColor = .cyan skView.presentScene(scene) return } if GameViewController.showsb { let sbScene=StoryBoardScene(size: CGSize(width: screenWidth, height: screenHeight),parent:self) let sbView=SKView(frame: UIScreen.main.bounds) sbView.layer.zPosition = 0 self.view.addSubview(sbView) sbView.preferredFramesPerSecond = maxfps sbView.showsFPS=true sbView.showsNodeCount=true sbView.showsDrawCount=true sbView.showsQuadCount=true sbView.ignoresSiblingOrder=true sbView.layer.zPosition = 0 sbScene.scaleMode = .aspectFit sbView.presentScene(sbScene) } if GameViewController.showvideo { //For video play BGVPlayer.initialize() BGVPlayer.view?.layer.zPosition = 1 view.addSubview(BGVPlayer.view!) } if GameViewController.showgame { let gameScene=GamePlayScene(size: CGSize(width: screenWidth, height: screenHeight)) //let skView=self.view as! SKView let gameView=SKView(frame: UIScreen.main.bounds) gameView.preferredFramesPerSecond = maxfps gameView.layer.zPosition=2 self.view.addSubview(gameView) //skView.allowsTransparency=true gameView.backgroundColor = .clear //(self.view as! SKView).allowsTransparency=true if GameViewController.showsb { gameView.showsFPS=false gameView.showsNodeCount=false } else { gameView.showsFPS=true gameView.showsNodeCount=true gameView.showsDrawCount=true gameView.showsQuadCount=true } gameView.ignoresSiblingOrder=true gameScene.scaleMode = .aspectFill gameScene.backgroundColor = .clear gameView.presentScene(gameScene) } BGMusicPlayer.instance.startPlaying() backBtn.removeFromSuperview() view.addSubview(backBtn) backBtn.layer.zPosition = 5 } @IBAction func onBack(_ sender: Any) { BGMusicPlayer.instance.stop() BGVPlayer.stop() BGVPlayer.view?.removeFromSuperview() dismiss(animated: true, completion: nil) } override func viewDidAppear(_ animated: Bool) { debugPrint("scene appears,\(alert)") if alert != nil { debugPrint("show alert") self.present(alert!, animated: true, completion: nil) } } override var shouldAutorotate: Bool { return true } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{ return .landscapeLeft } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .landscape } else { return .landscape } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override var prefersStatusBarHidden: Bool { return true } }
mit
f2d23047df42793d2b61718f72f4ddc1
32.864286
107
0.617591
5.142082
false
false
false
false
JohnCoates/Aerial
Resources/MainUI/Settings panels/TimeViewController.swift
1
8307
// // TimeViewController.swift // Aerial // // Created by Guillaume Louel on 19/07/2020. // Copyright © 2020 Guillaume Louel. All rights reserved. // import Cocoa class TimeViewController: NSViewController { // All the radios @IBOutlet var timeLocationRadio: NSButton! @IBOutlet var timeNightShiftRadio: NSButton! @IBOutlet var timeManualRadio: NSButton! @IBOutlet var timeLightDarkModeRadio: NSButton! @IBOutlet var timeDisabledRadio: NSButton! // Night Shift @IBOutlet var nightShiftLabel: NSTextField! // Manual @IBOutlet var sunriseTime: NSDatePicker! @IBOutlet var sunsetTime: NSDatePicker! // Advanced @IBOutlet var darkModeNightOverride: NSButton! @IBOutlet var myLocationImageView: NSImageView! @IBOutlet var nightShiftImageView: NSImageView! @IBOutlet var manualImageView: NSImageView! @IBOutlet var lightModeImageView: NSImageView! @IBOutlet var noAdaptImageView: NSImageView! @IBOutlet var popoverCalcMode: NSPopover! @IBOutlet var oSunrise: NSTextField! @IBOutlet var eSunrise: NSTextField! @IBOutlet var eSunset: NSTextField! @IBOutlet var oSunset: NSTextField! @IBOutlet var timeBarView: NSView! @IBOutlet var sunsetWindowPopup: NSPopUpButton! lazy var timeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "HH:mm" return formatter }() // swiftlint:disable cyclomatic_complexity override func viewDidLoad() { super.viewDidLoad() setupDarkMode() setupNightShift() if let dateSunrise = timeFormatter.date(from: PrefsTime.manualSunrise) { sunriseTime.dateValue = dateSunrise } if let dateSunset = timeFormatter.date(from: PrefsTime.manualSunset) { sunsetTime.dateValue = dateSunset } // Handle the time radios switch PrefsTime.timeMode { case .nightShift: timeNightShiftRadio.state = .on case .manual: timeManualRadio.state = .on case .lightDarkMode: timeLightDarkModeRadio.state = .on case .disabled: timeDisabledRadio.state = .on default: timeLocationRadio.state = .on } myLocationImageView.image = Aerial.helper.getSymbol("mappin.and.ellipse")?.tinting(with: .secondaryLabelColor) nightShiftImageView.image = Aerial.helper.getSymbol("house")?.tinting(with: .secondaryLabelColor) manualImageView.image = Aerial.helper.getSymbol("clock")?.tinting(with: .secondaryLabelColor) lightModeImageView.image = Aerial.helper.getSymbol("gear")?.tinting(with: .secondaryLabelColor) noAdaptImageView.image = Aerial.helper.getSymbol("xmark.circle")?.tinting(with: .secondaryLabelColor) updateTimeView() switch PrefsTime.sunEventWindow { case 60*60: sunsetWindowPopup.selectItem(at: 0) case 60*90: sunsetWindowPopup.selectItem(at: 1) case 60*120: sunsetWindowPopup.selectItem(at: 2) case 60*150: sunsetWindowPopup.selectItem(at: 3) case 60*180: sunsetWindowPopup.selectItem(at: 4) case 60*210: sunsetWindowPopup.selectItem(at: 5) default: sunsetWindowPopup.selectItem(at: 6) } } func setupDarkMode() { // Dark Mode is Mojave+ if #available(OSX 10.14, *) { if PrefsTime.darkModeNightOverride { darkModeNightOverride.state = .on } // We disable the checkbox if we are on nightShift mode if PrefsTime.timeMode == .lightDarkMode { darkModeNightOverride.isEnabled = false } } else { darkModeNightOverride.isEnabled = false } // Light/Dark mode only available on Mojave+ let (isLDMCapable, reason: _) = DarkMode.isAvailable() if !isLDMCapable { timeLightDarkModeRadio.isEnabled = false } } func setupNightShift() { // Night Shift requires 10.12.4+ and a compatible Mac let (isNSCapable, reason: NSReason) = NightShift.isAvailable() if !isNSCapable { timeNightShiftRadio.isEnabled = false } nightShiftLabel.stringValue = NSReason } @IBAction func sunsetSunriseWindowChange(_ sender: NSPopUpButton) { PrefsTime.sunEventWindow = 60 * ((2 + sender.indexOfSelectedItem) * 30) updateTimeView() } func updateTimeView() { switch PrefsTime.timeMode { case .disabled: timeBarView.isHidden = true return case .lightDarkMode: timeBarView.isHidden = true return case .nightShift: timeBarView.isHidden = false case .manual: timeBarView.isHidden = false case .coordinates: timeBarView.isHidden = true return case .locationService: timeBarView.isHidden = false _ = TimeManagement.sharedInstance.calculateFromCoordinates() } let (sunrise, sunset) = TimeManagement.sharedInstance.getSunriseSunset() if let lsunrise = sunrise, let lsunset = sunset { let esunrise = lsunrise.addingTimeInterval(TimeInterval(PrefsTime.sunEventWindow)) let psunset = lsunset.addingTimeInterval(TimeInterval(-PrefsTime.sunEventWindow)) oSunrise.stringValue = timeFormatter.string(from: lsunrise) oSunrise.sizeToFit() eSunrise.stringValue = timeFormatter.string(from: esunrise) eSunrise.sizeToFit() eSunset.stringValue = timeFormatter.string(from: psunset) eSunset.sizeToFit() oSunset.stringValue = timeFormatter.string(from: lsunset) oSunset.sizeToFit() } } @IBAction func timeModeChange(_ sender: NSButton) { if sender == timeLightDarkModeRadio { darkModeNightOverride.isEnabled = false } else { if #available(OSX 10.14, *) { darkModeNightOverride.isEnabled = true } } switch sender { case timeDisabledRadio: PrefsTime.timeMode = .disabled case timeNightShiftRadio: PrefsTime.timeMode = .nightShift case timeManualRadio: PrefsTime.timeMode = .manual case timeLightDarkModeRadio: PrefsTime.timeMode = .lightDarkMode case timeLocationRadio: PrefsTime.timeMode = .locationService default: () } updateTimeView() } @IBAction func sunriseChange(_ sender: NSDatePicker?) { guard let date = sender?.dateValue else { return } PrefsTime.manualSunrise = timeFormatter.string(from: date) updateTimeView() } @IBAction func sunsetChange(_ sender: NSDatePicker?) { guard let date = sender?.dateValue else { return } PrefsTime.manualSunset = timeFormatter.string(from: date) updateTimeView() } @IBAction func darkModeNightOverrideClick(_ sender: NSButton) { PrefsTime.darkModeNightOverride = sender.state == .on } @IBAction func testLocationClick(_ sender: Any) { // Get the location let location = Locations.sharedInstance location.getCoordinates(failure: { (_) in // swiftlint:disable:next line_length Aerial.helper.showInfoAlert(title: "Could not get your location", text: "Make sure you enabled location services on your Mac (and Wi-Fi!), and that Aerial (or legacyScreenSaver on macOS 10.15 and later) is allowed to use your location. If you use Aerial Companion, you will also need also allow location services for it.", button1: "OK", caution: true) }, success: { (coordinates) in let lat = String(format: "%.2f", coordinates.latitude) let lon = String(format: "%.2f", coordinates.longitude) Aerial.helper.showInfoAlert(title: "Success", text: "Aerial can access your location (latitude: \(lat), longitude: \(lon)) and will use it to show you the correct videos.") self.updateTimeView() }) } }
mit
edb02cef802d7d31f01a0e7a3bd972f0
33.18107
364
0.635685
4.708617
false
false
false
false
krizhanovskii/KKCircularProgressView
Pod/Classes/KKCircularProgressView.swift
1
8930
// // CircleLableProgressView.swift // UniversalFootApp // // Created by Krizhanovskii on 4/6/16. // Copyright © 2016 krizhanovskii. All rights reserved. // import UIKit import Foundation import KDCircularProgress /* KDCircularProgress taken from https://github.com/kaandedeoglu/KDCircularProgress . Look for more information */ public class KKCircularProgressView: UIView { private var isReverse : Bool = false /* variables for animating */ private var counter = 0 private var timer = NSTimer() private var percentToDone = 0 private var circleProgress = KDCircularProgress() private var percentLbl = UILabel() private var margins = CGFloat(10) /* Start percent from */ public var startPercent : Int = 0{ willSet(value) { let valueConverted = max(0,min(value,100)) self.circleProgress.angle = self.angleFromPercents(valueConverted) self.percentLbl.text = "\(valueConverted)%" } } /* Text color of Percent label */ public var labelColor : UIColor = .whiteColor() { willSet(color) { percentLbl.textColor = color } } /* The thickness of the background track. Between 0 and 1. Default is 0.5 */ public var trackThickness : CGFloat = KDCircularProgress().trackThickness { willSet(value) { circleProgress.trackThickness = value } } /* The color of the background track. Default is UIColor.blackColor(). */ public var trackColor : UIColor = KDCircularProgress().trackColor { willSet(color) { circleProgress.trackColor = color } } /* The thickness of the progress. Between 0 and 1. Default is 0.4 */ public var progressThickness : CGFloat = KDCircularProgress().progressThickness { willSet(value) { circleProgress.progressThickness = value } } /* the progres color. Default .whiteColor() */ public var progressColor : UIColor = .whiteColor() { willSet(color) { circleProgress.progressColors = [color] } } /* The colors used to generate the gradient of the progress. A gradient is used only if there is more than one color. A fill is used otherwise. The default is a white fill. */ public var progressColors : [UIColor] = KDCircularProgress().progressColors { willSet(colors) { circleProgress.progressColors = colors } } /* Clockwise if true, Counter-clockwise if false. Default is true. */ public var clockwise : Bool = KDCircularProgress().clockwise { willSet(value) { circleProgress.clockwise = value } } /* When true, the ends of the progress track will be drawn with a half circle radius. Default is false. */ public var roundedCorners : Bool = KDCircularProgress().roundedCorners { willSet(value) { circleProgress.roundedCorners = value } } /* Describes how many times the underlying gradient will perform a 2π rotation for each full cycle of the progress. Integer values recommended. Default is 0. */ public var gradientRotateSpeed : CGFloat = KDCircularProgress().gradientRotateSpeed { willSet(value) { circleProgress.gradientRotateSpeed = value } } /* The intensity of the glow. Between 0 and 1.0. Default is 1.0. */ public var glowAmount : CGFloat = KDCircularProgress().glowAmount { willSet(value) { circleProgress.glowAmount = value } } /* .Forward - The glow increases proportionaly to the angle. No glow at 0 degrees and full glow at 360 degrees. .Reverse - The glow increases inversely proportional to the angle. Full glow at 0 degrees and no glow at 360 degrees. .Constant - Constant glow. .NoGlow - No glow The default is .Forward */ public var glowMode : KDCircularProgressGlowMode = KDCircularProgress().glowMode { willSet(value) { circleProgress.glowMode = value } } /* The color of the center of the circle. Default is UIColor.clearColor(). */ public var progressInsideFillColor : UIColor = .clearColor() { willSet(color) { circleProgress.progressInsideFillColor = color } } override public var frame: CGRect { willSet(frame) { var _frame = frame _frame.size.width = min(frame.width,frame.height) _frame.size.height = min(frame.width,frame.height) super.frame = _frame self.configure() } } public override init(frame:CGRect) { var _frame = frame _frame.size.width = min(frame.width,frame.height) _frame.size.height = min(frame.width,frame.height) super.init(frame: _frame) self.configure() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /* animation actions */ @objc private func timerAction() { if isReverse { counter -= 1 } else { counter += 1 } self.percentLbl.text = "\(counter)%" if counter == percentToDone { timer.invalidate() counter == 0 } } /* start animating percent changes from 0 to percent */ public func startAnimatingWithDuration(duration : Double,toPercent percent:Int) { self.timer.invalidate() let toPercentConverted = max(0,min(percent,100)) self.percentToDone = toPercentConverted let timerTick = Double(duration/Double(percent)) let angleTo = self.angleFromPercents(toPercentConverted) self.circleProgress.animateToAngle(angleTo, duration: duration) { (flag) in } timer = NSTimer.scheduledTimerWithTimeInterval(timerTick, target: self, selector: #selector(self.timerAction), userInfo: nil, repeats: true) } /* start animating percent changes from to percent */ public func startAnimatingWithDuration(duration : Double, fromPercent:Int, toPercent:Int) { self.timer.invalidate() let fromPercentConverted = max(0,min(fromPercent,100)) let toPercentConverted = max(0,min(toPercent,100)) counter = fromPercentConverted self.percentToDone = toPercentConverted if toPercent > fromPercent { isReverse = false } else { isReverse = true } let timerTick = duration/abs(Double(toPercentConverted) - Double(fromPercentConverted)) timer = NSTimer.scheduledTimerWithTimeInterval(timerTick, target: self, selector: #selector(self.timerAction), userInfo: nil, repeats: true) let angleFrom = self.angleFromPercents(fromPercentConverted) let angleTo = self.angleFromPercents(toPercentConverted) self.circleProgress.animateFromAngle(angleFrom, toAngle: angleTo, duration: duration) { (flag) in } } private func angleFromPercents(percent:Int) -> Double { return 360*Double(percent)/100 } private func configure() { self.circleProgress.frame = bounds self.circleProgress.trackColor = self.trackColor self.circleProgress.trackThickness = self.trackThickness self.circleProgress.angle = self.angleFromPercents(self.startPercent) self.circleProgress.startAngle = -90 self.circleProgress.glowMode = self.glowMode self.circleProgress.glowAmount = self.glowAmount self.circleProgress.progressColors = self.progressColors self.circleProgress.progressThickness = self.progressThickness self.circleProgress.progressInsideFillColor = self.progressInsideFillColor self.circleProgress.gradientRotateSpeed = self.gradientRotateSpeed self.circleProgress.roundedCorners = self.roundedCorners self.circleProgress.clockwise = self.clockwise let minVal = min(bounds.width, bounds.height) self.percentLbl.frame = CGRectMake(margins, margins, minVal - margins*2, minVal - margins*2) percentLbl.text = "\(self.startPercent)%" percentLbl.textAlignment = .Center percentLbl.textColor = labelColor percentLbl.font = UIFont.systemFontOfSize(percentLbl.frame.width/3.3) self.addSubview(self.circleProgress) self.circleProgress.addSubview(self.percentLbl) } }
mit
0320cea527a97caac87f7865c5040516
29.786207
174
0.621192
4.794844
false
false
false
false
openHPI/xikolo-ios
Common/Data/Model/VisitProgress.swift
1
1620
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Foundation import Stockpile public class VisitProgress: NSObject, NSSecureCoding, IncludedPullable { public static var supportsSecureCoding: Bool { return true } public var itemsAvailable: Int? public var itemsVisited: Int? public var visitsPercentage: Double? public var percentage: Double? { guard let scored = itemsVisited else { return nil } guard let possible = itemsAvailable, possible > 0 else { return nil } return Double(scored) / Double(possible) } public required init(object: ResourceData) throws { self.itemsAvailable = try object.value(for: "items_available") self.itemsVisited = try object.value(for: "items_visited") self.visitsPercentage = try object.value(for: "visits_percentage") } public required init(coder decoder: NSCoder) { self.itemsAvailable = decoder.decodeObject(of: NSNumber.self, forKey: "items_available")?.intValue self.itemsVisited = decoder.decodeObject(of: NSNumber.self, forKey: "items_visited")?.intValue self.visitsPercentage = decoder.decodeObject(of: NSNumber.self, forKey: "visits_percentage")?.doubleValue } public func encode(with coder: NSCoder) { coder.encode(self.itemsAvailable.map(NSNumber.init(value:)), forKey: "items_available") coder.encode(self.itemsVisited.map(NSNumber.init(value:)), forKey: "items_visited") coder.encode(self.visitsPercentage.map(NSNumber.init(value:)), forKey: "visits_percentage") } }
gpl-3.0
e15ba30cab9ba12698774c1f171c0628
38.487805
113
0.704756
4.216146
false
false
false
false
erkekin/EERegression
EERegression/swix/swix/ndarray/helper-functions.swift
1
5818
// // helper-functions.swift // swix // // Created by Scott Sievert on 8/9/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation // NORM func norm(x: ndarray, ord:Double=2) -> Double{ // takes the norm of an array if ord==2 { return sqrt(sum(pow(x, power: 2)))} else if ord==1 { return sum(abs(x))} else if ord==0 { return sum(abs(x) > S2_THRESHOLD)} else if ord == -1 || ord == -2{ return pow(sum(abs(x)^ord.double), 1/ord.double) } else if ord.double == inf {return max(abs(x))} else if ord.double == -inf {return min(abs(x))} assert(false, "type of norm unrecongnized") return -1.0} func count_nonzero(x:ndarray)->Double{ return sum(abs(x) > S2_THRESHOLD) } // modifying elements of the array func clip(a:ndarray, a_min:Double, a_max:Double)->ndarray{ // clip the matrix var y = a.copy() y[argwhere(a < a_min)] <- a_min y[argwhere(a > a_max)] <- a_max return y } func reverse(x:ndarray) -> ndarray{ // reverse the array let y = x.copy() vDSP_vrvrsD(!y, 1.stride, y.n.length) return y } func delete(x:ndarray, idx:ndarray) -> ndarray{ // delete select elements var i = ones(x.n) i[idx] *= 0 let y = x[argwhere(i)] return y } func `repeat`(x: ndarray, N:Int, axis:Int=0) -> ndarray{ // repeat the array element wise or as a whole array var y = zeros((N, x.n)) // wrapping using OpenCV CVWrapper.`repeat`(!x, to:!y, n_x:x.n.cint, n_repeat:N.cint) if axis==0{} else if axis==1 { y = y.T} return y.flat } // SORTING and the like func sort(x:ndarray)->ndarray{ // sort the array and return a new array let y = x.copy() y.sort() return y } func unique(x:ndarray)->ndarray{ var y = sort(x) var z = concat(zeros(1), y: y) let diff = abs(z[1..<z.n] - z[0..<z.n-1]) > S2_THRESHOLD let un = y[argwhere(diff)] if abs(min(x)) < S2_THRESHOLD{ return sort(concat(zeros(1), y: un)) } else{ return un } } func shuffle(x:ndarray)->ndarray{ // randomly shuffle the array let y = x.copy() CVWrapper.shuffle(!y, n:y.n.cint) return y } func cbind(x:matrix, y:matrix)->matrix{ // concatenate two matrices assert(x.rows == y.rows, "to make a column bind, rows count should be equal.") let totalColumnCount = x.columns + y.columns let totalRowCount = x.rows var z = matrix(columns: totalColumnCount, rows: totalRowCount) for row in 0..<z.rows{ for column in 0..<z.columns{ z[row, column] = 9 } } // for i in 0..<min( x.count, y.count){ // let j = i*2 // z[j] = x[i] // z[j+1] = y[i] // // } return z } // SETS func intersection(x: ndarray, y:ndarray)->ndarray{ return x[argwhere(in1d(x, y: y))] } func union(x:ndarray, y:ndarray)->ndarray{ return unique(concat(x, y: y)) } func in1d(x: ndarray, y:ndarray)->ndarray{ var (xx, yy) = meshgrid(x, y: y) let i = abs(xx-yy) < S2_THRESHOLD let j = (sum(i, axis:1)) > 0.5 return 1-j } func concat(x:ndarray, y:ndarray)->ndarray{ // concatenate two matrices var z = zeros(x.n + y.n) z[0..<x.n] = x z[x.n..<y.n+x.n] = y return z } func bind(x:ndarray, y:ndarray)->ndarray{ // concatenate two matrices var z = zeros(x.n + y.n) for i in 0..<min( x.count, y.count){ let j = i*2 z[j] = x[i] z[j+1] = y[i] } return z } // ARG func argmax(x:ndarray)->Int{ // find the location of the max var m:CInt = 0 CVWrapper.argmax(!x, n: x.n.cint, max: &m) return Int(m) } func argmin(x:ndarray)->Int{ // find the location of the min var m:CInt = 0 CVWrapper.argmin(!x, n: x.n.cint, min: &m) return Int(m) } func argsort(x:ndarray)->ndarray{ // sort the array but use integers // the array of integers that OpenCV needs var y:[CInt] = Array(count:x.n, repeatedValue:0) // calling opencv's sortidx CVWrapper.argsort(!x, n: x.n.cint, into:&y) // the integer-->double conversion let z = zeros_like(x) vDSP_vflt32D(&y, 1.stride, !z, 1.stride, x.n.length) return z } func argwhere(idx: ndarray) -> ndarray{ // counts non-zero elements, return array of doubles (which can be indexed!). let i = arange(idx.n) let args = zeros(sum(idx).int) vDSP_vcmprsD(!i, 1.stride, !idx, 1.stride, !args, 1.stride, idx.n.length) return args } // LOGICAL func logical_and(x:ndarray, y:ndarray)->ndarray{ return x * y } func logical_or(x:ndarray, y:ndarray)->ndarray{ var i = x + y let j = argwhere(i > 0.5) i[j] <- 1.0 return i } func logical_not(x:ndarray)->ndarray{ return 1-x } func logical_xor(x:ndarray, y:ndarray)->ndarray{ let i = x + y let j = (i < 1.5) && (i > 0.5) return j } // PRINTING func println(x: ndarray, prefix:String="array([", postfix:String="])", newline:String="\n", format:String="%.3f", seperator:String=", ", printAllElements:Bool=false){ // print the matrix print(prefix, terminator: "") var suffix = seperator var printed = false for i in 0..<x.n{ if i==x.n-1 { suffix = "" } if printAllElements || (x.n)<16 || i<3 || i>(x.n-4){ print(NSString(format: format+suffix, x[i]), terminator: "") }else if printed == false{ printed = true print("..., ", terminator: "") } } print(postfix, terminator: "") print(newline, terminator: "") } func print(x: ndarray, prefix:String="ndarray([", postfix:String="])", format:String="%.3f", printWholeMatrix:Bool=false){ println(x, prefix:prefix, postfix:postfix, newline:"", format:format, printAllElements:printWholeMatrix) }
gpl-2.0
9bc8aebaa4acf9072e243e2c1adb6925
25.445455
166
0.579409
3.008273
false
false
false
false
VitoNYang/VTAutoSlideView
VTAutoSlideView/VTAutoSlideView.swift
1
12082
// // VTAutoSlideView.swift // VTAutoSlideView // // Created by hao on 2017/2/6. // Copyright © 2017年 Vito. All rights reserved. // import UIKit // MARK: - VTDirection enum public enum VTDirection: Int { case horizontal case vertical var collectionViewScrollDirection: UICollectionView.ScrollDirection { switch self { case .horizontal: return .horizontal case .vertical: return .vertical } } var scrollPosition: UICollectionView.ScrollPosition { switch self { case .horizontal: return .centeredHorizontally case .vertical: return .centeredVertically } } } // MARK: - VTAutoSlideViewDataSource @objc public protocol VTAutoSlideViewDataSource: NSObjectProtocol { func configuration(cell: UICollectionViewCell, for index: Int) } // MARK: - VTAutoSlideViewDelegate @objc public protocol VTAutoSlideViewDelegate: NSObjectProtocol { @objc optional func slideView(_ slideView: VTAutoSlideView!, didSelectItemAt index: Int) /// Can use this function to detect current index @objc optional func slideView(_ slideView: VTAutoSlideView!, currentIndex: Int) } // MARK: - VTAutoSlideView open class VTAutoSlideView: UIView { /// reuse identifier fileprivate static let cellIdentifier = "VTAutoSlideViewCell" fileprivate weak var collectionView: UICollectionView! /// Slide View Scroll Direction, default is horizontal private(set) var direction: VTDirection /// a flag to check has register cell private var isRegisterCell = false private var timer: Timer? open override var bounds: CGRect { didSet { // bounds change handle invalidateTimer() collectionView.collectionViewLayout.invalidateLayout() guard let indexPathForVisibleItem = collectionView.indexPathsForVisibleItems.first else { return } DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } strongSelf .collectionView .selectItem(at: indexPathForVisibleItem, animated: false, scrollPosition: strongSelf.direction.scrollPosition) strongSelf.setupTimer() } } } /// 自动轮播的间距 public var autoChangeTime: TimeInterval = 3 { didSet { setupTimer() } } /// 控制是否开启自动轮播,默认是 true public var activated = true { didSet { if activated { setupTimer() } else { invalidateTimer() } } } @IBOutlet public weak var dataSource: VTAutoSlideViewDataSource? @IBOutlet public weak var delegate: VTAutoSlideViewDelegate? /// 需要展示的数据源 public var dataList = [Any]() { didSet { guard isRegisterCell else { fatalError("必须先调用register(cellClass:) 或 register(nib:)方法") } collectionView.reloadData() } } /// 当数据多于一个的时候才允许滚动 fileprivate var totalCount: Int { return dataList.count > 1 ? dataList.count + 2 : dataList.count } // MARK: Lift Cycle public init(direction: VTDirection = .horizontal, dataSource: VTAutoSlideViewDataSource) { self.direction = direction self.dataSource = dataSource super.init(frame: .zero) setupCollectionView() } public required init?(coder aDecoder: NSCoder) { self.direction = .horizontal super.init(coder: aDecoder) setupCollectionView() } deinit { invalidateTimer() } open override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) DispatchQueue.main.async { [weak self] in guard let strongSelf = self, strongSelf.totalCount > 1 else { return } strongSelf .collectionView .selectItem(at: IndexPath(row: 1, section: 0), animated: false, scrollPosition: strongSelf.direction.scrollPosition) } } open override func removeFromSuperview() { super.removeFromSuperview() invalidateTimer() } open override func didMoveToSuperview() { super.didMoveToSuperview() setupTimer() } // MARK: Custom function /// register either a class or a nib from which to instantiate a cell open func register(cellClass: Swift.AnyClass?) { guard let cellClass = cellClass else { fatalError("cellClass 不能为空") } collectionView.register(cellClass, forCellWithReuseIdentifier: VTAutoSlideView.cellIdentifier) isRegisterCell = true } open func register(nib: UINib?) { guard let nib = nib else { fatalError("nib 不能为空") } collectionView.register(nib, forCellWithReuseIdentifier: VTAutoSlideView.cellIdentifier) isRegisterCell = true } private func setupCollectionView() { let flowLayout = UICollectionViewFlowLayout() flowLayout.minimumLineSpacing = 0 flowLayout.minimumInteritemSpacing = 0 flowLayout.scrollDirection = direction.collectionViewScrollDirection let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout) collectionView.isPagingEnabled = true collectionView.delegate = self collectionView.dataSource = self collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false self.addSubview(collectionView) NSLayoutConstraint.activate([ collectionView.leadingAnchor.constraint(equalTo: self.leadingAnchor), collectionView.topAnchor.constraint(equalTo: self.topAnchor), collectionView.trailingAnchor.constraint(equalTo: self.trailingAnchor), collectionView.bottomAnchor.constraint(equalTo: self.bottomAnchor) ]) self.collectionView = collectionView } fileprivate func setupTimer() { DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } strongSelf.invalidateTimer() if strongSelf.activated && strongSelf.dataList.count > 1{ let timer = Timer(timeInterval: strongSelf.autoChangeTime, target: strongSelf, selector: #selector(strongSelf.autoChangeCell), userInfo: nil, repeats: false) RunLoop.main.add(timer, forMode: .common) strongSelf.timer = timer } } } fileprivate func invalidateTimer() { timer?.invalidate() timer = nil } @objc fileprivate func autoChangeCell() { if let currentIndex = collectionView.indexPathsForVisibleItems.first { collectionView.scrollToItem(at: currentIndex + 1, at: direction.scrollPosition, animated: true) } setupTimer() } /// Converting the indexPath to dataList's real index fileprivate func currentIndex(indexPath: IndexPath) -> Int { var currentIndex: Int switch indexPath.row { case 0: currentIndex = dataList.count - 1 case totalCount - 1: currentIndex = 0 default: currentIndex = indexPath.row - 1 } return currentIndex } } // MARK: - Handle Scroll View Did Scroll extension VTAutoSlideView { public func scrollViewDidScroll(_ scrollView: UIScrollView) { guard scrollView == collectionView else { return } var offset: CGFloat var contentWidth: CGFloat let cellWidth: CGFloat switch direction { case .horizontal: offset = scrollView.contentOffset.x contentWidth = scrollView.contentSize.width cellWidth = scrollView.bounds.width case .vertical: offset = scrollView.contentOffset.y contentWidth = scrollView.contentSize.height cellWidth = scrollView.bounds.height } guard cellWidth > 0 else { return } if offset <= 0 { var targetContentOffset: CGPoint switch direction { case .horizontal: targetContentOffset = CGPoint(x: contentWidth - 2 * cellWidth, y: 0) case .vertical: targetContentOffset = CGPoint(x: 0, y: contentWidth - 2 * cellWidth) } collectionView.setContentOffset(targetContentOffset, animated: false) } else if offset >= contentWidth - cellWidth { var targetContentOffset: CGPoint switch direction { case .horizontal: targetContentOffset = CGPoint(x: cellWidth, y: 0) case .vertical: targetContentOffset = CGPoint(x: 0, y: cellWidth) } collectionView.setContentOffset(targetContentOffset, animated: false) } var currentIndex = Int(round(offset / cellWidth)) if currentIndex == 0{ currentIndex = dataList.count - 1 } else if currentIndex == totalCount - 1 { currentIndex = 0 } else { currentIndex -= 1 } delegate?.slideView?(self, currentIndex: currentIndex) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { guard scrollView == collectionView else { return } setupTimer() } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { guard scrollView == collectionView else { return } setupTimer() } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { guard scrollView == collectionView else { return } invalidateTimer() } } // MARK: - UICollectionViewDataSource extension VTAutoSlideView: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: VTAutoSlideView.cellIdentifier, for: indexPath) dataSource?.configuration(cell: cell, for: currentIndex(indexPath: indexPath)) return cell } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return totalCount } } // MARK: - UICollectionViewDelegate extension VTAutoSlideView: UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.slideView?(self, didSelectItemAt: currentIndex(indexPath: indexPath)) } } // MARK: - UICollectionViewDelegateFlowLayout extension VTAutoSlideView: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return collectionView.bounds.size } } // MARK: - Common function func +(lhs: IndexPath, rhs: Int) -> IndexPath{ return IndexPath(item: lhs.item + rhs, section: lhs.section) }
mit
2c6309ac2fa01950fb2e1e9ddabf43f7
31.585831
165
0.614433
5.856513
false
false
false
false
thePsguy/Nyan-Tunes
Nyan Tunes/NowPlayingAudioItem.swift
1
651
// // NowPlayingAudioItem.swift // Nyan Tunes // // Created by Pushkar Sharma on 21/10/2016. // Copyright © 2016 thePsguy. All rights reserved. // import Foundation class NowPlayingAudioItem:NSObject { var title: String! var artist: String! var url: URL? var audioData: Data? var duration: Int! var trackBytes: Int? init(title: String?, artist: String?, url: URL?, audioData: Data?, duration: Int, trackBytes: Int?) { self.title = title self.artist = artist self.url = url self.audioData = audioData self.duration = duration self.trackBytes = trackBytes } }
gpl-3.0
4f732f14fa9ed044d72401184f140aaa
22.214286
105
0.632308
3.77907
false
false
false
false
someoneAnyone/PageCollectionViewLayout
Pod/Classes/PageCollectionViewLayout.swift
1
7664
// // PageCollectionViewLayout.swift // PageCollectionViewLayout // // Created by Peter Ina on 10/30/15. // Copyright © 2015 Peter Ina. All rights reserved. // import UIKit /// Limitations // - only supports 1 section at the moment. // - only supports .Horizontal scrolling at the moment. // - at certain sizes, the first item isn't positioned correctly. public class PageCollectionViewLayout: UICollectionViewFlowLayout { private var safeCollectionView: UICollectionView { guard let collectionView = collectionView else { fatalError("no collection view found") } return collectionView } // How much is the view scaled down for a given screen. 1.0 == 100% of the bounds - any section insets public let scaleFactor: CGFloat = 1.0 private var pageWidth: CGFloat { return floor(safeCollectionView.bounds.size.width * scaleFactor) - sectionInset.totalHorizontalEdgeInset } private var pageHeight: CGFloat { return floor(safeCollectionView.bounds.size.height * scaleFactor) - sectionInset.totalVerticalEdgeInset } public override init() { super.init() scrollDirection = .Horizontal minimumInteritemSpacing = 10 registerClass(PageControlDecorationReusableView.self, forDecorationViewOfKind: PageControlDecorationReusableView.kind) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func prepareLayout() { // super.prepareLayout() //causes loop in viewDidLayoutSubviews. itemSize = CGSizeMake(pageWidth, pageHeight) setupLayout() } public override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attributesArray: [UICollectionViewLayoutAttributes] = super.layoutAttributesForElementsInRect(rect)!.map { ($0.copy() as! UICollectionViewLayoutAttributes) } // Resolves runtime warning from CollectionView regarding cache and copying orginal attributes. // Add decoration to the view. In this case its a UIPageControl let pageControlDecorationIndexPath = NSIndexPath(forItem: 0, inSection: 0) let pageControlDecorationAttributes = PageCollectionViewLayoutAttributes(forDecorationViewOfKind: PageControlDecorationReusableView.kind, withIndexPath: pageControlDecorationIndexPath) updatePageControlAttributes(pageControlDecorationAttributes) attributesArray.append(pageControlDecorationAttributes) // Add to the attributes array for attributes: UICollectionViewLayoutAttributes in attributesArray { if attributes.representedElementCategory != .Cell { continue } let frame = attributes.frame let distance = abs(safeCollectionView.contentOffset.x + safeCollectionView.contentInset.left - frame.origin.x) let scale = scaleFactor * min(max(1 - distance / (collectionView!.bounds.width), 0.75), 1) attributes.transform = CGAffineTransformMakeScale(scale, scale) } return attributesArray } public override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } public override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { let rectBounds: CGRect = safeCollectionView.bounds let halfWidth: CGFloat = rectBounds.size.width * CGFloat(0.50) let proposedContentOffsetCenterX: CGFloat = proposedContentOffset.x + halfWidth let proposedRect: CGRect = safeCollectionView.bounds let attributesArray: [UICollectionViewLayoutAttributes] = layoutAttributesForElementsInRect(proposedRect)!.map { ($0.copy() as! UICollectionViewLayoutAttributes) } var candidateAttributes:UICollectionViewLayoutAttributes? for layoutAttributes in attributesArray { if layoutAttributes.representedElementCategory != .Cell { continue } if candidateAttributes == nil { candidateAttributes = layoutAttributes continue } if fabsf(Float(layoutAttributes.center.x) - Float(proposedContentOffsetCenterX)) < fabsf(Float(candidateAttributes!.center.x) - Float(proposedContentOffsetCenterX)) { candidateAttributes = layoutAttributes } } if attributesArray.count == 0 { return CGPoint(x: proposedContentOffset.x - halfWidth * 2,y: proposedContentOffset.y) } return CGPoint(x: candidateAttributes!.center.x - halfWidth, y: proposedContentOffset.y) } public override func layoutAttributesForDecorationViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { if let decAttributes = layoutAttributesForDecorationViewOfKind(PageControlDecorationReusableView.kind, atIndexPath: indexPath) { updatePageControlAttributes(decAttributes as! PageCollectionViewLayoutAttributes) return decAttributes } return nil } private func setupLayout() { itemSize = CGSizeMake(pageWidth, pageHeight) safeCollectionView.showsHorizontalScrollIndicator = false safeCollectionView.decelerationRate = UIScrollViewDecelerationRateFast safeCollectionView.contentInset = UIEdgeInsets(top: 0, left: collectionView!.bounds.width / 2 - (pageWidth / 2), bottom: 0, right: safeCollectionView.bounds.width / 2 - (pageWidth / 2)) } private func updatePageControlAttributes(attributes: PageCollectionViewLayoutAttributes) { let indexPathsForVisibleItems = safeCollectionView.indexPathsForVisibleItems() let numberOfPages = safeCollectionView.numberOfItemsInSection(0) if let index = indexPathsForVisibleItems.first { attributes.currentPage = index.item } let currentBounds = collectionView!.bounds let contentOffset = collectionView!.contentOffset let frame = CGRect(x:0, y: currentBounds.maxY - 40, width: (collectionView?.bounds.width)!, height: 40) attributes.frame = frame attributes.zIndex = Int.max attributes.hidden = false attributes.center = CGPointMake((collectionView?.center.x)! + contentOffset.x, frame.midY) attributes.numberOfPages = numberOfPages } } // MARK: Extensions for common tasks that help. public extension UICollectionViewFlowLayout { public func isValidOffset(offset: CGFloat) -> Bool { return (offset >= CGFloat(minContentOffset) && offset <= CGFloat(maxContentOffset)) } public var minContentOffset: CGFloat { return -CGFloat(collectionView!.contentInset.left) } public var maxContentOffset: CGFloat { return CGFloat(minContentOffset + collectionView!.contentSize.width - itemSize.width) } public var snapStep: CGFloat { return itemSize.width + minimumLineSpacing; } } public extension UIEdgeInsets { public var totalHorizontalEdgeInset: CGFloat { return left + right } public var totalVerticalEdgeInset: CGFloat { return top + bottom } }
mit
6b03fb78cb565da8fba98793ba20b3f0
38.096939
265
0.680282
6.014914
false
false
false
false
AlbertWu0212/MyDailyTodo
MyDailyTodo/MyDailyTodo/ListDetailViewController.swift
1
3077
// // ListDetailViewController.swift // MyDailyTodo // // Created by WuZhengBin on 16/7/4. // Copyright © 2016年 WuZhengBin. All rights reserved. // import UIKit protocol ListDetailViewControllerDelegate: class { func listDetailViewControllerDidCancel(controller: ListDetailViewController) func listDetailViewController(controller: ListDetailViewController, didFinishAddingChecklist checklist: Checklist) func listDetailViewController(controller: ListDetailViewController, didFinishEditingChecklist checklist: Checklist) } class ListDetailViewController: UITableViewController, UITextFieldDelegate, IconPickerControllerDelegate { @IBOutlet weak var textField: UITextField! @IBOutlet weak var doneBarButton: UIBarButtonItem! @IBOutlet weak var iconImageView: UIImageView! var iconName = "Folder" weak var delegate: ListDetailViewControllerDelegate? var checklistToEdit: Checklist? // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() if let checklist = checklistToEdit { title = "Edit Checklist" textField.text = checklist.name doneBarButton.enabled = true iconName = checklist.iconName } iconImageView.image = UIImage(named: iconName) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) textField.becomeFirstResponder() } // MARK: IBActions @IBAction func cancel() { delegate?.listDetailViewControllerDidCancel(self) } @IBAction func done() { if let checklist = checklistToEdit { checklist.name = textField.text! checklist.iconName = iconName delegate?.listDetailViewController(self, didFinishEditingChecklist: checklist) } else { let checklist = Checklist(name: textField.text!,iconName: iconName) delegate?.listDetailViewController(self, didFinishAddingChecklist: checklist) } } // MARK: TableView Datasource & Delegate override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { if indexPath.section == 1 { return indexPath } else { return nil } } // MARK: TextField Delegate func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let oldText: NSString = textField.text! let newText: NSString = oldText.stringByReplacingCharactersInRange(range, withString: string) doneBarButton.enabled = (newText.length > 0) return true } // MARK: Segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "PickIcon" { let controller = segue.destinationViewController as! IconPickerViewController controller.delegate = self } } // MARK: IconPickerController delegate func iconPicker(picker: IconPickerViewController, didPickIcon iconName: String) { self.iconName = iconName iconImageView.image = UIImage(named: iconName) navigationController?.popViewControllerAnimated(true) } }
mit
c3a8b50d2466305d4f45096923ee71f8
31.702128
130
0.741705
5.346087
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/TableViewDataSources/DailyTableViewDataSource.swift
1
1874
// // DailyTableViewDataSoure.swift // Habitica // // Created by Phillip Thelen on 07.03.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models class DailyTableViewDataSource: TaskTableViewDataSource { init(predicate: NSPredicate) { super.init(predicate: predicate, taskType: TaskType.daily) } override func configure(cell: TaskTableViewCell, indexPath: IndexPath, task: TaskProtocol) { super.configure(cell: cell, indexPath: indexPath, task: task) if let dailycell = cell as? DailyTableViewCell { dailycell.checkboxTouched = {[weak self] in if task.isValid == false { return } self?.scoreTask(task: task, direction: task.completed ? .down : .up, soundEffect: .dailyCompleted) } dailycell.checklistItemTouched = {[weak self] checklistItem in if task.isValid == false { return } self?.disposable.add(self?.repository.score(checklistItem: checklistItem, task: task).observeCompleted {}) } dailycell.checklistIndicatorTouched = {[weak self] in if task.isValid == false { return } self?.expandSelectedCell(indexPath: indexPath) } } } override func predicates(filterType: Int) -> [NSPredicate] { var predicates = super.predicates(filterType: filterType) switch filterType { case 1: predicates.append(NSPredicate(format: "completed == false && isDue == true")) case 2: predicates.append(NSPredicate(format: "completed == true || isDue == false")) default: break } return predicates } }
gpl-3.0
562c912f751d8858b3055af6889c6df0
33.685185
122
0.582488
4.981383
false
false
false
false
littlelightwang/firefox-ios
Providers/AccountManager.swift
2
6494
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation let SuiteName = "group.org.allizom.Client" let KeyUsername = "username" let KeyLoggedIn = "loggedIn" class AccountProfileManager: NSObject { let loginCallback: (account: Profile) -> () let logoutCallback: LogoutCallback private let userDefaults = NSUserDefaults(suiteName: SuiteName)! init(loginCallback: (account: Profile) -> (), logoutCallback: LogoutCallback) { self.loginCallback = loginCallback self.logoutCallback = logoutCallback } func getAccount() -> Profile? { if !isLoggedIn() { return nil } if let user = getUsername() { let credential = getKeychainUser(user) return getRESTAccount(credential) } return nil } private func isLoggedIn() -> Bool { if let loggedIn = userDefaults.objectForKey(KeyLoggedIn) as? Bool { return loggedIn } return false } func getUsername() -> String? { return userDefaults.objectForKey(KeyUsername) as? String } // TODO: Logging in once saves the credentials for the entire session, making it impossible // to really log out. Using "None" as persistence should fix this -- why doesn't it? func login(username: String, password: String, error: ((error: RequestError) -> ())) { let credential = NSURLCredential(user: username, password: password, persistence: .None) RestAPI.sendRequest( credential, // TODO: this should use a different request request: "bookmarks/recent", success: { _ in println("Logged in as user \(username)") self.setKeychainUser(username, password: password) let account = self.getRESTAccount(credential) self.loginCallback(account: account) }, error: error ) } private func getRESTAccount(credential: NSURLCredential) -> RESTAccountProfile { return RESTAccountProfile(localName: "default", credential: credential, logoutCallback: { account in // Remove this user from the keychain, regardless of whether the account is actually logged in. self.removeKeychain(credential.user!) // If the username is the active account, log out. if credential.user! == self.getUsername() { self.userDefaults.removeObjectForKey(KeyUsername) self.userDefaults.setObject(false, forKey: KeyLoggedIn) self.logoutCallback(profile: account) } }) } func getKeychainUser(username: NSString) -> NSURLCredential { let kSecClassValue = NSString(format: kSecClass) let kSecAttrAccountValue = NSString(format: kSecAttrAccount) let kSecValueDataValue = NSString(format: kSecValueData) let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword) let kSecAttrServiceValue = NSString(format: kSecAttrService) let kSecMatchLimitValue = NSString(format: kSecMatchLimit) let kSecReturnDataValue = NSString(format: kSecReturnData) let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne) var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, "Firefox105", username, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue]) var dataTypeRef :Unmanaged<AnyObject>? // Search for the keychain items let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef) let opaque = dataTypeRef?.toOpaque() var contentsOfKeychain: NSString? if let op = opaque? { let retrievedData = Unmanaged<NSData>.fromOpaque(op).takeUnretainedValue() // Convert the data retrieved from the keychain into a string contentsOfKeychain = NSString(data: retrievedData, encoding: NSUTF8StringEncoding) } else { println("Nothing was retrieved from the keychain. Status code \(status)") } let credential = NSURLCredential(user: username, password: contentsOfKeychain!, persistence: .None) return credential } private func removeKeychain(username: NSString) { let kSecClassValue = NSString(format: kSecClass) let kSecAttrAccountValue = NSString(format: kSecAttrAccount) let kSecValueDataValue = NSString(format: kSecValueData) let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword) let kSecAttrServiceValue = NSString(format: kSecAttrService) let kSecMatchLimitValue = NSString(format: kSecMatchLimit) let kSecReturnDataValue = NSString(format: kSecReturnData) let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne) let query = NSDictionary(objects: [kSecClassGenericPassword, "Client", username], forKeys: [kSecClass,kSecAttrService, kSecAttrAccount]) SecItemDelete(query as CFDictionaryRef) } private func setKeychainUser(username: String, password: String) -> Bool { let kSecClassValue = NSString(format: kSecClass) let kSecAttrAccountValue = NSString(format: kSecAttrAccount) let kSecValueDataValue = NSString(format: kSecValueData) let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword) let kSecAttrServiceValue = NSString(format: kSecAttrService) let kSecMatchLimitValue = NSString(format: kSecMatchLimit) let kSecReturnDataValue = NSString(format: kSecReturnData) let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne) let secret: NSData = password.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let query = NSDictionary(objects: [kSecClassGenericPassword, "Firefox105", username, secret], forKeys: [kSecClass,kSecAttrService, kSecAttrAccount, kSecValueData]) SecItemDelete(query as CFDictionaryRef) SecItemAdd(query as CFDictionaryRef, nil) userDefaults.setObject(username, forKey: KeyUsername) userDefaults.setObject(true, forKey: KeyLoggedIn) return true } }
mpl-2.0
30b9b04ae219499c448b74625d78cdf9
42.006623
287
0.689714
5.407161
false
false
false
false
lyimin/iOS-Animation-Demo
iOS-Animation学习笔记/iOS-Animation学习笔记/Extension/UIView+XM.swift
1
2003
// // UIImageView+XM.swift // baiduCourse // // Created by 梁亦明 on 15/9/12. // Copyright © 2015年 xiaoming. All rights reserved. // import Foundation import UIKit public extension UIView { /** 添加点击事件 - parameter target: 对象 - parameter action: 动作 */ public func viewAddTarget(_ target : AnyObject,action : Selector) { let tap = UITapGestureRecognizer(target: target, action: action) self.isUserInteractionEnabled = true self.addGestureRecognizer(tap) } public var x : CGFloat { get { return self.frame.origin.x } set { var frame = self.frame frame.origin.x = newValue self.frame = frame } } public var y : CGFloat { get { return self.frame.origin.y } set { var frame = self.frame frame.origin.y = newValue self.frame = frame } } public var width : CGFloat { get { return self.frame.size.width } set { var frame = self.frame frame.size.width = newValue self.frame = frame } } public var height : CGFloat { get { return self.frame.size.height } set { var frame = self.frame frame.size.height = newValue self.frame = frame } } public var size : CGSize { get { return self.frame.size } set { var frame = self.frame frame.size = newValue self.frame = frame } } public var origin : CGPoint { get { return self.frame.origin } set { var frame = self.frame frame.origin = newValue self.frame = frame } } }
mit
5e610cde7ab8c0473eed3329bad9f95d
19.350515
72
0.472138
4.791262
false
false
false
false
Shuangzuan/Pew
Pew/Powerup.swift
1
1175
// // Powerup.swift // Pew // // Created by Shuangzuan He on 4/20/15. // Copyright (c) 2015 Pretty Seven. All rights reserved. // import SpriteKit class Powerup: Entity { required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init() { super.init(imageNamed: "powerup", maxHp: 1, healthBarType: .None) setupCollisionBody() } private func setupCollisionBody() { let offset = CGPoint(x: size.width * anchorPoint.x, y: size.height * anchorPoint.y) let path = CGPathCreateMutable() moveToPoint(CGPoint(x: 9, y: 30), path: path, offset: offset) addLineToPoint(CGPoint(x: 54, y: 29), path: path, offset: offset) addLineToPoint(CGPoint(x: 54, y: 8), path: path, offset: offset) addLineToPoint(CGPoint(x: 8, y: 9), path: path, offset: offset) CGPathCloseSubpath(path) physicsBody = SKPhysicsBody(polygonFromPath: path) physicsBody?.categoryBitMask = PhysicsCategory.Powerup physicsBody?.collisionBitMask = 0 physicsBody?.contactTestBitMask = PhysicsCategory.Player } }
mit
80bed6ba37f47d5b13ff3b0a10dcf279
30.756757
91
0.637447
4.151943
false
false
false
false
rjstelling/HTTPFormRequest
Projects/HTTPFormEncoder/HTTPFormEncoder/HTTPFormEncoder.swift
1
4648
// // HTTPFormEncoder.swift // HTTPFormEncoder // // Created by Richard Stelling on 10/07/2018. // Copyright © 2018 Lionheart Applications Ltd. All rights reserved. // import Foundation extension CodingUserInfoKey { internal static let ContainerName = CodingUserInfoKey(rawValue: "ContainerName.HTTPFormEncoder")! } public class HTTPFormEncoder: Encoder { public var codingPath: [CodingKey] = [] public var userInfo: [CodingUserInfoKey : Any] = [:] // This is an arrya so it can hold multiple parama keyed with `name[]` etc internal var parameters: [(String, String)] = [] // Config public typealias BoolBoxValue = (`true`: String, `false`: String) public var boolBoxValues: BoolBoxValue = (true: "true", false: "false") public init(codingPath: [CodingKey] = []) { self.codingPath = codingPath } public func encode<T>(_ value: T) throws -> [(String, String)] where T : Encodable { try value.encode(to: self) return self.parameters } internal func box(_ value: Bool) -> String { return "\(value ? self.boolBoxValues.true : self.boolBoxValues.false)" } internal func box(_ value: Int) -> String { return "\(value)" } internal func box(_ value: Int8) -> String { return "\(value)" } internal func box(_ value: Int16) -> String { return "\(value)" } internal func box(_ value: Int32) -> String { return "\(value)" } internal func box(_ value: Int64) -> String { return "\(value)" } internal func box(_ value: UInt) -> String { return "\(value)" } internal func box(_ value: UInt8) -> String { return "\(value)" } internal func box(_ value: UInt16) -> String { return "\(value)" } internal func box(_ value: UInt32) -> String { return "\(value)" } internal func box(_ value: UInt64) -> String { return "\(value)" } internal func box(_ value: Float) -> String { return "\(value)" } internal func box(_ value: Double) -> String { return "\(value)" } internal func box(_ value: String) -> String { return value } internal func box_<T: Encodable>(_ value: T) throws -> String /*where T : Encodable*/ { if T.self == Int.self { return self.box(value as! Int) } if T.self == Int64.self { //TODO: all other ints return self.box(value as! Int64) } else if T.self == Double.self { return self.box(value as! Double) } else if T.self == Float.self { return self.box(value as! Float) } else if T.self == Bool.self { return self.box(value as! Bool) } else if T.self == String.self { return self.box(value as! String) } else { fatalError() } } internal func box<T>(_ value: T, name: String) throws where T : Encodable { self.userInfo[.ContainerName] = name try value.encode(to: self) } } extension HTTPFormEncoder /* Encoder Overrides */ { public func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey { var containerName: String? = self.codingPath.first?.stringValue if let name = containerName { containerName = self.codingPath[1...].reduce(name) { $0 + "[\($1.stringValue)]" } } let container = HTTPFormKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, name: containerName) return KeyedEncodingContainer(container) } public func unkeyedContainer() -> UnkeyedEncodingContainer { let container = HTTPFormUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, name: self.userInfo[.ContainerName] as! String) return container } public func singleValueContainer() -> SingleValueEncodingContainer { var containerName: String? = self.codingPath.first?.stringValue if let name = containerName { containerName = self.codingPath[1...].reduce(name) { $0 + "[\($1.stringValue)]" } } return HTTPFormSingleValueEncodingContainer(referencing: self, codingPath: self.codingPath, name: containerName ?? "UNSUPPORTED") } public func nestedContainer<NestedKey, Key>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { fatalError("NOT IMP") } public func nestedUnkeyedContainer<Key>(forKey key: Key) -> UnkeyedEncodingContainer { fatalError("NOT IMP") } }
mit
aab6cd23d3684c59233ef6b78de10f3d
36.780488
152
0.611362
4.413105
false
false
false
false
practicalswift/swift
test/IDE/infer_import_as_member.swift
34
4894
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/custom-modules/CollisionImportAsMember.h -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=InferImportAsMember -always-argument-labels -enable-infer-import-as-member -skip-unavailable > %t.printed.A.txt // RUN: %target-swift-frontend -typecheck -import-objc-header %S/Inputs/custom-modules/CollisionImportAsMember.h -I %t -I %S/Inputs/custom-modules %s -enable-infer-import-as-member -verify // RUN: %FileCheck %s -check-prefix=PRINT -strict-whitespace < %t.printed.A.txt // REQUIRES: objc_interop import InferImportAsMember let mine = IAMStruct1() let _ = mine.getCollisionNonProperty(1) // TODO: more cases, eventually exhaustive, as we start inferring the result we // want // PRINT-LABEL: struct IAMStruct1 { // PRINT-NEXT: var x: Double // PRINT-NEXT: var y: Double // PRINT-NEXT: var z: Double // PRINT-NEXT: init() // PRINT-NEXT: init(x x: Double, y y: Double, z z: Double) // PRINT-NEXT: } // PRINT-LABEL: extension IAMStruct1 { // PRINT-NEXT: static var globalVar: Double // // PRINT-LABEL: /// Init // PRINT-NEXT: init(copyIn in: IAMStruct1) // PRINT-NEXT: init(simpleValue value: Double) // PRINT-NEXT: init(redundant redundant: Double) // PRINT-NEXT: init(specialLabel specialLabel: ()) // // PRINT-LABEL: /// Methods // PRINT-NEXT: func invert() -> IAMStruct1 // PRINT-NEXT: mutating func invertInPlace() // PRINT-NEXT: func rotate(radians radians: Double) -> IAMStruct1 // PRINT-NEXT: func selfComesLast(x x: Double) // PRINT-NEXT: func selfComesThird(a a: Double, b b: Float, x x: Double) // // PRINT-LABEL: /// Properties // PRINT-NEXT: var radius: Double { get nonmutating set } // PRINT-NEXT: var altitude: Double // PRINT-NEXT: var magnitude: Double { get } // PRINT-NEXT: var length: Double // // PRINT-LABEL: /// Various instance functions that can't quite be imported as properties. // PRINT-NEXT: func getNonPropertyNumParams() -> Float // PRINT-NEXT: func setNonPropertyNumParams(a a: Float, b b: Float) // PRINT-NEXT: func getNonPropertyType() -> Float // PRINT-NEXT: func setNonPropertyType(x x: Double) // PRINT-NEXT: func getNonPropertyNoSelf() -> Float // PRINT-NEXT: static func setNonPropertyNoSelf(x x: Double, y y: Double) // PRINT-NEXT: func setNonPropertyNoGet(x x: Double) // PRINT-NEXT: func setNonPropertyExternalCollision(x x: Double) // // PRINT-LABEL: /// Various static functions that can't quite be imported as properties. // PRINT-NEXT: static func staticGetNonPropertyNumParams() -> Float // PRINT-NEXT: static func staticSetNonPropertyNumParams(a a: Float, b b: Float) // PRINT-NEXT: static func staticGetNonPropertyNumParamsGetter(d d: Double) // PRINT-NEXT: static func staticGetNonPropertyType() -> Float // PRINT-NEXT: static func staticSetNonPropertyType(x x: Double) // PRINT-NEXT: static func staticGetNonPropertyNoSelf() -> Float // PRINT-NEXT: static func staticSetNonPropertyNoSelf(x x: Double, y y: Double) // PRINT-NEXT: static func staticSetNonPropertyNoGet(x x: Double) // // PRINT-LABEL: /// Static method // PRINT-NEXT: static func staticMethod() -> Double // PRINT-NEXT: static func tlaThreeLetterAcronym() -> Double // // PRINT-LABEL: /// Static computed properties // PRINT-NEXT: static var staticProperty: Double // PRINT-NEXT: static var staticOnlyProperty: Double { get } // // PRINT-LABEL: /// Omit needless words // PRINT-NEXT: static func onwNeedlessTypeArgLabel(_ Double: Double) -> Double // // PRINT-LABEL: /// Fuzzy // PRINT-NEXT: init(fuzzy fuzzy: ()) // PRINT-NEXT: init(fuzzyWithFuzzyName fuzzyWithFuzzyName: ()) // PRINT-NEXT: init(fuzzyName fuzzyName: ()) // // PRINT-NEXT: func getCollisionNonProperty(_ _: Int32) -> Float // // PRINT-NEXT: } // // PRINT-NEXT: func __IAMStruct1IgnoreMe(_ s: IAMStruct1) -> Double // // PRINT-LABEL: /// Mutable // PRINT-NEXT: struct IAMMutableStruct1 { // PRINT-NEXT: init() // PRINT-NEXT: } // PRINT-NEXT: extension IAMMutableStruct1 { // PRINT-NEXT: init(with withIAMStruct1: IAMStruct1) // PRINT-NEXT: init(url url: UnsafePointer<Int8>!) // PRINT-NEXT: func doSomething() // PRINT-NEXT: } // // PRINT-LABEL: struct TDStruct { // PRINT-NEXT: var x: Double // PRINT-NEXT: init() // PRINT-NEXT: init(x x: Double) // PRINT-NEXT: } // PRINT-NEXT: extension TDStruct { // PRINT-NEXT: init(float Float: Float) // PRINT-NEXT: } // // PRINT-LABEL: /// Class // PRINT-NEXT: class IAMClass { // PRINT-NEXT: } // PRINT-NEXT: typealias IAMOtherName = IAMClass // PRINT-NEXT: extension IAMClass { // PRINT-NEXT: class var typeID: UInt32 { get } // PRINT-NEXT: init!(i i: Double) // PRINT-NEXT: class func invert(_ iamOtherName: IAMOtherName!) // PRINT-NEXT: }
apache-2.0
2d7bd6445608e45833c18f1321d63d56
42.309735
329
0.688803
3.370523
false
false
false
false
mergesort/Communicado
Sources/Communicado/ShareDestination.swift
1
5717
import MessageUI import Photos import Social import UIKit /// A type that defines the values needed for a destination to share to. public protocol ShareDestination { /// The name of the destination we're sharing to. static var name: String { get } /// A computed var telling us whether or not we are currently capable of sharing to this destination. var canShare: Bool { get } /// A `UIActivityType` of the destination that we are sharing to. var activityType: UIActivity.ActivityType { get } } /// A type that defines the values needed for a social network backed destination to share to. public protocol SocialShareDestination: ShareDestination { /// The name of the destination we're sharing to. var name: String { get } } /// A ShareDestination for sharing to Messages. public struct MessagesShareDestination: ShareDestination { public static let name = UIActivity.ActivityType.message.rawValue public var canShare: Bool { return MFMessageComposeViewController.canSendText() } public var activityType: UIActivity.ActivityType { return UIActivity.ActivityType(MessagesShareDestination.name) } public init() {} } /// A ShareDestination for sharing to Mail. public struct MailShareDestination: ShareDestination { public static let name = UIActivity.ActivityType.mail.rawValue public var canShare: Bool { return MFMailComposeViewController.canSendMail() } public var activityType: UIActivity.ActivityType { return UIActivity.ActivityType(MailShareDestination.name) } public init() {} } /// A ShareDestination for sharing to the camera roll. public struct PhotosShareDestination: ShareDestination { public static let name = UIActivity.ActivityType.saveToCameraRoll.rawValue public var canShare: Bool { return PHPhotoLibrary.authorizationStatus() == .authorized } public var activityType: UIActivity.ActivityType { return UIActivity.ActivityType(PhotosShareDestination.name) } public init() {} } /// A ShareDestination for sharing to the pasteboard. public struct PasteboardShareDestination: ShareDestination { public static let name = UIActivity.ActivityType.copyToPasteboard.rawValue public var canShare: Bool { return true } public var activityType: UIActivity.ActivityType { return UIActivity.ActivityType(PasteboardShareDestination.name) } public init() {} } /// A ShareDestination for sharing to the `UIActivityViewController`. public struct ActivityControllerShareDestination: ShareDestination { public static let name = "com.apple.activityController" public var canShare: Bool { return true } public var activityType: UIActivity.ActivityType { return UIActivity.ActivityType(ActivityControllerShareDestination.name) } public init() {} } /// A ShareDestination for sharing to Twitter. /// Deprecated in iOS 11, as Apple removed the Social framework, which this was based on. @available(iOS, deprecated: 11.0) public struct TwitterShareDestination: SocialShareDestination { public static let name = SLServiceTypeTwitter public let name = SLServiceTypeTwitter public var canShare: Bool { return SLComposeViewController.isAvailable(forServiceType: SLServiceTypeTwitter) } public var activityType: UIActivity.ActivityType { return UIActivity.ActivityType(TwitterShareDestination.name) } public init() {} } /// A ShareDestination for sharing to Facebook. /// Deprecated in iOS 11, as Apple removed the Social framework, which this was based on. @available(iOS, deprecated: 11.0) public struct FacebookShareDestination: SocialShareDestination { public static let name = SLServiceTypeFacebook public let name = SLServiceTypeFacebook public var canShare: Bool { return SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook) } public var activityType: UIActivity.ActivityType { return UIActivity.ActivityType(FacebookShareDestination.name) } public init() {} } /// A ShareDestination for sharing to Tencent Weibo. /// Deprecated in iOS 11, as Apple removed the Social framework, which this was based on. @available(iOS, deprecated: 11.0) public struct TencentWeiboShareDestination: SocialShareDestination { public static let name = SLServiceTypeTencentWeibo public let name = SLServiceTypeTencentWeibo public var canShare: Bool { return SLComposeViewController.isAvailable(forServiceType: SLServiceTypeTencentWeibo) } public var activityType: UIActivity.ActivityType { return UIActivity.ActivityType(TencentWeiboShareDestination.name) } public init() {} } /// A ShareDestination for sharing to Sina Weibo. /// Deprecated in iOS 11, as Apple removed the Social framework, which this was based on. @available(iOS, deprecated: 11.0) public struct SinaWeiboShareDestination: SocialShareDestination { public static let name = SLServiceTypeSinaWeibo public let name = SLServiceTypeSinaWeibo public var canShare: Bool { return SLComposeViewController.isAvailable(forServiceType: SLServiceTypeSinaWeibo) } public var activityType: UIActivity.ActivityType { return UIActivity.ActivityType(SinaWeiboShareDestination.name) } public init() {} } public extension UIActivity.ActivityType { /// A `UIActivityType` which indicates that a share activity was cancelled by the user. static let cancelled = UIActivity.ActivityType("com.plugin.cancelled") }
mit
2c613882d17f582fc4c74e9386ac94f2
29.572193
105
0.732727
5.293519
false
false
false
false
tapglue/snaasSdk-iOS
Sources/RxCompositePage.swift
2
1301
// // RxCompositePage.swift // Tapglue // // Created by John Nilsen on 9/30/16. // Copyright © 2016 Tapglue. All rights reserved. // import RxSwift open class RxCompositePage<T: DefaultInstanceEntity> { open var data: T { get { return feed.flatten() } } open var previous: Observable<RxCompositePage<T>> { get { return generatePreviousObservable() } } fileprivate var feed: CompositeFlattenableFeed<T> fileprivate var prevPointer: String? init(feed: CompositeFlattenableFeed<T>, previousPointer: String?) { self.feed = feed self.prevPointer = previousPointer } func generatePreviousObservable() -> Observable<RxCompositePage<T>> { guard let prevPointer = prevPointer else { return Observable.just(RxCompositePage<T>(feed: CompositeFlattenableFeed<T>(), previousPointer: nil)) } var request: URLRequest request = Router.getOnURL(prevPointer) return Http().execute(request).map { (json: [String: Any]) in let newFeed = self.feed.newCopy(json: json) let page = RxCompositePage<T>(feed: newFeed!, previousPointer: newFeed!.page?.before) return page } } }
apache-2.0
3bb6df8584926a9942fb0fca833f8c28
27.26087
113
0.617692
4.304636
false
false
false
false
huonw/swift
stdlib/public/SDK/Foundation/DateInterval.swift
4
9053
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import _SwiftCoreFoundationOverlayShims /// DateInterval represents a closed date interval in the form of [startDate, endDate]. It is possible for the start and end dates to be the same with a duration of 0. DateInterval does not support reverse intervals i.e. intervals where the duration is less than 0 and the end date occurs earlier in time than the start date. @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) public struct DateInterval : ReferenceConvertible, Comparable, Hashable, Codable { public typealias ReferenceType = NSDateInterval /// The start date. public var start : Date /// The end date. /// /// - precondition: `end >= start` public var end : Date { get { return start + duration } set { precondition(newValue >= start, "Reverse intervals are not allowed") duration = newValue.timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate } } /// The duration. /// /// - precondition: `duration >= 0` public var duration : TimeInterval { willSet { precondition(newValue >= 0, "Negative durations are not allowed") } } /// Initializes a `DateInterval` with start and end dates set to the current date and the duration set to `0`. public init() { let d = Date() start = d duration = 0 } /// Initialize a `DateInterval` with the specified start and end date. /// /// - precondition: `end >= start` public init(start: Date, end: Date) { if end < start { fatalError("Reverse intervals are not allowed") } self.start = start duration = end.timeIntervalSince(start) } /// Initialize a `DateInterval` with the specified start date and duration. /// /// - precondition: `duration >= 0` public init(start: Date, duration: TimeInterval) { precondition(duration >= 0, "Negative durations are not allowed") self.start = start self.duration = duration } /** Compare two DateIntervals. This method prioritizes ordering by start date. If the start dates are equal, then it will order by duration. e.g. Given intervals a and b ``` a. |-----| b. |-----| ``` `a.compare(b)` would return `.OrderedAscending` because a's start date is earlier in time than b's start date. In the event that the start dates are equal, the compare method will attempt to order by duration. e.g. Given intervals c and d ``` c. |-----| d. |---| ``` `c.compare(d)` would result in `.OrderedDescending` because c is longer than d. If both the start dates and the durations are equal, then the intervals are considered equal and `.OrderedSame` is returned as the result. */ public func compare(_ dateInterval: DateInterval) -> ComparisonResult { let result = start.compare(dateInterval.start) if result == .orderedSame { if self.duration < dateInterval.duration { return .orderedAscending } if self.duration > dateInterval.duration { return .orderedDescending } return .orderedSame } return result } /// Returns `true` if `self` intersects the `dateInterval`. public func intersects(_ dateInterval: DateInterval) -> Bool { return contains(dateInterval.start) || contains(dateInterval.end) || dateInterval.contains(start) || dateInterval.contains(end) } /// Returns a DateInterval that represents the interval where the given date interval and the current instance intersect. /// /// In the event that there is no intersection, the method returns nil. public func intersection(with dateInterval: DateInterval) -> DateInterval? { if !intersects(dateInterval) { return nil } if self == dateInterval { return self } let timeIntervalForSelfStart = start.timeIntervalSinceReferenceDate let timeIntervalForSelfEnd = end.timeIntervalSinceReferenceDate let timeIntervalForGivenStart = dateInterval.start.timeIntervalSinceReferenceDate let timeIntervalForGivenEnd = dateInterval.end.timeIntervalSinceReferenceDate let resultStartDate : Date if timeIntervalForGivenStart >= timeIntervalForSelfStart { resultStartDate = dateInterval.start } else { // self starts after given resultStartDate = start } let resultEndDate : Date if timeIntervalForGivenEnd >= timeIntervalForSelfEnd { resultEndDate = end } else { // given ends before self resultEndDate = dateInterval.end } return DateInterval(start: resultStartDate, end: resultEndDate) } /// Returns `true` if `self` contains `date`. public func contains(_ date: Date) -> Bool { let timeIntervalForGivenDate = date.timeIntervalSinceReferenceDate let timeIntervalForSelfStart = start.timeIntervalSinceReferenceDate let timeIntervalforSelfEnd = end.timeIntervalSinceReferenceDate if (timeIntervalForGivenDate >= timeIntervalForSelfStart) && (timeIntervalForGivenDate <= timeIntervalforSelfEnd) { return true } return false } public var hashValue: Int { var buf: (UInt, UInt) = (UInt(start.timeIntervalSinceReferenceDate), UInt(end.timeIntervalSinceReferenceDate)) return withUnsafeMutablePointer(to: &buf) { $0.withMemoryRebound(to: UInt8.self, capacity: 2 * MemoryLayout<UInt>.size / MemoryLayout<UInt8>.size) { return Int(bitPattern: CFHashBytes($0, CFIndex(MemoryLayout<UInt>.size * 2))) } } } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) public static func ==(lhs: DateInterval, rhs: DateInterval) -> Bool { return lhs.start == rhs.start && lhs.duration == rhs.duration } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) public static func <(lhs: DateInterval, rhs: DateInterval) -> Bool { return lhs.compare(rhs) == .orderedAscending } } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) extension DateInterval : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { public var description: String { return "\(start) to \(end)" } public var debugDescription: String { return description } public var customMirror: Mirror { var c: [(label: String?, value: Any)] = [] c.append((label: "start", value: start)) c.append((label: "end", value: end)) c.append((label: "duration", value: duration)) return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct) } } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) extension DateInterval : _ObjectiveCBridgeable { public static func _getObjectiveCType() -> Any.Type { return NSDateInterval.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSDateInterval { return NSDateInterval(start: start, duration: duration) } public static func _forceBridgeFromObjectiveC(_ dateInterval: NSDateInterval, result: inout DateInterval?) { if !_conditionallyBridgeFromObjectiveC(dateInterval, result: &result) { fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ dateInterval : NSDateInterval, result: inout DateInterval?) -> Bool { result = DateInterval(start: dateInterval.startDate, duration: dateInterval.duration) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDateInterval?) -> DateInterval { var result: DateInterval? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) extension NSDateInterval : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self as DateInterval) } }
apache-2.0
66524151c5103cc5d1e2f88c2686866c
37.688034
327
0.638462
5.137911
false
false
false
false
YQqiang/Nunchakus
Pods/Kanna/Sources/Kanna/libxmlHTMLNode.swift
3
8282
/**@file libxmlHTMLNode.swift Kanna Copyright (c) 2015 Atsushi Kiwaki (@_tid_) 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 #if SWIFT_PACKAGE import SwiftClibxml2 #else import libxml2 #endif /** libxmlHTMLNode */ internal final class libxmlHTMLNode: XMLElement { var text: String? { if nodePtr != nil { return libxmlGetNodeContent(nodePtr!) } return nil } var toHTML: String? { let buf = xmlBufferCreate() htmlNodeDump(buf, docPtr, nodePtr) let html = String(cString: UnsafePointer((buf?.pointee.content)!)) xmlBufferFree(buf) return html } var toXML: String? { let buf = xmlBufferCreate() xmlNodeDump(buf, docPtr, nodePtr, 0, 0) let html = String(cString: UnsafePointer((buf?.pointee.content)!)) xmlBufferFree(buf) return html } var innerHTML: String? { if let html = self.toHTML { let inner = html.replacingOccurrences(of: "</[^>]*>$", with: "", options: .regularExpression, range: nil) .replacingOccurrences(of: "^<[^>]*>", with: "", options: .regularExpression, range: nil) return inner } return nil } var className: String? { return self["class"] } var tagName: String? { get { if nodePtr != nil { return String(cString: UnsafePointer((nodePtr?.pointee.name)!)) } return nil } set { if let newValue = newValue { xmlNodeSetName(nodePtr, newValue) } } } var content: String? { get { return text } set { if let newValue = newValue { let v = escape(newValue) xmlNodeSetContent(nodePtr, v) } } } var parent: XMLElement? { get { return libxmlHTMLNode(document: doc, docPtr: docPtr!, node: (nodePtr?.pointee.parent)!) } set { if let node = newValue as? libxmlHTMLNode { node.addChild(self) } } } fileprivate weak var weakDocument: XMLDocument? fileprivate var document: XMLDocument? fileprivate var docPtr: htmlDocPtr? = nil fileprivate var nodePtr: xmlNodePtr? = nil fileprivate var isRoot: Bool = false fileprivate var doc: XMLDocument? { return weakDocument ?? document } subscript(attributeName: String) -> String? { get { var attr = nodePtr?.pointee.properties while attr != nil { let mem = attr?.pointee if let tagName = String(validatingUTF8: UnsafeRawPointer((mem?.name)!).assumingMemoryBound(to: CChar.self)) { if attributeName == tagName { if let children = mem?.children { return libxmlGetNodeContent(children) } else { return "" } } } attr = attr?.pointee.next } return nil } set(newValue) { if let newValue = newValue { xmlSetProp(nodePtr, attributeName, newValue) } else { xmlUnsetProp(nodePtr, attributeName) } } } init(document: XMLDocument?, docPtr: xmlDocPtr) { self.weakDocument = document self.docPtr = docPtr self.nodePtr = xmlDocGetRootElement(docPtr) self.isRoot = true } init(document: XMLDocument?, docPtr: xmlDocPtr, node: xmlNodePtr) { self.document = document self.docPtr = docPtr self.nodePtr = node } // MARK: Searchable func xpath(_ xpath: String, namespaces: [String:String]?) -> XPathObject { let ctxt = xmlXPathNewContext(docPtr) if ctxt == nil { return XPathObject.none } ctxt?.pointee.node = nodePtr if let nsDictionary = namespaces { for (ns, name) in nsDictionary { xmlXPathRegisterNs(ctxt, ns, name) } } let result = xmlXPathEvalExpression(xpath, ctxt) defer { xmlXPathFreeObject(result) } xmlXPathFreeContext(ctxt) if result == nil { return XPathObject.none } return XPathObject(document: doc, docPtr: docPtr!, object: result!.pointee) } func xpath(_ xpath: String) -> XPathObject { return self.xpath(xpath, namespaces: nil) } func at_xpath(_ xpath: String, namespaces: [String:String]?) -> XMLElement? { return self.xpath(xpath, namespaces: namespaces).nodeSetValue.first } func at_xpath(_ xpath: String) -> XMLElement? { return self.at_xpath(xpath, namespaces: nil) } func css(_ selector: String, namespaces: [String:String]?) -> XPathObject { if let xpath = CSS.toXPath(selector) { if isRoot { return self.xpath(xpath, namespaces: namespaces) } else { return self.xpath("." + xpath, namespaces: namespaces) } } return XPathObject.none } func css(_ selector: String) -> XPathObject { return self.css(selector, namespaces: nil) } func at_css(_ selector: String, namespaces: [String:String]?) -> XMLElement? { return self.css(selector, namespaces: namespaces).nodeSetValue.first } func at_css(_ selector: String) -> XMLElement? { return self.css(selector, namespaces: nil).nodeSetValue.first } func addPrevSibling(_ node: XMLElement) { guard let node = node as? libxmlHTMLNode else { return } xmlAddPrevSibling(nodePtr, node.nodePtr) } func addNextSibling(_ node: XMLElement) { guard let node = node as? libxmlHTMLNode else { return } xmlAddNextSibling(nodePtr, node.nodePtr) } func addChild(_ node: XMLElement) { guard let node = node as? libxmlHTMLNode else { return } xmlUnlinkNode(node.nodePtr) xmlAddChild(nodePtr, node.nodePtr) } func removeChild(_ node: XMLElement) { guard let node = node as? libxmlHTMLNode else { return } xmlUnlinkNode(node.nodePtr) xmlFree(node.nodePtr) } } private func libxmlGetNodeContent(_ nodePtr: xmlNodePtr) -> String? { let content = xmlNodeGetContent(nodePtr) if let result = String(validatingUTF8: UnsafeRawPointer(content!).assumingMemoryBound(to: CChar.self)) { content?.deallocate(capacity: 1) return result } content?.deallocate(capacity: 1) return nil } let entities = [ "&": "&amp;", "<" : "&lt;", ">" : "&gt;", ] private func escape(_ str: String) -> String { var newStr = str for (unesc, esc) in entities { newStr = newStr.replacingOccurrences(of: unesc, with: esc, options: .regularExpression, range: nil) } return newStr }
mit
c3f013acf149afb4214cbf88c39be634
28.578571
125
0.579449
4.573164
false
false
false
false
skylib/SnapOnboarding-iOS
SnapOnboarding-iOSExample/Pods/HanekeSwift/Haneke/Data.swift
16
3434
// // Data.swift // Haneke // // Created by Hermes Pique on 9/19/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit // See: http://stackoverflow.com/questions/25922152/not-identical-to-self public protocol DataConvertible { associatedtype Result static func convertFromData(_ data:Data) -> Result? } public protocol DataRepresentable { func asData() -> Data! } private let imageSync = NSLock() extension UIImage : DataConvertible, DataRepresentable { public typealias Result = UIImage // HACK: UIImage data initializer is no longer thread safe. See: https://github.com/AFNetworking/AFNetworking/issues/2572#issuecomment-115854482 static func safeImageWithData(_ data:Data) -> Result? { imageSync.lock() let image = UIImage(data:data, scale: scale) imageSync.unlock() return image } public class func convertFromData(_ data: Data) -> Result? { let image = UIImage.safeImageWithData(data) return image } public func asData() -> Data! { return self.hnk_data() as Data! } fileprivate static let scale = UIScreen.main.scale } extension String : DataConvertible, DataRepresentable { public typealias Result = String public static func convertFromData(_ data: Data) -> Result? { let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) return string as? Result } public func asData() -> Data! { return self.data(using: String.Encoding.utf8) } } extension Data : DataConvertible, DataRepresentable { public typealias Result = Data public static func convertFromData(_ data: Data) -> Result? { return data } public func asData() -> Data! { return self } } public enum JSON : DataConvertible, DataRepresentable { public typealias Result = JSON case Dictionary([String:AnyObject]) case Array([AnyObject]) public static func convertFromData(_ data: Data) -> Result? { do { let object : Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) switch (object) { case let dictionary as [String:AnyObject]: return JSON.Dictionary(dictionary) case let array as [AnyObject]: return JSON.Array(array) default: return nil } } catch { Log.error(message: "Invalid JSON data", error: error) return nil } } public func asData() -> Data! { switch (self) { case .Dictionary(let dictionary): return try? JSONSerialization.data(withJSONObject: dictionary, options: JSONSerialization.WritingOptions()) case .Array(let array): return try? JSONSerialization.data(withJSONObject: array, options: JSONSerialization.WritingOptions()) } } public var array : [AnyObject]! { switch (self) { case .Dictionary(_): return nil case .Array(let array): return array } } public var dictionary : [String:AnyObject]! { switch (self) { case .Dictionary(let dictionary): return dictionary case .Array(_): return nil } } }
bsd-3-clause
18a2350af4bcb58b5f0b1f78cea5a67d
25.620155
148
0.606581
4.743094
false
false
false
false
NitWitStudios/NWSTokenView
Example/NWSTokenView/Controllers/NWSTokenViewExampleViewController.swift
1
15418
// // NWSTokenViewExampleViewController.swift // NWSTokenView // // Created by James Hickman on 8/11/15. // Copyright (c) 2015 Appmazo. All rights reserved. // import UIKit import NWSTokenView import DZNEmptyDataSet fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } class NWSTokenViewExampleViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NWSTokenDataSource, NWSTokenDelegate, UIGestureRecognizerDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate { @IBOutlet weak var tokenView: NWSTokenView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var tokenViewHeightConstraint: NSLayoutConstraint! let tokenViewMinHeight: CGFloat = 40.0 let tokenViewMaxHeight: CGFloat = 150.0 let tokenBackgroundColor = UIColor(red: 98.0/255.0, green: 203.0/255.0, blue: 255.0/255.0, alpha: 1.0) var isSearching = false var contacts: [NWSTokenContact]! var selectedContacts = [NWSTokenContact]() var filteredContacts = [NWSTokenContact]() override func viewDidLoad() { super.viewDidLoad() // Adjust tableView offset for keyboard NotificationCenter.default.addObserver(self, selector: #selector(NWSTokenViewExampleViewController.keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(NWSTokenViewExampleViewController.keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) // Create list of contacts to test let unsortedContacts = [ NWSTokenContact(name: "Albus Dumbledore", andImage: UIImage(named: "Albus-Dumbledore")!), NWSTokenContact(name: "Cedric Diggory", andImage: UIImage(named: "Cedric-Diggory")!), NWSTokenContact(name: "Cho Chang", andImage: UIImage(named: "Cho-Chang")!), NWSTokenContact(name: "Draco Malfoy", andImage: UIImage(named: "Draco-Malfoy")!), NWSTokenContact(name: "Fred Weasley", andImage: UIImage(named: "Fred-Weasley")!), NWSTokenContact(name: "George Weasley", andImage: UIImage(named: "George-Weasley")!), NWSTokenContact(name: "Ginny Weasley", andImage: UIImage(named: "Ginny-Weasley")!), NWSTokenContact(name: "Gregory Goyle", andImage: UIImage(named: "Gregory-Goyle")!), NWSTokenContact(name: "Harry Potter", andImage: UIImage(named: "Harry-Potter")!), NWSTokenContact(name: "Hermione Granger", andImage: UIImage(named: "Hermione-Granger")!), NWSTokenContact(name: "James Potter", andImage: UIImage(named: "James-Potter")!), NWSTokenContact(name: "Lily Potter", andImage: UIImage(named: "Lily-Potter")!), NWSTokenContact(name: "Luna Lovegood", andImage: UIImage(named: "Luna-Lovegood")!), NWSTokenContact(name: "Minerva McGonagal", andImage: UIImage(named: "Minerva-McGonagal")!), NWSTokenContact(name: "Moaning Myrtle", andImage: UIImage(named: "Moaning-Myrtle")!), NWSTokenContact(name: "Neville Longbottom", andImage: UIImage(named: "Neville-Longbottom")!), NWSTokenContact(name: "Nymphadora Tonks", andImage: UIImage(named: "Nymphadora-Tonks")!), NWSTokenContact(name: "Peter Pettigrew", andImage: UIImage(named: "Peter-Pettigrew")!), NWSTokenContact(name: "Remus Lupin", andImage: UIImage(named: "Remus-Lupin")!), NWSTokenContact(name: "Ron Weasley", andImage: UIImage(named: "Ron-Weasley")!), NWSTokenContact(name: "Rubeus Hagrid", andImage: UIImage(named: "Rubeus-Hagrid")!), NWSTokenContact(name: "Severus Snape", andImage: UIImage(named: "Severus-Snape")!), NWSTokenContact(name: "Sirius Black", andImage: UIImage(named: "Sirius-Black")!), NWSTokenContact(name: "Vincent Crabbe", andImage: UIImage(named: "Vincent-Crabbe")!), NWSTokenContact(name: "Voldemort", andImage: UIImage(named: "Voldemort")!), ] contacts = NWSTokenContact.sortedContacts(unsortedContacts) // TableView tableView.tableFooterView = UIView(frame: CGRect.zero) tableView.separatorStyle = .singleLine // TokenView tokenView.layoutIfNeeded() tokenView.dataSource = self tokenView.delegate = self tokenView.reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UIGestureRecognizerDelegate func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if let view = touch.view { if view.isDescendant(of: tableView) { return false } } return true } // MARK: Keyboard @objc func keyboardWillShow(_ notification: Notification) { if let keyboardSize = ((notification as NSNotification).userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) tableView.contentInset = contentInsets tableView.scrollIndicatorInsets = contentInsets } } @objc func keyboardWillHide(_ notification: NotificationCenter) { tableView.contentInset = UIEdgeInsets.zero tableView.scrollIndicatorInsets = UIEdgeInsets.zero } @IBAction func didTapView(_ sender: UITapGestureRecognizer) { dismissKeyboard() } func dismissKeyboard() { tokenView.resignFirstResponder() tokenView.endEditing(true) } // MARK: Search Contacts func searchContacts(_ text: String) { // Reset filtered contacts filteredContacts = [] // Filter contacts if contacts.count > 0 { filteredContacts = contacts.filter({ (contact: NWSTokenContact) -> Bool in return contact.name.range(of: text, options: .caseInsensitive) != nil }) self.isSearching = true self.tableView.reloadData() } } func didTypeEmailInTokenView() { let email = self.tokenView.textView.text.trimmingCharacters(in: CharacterSet.whitespaces) let contact = NWSTokenContact(name: email, andImage: UIImage(named: "TokenPlaceholder")!) self.selectedContacts.append(contact) self.tokenView.textView.text = "" self.isSearching = false self.tokenView.reloadData() self.tableView.reloadData() } // MARK: UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } // MARK: UITableViewDelegate func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if isSearching { return filteredContacts.count } return contacts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "NWSTokenViewExampleCellIdentifier", for: indexPath) as! NWSTokenViewExampleCell let currentContacts: [NWSTokenContact]! // Check if searching if isSearching { currentContacts = filteredContacts } else { currentContacts = contacts } // Load contact data let contact = currentContacts[(indexPath as NSIndexPath).row] cell.loadWithContact(contact) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! NWSTokenViewExampleCell cell.isSelected = false // Check if already selected if !selectedContacts.contains(cell.contact) { cell.contact.isSelected = true selectedContacts.append(cell.contact) isSearching = false tokenView.textView.text = "" tokenView.reloadData() tableView.reloadData() } } // MARK: DZNEmptyDataSetSource func customView(forEmptyDataSet scrollView: UIScrollView!) -> UIView! { if let view = UINib(nibName: "EmptyDataSet", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as? UIView { view.frame = scrollView.bounds view.translatesAutoresizingMaskIntoConstraints = false view.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight] return view } return nil } // MARK: NWSTokenDataSource func numberOfTokensForTokenView(_ tokenView: NWSTokenView) -> Int { return selectedContacts.count } func insetsForTokenView(_ tokenView: NWSTokenView) -> UIEdgeInsets? { return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) } func titleForTokenViewLabel(_ tokenView: NWSTokenView) -> String? { return "To:" } func fontForTokenViewLabel(_ tokenview: NWSTokenView) -> UIFont? { return nil } func textColorForTokenViewLabel(_ tokenview: NWSTokenView) -> UIColor? { return nil } func titleForTokenViewPlaceholder(_ tokenView: NWSTokenView) -> String? { return "Search contacts..." } func fontForTokenViewTextView(_ tokenview: NWSTokenView) -> UIFont? { return nil } func textColorForTokenViewPlaceholder(_ tokenview: NWSTokenView) -> UIColor? { return nil } func textColorForTokenViewTextView(_ tokenview: NWSTokenView) -> UIColor? { return nil } func tokenView(_ tokenView: NWSTokenView, viewForTokenAtIndex index: Int) -> UIView? { let contact = selectedContacts[Int(index)] if let token = NWSImageToken.initWithTitle(contact.name, image: contact.image) { return token } return nil } // MARK: NWSTokenDelegate func tokenView(_ tokenView: NWSTokenView, didSelectTokenAtIndex index: Int) { let token = tokenView.tokenForIndex(index) as! NWSImageToken token.backgroundColor = UIColor.blue } func tokenView(_ tokenView: NWSTokenView, didDeselectTokenAtIndex index: Int) { let token = tokenView.tokenForIndex(index) as! NWSImageToken token.backgroundColor = tokenBackgroundColor } func tokenView(_ tokenView: NWSTokenView, didDeleteTokenAtIndex index: Int) { // Ensure index is within bounds if index < self.selectedContacts.count { let contact = self.selectedContacts[Int(index)] as NWSTokenContact contact.isSelected = false self.selectedContacts.remove(at: Int(index)) tokenView.reloadData() tableView.reloadData() tokenView.layoutIfNeeded() tokenView.textView.becomeFirstResponder() // Check if search text exists, if so, reload table (i.e. user deleted a selected token by pressing an alphanumeric key) if tokenView.textView.text != "" { self.searchContacts(tokenView.textView.text) } } } func tokenView(_ tokenViewDidBeginEditing: NWSTokenView) { // Check if entering search field and it already contains text (ignore token selections) if tokenView.textView.isFirstResponder && tokenView.textView.text != "" { //self.searchContacts(tokenView.textView.text) } } func tokenViewDidEndEditing(_ tokenView: NWSTokenView) { if tokenView.textView.text.isEmail() { didTypeEmailInTokenView() } isSearching = false tableView.reloadData() } func tokenView(_ tokenView: NWSTokenView, didChangeText text: String) { // Check if empty (deleting text) if text == "" { isSearching = false tableView.reloadData() return } // Check if typed an email and hit space let lastChar = text[text.index(before: text.endIndex)] let isEmail = String(text[text.startIndex..<text.index(before: text.endIndex)]).isEmail() if lastChar == " " && isEmail { self.didTypeEmailInTokenView() return } self.searchContacts(text) } func tokenView(_ tokenView: NWSTokenView, didEnterText text: String) { if text == "" { return } if text.isEmail() { self.didTypeEmailInTokenView() } else { } } func tokenView(_ tokenView: NWSTokenView, contentSizeChanged size: CGSize) { self.tokenViewHeightConstraint.constant = max(tokenViewMinHeight,min(size.height, self.tokenViewMaxHeight)) self.view.layoutIfNeeded() } func tokenView(_ tokenView: NWSTokenView, didFinishLoadingTokens tokenCount: Int) { } } class NWSTokenContact: NSObject { var image: UIImage! var name: String! var isSelected = false init(name: String, andImage image: UIImage) { self.name = name self.image = image } class func sortedContacts(_ contacts: [NWSTokenContact]) -> [NWSTokenContact] { return contacts.sorted(by: { (first, second) -> Bool in return first.name < second.name }) } } class NWSTokenViewExampleCell: UITableViewCell { @IBOutlet weak var userTitleLabel: UILabel! @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var checkmarkImageView: UIImageView! var contact: NWSTokenContact! override func awakeFromNib() { super.awakeFromNib() // Round corners userImageView.layer.cornerRadius = 5.0 userImageView.clipsToBounds = true checkmarkImageView.image = UIImage(named: "Bolt") } func loadWithContact(_ contact: NWSTokenContact) { self.contact = contact userTitleLabel.text = contact.name userImageView.image = contact.image // Show/Hide Checkmark if contact.isSelected { checkmarkImageView.isHidden = false } else { checkmarkImageView.isHidden = true } } } extension String { func isEmail() -> Bool { let regex = try? NSRegularExpression(pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$", options: .caseInsensitive) return regex?.firstMatch(in: self, options: [], range: NSMakeRange(0, self.count)) != nil } }
mit
4c8ced0fca3295a76dc65f2219e3387c
32.156989
216
0.6244
4.603762
false
false
false
false
chrisjmendez/swift-exercises
Authentication/Firebase/Twitter/TwitterAuth/ViewController.swift
1
7845
// // ViewController.swift // TwitterAuth // // Created by Tommy Trojan on 12/9/15. // Copyright © 2015 Chris Mendez. All rights reserved. // // Inspiration: https://proxy.piratenpartij.nl/raw.githubusercontent.com/firebase/ios-swift-chat-example/master/FireChat-Swift/LoginViewController.swift // https://www.firebase.com/docs/ios/guide/login/twitter.html import UIKit import Firebase class ViewController: UIViewController { var SEGUE_LOGIN_COMPLETE = "onLoginComplete" var ref:Firebase! var twitterAuthHelper:TwitterAuthHelper! var accounts = [ACAccount]() var activityIndicator:UIActivityIndicatorView! @IBOutlet weak var buttonTwitter: UIButton! @IBAction func onTwitterLogin(sender: AnyObject) { print("onTwitterLogin") //let button = sender as? UIButton disableButtons() twitterAuthHelper.selectTwitterAccountWithCallback { error, accounts in if error != nil { // Error retrieving Twitter accounts self.showAlert("Please Set Up your Twitter Accounts") } //Check if you have any Twitter accounts at all else if accounts.count > 0 { //If you have more than one account, store them self.accounts = accounts as! [ACAccount] //Handle the setup self.handleMultipleTwitterAccounts(self.accounts) } else { print("No accounts availble \(accounts.count)") self.showAlert("No available accounts.") } } } func disableButtons(){ buttonTwitter.enabled = false } func enableButtons(){ buttonTwitter.enabled = true } // ////////////////////////////////////// // Alerts and Action Sheets // ////////////////////////////////////// func showAlert(message: String){ activityIndicator.stopAnimating() enableButtons() //Create the AlertController let actionSheetController: UIAlertController = UIAlertController(title: "Alert", message: message, preferredStyle: .Alert) //Create and an option action let nextAction: UIAlertAction = UIAlertAction(title: "OK", style: .Default) { action -> Void in //Do some other stuff } actionSheetController.addAction(nextAction) //Present the AlertController self.presentViewController(actionSheetController, animated: true, completion: nil) } func showActionSheet(accounts: [ACAccount]){ //Present the Options in an Alert Controller let actionSheetController: UIAlertController = UIAlertController(title: "Select Twitter Account", message: nil, preferredStyle: .ActionSheet) //Cancel let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in //Just dismiss the action sheet } actionSheetController.addAction(cancelAction) for account in accounts { let action: UIAlertAction = UIAlertAction(title: account.username, style: .Default) { action -> Void in let selectedTwitterHandle = action.title for account in accounts { if account.username == selectedTwitterHandle { self.authAccount(account) } } } actionSheetController.addAction(action) } //We need to provide a popover sourceView when using it on iPad //actionSheetController.popoverPresentationController?.sourceView = sender as? UIView; //Present the AlertController self.presentViewController(actionSheetController, animated: true, completion: nil) } // ////////////////////////////////////// // Twitter Auth // ////////////////////////////////////// func handleMultipleTwitterAccounts(accounts: [ACAccount]) { print("accounts: \(accounts)") switch accounts.count { case 0: UIApplication.sharedApplication().openURL(NSURL(string: "https://twitter.com/signup")!) case 1: self.authAccount(accounts[0]) default: self.selectTwitterAccount(accounts) } } func authAccount(account: ACAccount) { //print("authAccount: \(account)") activityIndicator.startAnimating() twitterAuthHelper.authenticateAccount(account, withCallback: { (error, authData) -> Void in if error != nil { // There was an error authenticating self.showAlert("Uh Oh. Authentication error.") } else { // We have an authenticated Twitter user print("auth.id: \(authData.uid) | authAccount: \(authData.providerData) | ") // Create a new user dictionary accessing the user's info // provided by the authData parameter if let providerData = authData.providerData { let newUser = [ "provider": authData.provider, "id": providerData["id"]!, "displayName": providerData["displayName"]!, "profileImageURL": providerData["profileImageURL"]!, "cachedUserProfile": providerData["cachedUserProfile"]! ] // Create a child path with a key set to the uid underneath the "users" node // This creates a URL path like the following: self.ref.childByAppendingPath("users").childByAppendingPath(authData.uid).setValue(newUser) } // segue to chat self.performSegueWithIdentifier(self.SEGUE_LOGIN_COMPLETE, sender: authData) } }) } func selectTwitterAccount(accounts: [ACAccount]) { showActionSheet(accounts) } // ////////////////////////////////////// // Transitions // ////////////////////////////////////// //Pack a few extra variables into the transition override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let messagesVc = segue.destinationViewController as! MainViewController if let authData = sender as? FAuthData { messagesVc.user = authData messagesVc.ref = ref messagesVc.sender = authData.providerData["username"] as! String } } // ////////////////////////////////////// // On Load // ////////////////////////////////////// func initLoader(){ activityIndicator = UIActivityIndicatorView(frame: CGRect(x: view.frame.midX, y: view.frame.midY, width: 20, height: 20)) activityIndicator.activityIndicatorViewStyle = .Gray activityIndicator.hidesWhenStopped = true view.addSubview(activityIndicator) } func onLoad(){ ref = Firebase(url: Config.db.firebase) twitterAuthHelper = TwitterAuthHelper(firebaseRef: ref, apiKey: Config.social.twitter) initLoader() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) title = "TwitterAuth through Firebase" } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. onLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
0b52ceeb6222311986b18366c9a82a35
36.352381
152
0.571392
5.684058
false
false
false
false
AlbertXYZ/HDCP
HDCP/HDCP/AppDelegate.swift
1
9731
// // AppDelegate.swift // HDCP // // Created by 徐琰璋 on 16/1/4. // Copyright © 2016年 batonsoft. All rights reserved. // import UIKit import CoreData import Alamofire import RxSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //设置导航栏和标签栏样式 setUpBarStyle(); //ShareSDK 初始化 HDShareSDKManager.initializeShareSDK(); //欢迎导航页面 showWelcome(); //监听网络变化 networkMonitoring(); //缓存参数设置 setCache(); //用户数据初始化 loadUserInfo(); add3DTouch(); return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. HDCoreDataManager.sharedInstance.saveContext() } // MARK: - 欢迎界面 func showWelcome() { /** * 判断欢迎界面是否已经执行 */ let userDefault = UserDefaults.standard let appVersion: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String if (userDefault.string(forKey: Constants.HDAppVersion)) == nil { //第一次进入 userDefault.setValue(appVersion, forKey: Constants.HDAppVersion) userDefault.synchronize() self.window?.rootViewController = WelcomeController() } else { //版本升级后,根据版本号来判断是否进入 let version: String = (userDefault.string(forKey: Constants.HDAppVersion))! if ( appVersion == version) { // UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true) self.window?.rootViewController = MainViewController() } else { userDefault.setValue(appVersion, forKey: Constants.HDAppVersion) userDefault.synchronize() self.window?.rootViewController = WelcomeController() } } } // MARK: - 设置导航栏和标签栏样式 func setUpBarStyle() { /** * 导航栏样式 */ UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont(name: "Heiti SC", size: 18.0)!] UINavigationBar.appearance().barTintColor = Constants.HDMainColor // UINavigationBar.appearance().barTintColor = CoreUtils.HDColor(245, g: 161, b: 0, a: 1) /** * 状态栏字体设置白色 */ // UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) /** * 底部TabBar的颜色 */ UITabBar.appearance().shadowImage = UIImage() UITabBar.appearance().tintColor = CoreUtils.HDfromHexValue(0xFFFFFF, alpha: 1.0) UITabBar.appearance().backgroundColor = CoreUtils.HDfromHexValue(0xFFFFFF, alpha: 1.0) UITabBar.appearance().barTintColor = CoreUtils.HDfromHexValue(0xFFFFFF, alpha: 1.0) // UITabBar.appearance().selectedImageTintColor = UIColor.clearColor() /** * 底部TabBar字体正常状态颜色 */ UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: Constants.HDMainTextColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13)], for: UIControl.State.normal) /** * 底部TabBar字体选择状态颜色 */ UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: Constants.HDMainColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13)], for: UIControl.State.selected) } // MARK: - 网络监听 func networkMonitoring() { // let reachability: Reachability // do { // reachability = try Reachability.reachabilityForInternetConnection() // } catch { // print("Unable to create Reachability") // return // } // // // reachability.whenReachable = { reachability in // // this is called on a background thread, but UI updates must // // be on the main thread, like this: // dispatch_async(dispatch_get_main_queue()) { // if reachability.isReachableViaWiFi() { // print("Reachable via WiFi") // } else { // print("Reachable via Cellular") // } // } // } // reachability.whenUnreachable = { reachability in // // this is called on a background thread, but UI updates must // // be on the main thread, like this: // dispatch_async(dispatch_get_main_queue()) { // print("Not reachable") // } // } // // do { // try reachability.startNotifier() // } catch { // print("Unable to start notifier") // } } // MARK: - 缓存参数设置 func setCache() { //是否将图片缓存到内存 // SDImageCache.shared().shouldCacheImagesInMemory = true // //缓存将保留5天 // SDImageCache.shared().maxCacheAge = 5*24*60*60 // //缓存最大占有内存100MB // SDImageCache.shared().maxCacheSize = UInt(1024*1024*100) } // MARK: - 初始化当前登录用户数据 func loadUserInfo() { //判断用户是否已登录 let defaults = UserDefaults.standard let sign = defaults.object(forKey: Constants.HDSign) if let _ = sign { //初始化用户数据 HDUserInfoManager.shareInstance.load() } } // MARK: - 添加3DTouch功能 func add3DTouch() { if (UIDevice().systemVersion as NSString).doubleValue > 8.0 { let ggShortcutIcon = UIApplicationShortcutIcon(templateImageName: "tab_icon_off_04"); let dtShortcutIcon = UIApplicationShortcutIcon(templateImageName: "tab_icon_on_02"); let myShortcutIcon = UIApplicationShortcutIcon(templateImageName: "tab_icon_off_05"); let ggShortcutItem = UIApplicationShortcutItem(type: "TAB_GG", localizedTitle: "逛逛", localizedSubtitle: "", icon: ggShortcutIcon, userInfo: nil); let dtShortcutItem = UIApplicationShortcutItem(type: "TAB_DT", localizedTitle: "动态", localizedSubtitle: "", icon: dtShortcutIcon, userInfo: nil); let myShortcutItem = UIApplicationShortcutItem(type: "TAB_CENTER", localizedTitle: "个人中心", localizedSubtitle: "", icon: myShortcutIcon, userInfo: nil); UIApplication.shared.shortcutItems = [ggShortcutItem, dtShortcutItem, myShortcutItem]; } } // MARK: - 3DTouch事件处理 func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { if shortcutItem.type == "TAB_GG" { let userDefualt = UserDefaults.standard; userDefualt.set("1", forKey: Constants.HDPushIndex) userDefualt.synchronize() self.window?.rootViewController = MainViewController() } if shortcutItem.type == "TAB_DT" { let userDefualt = UserDefaults.standard; userDefualt.set("3", forKey: Constants.HDPushIndex) userDefualt.synchronize() self.window?.rootViewController = MainViewController() } if shortcutItem.type == "TAB_CENTER" { let userDefualt = UserDefaults.standard; userDefualt.set("4", forKey: Constants.HDPushIndex) userDefualt.synchronize() self.window?.rootViewController = MainViewController() } } }
mit
bb4b1d2719ba507487bda0ac25d73d21
35.952381
285
0.644652
4.911392
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothGATT/GATTFirmwareRevisionString.swift
1
1838
// // GATTFirmwareRevisionString.swift // Bluetooth // // Created by Carlos Duclos on 6/21/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /*+ Firmware Revision String [Firmware Revision String](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.firmware_revision_string.xml) The value of this characteristic is a UTF-8 string representing the firmware revision for the firmware within the device. */ @frozen public struct GATTFirmwareRevisionString: RawRepresentable, GATTCharacteristic { public static var uuid: BluetoothUUID { return .firmwareRevisionString } public let rawValue: String public init(rawValue: String) { self.rawValue = rawValue } public init?(data: Data) { guard let rawValue = String(data: data, encoding: .utf8) else { return nil } self.init(rawValue: rawValue) } public var data: Data { return Data(rawValue.utf8) } } extension GATTFirmwareRevisionString: Equatable { public static func == (lhs: GATTFirmwareRevisionString, rhs: GATTFirmwareRevisionString) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTFirmwareRevisionString: CustomStringConvertible { public var description: String { return rawValue } } extension GATTFirmwareRevisionString: ExpressibleByStringLiteral { public init(stringLiteral value: String) { self.init(rawValue: value) } public init(extendedGraphemeClusterLiteral value: String) { self.init(rawValue: value) } public init(unicodeScalarLiteral value: String) { self.init(rawValue: value) } }
mit
2437ad12c68660751b515c81841355b5
23.171053
156
0.663038
4.734536
false
false
false
false
hustlzp/iOS-Base
Extensions/NSDate+Helper.swift
1
1030
// // NSDate+Helper.swift // duowen // // Created by hustlzp on 15/12/18. // Copyright © 2015年 hustlzp. All rights reserved. // import Foundation extension NSDate { func friendlyInterval() -> String { var friendlyString = "" let interval = -timeIntervalSinceNow if interval < 5 { friendlyString = "刚刚" } else if interval < 60 { friendlyString = "\(Int(interval))秒" } else if interval < 3600 { friendlyString = "\(Int(interval / 60))分钟" } else if interval < 3600 * 24 { friendlyString = "\(Int(interval / 3600))小时" } else if interval < 3600 * 24 * 30 { friendlyString = "\(Int(interval / (3600 * 24)))天" } else if interval < 3600 * 24 * 365 { friendlyString = "\(Int(interval / (3600 * 24 * 30)))个月" } else { friendlyString = "\(Int(interval / (3600 * 24 * 365)))年" } return friendlyString } }
mit
4635c22b5aa5b3dcf2807b0b591f3df2
27.742857
68
0.525373
4.118852
false
false
false
false
stripe/stripe-ios
StripePaymentsUI/StripePaymentsUI/Internal/UI/Views/STPCardLoadingIndicator.swift
1
3142
// // STPCardLoadingIndicator.swift // StripePaymentsUI // // Created by Cameron Sabol on 8/24/20. // Copyright © 2020 Stripe, Inc. All rights reserved. // import UIKit private let kCardLoadingIndicatorDiameter: CGFloat = 14.0 private let kCardLoadingInnerCircleDiameter: CGFloat = 10.0 private let kLoadingAnimationSpinDuration: CFTimeInterval = 0.6 private let kLoadingAnimationIdentifier = "STPCardLoadingIndicator.spinning" class STPCardLoadingIndicator: UIView { private var indicatorLayer: CALayer? override init( frame: CGRect ) { super.init(frame: frame) backgroundColor = UIColor( red: 79.0 / 255.0, green: 86.0 / 255.0, blue: 107.0 / 255.0, alpha: 1.0 ) // Make us a circle let shape = CAShapeLayer() let path = UIBezierPath( arcCenter: CGPoint( x: 0.5 * kCardLoadingIndicatorDiameter, y: 0.5 * kCardLoadingIndicatorDiameter ), radius: 0.5 * kCardLoadingIndicatorDiameter, startAngle: 0.0, endAngle: 2.0 * .pi, clockwise: true ) shape.path = path.cgPath layer.mask = shape // Add the inner circle let innerCircle = CAShapeLayer() innerCircle.anchorPoint = CGPoint(x: 0.5, y: 0.5) innerCircle.position = CGPoint( x: 0.5 * kCardLoadingIndicatorDiameter, y: 0.5 * kCardLoadingIndicatorDiameter ) let indicatorPath = UIBezierPath( arcCenter: CGPoint(x: 0.0, y: 0.0), radius: 0.5 * kCardLoadingInnerCircleDiameter, startAngle: 0.0, endAngle: 9.0 * .pi / 6.0, clockwise: true ) innerCircle.path = indicatorPath.cgPath innerCircle.strokeColor = UIColor(white: 1.0, alpha: 0.8).cgColor innerCircle.fillColor = UIColor.clear.cgColor layer.addSublayer(innerCircle) indicatorLayer = innerCircle } override var intrinsicContentSize: CGSize { return CGSize(width: kCardLoadingIndicatorDiameter, height: kCardLoadingIndicatorDiameter) } override func systemLayoutSizeFitting( _ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority ) -> CGSize { return intrinsicContentSize } override func didMoveToWindow() { super.didMoveToWindow() startAnimating() } func startAnimating() { let spinAnimation = CABasicAnimation(keyPath: "transform.rotation") spinAnimation.byValue = NSNumber(value: Float(2.0 * .pi)) spinAnimation.duration = kLoadingAnimationSpinDuration spinAnimation.repeatCount = .infinity indicatorLayer?.add(spinAnimation, forKey: kLoadingAnimationIdentifier) } func stopAnimating() { indicatorLayer?.removeAnimation(forKey: kLoadingAnimationIdentifier) } required init?( coder aDecoder: NSCoder ) { super.init(coder: aDecoder) } }
mit
83311b4c1a4d8c693a8ec56e35a8d19c
29.794118
98
0.633556
4.810107
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/TXTReader/BookDetail/Views/QSDiscussCell.swift
1
1350
// // QSDiscussCell.swift // zhuishushenqi // // Created by yung on 2017/4/24. // Copyright © 2017年 QS. All rights reserved. // import UIKit class QSDiscussCell: UITableViewCell { @IBOutlet weak var icon: UIImageView! @IBOutlet weak var name: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var commentLabel: UILabel! @IBOutlet weak var likeLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! var model:BookComment? { didSet{ icon.qs_setAvatarWithURLString(urlString: model?.author.avatar ?? "") name.text = "\(model?.author.nickname ?? "") lv.\(model?.author.lv ?? 0)" contentLabel.text = "\(model?.title ?? "")" commentLabel.text = "\(model?.commentCount ?? 0)" likeLabel.text = "\(model?.likeCount ?? 0)" timeLabel.qs_setCreateTime(createTime: model?.created ?? "", append: "") } } override func awakeFromNib() { super.awakeFromNib() // Initialization code icon.layer.cornerRadius = 5 backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
a925b51e2b3036e98e2d3b9c2b7b70f1
30.325581
85
0.616927
4.249211
false
false
false
false
mozilla-mobile/focus-ios
Blockzilla/AppDelegate.swift
1
20574
/* 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 import Sentry import Combine import Onboarding import AppShortcuts enum AppPhase { case notRunning case didFinishLaunching case willEnterForeground case didBecomeActive case willResignActive case didEnterBackground case willTerminate } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { private lazy var authenticationManager = AuthenticationManager() @Published private var appPhase: AppPhase = .notRunning // 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? private lazy var browserViewController = BrowserViewController( shortcutManager: shortcutManager, authenticationManager: authenticationManager, onboardingEventsHandler: onboardingEventsHandler, themeManager: themeManager ) private let nimbus = NimbusWrapper.shared private var queuedUrl: URL? private var queuedString: String? private let themeManager = ThemeManager() private var cancellables = Set<AnyCancellable>() private lazy var shortcutManager: ShortcutsManager = .init() private lazy var onboardingEventsHandler: OnboardingEventsHandling = { var shouldShowNewOnboarding: () -> Bool = { [unowned self] in !UserDefaults.standard.bool(forKey: OnboardingConstants.showOldOnboarding) } guard !AppInfo.isTesting() else { return TestOnboarding() } return OnboardingFactory.makeOnboardingEventsHandler(shouldShowNewOnboarding) }() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { appPhase = .didFinishLaunching $appPhase.sink { [unowned self] phase in switch phase { case .didFinishLaunching, .willEnterForeground: authenticateWithBiometrics() case .didBecomeActive: if authenticationManager.authenticationState == .loggedin { hidePrivacyProtectionWindow() } case .willResignActive: guard privacyProtectionWindow == nil else { return } showPrivacyProtectionWindow() case .didEnterBackground: authenticationManager.logout() case .notRunning, .willTerminate: break } } .store(in: &cancellables) authenticationManager .$authenticationState .receive(on: DispatchQueue.main) .sink { state in switch state { case .loggedin: self.hidePrivacyProtectionWindow() break case .loggedout: self.showPrivacyProtectionWindow() break case .canceled: break } } .store(in: &cancellables) if AppInfo.testRequestsReset() { if let bundleID = Bundle.main.bundleIdentifier { UserDefaults.standard.removePersistentDomain(forName: bundleID) } UserDefaults.standard.removePersistentDomain(forName: AppInfo.sharedContainerIdentifier) } setupCrashReporting() setupTelemetry() setupExperimentation() TPStatsBlocklistChecker.shared.startup() // Fix transparent navigation bar issue in iOS 15 if #available(iOS 15, *) { let appearance = UINavigationBarAppearance() appearance.configureWithOpaqueBackground() appearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.primaryText] appearance.backgroundColor = .systemGroupedBackground appearance.shadowColor = .clear UINavigationBar.appearance().standardAppearance = appearance UINavigationBar.appearance().scrollEdgeAppearance = appearance } // 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) // 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() window = UIWindow(frame: UIScreen.main.bounds) browserViewController.modalDelegate = self window?.rootViewController = browserViewController window?.makeKeyAndVisible() window?.overrideUserInterfaceStyle = themeManager.selectedTheme WebCacheUtils.reset() KeyboardHelper.defaultHelper.startObserving() if AppInfo.isTesting() { // Only show the First Run UI if the test asks for it. if AppInfo.isFirstRunUIEnabled() { onboardingEventsHandler.send(.applicationDidLaunch) } return true } onboardingEventsHandler.send(.applicationDidLaunch) return true } func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { guard let navigation = NavigationPath(url: url) else { return false } let navigationHandler = NavigationPath.handle(application, navigation: navigation, with: browserViewController) if case .text = navigation { queuedString = navigationHandler as? String } else if case .url = navigation { queuedUrl = navigationHandler as? URL } 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.photonActionSheetDidDismiss() browserViewController.dismiss(animated: true, completion: nil) browserViewController.navigationController?.popViewController(animated: true) browserViewController.resetBrowser(hidePreviousSession: true) } return true } private func authenticateWithBiometrics() { Task { await authenticationManager.authenticateWithBiometrics() } } func applicationWillResignActive(_ application: UIApplication) { appPhase = .willResignActive browserViewController.dismissActionSheet() browserViewController.deactivateUrlBar() } func applicationDidBecomeActive(_ application: UIApplication) { appPhase = .didBecomeActive 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) GleanMetrics.Siri.eraseInBackground.record() } 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.deactivateUrlBarOnHomeView() browserViewController.dismissSettings() browserViewController.dismissActionSheet() browserViewController.submit(url: url, source: .action) queuedUrl = nil } else if let text = queuedString { Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.openedFromExtension, object: TelemetryEventObject.app) browserViewController.ensureBrowsingMode() browserViewController.deactivateUrlBarOnHomeView() browserViewController.dismissSettings() browserViewController.dismissActionSheet() if let fixedUrl = URIFixup.getURL(entry: text) { browserViewController.submit(url: fixedUrl, source: .action) } else { browserViewController.submit(text: text, source: .action) } queuedString = nil } } func applicationWillEnterForeground(_ application: UIApplication) { appPhase = .willEnterForeground } 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. appPhase = .didEnterBackground 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 { browserViewController.photonActionSheetDidDismiss() 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) GleanMetrics.Siri.eraseAndOpen.record() 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.deactivateUrlBarOnHomeView() browserViewController.submit(url: url, source: .action) Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.siri, object: TelemetryEventObject.openFavoriteSite) GleanMetrics.Siri.openFavoriteSite.record() 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) GleanMetrics.Siri.eraseInBackground.record() default: break } return true } // MARK: Privacy Protection private var privacyProtectionWindow: UIWindow? private func showPrivacyProtectionWindow() { browserViewController.deactivateUrlBarOnHomeView() guard let windowScene = self.window?.windowScene else { return } privacyProtectionWindow = UIWindow(windowScene: windowScene) privacyProtectionWindow?.rootViewController = SplashViewController(authenticationManager: authenticationManager) privacyProtectionWindow?.windowLevel = .alert + 1 privacyProtectionWindow?.makeKeyAndVisible() } private func hidePrivacyProtectionWindow() { privacyProtectionWindow?.isHidden = true privacyProtectionWindow = nil browserViewController.activateUrlBarOnHomeView() KeyboardType.identifyKeyboardNameTelemetry() } } // MARK: - Crash Reporting private let SentryDSNKey = "SentryDSN" extension AppDelegate { func setupCrashReporting() { // Do not enable crash reporting if collection of anonymous usage data is disabled. if !Settings.getToggle(.sendAnonymousUsageData) { return } if let sentryDSN = Bundle.main.object(forInfoDictionaryKey: SentryDSNKey) as? String { SentrySDK.start { options in options.dsn = sentryDSN } } } } // MARK: - Telemetry & Tooling setup extension AppDelegate { 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 GleanMetrics.Search.defaultEngine.set(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) } if UserDefaults.standard.bool(forKey: GleanLogPingsToConsole) { Glean.shared.handleCustomUrl(url: URL(string: "focus-glean-settings://glean?logPings=true")!) } if UserDefaults.standard.bool(forKey: GleanEnableDebugView) { if let tag = UserDefaults.standard.string(forKey: GleanDebugViewTag), !tag.isEmpty, let encodedTag = tag.addingPercentEncoding(withAllowedCharacters: .urlQueryParameterAllowed) { Glean.shared.handleCustomUrl(url: URL(string: "focus-glean-settings://glean?debugViewTag=\(encodedTag)")!) } } let channel = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" ? "testflight" : "release" Glean.shared.initialize(uploadEnabled: Settings.getToggle(.sendAnonymousUsageData), configuration: Configuration(channel: channel), buildInfo: GleanMetrics.GleanBuild.info) // Send "at startup" telemetry GleanMetrics.Shortcuts.shortcutsOnHomeNumber.set(Int64(shortcutManager.shortcutsViewModels.count)) GleanMetrics.TrackingProtection.hasAdvertisingBlocked.set(Settings.getToggle(.blockAds)) GleanMetrics.TrackingProtection.hasAnalyticsBlocked.set(Settings.getToggle(.blockAnalytics)) GleanMetrics.TrackingProtection.hasContentBlocked.set(Settings.getToggle(.blockOther)) GleanMetrics.TrackingProtection.hasSocialBlocked.set(Settings.getToggle(.blockSocial)) GleanMetrics.MozillaProducts.hasFirefoxInstalled.set(UIApplication.shared.canOpenURL(URL(string: "firefox://")!)) GleanMetrics.Preferences.userTheme.set(UserDefaults.standard.theme.telemetryValue) } func setupExperimentation() { let isFirstRun = !UserDefaults.standard.bool(forKey: OnboardingConstants.onboardingDidAppear) do { // Enable nimbus when both Send Usage Data and Studies are enabled in the settings. try NimbusWrapper.shared.initialize(enabled: true, isFirstRun: isFirstRun) } catch { NSLog("Failed to setup experimentation: \(error)") } guard let nimbus = NimbusWrapper.shared.nimbus else { return } AppNimbus.shared.initialize { nimbus } NotificationCenter.default.addObserver( forName: Notification.Name.nimbusExperimentsApplied, object: nil, queue: OperationQueue.main) { _ in AppNimbus.shared.invalidateCachedValues() } } } extension AppDelegate: ModalDelegate { func dismiss(animated: Bool = true) { window?.rootViewController?.presentedViewController?.dismiss(animated: animated) } func presentModal(viewController: UIViewController, animated: Bool) { window?.rootViewController?.present(viewController, animated: animated, completion: nil) } func presentSheet(viewController: UIViewController) { let vc = SheetModalViewController(containerViewController: viewController) vc.modalPresentationStyle = .overCurrentContext // keep false // modal animation will be handled in VC itself window?.rootViewController?.present(vc, animated: false) } } protocol ModalDelegate { func presentModal(viewController: UIViewController, animated: Bool) func presentSheet(viewController: UIViewController) func dismiss(animated: Bool) }
mpl-2.0
41abdca56b7bb71eeabb2de014afe748
43.629067
190
0.70312
5.702328
false
true
false
false
nfls/nflsers
app/v2/Controller/Media/GalleryDetailController.swift
1
1667
// // GalleryDetailController.swift // NFLSers-iOS // // Created by Qingyang Hu on 2018/9/21. // Copyright © 2018 胡清阳. All rights reserved. // import Foundation import SDWebImage import Alamofire import QuickLook import IGListKit import AVFoundation class PhotoCell: UITableViewCell { @IBOutlet weak var photo: UIImageView! public func setImage(_ image: UIImage) { photo?.image = image photo?.frame = AVMakeRect(aspectRatio: image.size, insideRect: photo.frame) } } class GalleryDetailController: UITableViewController { var gallery: Gallery? = nil var current: [Photo] { get { if let gallery = self.gallery { return gallery.photos!.filter({ (photo) -> Bool in return photo.originUrl != nil || !isOriginal }) } else { return [] } } } var isOriginal = true override func viewDidLoad() { self.title = gallery?.title } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return current.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PhotoCell SDWebImageManager.shared().loadImage(with: current[indexPath.row].hdUrl, options: SDWebImageOptions.highPriority, progress: nil) { (image, _, _, _, _, _) in DispatchQueue.main.async { cell.setImage(image!) } } return cell } }
apache-2.0
4ede2315d3986b072f0a0dee018bed18
28.122807
164
0.618675
4.853801
false
false
false
false
pfvernon2/swiftlets
iOSX/iOS/LeftAlignedFlowLayout.swift
1
2430
// // LeftAlignedFlowLayout.swift // swiftlets // // Created by Frank Vernon on 5/27/20. // Copyright © 2020 Frank Vernon. All rights reserved. // import UIKit ///Custom flow layout to keep collection view cells aligned left. /// There are a lot of assumptions in here about cell spacing and insets but this implementation /// is simple enough that it should be adequate to subclass and override configure() for most applications. open class LeftAlignedFlowLayout: UICollectionViewFlowLayout { open var spacing: CGFloat = 8.0 { didSet { configure() } } required public override init() { super.init(); configure() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); configure() } ///Setup the spacing and insets. ///This is a likely candidate for overriding if you subclass. open func configure() { estimatedItemSize = UICollectionViewFlowLayout.automaticSize sectionInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing) minimumLineSpacing = spacing minimumInteritemSpacing = spacing } open override func layoutAttributesForElements( in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let attributes = super.layoutAttributesForElements(in:rect) else { return [] } let initalX: CGFloat = sectionInset.left let initalY: CGFloat = sectionInset.top var currX: CGFloat = initalX var currY: CGFloat = initalY attributes.forEach { (attribute) in guard attribute.representedElementCategory == .cell else { return } //move back to left margin if this cell is on a new row if attribute.frame.origin.y >= currY { currX = initalX } //make cell left at currX position attribute.frame.origin.x = currX //reset for next iteration... // next cell X position will be this cells right side + the collection cell spacing currX += attribute.frame.width + minimumInteritemSpacing //keep track of current Y position so we can move back to left margin if necessary currY = attribute.frame.maxY } return attributes } }
apache-2.0
0a35a010b753222974eea03ede35d2d2
32.273973
109
0.625772
5.201285
false
true
false
false
marcoconti83/morione
Sources/Subprocess.swift
1
6594
// //Copyright (c) Marco Conti 2016 // // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. import Foundation /** A definition of a subprocess to be invoked. The subprocess can be defined once and executed multiple times (using the `execute` or `output` method), each execution will spawn a separate process */ public class Subprocess { /// The path to the executable let executablePath : String /// Arguments to pass to the executable let arguments : [String] /// Working directory for the executable let workingDirectory : String /// Process to pipe to, if any let pipeDestination : Subprocess? /** Returns a subprocess ready to be executed - parameter executablePath: the path to the executable. The validity of the path won't be verified until the subprocess is executed - parameter arguments: the list of arguments. If not specified, no argument will be passed - parameter workingDirectiry: the working directory. If not specified, the current working directory will be used */ public convenience init( executablePath: String, arguments: [String] = [], workingDirectory: String = "." ) { self.init(executablePath: executablePath, arguments: arguments, workingDirectory: workingDirectory, pipeTo: nil) } private init( executablePath: String, arguments: [String] = [], workingDirectory: String = ".", pipeTo: Subprocess? ) { self.executablePath = executablePath self.arguments = arguments self.workingDirectory = workingDirectory self.pipeDestination = pipeTo } /** Returns a subprocess ready to be executed - SeeAlso: init(executablePath:arguments:workingDirectory) */ public convenience init( _ executablePath: String, _ arguments: String..., workingDirectory: String = ".") { self.init(executablePath: executablePath, arguments: arguments, workingDirectory: workingDirectory, pipeTo: nil) } } // MARK: - Public API extension Subprocess { /** Executes the subprocess and wait for completition, returning the exit status - returns: the termination status, or nil if it was not possible to execute the process */ public func run() -> Int32? { return self.execute(captureOutput: false)?.status } /** Executes the subprocess and wait for completion, returning the output - returns: the output of the process, or nil if it was not possible to execute the process - warning: the entire output will be stored in a String in memory */ public func output() -> String? { return self.execute(captureOutput: true)?.output } /** Executes the subprocess and wait for completition, returning the exit status - returns: the execution result, or nil if it was not possible to execute the process */ public func execute(captureOutput: Bool = false) -> ExecutionResult? { return buildPipeline(captureOutput: captureOutput).run() } } // MARK: - Piping extension Subprocess { /// Pipes the output to this process to another process. /// Will return a new subprocess, you should execute that subprocess to /// run the entire pipe public func pipe(to destination: Subprocess) -> Subprocess { let downstreamProcess : Subprocess if let existingPipe = self.pipeDestination { downstreamProcess = existingPipe.pipe(to: destination) } else { downstreamProcess = destination } return Subprocess(executablePath: self.executablePath, arguments: self.arguments, workingDirectory: self.workingDirectory, pipeTo: downstreamProcess) } } public func | (lhs: Subprocess, rhs: Subprocess) -> Subprocess { return lhs.pipe(to: rhs) } public func | (lhs: String, rhs: String) -> String { return "(\(lhs)\(rhs))" } // MARK: - Process execution public enum SubprocessError: Swift.Error { case error(reason: String) } extension Subprocess { /// Returns the task to execute private func task() -> Process { let task = Process() task.launchPath = self.executablePath task.arguments = self.arguments task.currentDirectoryPath = self.workingDirectory return task } /// Returns the task pipeline for all the downstream processes private func buildPipeline(captureOutput: Bool, input: AnyObject? = nil) -> TaskPipeline { let task = self.task() if let inPipe = input { task.standardInput = inPipe } if let downstreamProcess = self.pipeDestination { let downstreamPipeline = downstreamProcess.buildPipeline(captureOutput: captureOutput, input: task.standardOutput as AnyObject?) return downstreamPipeline.addToHead(task: task) } return TaskPipeline(task: task, captureOutput: captureOutput) } } // MARK: - Description extension Subprocess : CustomStringConvertible { public var description : String { return self.executablePath + (self.arguments.count > 0 ? " " + (self.arguments .map { $0.replacingOccurrences(of: " ", with: "\\ ") } .joined(separator: " ")) : "" ) + (self.pipeDestination != nil ? " | " + self.pipeDestination!.description : "" ) } }
mit
6d6703e34cfd4d894ec9065602417a1a
34.451613
157
0.66333
4.809628
false
false
false
false
JamieScanlon/AugmentKit
AugmentKit/Renderer/DrawCall.swift
1
8877
// // DrawCall.swift // AugmentKit // // MIT License // // Copyright (c) 2018 JamieScanlon // // 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 // MARK: - DrawCall /// Represents a draw call which is a single mesh geometry that is rendered with a Vertex / Fragment Shader. A single draw call can have many submeshes. Each submesh calls `drawIndexPrimitives` struct DrawCall { var uuid: UUID var renderPipelineState: MTLRenderPipelineState var depthStencilState: MTLDepthStencilState? var cullMode: MTLCullMode = .back var depthBias: RenderPass.DepthBias? var drawData: DrawData? var usesSkins: Bool { if let myDrawData = drawData { return myDrawData.skins.count > 0 } else { return false } } var vertexFunction: MTLFunction? var fragmentFunction: MTLFunction? init(renderPipelineState: MTLRenderPipelineState, depthStencilState: MTLDepthStencilState? = nil, cullMode: MTLCullMode = .back, depthBias: RenderPass.DepthBias? = nil, drawData: DrawData? = nil, uuid: UUID = UUID()) { self.uuid = uuid self.renderPipelineState = renderPipelineState self.depthStencilState = depthStencilState self.cullMode = cullMode self.depthBias = depthBias self.drawData = drawData } init(withDevice device: MTLDevice, renderPipelineDescriptor: MTLRenderPipelineDescriptor, depthStencilDescriptor: MTLDepthStencilDescriptor? = nil, cullMode: MTLCullMode = .back, depthBias: RenderPass.DepthBias? = nil, drawData: DrawData? = nil) { let myPipelineState: MTLRenderPipelineState = { do { return try device.makeRenderPipelineState(descriptor: renderPipelineDescriptor) } catch let error { print("failed to create render pipeline state for the device. ERROR: \(error)") let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: error)))) NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]]) fatalError() } }() let myDepthStencilState: MTLDepthStencilState? = { if let depthStencilDescriptor = depthStencilDescriptor { return device.makeDepthStencilState(descriptor: depthStencilDescriptor) } else { return nil } }() self.init(renderPipelineState: myPipelineState, depthStencilState: myDepthStencilState, cullMode: cullMode, depthBias: depthBias, drawData: drawData) } init(metalLibrary: MTLLibrary, renderPass: RenderPass, vertexFunctionName: String, fragmentFunctionName: String, vertexDescriptor: MTLVertexDescriptor? = nil, depthComareFunction: MTLCompareFunction = .less, depthWriteEnabled: Bool = true, cullMode: MTLCullMode = .back, depthBias: RenderPass.DepthBias? = nil, drawData: DrawData? = nil, uuid: UUID = UUID()) { let funcConstants = RenderUtilities.getFuncConstants(forDrawData: drawData) let fragFunc: MTLFunction = { do { return try metalLibrary.makeFunction(name: fragmentFunctionName, constantValues: funcConstants) } catch let error { print("Failed to create fragment function for pipeline state descriptor, error \(error)") let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: error)))) NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]]) fatalError() } }() let vertFunc: MTLFunction = { do { // Specify which shader to use based on if the model has skinned puppet suppot return try metalLibrary.makeFunction(name: vertexFunctionName, constantValues: funcConstants) } catch let error { print("Failed to create vertex function for pipeline state descriptor, error \(error)") let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: error)))) NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]]) fatalError() } }() guard let renderPipelineStateDescriptor = renderPass.renderPipelineDescriptor(withVertexDescriptor: vertexDescriptor, vertexFunction: vertFunc, fragmentFunction: fragFunc) else { print("failed to create render pipeline state descriptorfor the device.") let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: nil)))) NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]]) fatalError() } let renderPipelineState: MTLRenderPipelineState = { do { return try renderPass.device.makeRenderPipelineState(descriptor: renderPipelineStateDescriptor) } catch let error { print("failed to create render pipeline state for the device. ERROR: \(error)") let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: error)))) NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]]) fatalError() } }() let depthStencilDescriptor = renderPass.depthStencilDescriptor(withDepthComareFunction: depthComareFunction, isDepthWriteEnabled: depthWriteEnabled) let myDepthStencilState: MTLDepthStencilState? = renderPass.device.makeDepthStencilState(descriptor: depthStencilDescriptor) self.uuid = uuid self.vertexFunction = vertFunc self.fragmentFunction = fragFunc self.renderPipelineState = renderPipelineState self.depthStencilState = myDepthStencilState self.cullMode = cullMode self.depthBias = depthBias self.drawData = drawData } /// Prepares the Render Command Encoder with the draw call state. /// You must call `prepareRenderCommandEncoder(withCommandBuffer:)` before calling this method func prepareDrawCall(withRenderPass renderPass: RenderPass) { guard let renderCommandEncoder = renderPass.renderCommandEncoder else { return } renderCommandEncoder.setRenderPipelineState(renderPipelineState) renderCommandEncoder.setDepthStencilState(depthStencilState) renderCommandEncoder.setCullMode(cullMode) if let depthBias = depthBias { renderCommandEncoder.setDepthBias(depthBias.bias, slopeScale: depthBias.slopeScale, clamp: depthBias.clamp) } } } extension DrawCall: CustomDebugStringConvertible, CustomStringConvertible { /// :nodoc: var description: String { return debugDescription } /// :nodoc: var debugDescription: String { let myDescription = "<DrawCall: > uuid: \(uuid), renderPipelineState:\(String(describing: renderPipelineState.debugDescription)), depthStencilState:\(depthStencilState?.debugDescription ?? "None"), cullMode: \(cullMode), usesSkins: \(usesSkins), vertexFunction: \(vertexFunction?.debugDescription ?? "None"), fragmentFunction: \(fragmentFunction?.debugDescription ?? "None")" return myDescription } }
mit
05256936741195a6f16628478c981f55
50.912281
383
0.689873
5.690385
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/UIImage+Extensions.swift
1
14497
// // UIImage+Extensions.swift // Slide for Reddit // // Created by Jonathan Cole on 6/26/18. // Copyright © 2018 Haptic Apps. All rights reserved. // import UIKit extension UIImage { func getCopy(withSize size: CGSize) -> UIImage { let maxWidth = size.width let maxHeight = size.height let imgWidth = self.size.width let imgHeight = self.size.height let widthRatio = maxWidth / imgWidth let heightRatio = maxHeight / imgHeight let bestRatio = min(widthRatio, heightRatio) let newWidth = imgWidth * bestRatio, newHeight = imgHeight * bestRatio let biggerSize = CGSize(width: newWidth, height: newHeight) var newImage: UIImage if #available(iOS 10.0, *) { let renderFormat = UIGraphicsImageRendererFormat.default() renderFormat.opaque = false let renderer = UIGraphicsImageRenderer(size: CGSize(width: biggerSize.width, height: biggerSize.height), format: renderFormat) newImage = renderer.image { (_) in self.draw(in: CGRect(x: 0, y: 0, width: biggerSize.width, height: biggerSize.height)) } } else { UIGraphicsBeginImageContextWithOptions(CGSize(width: biggerSize.width, height: biggerSize.height), false, 0) self.draw(in: CGRect(x: 0, y: 0, width: biggerSize.width, height: biggerSize.height)) newImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() } return newImage } func cropImageByAlpha() -> UIImage { let cgImage = self.cgImage let context = createARGBBitmapContextFromImage(inImage: cgImage!) let height = cgImage!.height let width = cgImage!.width var rect: CGRect = CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height)) context?.draw(cgImage!, in: rect) let pixelData = self.cgImage!.dataProvider!.data let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData) var minX = width var minY = height var maxX: Int = 0 var maxY: Int = 0 //Filter through data and look for non-transparent pixels. for y in 0..<height { for x in 0..<width { let pixelIndex = (width * y + x) * 4 /* 4 for A, R, G, B */ if data[Int(pixelIndex)] != 0 { //Alpha value is not zero pixel is not transparent. if x < minX { minX = x } if x > maxX { maxX = x } if y < minY { minY = y } if y > maxY { maxY = y } } } } rect = CGRect( x: CGFloat(minX), y: CGFloat(minY), width: CGFloat(maxX - minX), height: CGFloat(maxY - minY)) let imageScale: CGFloat = self.scale let cgiImage = self.cgImage?.cropping(to: rect) return UIImage(cgImage: cgiImage!, scale: imageScale, orientation: self.imageOrientation) } private func createARGBBitmapContextFromImage(inImage: CGImage) -> CGContext? { let width = cgImage!.width let height = cgImage!.height let bitmapBytesPerRow = width * 4 let bitmapByteCount = bitmapBytesPerRow * height let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapData = malloc(bitmapByteCount) if bitmapData == nil { return nil } let context = CGContext(data: bitmapData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bitmapBytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue) return context } convenience init?(sfString: SFSymbol, overrideString: String) { if #available(iOS 13, *) { let config = UIImage.SymbolConfiguration(pointSize: 15, weight: UIImage.SymbolWeight.regular, scale: UIImage.SymbolScale.small) self.init(systemName: sfString.rawValue, withConfiguration: config) } else { self.init(named: overrideString) } } convenience init?(sfStringHQ: SFSymbol, overrideString: String) { if #available(iOS 13, *) { let config = UIImage.SymbolConfiguration(pointSize: 30, weight: UIImage.SymbolWeight.regular, scale: UIImage.SymbolScale.large) self.init(systemName: sfStringHQ.rawValue, withConfiguration: config) } else { self.init(named: overrideString) } } func getCopy(withColor color: UIColor) -> UIImage { if #available(iOS 10, *) { let renderer = UIGraphicsImageRenderer(size: size) return renderer.image { context in color.setFill() self.draw(at: .zero) context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height), blendMode: .sourceAtop) } } else { var image = withRenderingMode(.alwaysTemplate) UIGraphicsBeginImageContextWithOptions(size, false, scale) color.set() image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } func getCopy(withSize size: CGSize, withColor color: UIColor) -> UIImage { return self.getCopy(withSize: size).getCopy(withColor: color) } // TODO: - These should make only one copy and do in-place operations on those func navIcon(_ white: Bool = false) -> UIImage { return self.getCopy(withSize: CGSize(width: 25, height: 25), withColor: SettingValues.reduceColor && !white ? ColorUtil.theme.navIconColor : .white) } func smallIcon() -> UIImage { return self.getCopy(withSize: CGSize(width: 12, height: 12), withColor: ColorUtil.theme.navIconColor) } func toolbarIcon() -> UIImage { return self.getCopy(withSize: CGSize(width: 25, height: 25), withColor: ColorUtil.theme.navIconColor) } func menuIcon() -> UIImage { return self.getCopy(withSize: CGSize(width: 20, height: 20), withColor: ColorUtil.theme.navIconColor) } func cropToBounds(image: UIImage, width: Double, height: Double) -> UIImage { let contextImage: UIImage = UIImage(cgImage: image.cgImage!) let contextSize: CGSize = contextImage.size var posX: CGFloat = 0.0 var posY: CGFloat = 0.0 var cgwidth: CGFloat = CGFloat(width) var cgheight: CGFloat = CGFloat(height) // See what size is longer and create the center off of that if contextSize.width > contextSize.height { posX = ((contextSize.width - contextSize.height) / 2) posY = 0 cgwidth = contextSize.height cgheight = contextSize.height } else { posX = 0 posY = ((contextSize.height - contextSize.width) / 2) cgwidth = contextSize.width cgheight = contextSize.width } let rect: CGRect = CGRect.init(x: posX, y: posY, width: cgwidth, height: cgheight) // Create bitmap image from context using the rect let imageRef: CGImage = (contextImage.cgImage?.cropping(to: rect)!)! // Create a new image based on the imageRef and rotate back to the original orientation let image: UIImage = UIImage.init(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation) return image } public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image?.cgImage else { return nil } self.init(cgImage: cgImage) } func overlayWith(image: UIImage, posX: CGFloat, posY: CGFloat) -> UIImage { let newWidth = size.width < posX + image.size.width ? posX + image.size.width : size.width let newHeight = size.height < posY + image.size.height ? posY + image.size.height : size.height let newSize = CGSize(width: newWidth, height: newHeight) UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) draw(in: CGRect(origin: CGPoint.zero, size: size)) image.draw(in: CGRect(origin: CGPoint(x: posX, y: posY), size: image.size)) let newImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } class func convertGradientToImage(colors: [UIColor], frame: CGSize) -> UIImage { let rect = CGRect.init(x: 0, y: 0, width: frame.width, height: frame.height) // start with a CAGradientLayer let gradientLayer = CAGradientLayer() gradientLayer.frame = rect // add colors as CGCologRef to a new array and calculate the distances var colorsRef = [CGColor]() var locations = [NSNumber]() for i in 0 ..< colors.count { colorsRef.append(colors[i].cgColor as CGColor) locations.append(NSNumber(value: Float(i) / Float(colors.count - 1))) } gradientLayer.colors = colorsRef let x: CGFloat = 135.0 / 360.0 let a: CGFloat = pow(sin(2.0 * CGFloat.pi * ((x + 0.75) / 2.0)), 2.0) let b: CGFloat = pow(sin(2.0 * CGFloat.pi * ((x + 0.00) / 2.0)), 2.0) let c: CGFloat = pow(sin(2.0 * CGFloat.pi * ((x + 0.25) / 2.0)), 2.0) let d: CGFloat = pow(sin(2.0 * CGFloat.pi * ((x + 0.50) / 2.0)), 2.0) gradientLayer.endPoint = CGPoint(x: c, y: d) gradientLayer.startPoint = CGPoint(x: a, y: b) // now build a UIImage from the gradient UIGraphicsBeginImageContext(gradientLayer.bounds.size) gradientLayer.render(in: UIGraphicsGetCurrentContext()!) let gradientImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // return the gradient image return gradientImage! } func areaAverage() -> UIColor { var bitmap = [UInt8](repeating: 0, count: 4) if #available(iOS 9.0, *) { // Get average color. let context = CIContext() let inputImage: CIImage = ciImage ?? CoreImage.CIImage(cgImage: cgImage!) let extent = inputImage.extent let inputExtent = CIVector(x: extent.origin.x, y: extent.origin.y, z: extent.size.width, w: extent.size.height) let filter = CIFilter(name: "CIAreaAverage", parameters: [kCIInputImageKey: inputImage, kCIInputExtentKey: inputExtent])! let outputImage = filter.outputImage! let outputExtent = outputImage.extent assert(outputExtent.size.width == 1 && outputExtent.size.height == 1) // Render to bitmap. context.render(outputImage, toBitmap: &bitmap, rowBytes: 4, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), format: CIFormat.RGBA8, colorSpace: CGColorSpaceCreateDeviceRGB()) } else { // Create 1x1 context that interpolates pixels when drawing to it. let context = CGContext(data: &bitmap, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! let inputImage = cgImage ?? CIContext().createCGImage(ciImage!, from: ciImage!.extent) // Render to bitmap. context.draw(inputImage!, in: CGRect(x: 0, y: 0, width: 1, height: 1)) } // Compute result. let result = UIColor(red: CGFloat(bitmap[0]) / 255.0, green: CGFloat(bitmap[1]) / 255.0, blue: CGFloat(bitmap[2]) / 255.0, alpha: CGFloat(bitmap[3]) / 255.0) return result } /** https://stackoverflow.com/a/62862742/3697225 Rounds corners of UIImage - Parameter proportion: Proportion to minimum paramter (width or height) in order to have the same look of corner radius independetly from aspect ratio and actual size */ func roundCorners(proportion: CGFloat) -> UIImage { let minValue = min(self.size.width, self.size.height) let radius = minValue/proportion let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: self.size) UIGraphicsBeginImageContextWithOptions(self.size, false, 1) UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip() self.draw(in: rect) let image = UIGraphicsGetImageFromCurrentImageContext() ?? self UIGraphicsEndImageContext() return image } } extension UIImage { func withBackground(color: UIColor, opaque: Bool = true) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, opaque, scale) guard let ctx = UIGraphicsGetCurrentContext(), let image = cgImage else { return self } defer { UIGraphicsEndImageContext() } let rect = CGRect(origin: .zero, size: size) ctx.setFillColor(color.cgColor) ctx.fill(rect) ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height)) ctx.draw(image, in: rect) return UIGraphicsGetImageFromCurrentImageContext() ?? self } } extension UIImage { func withPadding(_ padding: CGFloat) -> UIImage? { return withPadding(x: padding, y: padding) } func withPadding(x: CGFloat, y: CGFloat) -> UIImage? { let newWidth = size.width + 2 * x let newHeight = size.height + 2 * y let newSize = CGSize(width: newWidth, height: newHeight) UIGraphicsBeginImageContextWithOptions(newSize, false, 0) let origin = CGPoint(x: (newWidth - size.width) / 2, y: (newHeight - size.height) / 2) draw(at: origin) let imageWithPadding = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return imageWithPadding } }
apache-2.0
bc2e2fd9c32c45f2d05df7758b61971d
40.065156
209
0.609547
4.580095
false
false
false
false
michaelhayman/SeededNSURLSession
Example/SeededNSURLSession/ViewController.swift
1
1557
// // ViewController.swift // SeededNSURLSession // // Created by Michael Hayman on 05/18/2016. // Copyright (c) 2016 Michael Hayman. All rights reserved. // import UIKit import SeededNSURLSession class ViewController: UIViewController { @IBOutlet weak var medicationLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() fetchMedication() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func fetchMedication() { guard let requestURL = NSURL(string: "https://example.com/medications") else { return } let session = SeededURLSession.defaultSession() let request = NSMutableURLRequest(URL: requestURL) request.HTTPMethod = "GET" session.dataTaskWithRequest(request, completionHandler: { [weak self] (data, response, error) -> Void in guard let weakSelf = self else { return } if let data = data, dict = weakSelf.parse(data), let medications = dict["medications"] as? [JSONDictionary], medication = medications.first { weakSelf.medicationLabel.text = medication["name"] as? String } }).resume() } typealias JSONDictionary = [String: AnyObject] func parse(data: NSData) -> JSONDictionary? { do { return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? JSONDictionary } catch let error { print(error) } return nil } }
mit
4062027bba655226ddb7d9f059bbecbf
25.844828
112
0.624277
4.896226
false
false
false
false
qingtianbuyu/Mono
Moon/Classes/Other/Extension/MNBarButtonItem+Extension.swift
1
2679
// // MNBarButtonItem+Extension.swift // Moon // // Created by YKing on 16/6/9. // Copyright © 2016年 YKing. All rights reserved. // import UIKit extension UIBarButtonItem { /** 快速创建barButton 高亮图片 - parameter imageName: 图片 - parameter heightedImageName: 高亮图片 - parameter target: - parameter action: - returns: barButton */ class func buttonWithImage( _ imageName: String, heightedImageName: String,target: AnyObject?, action: Selector) -> UIBarButtonItem { let button = UIButton(type: UIButtonType.custom) button.setImage(UIImage(named: imageName), for: UIControlState.normal) if heightedImageName.characters.count > 0 { button.setImage(UIImage(named: heightedImageName), for: UIControlState.highlighted) } let size = button.currentImage!.size button.addTarget(target, action: action, for: UIControlEvents.touchUpInside) button.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) return UIBarButtonItem(customView: button) } /** 快速创建barButton - parameter imageName: 图片 - parameter target: - parameter action: - returns: barButton */ class func buttonWithImage( _ imageName: String, target: AnyObject?, action: Selector) -> UIBarButtonItem { return self.buttonWithImage(imageName, heightedImageName: "", target: target, action: action) } /** 快速创建BarButtonItem带有高亮颜色 - parameter title: 文字 - parameter color: 文字颜色 - parameter highlightColor: 文字高亮颜色 - parameter target: - parameter action: - returns: return value description */ class func buttonWithText(_ title: String?, color: UIColor, highlightColor: UIColor, target: AnyObject?, action:Selector) -> UIBarButtonItem { let rightButton = UIBarButtonItem() rightButton.title = title rightButton.target = target rightButton.action = action rightButton.setTitleTextAttributes([NSForegroundColorAttributeName: color], for: UIControlState.normal) rightButton.setTitleTextAttributes([NSForegroundColorAttributeName: highlightColor], for: UIControlState.highlighted) return rightButton } /** 快速创建BarButtonItem - parameter title: 文字 - parameter color: 文字颜色 - parameter target: - parameter action: - returns: BarButtonItem */ class func buttonWithText(_ title: String?, color: UIColor, target: AnyObject?, action:Selector) -> UIBarButtonItem { return self.buttonWithText(title, color:color, highlightColor: color, target: target, action: action) } }
mit
4f280de0dc924770da19eff9adb18cbc
28.906977
144
0.700622
4.609319
false
false
false
false
tardieu/swift
stdlib/public/core/StringBridge.swift
7
10924
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims #if _runtime(_ObjC) // Swift's String bridges NSString via this protocol and these // variables, allowing the core stdlib to remain decoupled from // Foundation. /// Effectively an untyped NSString that doesn't require foundation. public typealias _CocoaString = AnyObject public // @testable func _stdlib_binary_CFStringCreateCopy( _ source: _CocoaString ) -> _CocoaString { let result = _swift_stdlib_CFStringCreateCopy(nil, source) as AnyObject Builtin.release(result) return result } public // @testable func _stdlib_binary_CFStringGetLength( _ source: _CocoaString ) -> Int { return _swift_stdlib_CFStringGetLength(source) } public // @testable func _stdlib_binary_CFStringGetCharactersPtr( _ source: _CocoaString ) -> UnsafeMutablePointer<UTF16.CodeUnit>? { return UnsafeMutablePointer(mutating: _swift_stdlib_CFStringGetCharactersPtr(source)) } /// Bridges `source` to `Swift.String`, assuming that `source` has non-ASCII /// characters (does not apply ASCII optimizations). @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency func _cocoaStringToSwiftString_NonASCII( _ source: _CocoaString ) -> String { let cfImmutableValue = _stdlib_binary_CFStringCreateCopy(source) let length = _stdlib_binary_CFStringGetLength(cfImmutableValue) let start = _stdlib_binary_CFStringGetCharactersPtr(cfImmutableValue) return String(_StringCore( baseAddress: start, count: length, elementShift: 1, hasCocoaBuffer: true, owner: unsafeBitCast(cfImmutableValue, to: Optional<AnyObject>.self))) } /// Loading Foundation initializes these function variables /// with useful values /// Produces a `_StringBuffer` from a given subrange of a source /// `_CocoaString`, having the given minimum capacity. @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringToContiguous( source: _CocoaString, range: Range<Int>, minimumCapacity: Int ) -> _StringBuffer { _sanityCheck(_swift_stdlib_CFStringGetCharactersPtr(source) == nil, "Known contiguously stored strings should already be converted to Swift") let startIndex = range.lowerBound let count = range.upperBound - startIndex let buffer = _StringBuffer(capacity: max(count, minimumCapacity), initialSize: count, elementWidth: 2) _swift_stdlib_CFStringGetCharacters( source, _swift_shims_CFRange(location: startIndex, length: count), buffer.start.assumingMemoryBound(to: _swift_shims_UniChar.self)) return buffer } /// Reads the entire contents of a _CocoaString into contiguous /// storage of sufficient capacity. @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringReadAll( _ source: _CocoaString, _ destination: UnsafeMutablePointer<UTF16.CodeUnit> ) { _swift_stdlib_CFStringGetCharacters( source, _swift_shims_CFRange( location: 0, length: _swift_stdlib_CFStringGetLength(source)), destination) } @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringSlice( _ target: _StringCore, _ bounds: Range<Int> ) -> _StringCore { _sanityCheck(target.hasCocoaBuffer) let cfSelf: _swift_shims_CFStringRef = target.cocoaBuffer.unsafelyUnwrapped _sanityCheck( _swift_stdlib_CFStringGetCharactersPtr(cfSelf) == nil, "Known contiguously stored strings should already be converted to Swift") let cfResult = _swift_stdlib_CFStringCreateWithSubstring( nil, cfSelf, _swift_shims_CFRange( location: bounds.lowerBound, length: bounds.count)) as AnyObject return String(_cocoaString: cfResult)._core } @_versioned @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringSubscript( _ target: _StringCore, _ position: Int ) -> UTF16.CodeUnit { let cfSelf: _swift_shims_CFStringRef = target.cocoaBuffer.unsafelyUnwrapped _sanityCheck(_swift_stdlib_CFStringGetCharactersPtr(cfSelf) == nil, "Known contiguously stored strings should already be converted to Swift") return _swift_stdlib_CFStringGetCharacterAtIndex(cfSelf, position) } // // Conversion from NSString to Swift's native representation // internal var kCFStringEncodingASCII : _swift_shims_CFStringEncoding { return 0x0600 } extension String { @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency public // SPI(Foundation) init(_cocoaString: AnyObject) { if let wrapped = _cocoaString as? _NSContiguousString { self._core = wrapped._core return } // "copy" it into a value to be sure nobody will modify behind // our backs. In practice, when value is already immutable, this // just does a retain. let cfImmutableValue = _stdlib_binary_CFStringCreateCopy(_cocoaString) as AnyObject let length = _swift_stdlib_CFStringGetLength(cfImmutableValue) // Look first for null-terminated ASCII // Note: the code in clownfish appears to guarantee // nul-termination, but I'm waiting for an answer from Chris Kane // about whether we can count on it for all time or not. let nulTerminatedASCII = _swift_stdlib_CFStringGetCStringPtr( cfImmutableValue, kCFStringEncodingASCII) // start will hold the base pointer of contiguous storage, if it // is found. var start: UnsafeMutableRawPointer? let isUTF16 = (nulTerminatedASCII == nil) if isUTF16 { let utf16Buf = _swift_stdlib_CFStringGetCharactersPtr(cfImmutableValue) start = UnsafeMutableRawPointer(mutating: utf16Buf) } else { start = UnsafeMutableRawPointer(mutating: nulTerminatedASCII) } self._core = _StringCore( baseAddress: start, count: length, elementShift: isUTF16 ? 1 : 0, hasCocoaBuffer: true, owner: cfImmutableValue) } } // At runtime, this class is derived from `_SwiftNativeNSStringBase`, // which is derived from `NSString`. // // The @_swift_native_objc_runtime_base attribute // This allows us to subclass an Objective-C class and use the fast Swift // memory allocator. @objc @_swift_native_objc_runtime_base(_SwiftNativeNSStringBase) public class _SwiftNativeNSString {} @objc public protocol _NSStringCore : _NSCopying, _NSFastEnumeration { // The following methods should be overridden when implementing an // NSString subclass. func length() -> Int func characterAtIndex(_ index: Int) -> UInt16 // We also override the following methods for efficiency. } /// An `NSString` built around a slice of contiguous Swift `String` storage. public final class _NSContiguousString : _SwiftNativeNSString { public init(_ _core: _StringCore) { _sanityCheck( _core.hasContiguousStorage, "_NSContiguousString requires contiguous storage") self._core = _core super.init() } init(coder aDecoder: AnyObject) { _sanityCheckFailure("init(coder:) not implemented for _NSContiguousString") } func length() -> Int { return _core.count } func characterAtIndex(_ index: Int) -> UInt16 { return _core[index] } @inline(__always) // Performance: To save on reference count operations. func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange) { _precondition(aRange.location + aRange.length <= Int(_core.count)) if _core.elementWidth == 2 { UTF16._copy( source: _core.startUTF16 + aRange.location, destination: UnsafeMutablePointer<UInt16>(buffer), count: aRange.length) } else { UTF16._copy( source: _core.startASCII + aRange.location, destination: UnsafeMutablePointer<UInt16>(buffer), count: aRange.length) } } @objc func _fastCharacterContents() -> UnsafeMutablePointer<UInt16>? { return _core.elementWidth == 2 ? _core.startUTF16 : nil } // // Implement sub-slicing without adding layers of wrapping // func substringFromIndex(_ start: Int) -> _NSContiguousString { return _NSContiguousString(_core[Int(start)..<Int(_core.count)]) } func substringToIndex(_ end: Int) -> _NSContiguousString { return _NSContiguousString(_core[0..<Int(end)]) } func substringWithRange(_ aRange: _SwiftNSRange) -> _NSContiguousString { return _NSContiguousString( _core[Int(aRange.location)..<Int(aRange.location + aRange.length)]) } func copy() -> AnyObject { // Since this string is immutable we can just return ourselves. return self } /// The caller of this function guarantees that the closure 'body' does not /// escape the object referenced by the opaque pointer passed to it or /// anything transitively reachable form this object. Doing so /// will result in undefined behavior. @_semantics("self_no_escaping_closure") func _unsafeWithNotEscapedSelfPointer<Result>( _ body: (OpaquePointer) throws -> Result ) rethrows -> Result { let selfAsPointer = unsafeBitCast(self, to: OpaquePointer.self) defer { _fixLifetime(self) } return try body(selfAsPointer) } /// The caller of this function guarantees that the closure 'body' does not /// escape either object referenced by the opaque pointer pair passed to it or /// transitively reachable objects. Doing so will result in undefined /// behavior. @_semantics("pair_no_escaping_closure") func _unsafeWithNotEscapedSelfPointerPair<Result>( _ rhs: _NSContiguousString, _ body: (OpaquePointer, OpaquePointer) throws -> Result ) rethrows -> Result { let selfAsPointer = unsafeBitCast(self, to: OpaquePointer.self) let rhsAsPointer = unsafeBitCast(rhs, to: OpaquePointer.self) defer { _fixLifetime(self) _fixLifetime(rhs) } return try body(selfAsPointer, rhsAsPointer) } public let _core: _StringCore } extension String { /// Same as `_bridgeToObjectiveC()`, but located inside the core standard /// library. public func _stdlib_binary_bridgeToObjectiveCImpl() -> AnyObject { if let ns = _core.cocoaBuffer, _swift_stdlib_CFStringGetLength(ns) == _core.count { return ns } _sanityCheck(_core.hasContiguousStorage) return _NSContiguousString(_core) } @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency public func _bridgeToObjectiveCImpl() -> AnyObject { return _stdlib_binary_bridgeToObjectiveCImpl() } } #endif
apache-2.0
2c83b8c5195cfde6c3ffd1358286d385
32.203647
87
0.707799
4.561169
false
false
false
false
auth0/Lock.swift
Lock/Extensions.swift
1
5758
// Extensions.swift // // Copyright (c) 2016 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit extension Optional { func verbatim() -> String { switch self { case .some(let value): return String(describing: value) case _: return "<no value>" } } } extension UIView { func styleSubViews(style: Style) { self.subviews.forEach { view in if let view = view as? Stylable { view.apply(style: style) } view.styleSubViews(style: style) } } } extension UILayoutPriority { #if swift(>=4.0) static let priorityRequired = required static let priorityDefaultLow = defaultLow static let priorityDefaultHigh = defaultHigh #else static let priorityRequired = UILayoutPriorityRequired static let priorityDefaultLow = UILayoutPriorityDefaultLow static let priorityDefaultHigh = UILayoutPriorityDefaultHigh #endif } extension NSAttributedString { #if swift(>=4.2) static let attributedKeyColor = Key.foregroundColor static let attributedFont = Key.font #elseif swift(>=4.0) static let attributedKeyColor = NSAttributedStringKey.foregroundColor static let attributedFont = NSAttributedStringKey.font #else static let attributedKeyColor = NSForegroundColorAttributeName static let attributedFont = NSFontAttributeName #endif } extension UIFont { #if swift(>=4.0) static let weightLight = Weight.light static let weightMedium = Weight.medium static let weightRegular = Weight.regular static let weightSemiBold = Weight.semibold static let weightBold = Weight.bold #else static let weightLight = UIFontWeightLight static let weightMedium = UIFontWeightMedium static let weightRegular = UIFontWeightRegular static let weightSemiBold = UIFontWeightSemibold static let weightBold = UIFontWeightBold #endif } #if swift(>=4.2) let accessibilityIsReduceTransparencyEnabled = UIAccessibility.isReduceTransparencyEnabled #else let accessibilityIsReduceTransparencyEnabled = UIAccessibilityIsReduceTransparencyEnabled() #endif extension UIView { #if swift(>=4.2) static let viewNoIntrinsicMetric = noIntrinsicMetric #else static let viewNoIntrinsicMetric = UIViewNoIntrinsicMetric #endif } // swiftlint:disable identifier_name extension UIResponder { #if swift(>=4.2) static let responderKeyboardWillShowNotification = keyboardWillShowNotification static let responderKeyboardWillHideNotification = keyboardWillHideNotification static let responderKeyboardFrameEndUserInfoKey = keyboardFrameEndUserInfoKey static let responderKeyboardAnimationDurationUserInfoKey = keyboardAnimationDurationUserInfoKey static let responderKeyboardAnimationCurveUserInfoKey = keyboardAnimationCurveUserInfoKey #else static let responderKeyboardWillShowNotification = NSNotification.Name.UIKeyboardWillShow static let responderKeyboardWillHideNotification = NSNotification.Name.UIKeyboardWillHide static let responderKeyboardFrameEndUserInfoKey = UIKeyboardFrameEndUserInfoKey static let responderKeyboardAnimationDurationUserInfoKey = UIKeyboardAnimationDurationUserInfoKey static let responderKeyboardAnimationCurveUserInfoKey = UIKeyboardAnimationCurveUserInfoKey #endif } // swiftlint:enable identifier_name // MARK: - Public Typealiases #if swift(>=4.2) public typealias A0AlertActionStyle = UIAlertAction.Style #else public typealias A0AlertActionStyle = UIAlertActionStyle #endif #if swift(>=4.2) public typealias A0AlertControllerStyle = UIAlertController.Style #else public typealias A0AlertControllerStyle = UIAlertControllerStyle #endif #if swift(>=4.2) public typealias A0URLOptionsKey = UIApplication.OpenURLOptionsKey #else public typealias A0URLOptionsKey = UIApplicationOpenURLOptionsKey #endif #if swift(>=4.2) public typealias A0ApplicationLaunchOptionsKey = UIApplication.LaunchOptionsKey #else public typealias A0ApplicationLaunchOptionsKey = UIApplicationLaunchOptionsKey #endif #if swift(>=4.2) public typealias A0BlurEffectStyle = UIBlurEffect.Style #else public typealias A0BlurEffectStyle = UIBlurEffectStyle #endif #if swift(>=4.2) public typealias A0ControlState = UIControl.State #else public typealias A0ControlState = UIControlState #endif #if swift(>=4.2) public typealias A0SearchBarStyle = UISearchBar.Style #else public typealias A0SearchBarStyle = UISearchBarStyle #endif #if swift(>=4.2) public typealias A0ViewAnimationOptions = UIView.AnimationOptions #else public typealias A0ViewAnimationOptions = UIViewAnimationOptions #endif
mit
0f2eafba46cd6a28a3786b082a8ce8fe
32.672515
101
0.774575
5.141071
false
false
false
false
nakau1/NeroBlu
NeroBlu/NBDialog.swift
1
9665
// ============================================================================= // NerobluCore // Copyright (C) NeroBlu. All rights reserved. // ============================================================================= import UIKit // - MARK: UIAlertAction拡張- public extension UIAlertAction { // MARK: コンビニエンスイニシャライザ /// イニシャライザ (UIAlertActionStyle.Defaultとして初期化) /// - parameter title: タイトル /// - parameter handler: 押下時のハンドラ public convenience init(_ title: String?, _ handler: VoidClosure? = nil) { self.init(title: title, style: .default, handler: { _ in handler?() }) } /// イニシャライザ (UIAlertActionStyle.Destructiveとして初期化) /// - parameter title: タイトル /// - parameter handler: 押下時のハンドラ public convenience init(destructive title: String?, _ handler: VoidClosure? = nil) { self.init(title: title, style: .destructive, handler: { _ in handler?() }) } /// イニシャライザ (UIAlertActionStyle.Cancelとして初期化) /// - parameter title: タイトル /// - parameter handler: 押下時のハンドラ public convenience init(cancel title: String?, _ handler: VoidClosure? = nil) { self.init(title: title, style: .cancel, handler: { _ in handler?() }) } // MARK: 定型アクション /// "OK"アクションを返す /// - parameter handler: 押下時のハンドラ /// - returns: UIAlertAction public class func ok(_ handler: VoidClosure? = nil) -> UIAlertAction { return UIAlertAction("OK".localize(), handler) } /// "キャンセル"アクションを返す /// - parameter handler: 押下時のハンドラ /// - returns: UIAlertAction public class func cancel(_ handler: VoidClosure? = nil) -> UIAlertAction { return UIAlertAction(cancel: "Cancel".localize(), handler) } /// "はい"アクションを返す /// - parameter handler: 押下時のハンドラ /// - returns: UIAlertAction public class func yes(_ handler: VoidClosure? = nil) -> UIAlertAction { return UIAlertAction("Yes".localize(), handler) } /// "いいえ"アクションを返す /// - parameter handler: 押下時のハンドラ /// - returns: UIAlertAction public class func no(_ handler: VoidClosure? = nil) -> UIAlertAction { return UIAlertAction(cancel: "No".localize(), handler) } /// "戻る"アクションを返す /// - parameter handler: 押下時のハンドラ /// - returns: UIAlertAction public class func back(_ handler: VoidClosure? = nil) -> UIAlertAction { return UIAlertAction(cancel: "Back".localize(), handler) } /// "次へ"アクションを返す /// - parameter handler: 押下時のハンドラ /// - returns: UIAlertAction public class func next(_ handler: VoidClosure? = nil) -> UIAlertAction { return UIAlertAction("Next".localize(), handler) } } // MARK: - NBAlert - /// アラートの表示を行うクラス open class NBAlert { /// アラートを表示する /// - parameter controller: 表示を行うビューコントローラ /// - parameter title: タイトル文言 /// - parameter message: メッセージ文言 /// - parameter actions: UIAlertActionの配列 open class func show(_ controller: UIViewController, title: String? = nil, message: String?, actions: [UIAlertAction]) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) actions.forEach { alert.addAction($0) } controller.present(alert, animated: true, completion: nil) } } // MARK: 「OK」のみのアラート public extension NBAlert { /// 「OK」のみのアラートを表示する /// - parameter controller: 表示を行うビューコントローラ /// - parameter title: タイトル文言 /// - parameter message: メッセージ文言 /// - parameter handler: アラートのボタン押下時のイベントハンドラ public class func show(OK controller: UIViewController, title: String? = nil, message: String?, handler: VoidClosure? = nil) { let actions = [ UIAlertAction.ok() { _ in handler?() }, ] self.show(controller, title: title, message: message, actions: actions) } } // MARK: 「はい/いいえ」のアラート public extension NBAlert { /// 「はい/いいえ」のアラートを表示する /// - parameter controller: 表示を行うビューコントローラ /// - parameter title: タイトル文言 /// - parameter message: メッセージ文言 /// - parameter handler: 「はい」押下時のイベントハンドラ public class func show(YesNo controller: UIViewController, title: String? = nil, message: String?, handler: VoidClosure?) { let actions = [ UIAlertAction.no(), UIAlertAction.yes(handler), ] self.show(controller, title: title, message: message, actions: actions) } /// 「はい/いいえ」のアラートを表示する /// - parameter controller: 表示を行うビューコントローラ /// - parameter title: タイトル文言 /// - parameter message: メッセージ文言 /// - parameter yes: 「はい」押下時のイベントハンドラ /// - parameter no: 「いいえ」押下時のイベントハンドラ public class func show(YesNo controller: UIViewController, title: String? = nil, message: String?, yes: @escaping VoidClosure, no: @escaping VoidClosure) { let actions = [ UIAlertAction.no(no), UIAlertAction.yes(yes), ] self.show(controller, title: title, message: message, actions: actions) } } // MARK: 「OK/キャンセル」のアラート public extension NBAlert { /// 「OK/キャンセル」のアラートを表示する /// - parameter controller: 表示を行うビューコントローラ /// - parameter title: タイトル文言 /// - parameter message: メッセージ文言 /// - parameter handler: 「OK」押下時のイベントハンドラ public class func show(OKCancel controller: UIViewController, title: String? = nil, message: String?, handler: VoidClosure?) { let actions = [ UIAlertAction.cancel(), UIAlertAction.ok(handler), ] self.show(controller, title: title, message: message, actions: actions) } /// 「OK/キャンセル」のアラートを表示する /// - parameter controller: 表示を行うビューコントローラ /// - parameter title: タイトル文言 /// - parameter message: メッセージ文言 /// - parameter ok: 「OK」押下時のイベントハンドラ /// - parameter cancel: 「キャンセル」押下時のイベントハンドラ public class func show(OKCancel controller: UIViewController, title: String? = nil, message: String?, ok: @escaping VoidClosure, cancel: @escaping VoidClosure) { let actions = [ UIAlertAction.cancel(cancel), UIAlertAction.ok(ok), ] self.show(controller, title: title, message: message, actions: actions) } } // MARK: 「OK/戻る」のアラート public extension NBAlert { /// 「OK/戻る」のアラートを表示する /// - parameter controller: 表示を行うビューコントローラ /// - parameter title: タイトル文言 /// - parameter message: メッセージ文言 /// - parameter handler: 「OK」押下時のイベントハンドラ public class func show(OKBack controller: UIViewController, title: String? = nil, message: String?, handler: VoidClosure?) { let actions = [ UIAlertAction.back(), UIAlertAction.ok(handler), ] self.show(controller, title: title, message: message, actions: actions) } /// 「OK/戻る」のアラートを表示する /// - parameter controller: 表示を行うビューコントローラ /// - parameter title: タイトル文言 /// - parameter message: メッセージ文言 /// - parameter ok: 「OK」押下時のイベントハンドラ /// - parameter back: 「戻る」押下時のイベントハンドラ public class func show(OKBack controller: UIViewController, title: String? = nil, message: String?, ok: @escaping VoidClosure, back: @escaping VoidClosure) { let actions = [ UIAlertAction.back(back), UIAlertAction.ok(ok), ] self.show(controller, title: title, message: message, actions: actions) } } // MARK: - NBActionSheet - /// アクションシートの表示を行うクラス open class NBActionSheet { /// アクションシートを表示する /// - parameter controller: 表示を行うビューコントローラ /// - parameter title: タイトル文言 /// - parameter message: メッセージ文言 /// - parameter actions: UIAlertActionの配列 open class func show(_ controller: UIViewController, title: String? = nil, message: String? = nil, actions: [UIAlertAction]) { if actions.isEmpty { return } let alert = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) actions.forEach { alert.addAction($0) } controller.present(alert, animated: true, completion: nil) } }
mit
7116ae99edeb17e76bd5fb30f96a606e
35.303167
165
0.617225
3.923227
false
false
false
false
xuech/OMS-WH
OMS-WH/Classes/FeedBack/View/InstrumentConsumCell.swift
1
2777
// // InstrumentConsumCell.swift // OMS-WH // // Created by xuech on 2017/11/15. // Copyright © 2017年 medlog. All rights reserved. // import UIKit import SVProgressHUD protocol InstrumentConsumCellDelegate { func cellBtn(didSelected inCell: UITableViewCell,withTag tag:Int) func editUseReqTableViewCell(cell: UITableViewCell, modifiedModel: FeedBackMedModel,viewType:InstrumentConsumptionType) } class InstrumentConsumCell: UITableViewCell { @IBOutlet weak var metailBatch: UILabel! @IBOutlet weak var metailType: UILabel! @IBOutlet weak var metailRule: UILabel! @IBOutlet weak var metailCode: UILabel! @IBOutlet weak var metailName: UILabel! @IBOutlet weak var metailUseQty: UILabel! @IBOutlet weak var deleteBtn: UIButton! @IBOutlet weak var editBtn: UIButton! @IBOutlet weak var copyBtn: UIButton! @IBOutlet weak var stepper: StepperSwift! var delegate : InstrumentConsumCellDelegate? fileprivate var model : FeedBackMedModel? override func awakeFromNib() { super.awakeFromNib() // Initialization code } fileprivate var vcType : InstrumentConsumptionType = .insideOutBound func configMetailData(feedBackMedMaterial:FeedBackMedModel,viewType:InstrumentConsumptionType) { model = feedBackMedMaterial vcType = viewType metailName.text = "名称:\(feedBackMedMaterial.medMIName)" metailCode.text = "编码:\(feedBackMedMaterial.medMICode)" metailRule.text = "规格:\(feedBackMedMaterial.specification)" metailType.text = "类型:\(feedBackMedMaterial.categoryByPlatformName)" metailBatch.text = "批次/序列号:\(feedBackMedMaterial.lotSerial)" // metailUseQty.text = "使用数量:\(feedBackMedMaterial.useQty)" stepper.value = Double(feedBackMedMaterial.useQty) } @IBAction func cellButtonsEvent(_ sender: UIButton) { guard let delege = delegate else { return } delege.cellBtn(didSelected: self, withTag: sender.tag) } @IBAction func stepperValue(_ sender: StepperSwift) { var useReq = Int(stepper.value) let reqQty = Int(model?.reqQty ?? 0) if useReq > reqQty && vcType == .insideOutBound{ useReq = useReq - 1 stepper.value = Double(useReq) SVProgressHUD.showError("器械使用数量大于出单数量!") return } model?.useQty = useReq delegate?.editUseReqTableViewCell(cell: self, modifiedModel: model!, viewType: vcType) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
2b242c4d811deeb05d5111cfca3e5d76
35.026667
123
0.687639
4.156923
false
false
false
false
zoeyzhong520/InformationTechnology
InformationTechnology/InformationTechnology/Classes/Recommend推荐/Science科技/View/HasTypeLiveCell.swift
1
2873
// // HasTypeLiveCell.swift // InformationTechnology // // Created by qianfeng on 16/11/17. // Copyright © 2016年 zzj. All rights reserved. // import UIKit class HasTypeLiveCell: UITableViewCell { //点击事件 var jumpClosure:RecommendJumpClosure? @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var imgView: UIImageView! @IBOutlet weak var stateLabel: UILabel! //数据 var itemArray:Array<RecommendValueZeroItem>? { didSet { //显示数据 showData() } } //显示数据 func showData() { let cnt = itemArray?.count for i in 0..<cnt! { if itemArray?.count > 0 { //标题 let tmpTitle = itemArray![i] titleLabel.text = tmpTitle.title //新闻状态Label stateLabel.text = "进行中・・・" //图片 let model = itemArray![i] //创建图片 if model.thumbnail != nil { let url = NSURL(string: model.thumbnail!) imgView.kf_setImageWithURL(url!, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) } //添加点击事件 contentView.tag = 200+i let g = UITapGestureRecognizer(target: self, action: #selector(tapImage(_:))) contentView.addGestureRecognizer(g) } } } func tapImage(g: UIGestureRecognizer) { let index = (g.view?.tag)! - 200 //获取点击的数据 let item = itemArray![index] if jumpClosure != nil && item.commentsUrl != nil { jumpClosure!(item.commentsUrl!) } } //创建cell的方法 class func createHasTypeLiveCellFor(tableView:UITableView, atIndexPath indexPath:NSIndexPath, itemArray:Array<RecommendValueZeroItem>?) -> HasTypeLiveCell { let cellId = "hasTypeLiveCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? HasTypeLiveCell if cell == nil { cell = NSBundle.mainBundle().loadNibNamed("HasTypeLiveCell", owner: nil, options: nil).last as? HasTypeLiveCell } cell?.itemArray = itemArray return cell! } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
eff5f0310109df1350b06ebecb8af012
26.979798
165
0.532852
5.236295
false
false
false
false
Affix/tvSnake
tvSnake/SnakeView.swift
1
1706
// // SnakeView.swift // tvSnake // // Created by Keiran Smith on 16/10/2015. // Copyright © 2015 Affix.ME. All rights reserved. // import UIKit protocol SnakeViewDelegate { func snakeForSnakeView(view:SnakeView) -> Snake? func pointOfFruitForSnakeView(view:SnakeView) -> Point? } class SnakeView : UIView { var delegate:SnakeViewDelegate? var pointsLabel : UILabel! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.backgroundColor = UIColor.whiteColor() } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.whiteColor() pointsLabel = UILabel(frame: CGRectMake(100, 100, 60, 30)) pointsLabel.font = UIFont.systemFontOfSize(38) pointsLabel.textAlignment = .Center pointsLabel.textColor = UIColor.darkGrayColor() self.addSubview(pointsLabel) } override func drawRect(rect: CGRect) { super.drawRect(rect) if let snake:Snake = delegate?.snakeForSnakeView(self) { let worldSize = snake.worldSize if worldSize.width <= 0 || worldSize.height <= 0 { return } pointsLabel.text = String(snake.gamePoints) let w = Int(Float(self.bounds.size.width) / Float(worldSize.width)) let h = Int(Float(self.bounds.size.height) / Float(worldSize.height)) UIColor.blackColor().set() let points = snake.points for point in points { let rect = CGRect(x: point.x * w, y: point.y * h, width: w, height: h) UIBezierPath(rect: rect).fill() } if let fruit = delegate?.pointOfFruitForSnakeView(self) { UIColor.redColor().set() let rect = CGRect(x: fruit.x * w, y: fruit.y * h, width: w, height: h) UIBezierPath(ovalInRect: rect).fill() } } } }
gpl-3.0
157fc1516a27831faaaf781b19915244
25.640625
74
0.68915
3.247619
false
false
false
false
yunzixun/V2ex-Swift
View/V2PhotoBrowser/V2ZoomingScrollView.swift
1
8635
// // V2ZoomingScrollView.swift // V2ex-Swift // // Created by huangfeng on 2/22/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit class V2ZoomingScrollView: UIScrollView ,V2TapDetectingImageViewDelegate , UIScrollViewDelegate{ var index:Int = Int.max var photoImageView:V2TapDetectingImageView = V2TapDetectingImageView() var _photo:V2Photo? var photo:V2Photo? { get{ return self._photo } set { self._photo = newValue if let _ = self._photo?.underlyingImage { self.displayImage() } else { self.loadingView.isHidden = false self.loadingView.startAnimating() self._photo?.performLoadUnderlyingImageAndNotify() } } } fileprivate var loadingView = UIActivityIndicatorView(activityIndicatorStyle: .white) weak var photoBrowser:V2PhotoBrowser? init(browser:V2PhotoBrowser){ super.init(frame: CGRect.zero) self.photoImageView.tapDelegate = self self.photoImageView.contentMode = .center self.photoImageView.backgroundColor = UIColor.clear self.addSubview(self.photoImageView) self.addSubview(self.loadingView) self.loadingView.startAnimating() self.loadingView.center = browser.view.center self.delegate = self self.showsHorizontalScrollIndicator = false self.showsVerticalScrollIndicator = false self.decelerationRate = UIScrollViewDecelerationRateFast NotificationCenter.default.addObserver(self, selector: #selector(V2ZoomingScrollView.loadingDidEndNotification(_:)), name: NSNotification.Name(rawValue: V2Photo.V2PHOTO_LOADING_DID_END_NOTIFICATION), object: nil) self.photoBrowser = browser } deinit { NotificationCenter.default.removeObserver(self) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { self.singleTap() self.next?.touchesEnded(touches, with: event) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func loadingDidEndNotification(_ notification:Notification){ self.loadingView.isHidden = true self.loadingView.stopAnimating() if notification.object as? V2Photo == self.photo , let _ = self._photo?.underlyingImage { self.displayImage() } } func prepareForReuse(){ self.photo = nil self.photoImageView.image = nil self.index = Int.max } func displayImage(){ if self.photoImageView.image == nil , let image = self.photo?.underlyingImage { self.maximumZoomScale = 1 self.minimumZoomScale = 1 self.zoomScale = 1 self.contentSize = CGSize(width: 0, height: 0) self.photoImageView.image = image let photoImageViewFrame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height) self.photoImageView.frame = photoImageViewFrame self.contentSize = photoImageViewFrame.size self.setMaxMinZoomScalesForCurrentBounds() self.loadingView.isHidden = true self.loadingView.stopAnimating() } self.setNeedsLayout() } func setMaxMinZoomScalesForCurrentBounds(){ // Reset self.maximumZoomScale = 1 self.minimumZoomScale = 1 self.zoomScale = 1 if self.photoImageView.image == nil { return } self.photoImageView.frame = CGRect(x: 0, y: 0, width: self.photoImageView.frame.size.width, height: self.photoImageView.frame.size.height); let boundsSize = self.bounds.size; let imageSize = self.photoImageView.image!.size let xScale = boundsSize.width / imageSize.width let yScale = boundsSize.height / imageSize.height var minScale = min(xScale,yScale) let maxScale:CGFloat = 3 // Image is smaller than screen so no zooming! if xScale >= 1 && yScale >= 1 { minScale = 1 } self.maximumZoomScale = maxScale self.minimumZoomScale = minScale // self.zoomScale = self.initialZoomScaleWithMinScale() self.zoomScale = self.minimumZoomScale if self.zoomScale != minScale { self.contentOffset = CGPoint(x: (imageSize.width * self.zoomScale - boundsSize.width) / 2.0, y: (imageSize.height * self.zoomScale - boundsSize.height) / 2.0); } self.isScrollEnabled = false self.setNeedsLayout() } func initialZoomScaleWithMinScale() -> CGFloat{ var zoomScale = self.minimumZoomScale if self.photoImageView.image != nil { let boundsSize = self.bounds.size let imageSize = self.photoImageView.image!.size let boundsAR = boundsSize.width / boundsSize.height let imageAR = imageSize.width / imageSize.height let xScale = boundsSize.width / imageSize.width let yScale = boundsSize.height / imageSize.height // Zooms standard portrait images on a 3.5in screen but not on a 4in screen. if abs(boundsAR - imageAR) < 0.17 { zoomScale = max(xScale, yScale); // Ensure we don't zoom in or out too far, just in case zoomScale = min(max(self.minimumZoomScale, zoomScale), self.maximumZoomScale); } } return zoomScale } override func layoutSubviews() { super.layoutSubviews() let boundsSize = self.bounds.size var frameToCenter = self.photoImageView.frame // Horizontally if (frameToCenter.size.width < boundsSize.width) { let f = Float( (boundsSize.width - frameToCenter.size.width) / CGFloat(2.0) ) frameToCenter.origin.x = CGFloat( floorf(f) ); } else { frameToCenter.origin.x = 0; } // Vertically if (frameToCenter.size.height < boundsSize.height) { let f = Float( (boundsSize.height - frameToCenter.size.height) / CGFloat(2.0) ) frameToCenter.origin.y = CGFloat( floorf(f) ); } else { frameToCenter.origin.y = 0; } if !(self.photoImageView.frame).equalTo(frameToCenter) { self.photoImageView.frame = frameToCenter } } //MARK: UIScrollViewDelegate func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self.photoImageView } func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { self.isScrollEnabled = true } func scrollViewDidZoom(_ scrollView: UIScrollView) { self.setNeedsLayout() self.layoutIfNeeded() } func singleTap(){ self.handelSingleTap() } func singleTapDetected(_ imageView: UIImageView, touch: UITouch) { self.handelSingleTap() } func handelSingleTap(){ if self.photo?.underlyingImage == nil { self.photoBrowser?.dismiss() } // Zoom if (self.zoomScale != self.minimumZoomScale && self.zoomScale != self.initialZoomScaleWithMinScale()) { // Zoom out self.setZoomScale(self.minimumZoomScale, animated: true) } else { self.photoBrowser?.dismiss() } } func doubleTapDetected(_ imageView: UIImageView, touch: UITouch) { // Zoom if (self.zoomScale != self.minimumZoomScale && self.zoomScale != self.initialZoomScaleWithMinScale()) { // Zoom out self.setZoomScale(self.minimumZoomScale, animated: true) } else { let touchPoint = touch.location(in: imageView) // Zoom in to twice the size let newZoomScale = ((self.maximumZoomScale + self.minimumZoomScale) / 2); let xsize = self.bounds.size.width / newZoomScale; let ysize = self.bounds.size.height / newZoomScale; self.zoom(to: CGRect(x: touchPoint.x - xsize/2, y: touchPoint.y - ysize/2, width: xsize, height: ysize), animated: true) } } }
mit
7d729435cb12fbfb587e50e78c4ba351
33.674699
220
0.594858
5.145411
false
false
false
false
gtsif21/UIKeyboardLikePickerTextField
Pod/Classes/UIKeyboardLikePickerTextField.swift
1
6223
// // UIKeyboardLikePickerTextField.swift // Gia Ola // // Created by George Tsifrikas on 16/12/15. // Copyright © 2015 George Tsifrikas. All rights reserved. // import UIKit public class UIKeyboardLikePickerTextField: UITextField, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate { static var picker:UIPickerView? static var pickerToolbar:UIToolbar? static var picketToolbarButton: UIBarButtonItem? weak var otherDelegate: UITextFieldDelegate? = nil; weak private var parentView:UIView? override weak public var delegate: UITextFieldDelegate? { get { return self } set(newDelegate) { otherDelegate = newDelegate } } public var pickerDataSource:[String] = [] { didSet { focusedOnMe() } } override init(frame: CGRect) { super.init(frame: frame) super.delegate = self checkStatus() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) super.delegate = self checkStatus() } private func checkStatus() { if UIKeyboardLikePickerTextField.picker == nil { self.createPicker() } self.inputAccessoryView = UIKeyboardLikePickerTextField.pickerToolbar self.inputView = UIKeyboardLikePickerTextField.picker // NSNotificationCenter.defaultCenter().addObserver(self, selector: "focusedOnMe", name: UITextViewTextDidBeginEditingNotification, object: nil) } func focusedOnMe() { UIKeyboardLikePickerTextField.picker?.dataSource = self UIKeyboardLikePickerTextField.picker?.delegate = self UIKeyboardLikePickerTextField.picker?.reloadAllComponents() if self.text == "" { UIKeyboardLikePickerTextField.picker?.selectRow(0, inComponent: 0, animated: false) } else { var index = 0 for option in self.pickerDataSource { if option == self.text { UIKeyboardLikePickerTextField.picker?.selectRow(index + 1, inComponent: 0, animated: false) } index++ } } } private func createPicker() { var heightOfPicker:CGFloat = 216 if UIDevice.currentDevice().userInterfaceIdiom == .Pad { if UIDevice.currentDevice().orientation == .Portrait || UIDevice.currentDevice().orientation == .PortraitUpsideDown { heightOfPicker = 264 } else { heightOfPicker = 352 } } else { if UIDevice.currentDevice().orientation == .Portrait || UIDevice.currentDevice().orientation == .PortraitUpsideDown { heightOfPicker = 216 } else { heightOfPicker = 162 } } heightOfPicker += 20 let screenHeight = UIScreen.mainScreen().bounds.size.height let picker = UIPickerView(frame: CGRectMake(0, screenHeight - heightOfPicker, UIScreen.mainScreen().bounds.size.width, heightOfPicker)) UIKeyboardLikePickerTextField.picker = picker let toolBar = UIToolbar() toolBar.barStyle = UIBarStyle.Default toolBar.translucent = true // toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1) let doneButton = UIBarButtonItem(title: "Done".localizedString, style: UIBarButtonItemStyle.Done, target: self, action: "donePressed") // var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelPressed") let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) toolBar.setItems([spaceButton, doneButton], animated: false) toolBar.userInteractionEnabled = true toolBar.sizeToFit() UIKeyboardLikePickerTextField.pickerToolbar = toolBar self.inputAccessoryView = toolBar } func donePressed() { self.textFieldShouldReturn(self) } //MARK: - text filed self delegate public func textFieldDidBeginEditing(textField: UITextField){ otherDelegate?.textFieldDidBeginEditing?(textField); } public func textFieldShouldBeginEditing(textField: UITextField) -> Bool { focusedOnMe() return otherDelegate?.textFieldShouldBeginEditing?(textField) ?? true } public func textFieldShouldEndEditing(textField: UITextField) -> Bool { return otherDelegate?.textFieldShouldEndEditing?(textField) ?? true } public func textFieldDidEndEditing(textField: UITextField) { otherDelegate?.textFieldDidEndEditing?(textField) } public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { return otherDelegate?.textField?(textField, shouldChangeCharactersInRange: range, replacementString: string) ?? true } public func textFieldShouldClear(textField: UITextField) -> Bool { return otherDelegate?.textFieldShouldClear?(textField) ?? true } public func textFieldShouldReturn(textField: UITextField) -> Bool { return otherDelegate?.textFieldShouldReturn?(textField) ?? true } //MARK: - picker delegate public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } public func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return self.pickerDataSource.count + 1 } public func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { self.text = row == 0 ? "" : self.pickerDataSource[row - 1] } public func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return row > 0 ? self.pickerDataSource[row - 1] : "" } } extension String { var localizedString: String { return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "") } }
mit
6c847bdb99df412396f60f1909390370
36.945122
151
0.658631
5.405734
false
false
false
false
hooman/swift
test/AutoDiff/compiler_crashers_fixed/sr13933-vjpcloner-apply-multiple-consuming-users.swift
1
1732
// RUN: %target-build-swift %s -Xfrontend -requirement-machine=off // SR-13933: Fix "multiple consuming users" ownership error caused by // `VJPCloner::visitApply` related to `@differentiable`-function-typed callees. import _Differentiation protocol P: Differentiable { associatedtype Assoc: Differentiable } struct S<T: P> { var fn: @differentiable(reverse) (T.Assoc, T.Assoc) -> Float func method(y: T.Assoc) { _ = gradient(at: y) { y in return self.fn(y, y) } } } // Original error: // Begin Error in Function: 'AD__$s4main1SV6method1yy5AssocQz_tFSfAGcfU___vjp_src_0_wrt_0_4main1PRzl' // Found over consume?! // Value: %5 = copy_value %4 : $@differentiable(reverse) @callee_guaranteed @substituted <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_1) -> Float for <τ_0_0.Assoc, τ_0_0.Assoc> // users: %19, %6 // User: %6 = convert_function %5 : $@differentiable(reverse) @callee_guaranteed @substituted <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_1) -> Float for <τ_0_0.Assoc, τ_0_0.Assoc> to $@differentiable(reverse) @callee_guaranteed (@in_guaranteed τ_0_0.Assoc, @in_guaranteed τ_0_0.Assoc) -> Float // user: %7 // Block: bb0 // Consuming Users: // destroy_value %5 : $@differentiable(reverse) @callee_guaranteed @substituted <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_1) -> Float for <τ_0_0.Assoc, τ_0_0.Assoc> // id: %19 // %6 = convert_function %5 : $@differentiable(reverse) @callee_guaranteed @substituted <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_1) -> Float for <τ_0_0.Assoc, τ_0_0.Assoc> to $@differentiable(reverse) @callee_guaranteed (@in_guaranteed τ_0_0.Assoc, @in_guaranteed τ_0_0.Assoc) -> Float // user: %7
apache-2.0
3741756e9f560c0a9f75a161e3b46493
59.857143
321
0.680164
2.788871
false
false
false
false
higepon/Spark-Core-Examples
9.Temperature/Temperature/Temperature/ViewController.swift
2
1763
// // ViewController.swift // Temperature // // Created by Taro Minowa on 9/14/14. // Copyright (c) 2014 Higepon Taro Minowa. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var reloadButton: UIButton! @IBOutlet weak var temperatureLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // initial load reloadTemperature() } // when the reload button tapped @IBAction func reloadDidTap(sender: AnyObject) { reloadTemperature() } // call the API, parse the response and show result private func reloadTemperature() { let url = NSURL(string: "https://api.spark.io/v1/devices/53ff73065075535150531587/temperature?access_token=2154fc343dd4420ac61efbe55c625cf063706cb2") let request = NSURLRequest(URL: url) temperatureLabel.text = "Loading..." // call the API NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in if error != nil { println("Request Error \(error.localizedDescription)") return; } var err: NSError? // parse the API response var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary if err != nil { println("JSON Error \(err!.localizedDescription)") } println(jsonResult) if let temperature = jsonResult["result"] as? Float { // Show the result self.temperatureLabel.text = String(format: "%.2f°C", temperature) } } } }
mit
85b4b0d0d1abbb68527794240bbf52c3
32.245283
157
0.625426
4.68617
false
false
false
false
juheon0615/HandongSwift2
HandongAppSwift/StoreModel.swift
3
615
// // DeliveryFoodItemModel.swift // HandongAppSwift // // Created by csee on 2015. 2. 10.. // Copyright (c) 2015년 GHOST. All rights reserved. // import Foundation class StoreModel { var id: String var name: String var phone: String var runTime: String var category: String init(id: String, name: String, phone: String?, runTime: String?, category: String?) { self.id = id self.name = name self.phone = (phone != nil ? phone! : "") self.runTime = (runTime != nil ? runTime! : "") self.category = (category != nil ? category! : "") } }
mit
d7b75da423a48ffce866b81c0d85b4c5
23.56
89
0.59217
3.584795
false
false
false
false