repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
weareyipyip/SwiftStylable | Sources/SwiftStylable/Classes/Style/StylableComponents/STTextField.swift | 1 | 5671 | //
// STTextField.swift
// Pods
//
// Created by Marcel Bloemendaal on 24/08/16.
//
//
import UIKit
@IBDesignable open class STTextField : UITextField, UITextFieldDelegate, Stylable, BackgroundAndBorderStylable, TextBorderStylable, ForegroundStylable, TextStylable, PlaceholderStylable {
private var _stComponentHelper: STComponentHelper!
private var _styledText:String?
private var _placeholder:String?
private var _styledPlaceholder:String?
private var _delegate:UITextFieldDelegate?
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Initializers & deinit
//
// -----------------------------------------------------------------------------------------------------------------------
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self._placeholder = super.placeholder
self.setUpSTComponentHelper()
}
override public init(frame: CGRect) {
super.init(frame: frame)
self._placeholder = super.placeholder
self.setUpSTComponentHelper()
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Computed properties
//
// -----------------------------------------------------------------------------------------------------------------------
@IBInspectable open var styleName:String? {
set {
self._stComponentHelper.styleName = newValue
}
get {
return self._stComponentHelper.styleName
}
}
@IBInspectable open var substyleName:String? {
set {
self._stComponentHelper.substyleName = newValue
}
get {
return self._stComponentHelper.substyleName
}
}
open override var attributedText: NSAttributedString? {
didSet {
self._styledText = nil
}
}
var styledTextAttributes:[NSAttributedString.Key:Any]? {
didSet {
if self._styledText != nil {
self.styledText = self._styledText
}
}
}
@IBInspectable open var styledText:String? {
set {
self._styledText = newValue
if let text = newValue {
super.attributedText = NSAttributedString(string: text, attributes: self.styledTextAttributes ?? [NSAttributedString.Key:Any]())
}
}
get {
return self._styledText
}
}
open var foregroundColor: UIColor? {
set {
self.textColor = newValue ?? UIColor.black
}
get {
return self.textColor
}
}
open var textFont:UIFont? {
set {
if let font = newValue {
self.font = font
}
}
get {
return self.font
}
}
open var fullUppercaseText = false {
didSet {
if self.fullUppercaseText {
print("WARNING: fullUppercaseText is not supported by STTextView and STTextField!")
}
}
}
open override var placeholder: String? {
set {
self._placeholder = newValue
super.placeholder = self.fullUppercasePlaceholder ? newValue?.uppercased() : newValue
self._styledPlaceholder = nil
}
get {
return self._placeholder
}
}
open override var attributedPlaceholder: NSAttributedString? {
didSet {
self._styledPlaceholder = nil
}
}
var styledPlaceholderAttributes:[NSAttributedString.Key:Any]? {
didSet {
if self._styledPlaceholder != nil {
self.styledPlaceholder = self._styledPlaceholder
}
}
}
@IBInspectable open var styledPlaceholder:String? {
set {
self._styledPlaceholder = newValue
self._placeholder = newValue
if let placeholder = newValue {
let casedPlaceholder = self.fullUppercasePlaceholder ? placeholder.uppercased() : placeholder
super.attributedPlaceholder = NSAttributedString(string: casedPlaceholder, attributes: self.styledPlaceholderAttributes ?? [NSAttributedString.Key:Any]())
}
}
get {
return self._styledPlaceholder
}
}
open var fullUppercasePlaceholder:Bool = false {
didSet {
self.placeholder = self._placeholder
}
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Public methods
//
// -----------------------------------------------------------------------------------------------------------------------
open func applyStyle(_ style:Style) {
self._stComponentHelper.applyStyle(style)
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Private methods
//
// -----------------------------------------------------------------------------------------------------------------------
private func setUpSTComponentHelper() {
self._stComponentHelper = STComponentHelper(stylable: self, stylePropertySets: [
BackgroundAndBorderStyler(self),
TextBorderStyler(self),
ForegroundStyler(self),
TextStyler(self),
PlaceholderTextStyler(self)
])
}
}
| mit | 64d59c2c46e08cb0bd3cc8d800ebab66 | 29.005291 | 188 | 0.475048 | 6.150759 | false | false | false | false |
kdawgwilk/vapor | Sources/Vapor/Utilities/Byte/Data.swift | 1 | 2437 | extension Data {
func split(separator: Data, excludingFirst: Bool = false, excludingLast: Bool = false, maxSplits: Int? = nil) -> [Data] {
// "\r\n\r\n\r\n".split(separator: "\r\n\r\n") would break without this because it occurs twice in the same place
var parts = [Data]()
let array = self.enumerated().filter { (index, element) in
// If this first element matches and there are enough bytes left
let leftMatch = element == separator.first
let rightIndex = index + separator.count - 1
// Take the last byte of where the end of the separator would be and check it
let rightMatch: Bool
if rightIndex < self.bytes.count {
rightMatch = self[rightIndex] == separator.bytes.last
} else {
rightMatch = false
}
if leftMatch && rightMatch {
// Check if this range matches (put separately for efficiency)
return Data(self[index..<(index+separator.count)]) == separator
} else {
return false
}
}
let separatorLength = separator.count
var ranges = array.map { (index, element) -> (from: Int, to: Int) in
return (index, index + separatorLength)
}
if let max = maxSplits {
if ranges.count > max {
ranges = ranges.prefix(upTo: max).array
}
}
// The first data (before the first separator)
if let firstRange = ranges.first where !excludingFirst {
parts.append(Data(self[0..<firstRange.from]))
}
// Loop over the ranges
for (pos, range) in ranges.enumerated() {
// If this is before the last separator
if pos < ranges.count - 1 {
// Take the data inbetween this and the next boundry
let nextRange = ranges[pos + 1]
parts.append(Data(self[range.to..<nextRange.from]))
// If this is after the last separator and shouldn't be thrown away
} else if ranges[ranges.count - 1].to < self.count && !excludingLast {
parts.append(Data(self[range.to..<self.count]))
}
}
return parts
}
}
func +=(lhs: inout Data, rhs: Data) {
lhs.bytes += rhs.bytes
}
func +=(lhs: inout Data, rhs: Byte) {
lhs.bytes.append(rhs)
}
| mit | 239dcfde37f29ada0594921d7c38182e | 36.492308 | 125 | 0.552729 | 4.47156 | false | false | false | false |
contentful/blog-app-ios | Code/BlogPostList.swift | 1 | 5443 | //
// BlogPostList.swift
// Blog
//
// Created by Boris Bügling on 22/01/15.
// Copyright (c) 2015 Contentful GmbH. All rights reserved.
//
import UIKit
class BlogPostListCell : UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style:.Subtitle, reuseIdentifier: reuseIdentifier)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
textLabel?.frame.origin.y = 0.0
textLabel?.frame.size.height = 55.0
detailTextLabel?.frame.origin.y = (textLabel?.frame.maxY)!
}
}
class BlogPostList: UITableViewController {
var dataManager: ContentfulDataManager?
var dataSource: CoreDataFetchDataSource?
var metadataViewController: PostListMetadataViewController!
var predicate: String?
var showsAuthor: Bool = true
func refresh() {
dataManager?.performSynchronization({ (error) -> Void in
if error != nil && error.code != NSURLErrorNotConnectedToInternet {
let alert = UIAlertView(title: NSLocalizedString("Error", comment: ""), message: error.localizedDescription, delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: ""))
alert.show()
}
self.dataSource?.performFetch()
})
}
func showMetadataHeader() {
tableView.contentInset = UIEdgeInsets(top: 20.0, left: 0.0, bottom: 0.0, right: 0.0)
metadataViewController = storyboard?.instantiateViewControllerWithIdentifier(ViewControllerStoryboardIdentifier.AuthorViewControllerId.rawValue) as! PostListMetadataViewController
metadataViewController.client = dataManager?.client
metadataViewController.view.autoresizingMask = .None
metadataViewController.view.frame.size.height = 160.0
tableView.tableHeaderView = metadataViewController.view
}
override func viewDidLoad() {
super.viewDidLoad()
addInfoButton()
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
dataManager = ContentfulDataManager()
let controller = dataManager?.fetchedResultsControllerForContentType(ContentfulDataManager.PostContentTypeId, predicate: predicate, sortDescriptors: [NSSortDescriptor(key: "date", ascending: true)])
let tableView = self.tableView!
dataSource = CoreDataFetchDataSource(fetchedResultsController: controller, tableView: tableView, cellIdentifier: NSStringFromClass(BlogPostList.self))
dataSource?.cellConfigurator = { (cell, indexPath) -> Void in
if let tcell = cell as? UITableViewCell {
tcell.accessoryType = .DisclosureIndicator
tcell.detailTextLabel?.font = UIFont.bodyTextFont().fontWithSize(12.0)
tcell.detailTextLabel?.textColor = UIColor.contentfulDeactivatedColor()
tcell.selectionStyle = .None
tcell.textLabel?.font = UIFont.titleBarFont()
tcell.textLabel?.numberOfLines = 2
if tcell.respondsToSelector(Selector("setLayoutMargins:")) {
tcell.layoutMargins = UIEdgeInsetsZero
tcell.preservesSuperviewLayoutMargins = false
}
if let post = self.dataSource?.objectAtIndexPath(indexPath) as? Post {
tcell.textLabel?.text = post.title
if let date = post.date {
let authorString = post.author != nil ? NSLocalizedString("by ", comment: "") + ((post.author!.array as NSArray).valueForKey("name") as! NSArray).componentsJoinedByString(", ") : NSLocalizedString("Unknown", comment: "Unknown author")
let dateString = NSDateFormatter.customDateFormatter().stringFromDate(date)
tcell.detailTextLabel?.text = String(format:"%@. %@", dateString.uppercaseString, self.showsAuthor ? authorString : "")
}
}
}
}
tableView.dataSource = dataSource
tableView.rowHeight = 80.0
tableView.separatorInset = UIEdgeInsetsZero
tableView.registerClass(BlogPostListCell.self, forCellReuseIdentifier: NSStringFromClass(BlogPostList.self))
}
override func viewWillAppear(animated: Bool) {
refresh()
}
// MARK: UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let post = self.dataSource?.objectAtIndexPath(indexPath) as? Post {
let identifier = ViewControllerStoryboardIdentifier.BlogPostViewControllerId.rawValue
let blogPostViewController = storyboard?.instantiateViewControllerWithIdentifier(identifier) as? BlogPostViewController
blogPostViewController?.client = dataManager?.client
blogPostViewController?.post = post
navigationController?.pushViewController(blogPostViewController!, animated: true)
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if metadataViewController != nil {
metadataViewController.numberOfPosts = tableView.numberOfRowsInSection(0)
}
}
}
| mit | cf35584c0af68a05418d6dd67ed8c2fc | 42.190476 | 258 | 0.677876 | 5.570113 | false | false | false | false |
SwiftyMagic/Magic | Magic/Magic/UIKit/UILabelExtension.swift | 1 | 1869 | //
// UILabelExtension.swift
// Magic
//
// Created by Broccoli on 2016/9/22.
// Copyright © 2016年 broccoliii. All rights reserved.
//
import Foundation
// MARK: - Properties
public extension UILabel {
var estimatedSize: CGSize {
return sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
}
var estimatedHeight: CGFloat {
return sizeThatFits(CGSize(width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude)).height
}
var estimatedWidth: CGFloat {
return sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: self.frame.size.height)).width
}
}
// MARK: - Methods
public extension UILabel {
var contentSize: CGSize {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = lineBreakMode
paragraphStyle.alignment = textAlignment
let attributes = [NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle] as [String : Any]
let contentSize = text!.boundingRect(
with: frame.size,
options: ([.usesLineFragmentOrigin, .usesFontLeading]),
attributes: attributes,
context: nil
).size
return contentSize
}
func vertical() {
assert(self.text == nil, "Invalid label text.")
let textAttributes: [String : AnyObject] = [NSFontAttributeName: self.font]
let labelSize = self.text?.boundingRect(with: CGSize(width: font.pointSize, height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: textAttributes, context: nil)
attributedText = NSAttributedString(string: text!, attributes: textAttributes)
lineBreakMode = .byCharWrapping
numberOfLines = 0
self.frame = labelSize!
}
}
| mit | f8541f7e17f1599794913b784c067cc4 | 34.207547 | 194 | 0.678992 | 5.226891 | false | true | false | false |
Jintin/Swimat | Swimat/SwimatViewController.swift | 1 | 3899 | import Cocoa
class SwimatViewController: NSViewController {
let installPath = "/usr/local/bin/"
@IBOutlet weak var swimatTabView: NSTabView!
@IBOutlet weak var versionLabel: NSTextField! {
didSet {
guard let infoDictionary = Bundle.main.infoDictionary,
let version = infoDictionary["CFBundleShortVersionString"],
let build = infoDictionary[kCFBundleVersionKey as String] else {
return
}
versionLabel.stringValue = "Version \(version) (\(build))"
}
}
@IBOutlet weak var installationLabel: NSTextField! {
didSet {
guard let url = Bundle.main.url(forResource: "Installation", withExtension: "html"),
let string = try? NSMutableAttributedString(url: url, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else {
return
}
string.addAttributes([.foregroundColor: NSColor.textColor], range: NSRange(location: 0, length: string.length))
installationLabel.attributedStringValue = string
}
}
@IBOutlet weak var installButton: NSButton! {
didSet {
refreshInstallButton()
}
}
@IBOutlet weak var parameterAlignmentCheckbox: NSButton! {
didSet {
parameterAlignmentCheckbox.state = Preferences.areParametersAligned ? .on : .off
}
}
@IBOutlet weak var removeSemicolonsCheckbox: NSButton! {
didSet {
removeSemicolonsCheckbox.state = Preferences.areSemicolonsRemoved ? .on : .off
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
override func viewDidAppear() {
guard let window = view.window else {
return
}
window.titleVisibility = .hidden
window.titlebarAppearsTransparent = true
}
@IBAction func install(_ sender: Any) {
// Migrate this to SMJobBless?
let path = Bundle.main.bundleURL
.appendingPathComponent("Contents", isDirectory: true)
.appendingPathComponent("Helpers", isDirectory: true)
.appendingPathComponent("swimat")
.path
var error: NSDictionary?
let script = NSAppleScript(source: "do shell script \"ln -s \'\(path)\' \(installPath)swimat\" with administrator privileges")
script?.executeAndReturnError(&error)
if error != nil {
let alert = NSAlert()
alert.messageText = "There was an error symlinking swimat."
alert.informativeText = "You can try manually linking swimat by running:\n\nln -s /Applications/Swimat.app/Contents/Helpers/swimat \(installPath)swimat"
alert.alertStyle = .warning
alert.runModal()
}
refreshInstallButton()
}
@IBAction func updateParameterAlignment(_ sender: NSButton) {
Preferences.areParametersAligned = sender.state == .on
preferencesChanged()
}
@IBAction func updateRemoveSemicolons(_ sender: NSButton) {
Preferences.areSemicolonsRemoved = sender.state == .on
preferencesChanged()
}
func preferencesChanged() {
let notification = Notification(name: Notification.Name("SwimatPreferencesChangedNotification"))
NotificationCenter.default.post(notification)
}
func refreshInstallButton() {
// Check for swimat, fileExists(atPath:) returns false for symlinks
if (try? FileManager.default.attributesOfItem(atPath: "\(installPath)swimat")) != nil {
installButton.title = "swimat installed to \(installPath)"
installButton.isEnabled = false
} else {
installButton.title = "Install swimat to \(installPath)"
installButton.isEnabled = true
}
}
}
| mit | acfe326199e7ab4809273644ad9fffca | 36.133333 | 165 | 0.629649 | 5.304762 | false | false | false | false |
cloudinary/cloudinary_ios | Cloudinary/Classes/Core/Features/Helpers/CLDExpression.swift | 1 | 14043 | //
// CLDExpression.swift
//
// Copyright (c) 2016 Cloudinary (http://cloudinary.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
@objcMembers open class CLDExpression: NSObject {
internal enum ExpressionKeys : String, CaseIterable {
case width
case height
case initial_width
case initialWidth
case initial_height
case initialHeight
case initial_aspect_ratio
case aspect_ratio
case aspectRatio
case initialAspectRatio
case page_count
case pageCount
case face_count
case faceCount
case illustration_score
case illustrationScore
case current_page
case currentPage
case tags
case pageX
case pageY
case duration
case initial_duration
case initialDuration
var asString: String {
switch self {
case .width : return "w"
case .height: return "h"
case .initial_width : return "iw"
case .initialWidth : return "iw"
case .initial_height: return "ih"
case .initialHeight : return "ih"
case .initial_aspect_ratio: return "iar"
case .aspect_ratio : return "ar"
case .aspectRatio : return "ar"
case .initialAspectRatio : return "iar"
case .page_count: return "pc"
case .pageCount : return "pc"
case .face_count: return "fc"
case .faceCount : return "fc"
case .illustration_score: return "ils"
case .illustrationScore : return "ils"
case .current_page: return "cp"
case .currentPage : return "cp"
case .tags: return "tags"
case .pageX: return "px"
case .pageY: return "py"
case .duration: return "du"
case .initial_duration: return "idu"
case .initialDuration : return "idu"
}
}
}
internal var currentValue : String
internal var currentKey : String
private var allSpaceAndOrDash : Bool = false
private let consecutiveDashesRegex : String = "[ _]+"
private let userVariableRegex : String = "\\$_*[^_]+"
// MARK: - Init
public override init() {
self.currentKey = String()
self.currentValue = String()
super.init()
}
public init(value: String) {
var components = value.components(separatedBy: .whitespacesAndNewlines)
self.currentKey = components.removeFirst()
self.currentValue = components.joined(separator: CLDVariable.elementsSeparator)
let range = NSRange(location: 0, length: value.utf16.count)
let regex = try? NSRegularExpression(pattern: "^" + consecutiveDashesRegex)
self.allSpaceAndOrDash = !(regex?.firstMatch(in: value, options: [], range: range) == nil)
super.init()
}
fileprivate init(expressionKey: ExpressionKeys) {
self.currentKey = expressionKey.asString
self.currentValue = String()
super.init()
}
// MARK: - class func
public class func width() -> CLDExpression {
return CLDExpression(expressionKey: .width)
}
public class func height() -> CLDExpression {
return CLDExpression(expressionKey: .height)
}
public class func initialWidth() -> CLDExpression {
return CLDExpression(expressionKey: .initialWidth)
}
public class func initialHeight() -> CLDExpression {
return CLDExpression(expressionKey: .initialHeight)
}
public class func aspectRatio() -> CLDExpression {
return CLDExpression(expressionKey: .aspectRatio)
}
public class func initialAspectRatio() -> CLDExpression {
return CLDExpression(expressionKey: .initialAspectRatio)
}
public class func pageCount() -> CLDExpression {
return CLDExpression(expressionKey: .pageCount)
}
public class func faceCount() -> CLDExpression {
return CLDExpression(expressionKey: .faceCount)
}
public class func tags() -> CLDExpression {
return CLDExpression(expressionKey: .tags)
}
public class func pageXOffset() -> CLDExpression {
return CLDExpression(expressionKey: .pageX)
}
public class func pageYOffset() -> CLDExpression {
return CLDExpression(expressionKey: .pageY)
}
public class func illustrationScore() -> CLDExpression {
return CLDExpression(expressionKey: .illustrationScore)
}
public class func currentPageIndex() -> CLDExpression {
return CLDExpression(expressionKey: .currentPage)
}
public class func duration() -> CLDExpression {
return CLDExpression(expressionKey: .duration)
}
public class func initialDuration() -> CLDExpression {
return CLDExpression(expressionKey: .initialDuration)
}
// MARK: - Public methods
@objc(addByInt:)
@discardableResult
public func add(by number: Int) -> Self {
appendOperatorToCurrentValue(.add, inputValue: "\(number)")
return self
}
@objc(addByFloat:)
@discardableResult
public func add(by number: Float) -> Self {
appendOperatorToCurrentValue(.add, inputValue: number.cldFloatFormat())
return self
}
@objc(addByString:)
@discardableResult
public func add(by number: String) -> Self {
appendOperatorToCurrentValue(.add, inputValue: number)
return self
}
@objc(subtractByInt:)
@discardableResult
public func subtract(by number: Int) -> Self {
appendOperatorToCurrentValue(.subtract, inputValue: "\(number)")
return self
}
@objc(subtractByFloat:)
@discardableResult
public func subtract(by number: Float) -> Self {
appendOperatorToCurrentValue(.subtract, inputValue: number.cldFloatFormat())
return self
}
@objc(subtractByString:)
@discardableResult
public func subtract(by number: String) -> Self {
appendOperatorToCurrentValue(.subtract, inputValue: number)
return self
}
@objc(multipleByInt:)
@discardableResult
public func multiple(by number: Int) -> Self {
appendOperatorToCurrentValue(.multiple, inputValue: "\(number)")
return self
}
@objc(multipleByFloat:)
@discardableResult
public func multiple(by number: Float) -> Self {
appendOperatorToCurrentValue(.multiple, inputValue: number.cldFloatFormat())
return self
}
@objc(multipleByString:)
@discardableResult
public func multiple(by number: String) -> Self {
appendOperatorToCurrentValue(.multiple, inputValue: number)
return self
}
@objc(divideByInt:)
@discardableResult
public func divide(by number: Int) -> Self {
appendOperatorToCurrentValue(.divide, inputValue: "\(number)")
return self
}
@objc(divideByFloat:)
@discardableResult
public func divide(by number: Float) -> Self {
appendOperatorToCurrentValue(.divide, inputValue: number.cldFloatFormat())
return self
}
@objc(divideByString:)
@discardableResult
public func divide(by number: String) -> Self {
appendOperatorToCurrentValue(.divide, inputValue: number)
return self
}
@objc(powerByInt:)
@discardableResult
public func power(by number: Int) -> Self {
appendOperatorToCurrentValue(.power, inputValue: "\(number)")
return self
}
@objc(powerByFloat:)
@discardableResult
public func power(by number: Float) -> Self {
appendOperatorToCurrentValue(.power, inputValue: number.cldFloatFormat())
return self
}
@objc(powerByString:)
@discardableResult
public func power(by number: String) -> Self {
appendOperatorToCurrentValue(.power, inputValue: number)
return self
}
// MARK: - provide content
public func asString() -> String {
guard !currentKey.isEmpty else {
if allSpaceAndOrDash {
return "_"
}
return String()
}
let key = removeExtraDashes(from: replaceAllExpressionKeys(in: currentKey))
if currentValue.isEmpty {
return "\(key)"
}
let value = removeExtraDashes(from: replaceAllUnencodeChars(in: currentValue))
return "\(key)_\(value)"
}
public func asParams() -> [String : String] {
guard !currentKey.isEmpty && !currentValue.isEmpty else {
return [String : String]()
}
let key = replaceAllExpressionKeys(in: currentKey)
let value = removeExtraDashes(from: replaceAllUnencodeChars(in: currentValue))
return [key:value]
}
internal func asInternalString() -> String {
guard !currentValue.isEmpty else {
return "\(currentKey)"
}
return "\(currentKey) \(currentValue)"
}
// MARK: - Private methods
private func replaceAllUnencodeChars(in string: String) -> String {
var wipString = string
wipString = replaceAllOperators(in: string)
wipString = replaceAllExpressionKeys(in: wipString)
return wipString
}
private func replaceAllOperators(in string: String) -> String {
var wipString = string
CLDOperators.allCases.forEach {
wipString = replace(cldOperator: $0, in: wipString)
}
return wipString
}
private func replace(cldOperator: CLDOperators, in string: String) -> String {
return string.replacingOccurrences(of: cldOperator.rawValue, with: cldOperator.asString())
}
private func replaceAllExpressionKeys(in string: String) -> String {
var wipString = string
ExpressionKeys.allCases.forEach {
wipString = replace(expressionKey: $0, in: wipString)
}
return wipString
}
private func replace(expressionKey: ExpressionKeys, in string: String) -> String {
var result : String!
let string = removeExtraDashes(from: string)
if string.contains(CLDVariable.variableNamePrefix) {
let range = NSRange(location: 0, length: string.utf16.count)
let regex = try? NSRegularExpression(pattern: userVariableRegex)
let allRanges = regex?.matches(in: string, options: [], range: range).map({ $0.range }) ?? []
// Replace substring in between user variables. e.x $initial_aspect_ratio_$width, only '_aspect_ratio_' will be addressed.
for (index, range) in allRanges.enumerated() {
let location = range.length + range.location
var length = range.length
if index + 1 == allRanges.count {
length = string.count
} else {
let nextRange = allRanges[index + 1]
length = nextRange.location
}
if let stringRange = Range(NSRange(location: location, length: length - location), in: string) {
result = string.replacingOccurrences(of: expressionKey.rawValue, with: expressionKey.asString, options: .regularExpression, range: stringRange)
}
}
} else {
result = string.replacingOccurrences(of: expressionKey.rawValue, with: expressionKey.asString)
}
return result
}
internal func appendOperatorToCurrentValue(_ cldoperator: CLDOperators, inputValue: String = String()) {
appendOperatorToCurrentValue(cldoperator.asString(), inputValue: inputValue)
}
internal func appendOperatorToCurrentValue(_ cldoperator: String, inputValue: String = String()) {
var stringValue = String()
if !currentValue.isEmpty {
stringValue.append(CLDVariable.elementsSeparator)
}
stringValue.append(cldoperator)
if !inputValue.isEmpty {
stringValue.append(CLDVariable.elementsSeparator + inputValue)
}
currentValue.append(stringValue)
}
private func removeExtraDashes(from string: String) -> String {
return string.replacingOccurrences(of: consecutiveDashesRegex, with: CLDVariable.elementsSeparator, options: .regularExpression, range: nil)
}
}
| mit | cf6e959a56cb925da64d726f95008317 | 32.042353 | 163 | 0.610625 | 4.981554 | false | false | false | false |
yanif/circator | MetabolicCompass/Model/ProfileModel.swift | 1 | 5611 | //
// ProfileModel.swift
// MetabolicCompass
//
// Created by Anna Tkach on 5/11/16.
// Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved.
//
import UIKit
import MetabolicCompassKit
class ProfileModel: UserInfoModel {
override func modelItems() -> [ModelItem] {
var fields = [ModelItem]()
fields.append(self.loadPhotoField)
fields.append(self.firstNameField)
fields.append(self.lastNameField)
fields.append(self.emailField)
fields.append(self.genderField)
fields.append(self.ageField)
fields.append(self.unitsSystemField)
fields.append(self.weightField)
fields.append(self.heightField)
if self.units == .Imperial {
fields.append(self.heightInchesField)
}
return fields
}
func setupValues() {
let profileInfo = UserManager.sharedManager.getProfileCache()
let units: UnitsSystem! = UserManager.sharedManager.useMetricUnits() ? UnitsSystem.Metric : UnitsSystem.Imperial
for item in items {
if item.type == .Units {
item.setNewValue(units.rawValue)
}
else if item.type == .FirstName {
item.setNewValue(AccountManager.shared.userInfo?.firstName)
}
else if item.type == .LastName {
item.setNewValue(AccountManager.shared.userInfo?.lastName)
}
else if item.type == .Photo {
item.setNewValue(UserManager.sharedManager.userProfilePhoto())
}
else if item.type == .Email {
item.setNewValue(UserManager.sharedManager.getUserId())
} else {
if item.type == .HeightInches {
var cmHeightAsDouble = 0.0
if let heightInfo = profileInfo[heightField.name] as? String, heightAsDouble = Double(heightInfo) {
cmHeightAsDouble = heightAsDouble
}
else if let heightAsDouble = profileInfo[heightField.name] as? Double {
cmHeightAsDouble = heightAsDouble
}
else if let heightAsInt = profileInfo[heightField.name] as? Int {
cmHeightAsDouble = Double(heightAsInt)
}
let heightFtIn = UnitsUtils.heightValue(valueInDefaultSystem: Float(cmHeightAsDouble), withUnits: units)
item.setNewValue(Int(floor((heightFtIn % 1.0) * 12.0)))
}
else if let profileItemInfo = profileInfo[item.name]{
if item.type == .Gender {
let gender = Gender.valueByTitle(profileItemInfo as! String)
item.setNewValue(gender.rawValue)
}
else if item.type == .Weight {
item.setNewValue(profileItemInfo)
if let value = item.floatValue() {
// Convert from kg to lb as needed
item.setNewValue(UnitsUtils.weightValue(valueInDefaultSystem: value, withUnits: units))
}
}
else if item.type == .Height {
item.setNewValue(profileItemInfo)
if let value = item.floatValue() {
// Convert from cm to ft/in as needed
var convertedValue = UnitsUtils.heightValue(valueInDefaultSystem: value, withUnits: units)
if units == .Imperial { convertedValue = floor(convertedValue) }
item.setNewValue(convertedValue)
}
}
else if item.type == .Weight || item.type == .Height {
item.setNewValue(profileItemInfo)
if let value = item.floatValue() {
if item.type == .Weight {
// Convert from kg to lb as needed
item.setNewValue(UnitsUtils.weightValue(valueInDefaultSystem: value, withUnits: units))
} else {
// Convert from cm to ft/in as needed
item.setNewValue(UnitsUtils.heightValue(valueInDefaultSystem: value, withUnits: units))
}
}
}
else {
item.setNewValue(profileItemInfo)
}
} else {
log.warning("Could not find profile field for \(item.name)")
}
}
}
}
private let uneditableFields:[UserInfoFieldType] = [.Email, .FirstName, .LastName]
func isItemEditable(item: ModelItem) -> Bool {
return !uneditableFields.contains(item.type)
}
override func profileItems() -> [String : String] {
var newItems : [ModelItem] = [ModelItem]()
for item in items {
if isItemEditable(item) {
newItems.append(item)
}
}
return profileItems(newItems)
}
override func isModelValid() -> Bool {
resetValidationResults()
return isPhotoValid() && /* isEmailValid() && isPasswordValid() && isFirstNameValid() && isLastNameValid() && */ isAgeValid()
&& isWeightValid() && isHeightValid() && (self.units == .Metric ? true : isHeightInchesValid())
}
}
| apache-2.0 | 9a2afe926b1c2c73758b30d453e9dcc7 | 40.555556 | 133 | 0.523886 | 5.137363 | false | false | false | false |
barteljan/VISPER | VISPER-Wireframe/Classes/Wireframe/DefaultRouteResultHandler.swift | 1 | 6848 | //
// DefaultRouteResultHandler.swift
// VISPER-Wireframe
//
// Created by bartel on 25.12.17.
//
import Foundation
import VISPER_Core
import VISPER_Presenter
import VISPER_Objc
open class DefaultRouteResultHandler: RouteResultHandler {
public init(){}
open func handleRouteResult(routeResult: RouteResult,
optionProvider: RoutingOptionProvider,
routingHandlerContainer: RoutingHandlerContainer,
controllerProvider: ComposedControllerProvider,
presenterProvider: PresenterProvider,
routingDelegate: RoutingDelegate,
routingObserver: RoutingObserver,
routingPresenter: RoutingPresenter,
wireframe: Wireframe,
completion: @escaping () -> Void) throws {
var modifiedRouteResult = routeResult
var routingDelegate = routingDelegate
//check if someone wants to modify your routing option
let modifiedRoutingOption : RoutingOption? = optionProvider.option(routeResult: modifiedRouteResult)
modifiedRouteResult.routingOption = modifiedRoutingOption
//check if there is a routing handler responsible for this RouteResult/RoutingOption combination
let handlerPriority = routingHandlerContainer.priorityOfHighestResponsibleProvider(routeResult: modifiedRouteResult)
//check if there is a controller provider responsible for this RouteResult/RoutingOption combination
let controllerPriority = controllerProvider.priorityOfHighestResponsibleProvider(routeResult: modifiedRouteResult)
//call handler and terminate if its priority is higher than the controllers provider
if controllerPriority != nil && handlerPriority != nil {
if handlerPriority! >= controllerPriority! {
try self.callHandler(routeResult: modifiedRouteResult,
container: routingHandlerContainer,
completion: completion)
return
}
} else if controllerPriority == nil && handlerPriority != nil {
try self.callHandler(routeResult: modifiedRouteResult,
container: routingHandlerContainer,
completion: completion)
return
}
//proceed with controller presentation if no handler with higher priority was found
//check if a controller could be provided by the composedControllerProvider
guard controllerProvider.isResponsible(routeResult: modifiedRouteResult) else {
throw DefaultWireframeError.canNotHandleRoute(routeResult: modifiedRouteResult)
}
let controller = try controllerProvider.makeController(routeResult: modifiedRouteResult)
//get all presenters responsible for this route pattern / controller combination
for presenter in try presenterProvider.makePresenters(routeResult: modifiedRouteResult, controller: controller) {
if presenter.isResponsible(routeResult:modifiedRouteResult, controller: controller) {
try presenter.addPresentationLogic(routeResult: modifiedRouteResult, controller: controller)
controller.retainPresenter(PresenterObjc(presenter: presenter))
}
}
routingDelegate.routingObserver = routingObserver
//check if we have a presenter responsible for this option
guard routingPresenter.isResponsible(routeResult: modifiedRouteResult) else {
throw DefaultWireframeError.noRoutingPresenterFoundFor(result: modifiedRouteResult)
}
try self.runOnMainThread {
//present view controller
try routingPresenter.present(controller: controller,
routeResult: modifiedRouteResult,
wireframe: wireframe,
delegate: routingDelegate,
completion: completion)
}
}
func runOnMainThread(_ completion: @escaping () throws -> Void ) throws {
if Thread.isMainThread {
try completion()
} else {
try DispatchQueue.main.sync { () -> Void in
try completion()
}
}
}
func callHandler(routeResult: RouteResult,
container: RoutingHandlerContainer,
completion: @escaping () -> Void) throws{
if let handler = container.handler(routeResult: routeResult) {
handler(routeResult)
completion()
return
}
throw DefaultWireframeError.canNotHandleRoute(routeResult: routeResult)
}
open func controller(routeResult: RouteResult,
controllerProvider: ControllerProvider,
presenterProvider: PresenterProvider,
routingDelegate: RoutingDelegate,
routingObserver: RoutingObserver,
wireframe: Wireframe) throws -> UIViewController? {
if controllerProvider.isResponsible(routeResult: routeResult) {
let controller = try controllerProvider.makeController(routeResult: routeResult)
//get all presenters responsible for this route pattern / controller combination
for presenter in try presenterProvider.makePresenters(routeResult: routeResult, controller: controller) {
try presenter.addPresentationLogic(routeResult: routeResult, controller: controller)
controller.retainPresenter(PresenterObjc(presenter: presenter))
}
var routingDelegate = routingDelegate
routingDelegate.routingObserver = routingObserver
try routingDelegate.willPresent(controller: controller,
routeResult: routeResult,
routingPresenter: nil,
wireframe: wireframe)
routingDelegate.didPresent(controller: controller,
routeResult: routeResult,
routingPresenter: nil,
wireframe: wireframe)
return controller
}
return nil
}
}
| mit | 590580fce5022e417b009b643914cf6c | 43.75817 | 124 | 0.590099 | 6.848 | false | false | false | false |
fortmarek/AnnotationETA | AnnotationETA/Classes/EtaAnnotationView.swift | 1 | 2749 | //
// AnnotationETAView.swift
// Pods
//
// Created by Marek Fořt on 2/2/17.
//
//
import Foundation
import MapKit
open class EtaAnnotationView: MKAnnotationView {
open var pinColor = UIColor(red: 1.00, green: 0.50, blue: 0.00, alpha: 1.0)
open var pinSecondaryColor = UIColor.white
open var rightButton: UIButton?
public override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
self.annotation = annotation
self.canShowCallout = true
self.frame = CGRect(origin: self.frame.origin, size: CGSize(width: 29, height: 43))
//Bottom part of the pin is on the location, not the center, offset needed
self.centerOffset = CGPoint(x: 0, y: -(self.frame.height)/2)
self.backgroundColor = UIColor.clear
}
open override var leftCalloutAccessoryView: UIView? {
didSet {
leftCalloutAccessoryView?.backgroundColor = pinColor
}
}
override open func draw(_ rect: CGRect) {
//Orange Circle
var bigCircleRect = rect
bigCircleRect.size.height = rect.size.width
let path = UIBezierPath(ovalIn: bigCircleRect)
pinColor.setFill()
path.fill()
//Bottom part of the pin with arc
let bottomPath = UIBezierPath()
bottomPath.move(to: CGPoint(x: 0, y: bigCircleRect.size.height/2 + 2.5))
bottomPath.addLine(to: CGPoint(x: self.frame.width, y: bigCircleRect.size.height/2 + 2.5))
bottomPath.addArc(withCenter: CGPoint(x: self.frame.width/2, y: self.frame.height - 2), radius: 2, startAngle: CGFloat(0), endAngle: CGFloat(M_PI), clockwise: true)
bottomPath.addLine(to: CGPoint(x: 0, y: bigCircleRect.size.height/2 + 2.5))
bottomPath.close()
pinColor.setFill()
bottomPath.fill()
//small white circle in the center
let smallSize = bigCircleRect.size.width * 0.5
let smallCircleRect = CGRect(x: (bigCircleRect.size.width - smallSize)/2, y: (bigCircleRect.size.width - smallSize)/2, width: smallSize, height: smallSize)
let smallPath = UIBezierPath(ovalIn: smallCircleRect)
pinSecondaryColor.setFill()
smallPath.fill()
}
public func setDetailShowButton() {
//Detailed toilet info button
rightButton = UIButton.init(type: .detailDisclosure)
rightButton?.tintColor = pinColor
rightCalloutAccessoryView = rightButton
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | e9dc1b6bfcb7d68233d1513616ded2b1 | 32.108434 | 172 | 0.632824 | 4.20827 | false | false | false | false |
J1aDong/GoodBooks | GoodBooks/photoPickerViewController.swift | 1 | 3600 | //
// photoPickerViewController.swift
// GoodBooks
//
// Created by J1aDong on 2017/1/26.
// Copyright © 2017年 J1aDong. All rights reserved.
//
import UIKit
protocol PhotoPickerDelegate {
func getImageFromPicker(image:UIImage)
}
class photoPickerViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var alert:UIAlertController?
var picker:UIImagePickerController?
var delegate:PhotoPickerDelegate?
init() {
super.init(nibName: nil, bundle: nil)
self.modalPresentationStyle = .overFullScreen
self.view.backgroundColor = UIColor.clear
self.picker = UIImagePickerController()
// 禁止编辑
self.picker?.allowsEditing = false
self.picker?.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
if(self.alert == nil){
self.alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
self.alert?.addAction(UIAlertAction(title: "从相册选择", style: .default, handler: { (action) in
self.localPhoto()
}))
self.alert?.addAction(UIAlertAction(title: "打开相机", style: .default, handler: { (action) in
self.takePhoto()
}))
self.alert?.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
self.dismiss(animated: true, completion: {
})
}))
self.present(self.alert!, animated: true, completion: {
})
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK:- 打开相机
private func takePhoto() {
if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
self.picker?.sourceType = .camera
self.present(self.picker!, animated: true, completion: {
})
}else{
let alertView = UIAlertController(title: "此机型无相机", message: nil, preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: "关闭", style: .cancel, handler: { (action) in
self.dismiss(animated: true, completion: {
})
}))
self.present(alertView, animated: true, completion: {
})
}
}
//MARK:- 打开相册
func localPhoto() {
self.picker?.sourceType = .photoLibrary
self.present(self.picker!, animated: true) {
}
}
//MARK:- 取消照片
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.picker?.dismiss(animated: true, completion: {
self.dismiss(animated: true, completion: {
})
})
}
//MARK:- 确定照片
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
self.picker?.dismiss(animated: true, completion: {
self.dismiss(animated: true, completion: {
self.delegate?.getImageFromPicker(image: image)
})
})
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 6358b4da627326802c1853ef17bc172a | 29.868421 | 119 | 0.574311 | 5.04878 | false | false | false | false |
NUKisZ/MyTools | MyTools/MyTools/Tools/CustomView.swift | 1 | 2709 | //
// ButtonAddBadge.swift
// MengWuShe
//
// Created by zhangk on 16/10/26.
// Copyright © 2016年 zhangk. All rights reserved.
//
import UIKit
class ButtonBadge: UIView {
//有提示的Button
var badge:Int = 0{
didSet{
if badge > 0 {
for subView in subviews{
if subView.tag == 100{
subView.removeFromSuperview()
}
}
let label = ZKTools.createLabel(CGRect(x: frame.size.width-15, y: 0, width:15, height: 15), title: "\(badge)", textAlignment: NSTextAlignment.center, font: UIFont.systemFont(ofSize: 8), textColor: UIColor.red)
label.layer.cornerRadius = label.frame.size.width/2
label.layer.masksToBounds = true
label.backgroundColor = UIColor.red
label.textColor = UIColor.white
label.tag = 100
addSubview(label)
}else{
for subView in subviews{
if subView.tag == 100{
subView.removeFromSuperview()
}
}
}
}
}
init(frame: CGRect,title:String?,imageName:String?,bgImageName:String?,target:AnyObject?,action:Selector?) {
super.init(frame: frame)
let btn = ZKTools.createButton(CGRect(x: frame.origin.x, y: frame.origin.y+5, width: frame.size.width-5, height: frame.size.height-5), title: title, imageName: imageName, bgImageName: bgImageName, target: target, action: action)
addSubview(btn)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class OtherLoginView:UIControl{
//其他登录方式的按钮
init(frame: CGRect,imageName:String,title:String) {
super.init(frame: frame)
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height*0.8))
let path = Bundle.main.path(forResource: imageName, ofType: "png")
let image1 = UIImage(contentsOfFile: path!)
imageView.image = image1
addSubview(imageView)
let label = ZKTools.createLabel(CGRect(x: 0, y: frame.size.height*0.8, width: frame.size.width, height: frame.size.height*0.2), title: title, textAlignment: NSTextAlignment.center, font: UIFont.systemFont(ofSize: 10), textColor: UIColor.black)
addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | f3be6b2334b939f9b97b0862500a5a24 | 32.5 | 251 | 0.570522 | 4.357724 | false | false | false | false |
avtr/bluejay | Bluejay/Bluejay/Peripheral.swift | 1 | 18612 | //
// Peripheral.swift
// Bluejay
//
// Created by Jeremy Chiang on 2017-01-03.
// Copyright © 2017 Steamclock Software. All rights reserved.
//
import Foundation
import CoreBluetooth
/**
An interface to the Bluetooth peripheral.
*/
public class Peripheral: NSObject {
// MARK: Properties
private(set) weak var bluejay: Bluejay?
private(set) var cbPeripheral: CBPeripheral
fileprivate var listeners: [CharacteristicIdentifier : (ReadResult<Data?>) -> Void] = [:]
fileprivate var listenersBeingCancelled: [CharacteristicIdentifier] = []
fileprivate var observers: [WeakRSSIObserver] = []
// MARK: - Initialization
init(bluejay: Bluejay, cbPeripheral: CBPeripheral) {
self.bluejay = bluejay
self.cbPeripheral = cbPeripheral
super.init()
self.cbPeripheral.delegate = self
}
deinit {
log("Deinit peripheral: \(String(describing: cbPeripheral.name ?? cbPeripheral.identifier.uuidString))")
}
// MARK: - Attributes
/// The UUID of the peripheral.
public var uuid: PeripheralIdentifier {
return PeripheralIdentifier(uuid: cbPeripheral.identifier)
}
/// The name of the peripheral.
public var name: String? {
return cbPeripheral.name
}
// MARK: - Operations
private func updateOperations() {
guard let bluejay = bluejay else {
preconditionFailure("Cannot update operation: Bluejay is nil.")
}
if cbPeripheral.state == .disconnected {
bluejay.queue.cancelAll(BluejayError.notConnected)
return
}
bluejay.queue.update()
}
private func addOperation(_ operation: Operation) {
guard let bluejay = bluejay else {
preconditionFailure("Cannot add operation: Bluejay is nil.")
}
bluejay.queue.add(operation)
}
/// Queue the necessary operations needed to discover the specified characteristic.
private func discoverCharactersitic(_ characteristicIdentifier: CharacteristicIdentifier, callback: @escaping (Bool) -> Void) {
addOperation(DiscoverService(serviceIdentifier: characteristicIdentifier.service, peripheral: cbPeripheral, callback: { [weak self] result in
guard let weakSelf = self else {
return
}
switch result {
case .success:
weakSelf.addOperation(DiscoverCharacteristic(
characteristicIdentifier: characteristicIdentifier, peripheral: weakSelf.cbPeripheral, callback: { result in
switch result {
case .success:
callback(true)
case .cancelled:
callback(false)
case .failure(_):
callback(false)
}
}))
case .cancelled:
callback(false)
case .failure(_):
callback(false)
}
}))
}
// MARK: - Bluetooth Event
fileprivate func handleEvent(_ event: Event, error: NSError?) {
guard let bluejay = bluejay else {
preconditionFailure("Cannot handle event: Bluejay is nil.")
}
bluejay.queue.process(event: event, error: error)
updateOperations()
}
// MARK: - RSSI Event
/// Requests the current RSSI value from the peripheral, and the value is returned via the `RSSIObserver` delegation.
public func readRSSI() {
cbPeripheral.readRSSI()
}
/// Register a RSSI observer that can receive the RSSI value when `readRSSI` is called.
public func register(observer: RSSIObserver) {
observers = observers.filter { $0.weakReference != nil && $0.weakReference !== observer }
observers.append(WeakRSSIObserver(weakReference: observer))
}
/// Unregister a RSSI observer.
public func unregister(observer: RSSIObserver) {
observers = observers.filter { $0.weakReference != nil && $0.weakReference !== observer }
}
// MARK: - Actions
/// Read from a specified characteristic.
public func read<R: Receivable>(from characteristicIdentifier: CharacteristicIdentifier, completion: @escaping (ReadResult<R>) -> Void) {
precondition(
listeners[characteristicIdentifier] == nil,
"Cannot read from characteristic: \(characteristicIdentifier.uuid), which is already being listened on."
)
// log.debug("Queueing read to: \(characteristicIdentifier.uuid.uuidString)")
discoverCharactersitic(characteristicIdentifier, callback: { [weak self] success in
guard let weakSelf = self else {
return
}
if success {
weakSelf.addOperation(
ReadCharacteristic(characteristicIdentifier: characteristicIdentifier, peripheral: weakSelf.cbPeripheral, callback: completion)
)
}
else {
completion(.failure(BluejayError.missingCharacteristic(characteristicIdentifier)))
}
})
}
/// Write to a specified characteristic.
public func write<S: Sendable>(to characteristicIdentifier: CharacteristicIdentifier, value: S, type: CBCharacteristicWriteType = .withResponse, completion: @escaping (WriteResult) -> Void) {
// log.debug("Queueing write to: \(characteristicIdentifier.uuid.uuidString) with value of: \(value)")
discoverCharactersitic(characteristicIdentifier, callback: { [weak self] success in
guard let weakSelf = self else {
return
}
// Not using the success variable here because the write operation will also catch the error if the service or the characteristic is not discovered.
weakSelf.addOperation(
WriteCharacteristic(characteristicIdentifier: characteristicIdentifier, peripheral: weakSelf.cbPeripheral, value: value, type: type, callback: completion))
})
}
/// Checks whether Bluejay is currently listening to the specified charactersitic.
public func isListening(to characteristicIdentifier: CharacteristicIdentifier) -> Bool {
return listeners.keys.contains(characteristicIdentifier)
}
/// Listen for notifications on a specified characterstic.
public func listen<R: Receivable>(to characteristicIdentifier: CharacteristicIdentifier, completion: @escaping (ReadResult<R>) -> Void) {
discoverCharactersitic(characteristicIdentifier, callback: { [weak self] success in
guard let weakSelf = self else {
return
}
// Not using the success variable here because the listen operation will also catch the error if the service or the characteristic is not discovered.
weakSelf.addOperation(
ListenCharacteristic(characteristicIdentifier: characteristicIdentifier, peripheral: weakSelf.cbPeripheral, value: true, callback: { result in
precondition(
weakSelf.listeners[characteristicIdentifier] == nil,
"Cannot have multiple active listens against the same characteristic: \(characteristicIdentifier.uuid)"
)
switch result {
case .success:
weakSelf.listeners[characteristicIdentifier] = { dataResult in
completion(ReadResult<R>(dataResult: dataResult))
}
// Only bother caching if listen restoration is enabled.
if
let restoreIdentifier = weakSelf.bluejay?.restoreIdentifier,
weakSelf.bluejay?.listenRestorer != nil
{
do {
// Make sure a successful listen is cached, so Bluejay can inform its delegate on which characteristics need their listens restored during state restoration.
try weakSelf.cache(listeningCharacteristic: characteristicIdentifier, restoreIdentifier: restoreIdentifier)
}
catch {
log("Failed to cache listen on characteristic: \(characteristicIdentifier.uuid) of service: \(characteristicIdentifier.service.uuid) for restore id: \(restoreIdentifier) with error: \(error.localizedDescription)")
}
}
case .cancelled:
completion(.cancelled)
case .failure(let error):
completion(.failure(error))
}
}))
})
}
/**
End listening on a specified characteristic.
Provides the ability to suppress the failure message to the listen callback. This is useful in the internal implimentation of some of the listening logic, since we want to be able to share the clear logic on a .done exit, but don't need to send a failure in that case.
- Note
Currently this can also cancel a regular in-progress read as well, but that behaviour may change down the road.
*/
public func endListen(to characteristicIdentifier: CharacteristicIdentifier, error: Error? = nil, completion: ((WriteResult) -> Void)? = nil) {
discoverCharactersitic(characteristicIdentifier, callback: { [weak self] success in
guard let weakSelf = self else {
return
}
weakSelf.listenersBeingCancelled.append(characteristicIdentifier)
// Not using the success variable here because the listen operation will also catch the error if the service or the characteristic is not discovered.
weakSelf.addOperation(
ListenCharacteristic(characteristicIdentifier: characteristicIdentifier, peripheral: weakSelf.cbPeripheral, value: false, callback: { result in
let listenCallback = weakSelf.listeners[characteristicIdentifier]
weakSelf.listeners[characteristicIdentifier] = nil
if let error = error {
listenCallback?(.failure(error))
}
else {
listenCallback?(.cancelled)
}
// Only bother removing the listen cache if listen restoration is enabled.
if
let restoreIdentifier = weakSelf.bluejay?.restoreIdentifier,
weakSelf.bluejay?.listenRestorer != nil
{
do {
// Make sure an ended listen does not exist in the cache, as we don't want to restore a cancelled listen on state restoration.
try weakSelf.remove(listeningCharacteristic: characteristicIdentifier, restoreIdentifier: restoreIdentifier)
}
catch {
log("Failed to remove cached listen on characteristic: \(characteristicIdentifier.uuid) of service: \(characteristicIdentifier.service.uuid) for restore id: \(restoreIdentifier) with error: \(error.localizedDescription)")
}
}
completion?(result)
}))
})
}
/// Restore a (believed to be) active listening session, so if we start up in response to a notification, we can receive it.
public func restoreListen<R: Receivable>(to characteristicIdentifier: CharacteristicIdentifier, completion: @escaping (ReadResult<R>) -> Void) {
precondition(
listeners[characteristicIdentifier] == nil,
"Cannot have multiple active listens against the same characteristic"
)
listeners[characteristicIdentifier] = { dataResult in
completion(ReadResult<R>(dataResult: dataResult))
}
}
// MARK: - Listen Caching
private func cache(listeningCharacteristic: CharacteristicIdentifier, restoreIdentifier: RestoreIdentifier) throws {
let serviceUUID = listeningCharacteristic.service.uuid.uuidString
let characteristicUUID = listeningCharacteristic.uuid.uuidString
let encoder = JSONEncoder()
do {
let cacheData = try encoder.encode(ListenCache(serviceUUID: serviceUUID, characteristicUUID: characteristicUUID))
// If the UserDefaults for the specified restore identifier doesn't exist yet, create one and add the ListenCache to it.
guard
let listenCaches = UserDefaults.standard.dictionary(forKey: Constant.listenCaches),
let listenCacheData = listenCaches[restoreIdentifier] as? [Data]
else {
UserDefaults.standard.set([restoreIdentifier : [cacheData]], forKey: Constant.listenCaches)
UserDefaults.standard.synchronize()
return
}
// If the ListenCache already exists, don't add it to the cache again.
if listenCacheData.contains(cacheData) {
return
}
else {
// Add the ListenCache to the existing UserDefaults for the specified restore identifier.
var newListenCacheData = listenCacheData
newListenCacheData.append(cacheData)
var newListenCaches = listenCaches
newListenCaches[restoreIdentifier] = newListenCacheData
UserDefaults.standard.set(newListenCaches, forKey: Constant.listenCaches)
UserDefaults.standard.synchronize()
}
}
catch {
throw BluejayError.listenCacheEncoding(error)
}
}
private func remove(listeningCharacteristic: CharacteristicIdentifier, restoreIdentifier: RestoreIdentifier) throws {
let serviceUUID = listeningCharacteristic.service.uuid.uuidString
let characteristicUUID = listeningCharacteristic.uuid.uuidString
guard
let listenCaches = UserDefaults.standard.dictionary(forKey: Constant.listenCaches),
let cacheData = listenCaches[restoreIdentifier] as? [Data]
else {
// Nothing to remove.
return
}
var newCacheData = cacheData
let decoder = JSONDecoder()
newCacheData = try newCacheData.filter { (data) -> Bool in
do {
let listenCache = try decoder.decode(ListenCache.self, from: data)
return (listenCache.serviceUUID != serviceUUID) && (listenCache.characteristicUUID != characteristicUUID)
}
catch {
throw BluejayError.listenCacheDecoding(error)
}
}
var newListenCaches = listenCaches
// If the new cache data is empty after the filter removal, remove the entire cache entry for the specified restore identifier as well.
if newCacheData.isEmpty {
newListenCaches.removeValue(forKey: restoreIdentifier)
}
else {
newListenCaches[restoreIdentifier] = newCacheData
}
UserDefaults.standard.set(newListenCaches, forKey: Constant.listenCaches)
UserDefaults.standard.synchronize()
listenersBeingCancelled = listenersBeingCancelled.filter { (characteristicIdentifier) -> Bool in
return characteristicIdentifier.uuid.uuidString != listeningCharacteristic.uuid.uuidString
}
}
}
// MARK: - CBPeripheralDelegate
extension Peripheral: CBPeripheralDelegate {
public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
handleEvent(.didDiscoverServices, error: error as NSError?)
}
public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
handleEvent(.didDiscoverCharacteristics, error: error as NSError?)
}
public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
handleEvent(.didWriteCharacteristic(characteristic), error: error as NSError?)
}
public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
guard let bluejay = bluejay else {
preconditionFailure("Cannot handle did update value for \(characteristic.uuid.uuidString): Bluejay is nil.")
}
guard let listener = listeners[CharacteristicIdentifier(characteristic)] else {
// Handle attempting to read a characteristic whose listen is being cancelled during state restoration.
let isCancellingListenOnCurrentRead = listenersBeingCancelled.contains(where: { (characteristicIdentifier) -> Bool in
return characteristicIdentifier.uuid.uuidString == characteristic.uuid.uuidString
})
let isReadUnhandled = isCancellingListenOnCurrentRead || (listeners.isEmpty && bluejay.queue.isEmpty())
if isReadUnhandled {
return
}
else {
handleEvent(.didReadCharacteristic(characteristic, characteristic.value ?? Data()), error: error as NSError?)
return
}
}
if let error = error {
listener(.failure(error))
}
else {
listener(.success(characteristic.value))
}
}
public func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
handleEvent(.didUpdateCharacteristicNotificationState(characteristic), error: error as NSError?)
}
public func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
for observer in observers {
observer.weakReference?.peripheral(peripheral, didReadRSSI: RSSI, error: error)
}
}
}
| mit | b6fa41fe4e5b0fde5b9d4a543b8729dc | 42.790588 | 273 | 0.613078 | 5.999678 | false | false | false | false |
domenicosolazzo/practice-swift | CoreData/Custom Data Types/Custom Data Types/AppDelegate.swift | 1 | 7907 | //
// AppDelegate.swift
// Custom Data Types
//
// Created by Domenico Solazzo on 17/05/15.
// License MIT
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
/* Save the laptop with a given color first */
let laptop = NSEntityDescription.insertNewObjectForEntityForName(
NSStringFromClass(Laptop.classForCoder()),
inManagedObjectContext: managedObjectContext!) as! Laptop
laptop.model = "model name"
laptop.color = UIColor.redColor()
var savingError: NSError?
if managedObjectContext!.save() == false{
if let error = savingError{
print("Failed to save the laptop. Error = \(error)")
}
}
/* Now find the same laptop */
let fetch = NSFetchRequest(entityName:
NSStringFromClass(Laptop.classForCoder()))
fetch.fetchLimit = 1
fetch.predicate = NSPredicate(format: "color == %@", UIColor.redColor())
var fetchingError: NSError?
let laptops = managedObjectContext!.executeFetchRequest(fetch) as [AnyObject]!
/* Check for 1 because out fetch limit is 1 */
if laptops.count == 1 && fetchingError == nil{
let fetchedLaptop = laptops[0] as! Laptop
if fetchedLaptop.color == UIColor.redColor(){
print("Right colored laptop was fetched")
} else {
print("Could not find the laptop with the given color")
}
} else {
if let error = fetchingError{
print("Could not fetch the laptop with the given color. " +
"Error = \(error)")
}
}
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.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.domenicosolazzo.swift.Custom_Data_Types" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Custom_Data_Types", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Custom_Data_Types.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
}
| mit | 4536e81c507201ec121c210382e5eab4 | 48.111801 | 290 | 0.667383 | 5.72971 | false | false | false | false |
iAladdin/SwiftyFORM | Source/Cells/SliderCell.swift | 1 | 1473 | // Copyright (c) 2015 Simon Strandgaard. All rights reserved.
import UIKit
public struct SliderCellModel {
var title: String = ""
var value: Float = 0.0
var minimumValue: Float = 0.0
var maximumValue: Float = 1.0
var valueDidChange: Float -> Void = { (value: Float) in
DLog("value \(value)")
}
}
public class SliderCell: UITableViewCell, CellHeightProvider {
public let model: SliderCellModel
public let slider = UISlider()
public init(model: SliderCellModel) {
self.model = model
super.init(style: .Default, reuseIdentifier: nil)
selectionStyle = .None
contentView.addSubview(slider)
slider.minimumValue = model.minimumValue
slider.maximumValue = model.maximumValue
slider.value = model.value
slider.addTarget(self, action: "valueChanged", forControlEvents: .ValueChanged)
clipsToBounds = true
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func layoutSubviews() {
super.layoutSubviews()
slider.sizeToFit()
slider.frame = bounds.rectByInsetting(dx: 16, dy: 0)
}
public func form_cellHeight(indexPath: NSIndexPath, tableView: UITableView) -> CGFloat {
return 60
}
public func valueChanged() {
DLog("value did change")
model.valueDidChange(slider.value)
}
public func setValueWithoutSync(value: Float, animated: Bool) {
DLog("set value \(value), animated \(animated)")
slider.setValue(value, animated: animated)
}
}
| mit | 673375c20699507cf51ae578fc245805 | 23.966102 | 89 | 0.725051 | 3.719697 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/02237-swift-parser-parsetypecomposition.swift | 11 | 799 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
private class A {
class d>(Any) {
}
struct e = mx : B, o>() {
}
init<D>(b> {
}
self.Type) {
}
var b {
func c: d = B<Q<T> T! {
var d {
}
func i: b {
}
let c {
class A : c {
extension NSData {
}
}
func hg(array: d where g, f(Any, 3] {
class B == Int>(("foo: AnyObject) -> (b<d<o {
protocol d = ["" }
}
case .init(() -> {
}
protocol P {
}
}
protocol b {
typealias d: a {
"""][0x31] {
private class func a!.c {
| apache-2.0 | 3ee0171b7fb5569d7f1ce5d7eb16ed8f | 18.487805 | 78 | 0.634543 | 2.843416 | false | false | false | false |
lgaches/Kitura-GraphQL | Sources/GraphQLMiddleware/GraphQLMiddleware.swift | 1 | 5729 | //
// GraphQLMiddleware.swift
// Kitura-GraphQL
//
// Created by Laurent Gaches on 16/11/2016.
// Copyright (c) 2016 Laurent Gaches
//
// 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 Kitura
import SwiftyJSON
import GraphQL
import Graphiti
import LoggerAPI
public let noRootValue: Void = Void()
/// Kitura GraphQL Middleware
public class GraphQLMiddleware<Root, Context>: RouterMiddleware {
let schema: Schema<Root, Context>
let showGraphiQL: Bool
let rootValue: Root
let context: Context?
/// Init Kitura GraphQL Middleware
///
/// - Parameters:
/// - schema: A `Schema` instance from [Graphiti](https://github.com/GraphQLSwift/Graphiti). A `Schema` *must* be provided.
/// - showGraphiQL:If `true`, presentss [GraphiQL](https://github.com/graphql/graphiql) when the GraphQL endpoint is loaded in a browser. We recommend that you set `showGraphiQL` to `true` when your app is in development because it's quite useful. You may or may not want it in production.
/// - rootValue: A value to pass as the `rootValue` to the schema's `execute` function from [Graphiti](https://github.com/GraphQLSwift/Graphiti).
/// - context: A value to pass as the `context` to the schema's `execute` function from [Graphiti](https://github.com/GraphQLSwift/Graphiti).
public init(schema: Schema<Root, Context>, showGraphiQL: Bool, rootValue: Root, context: Context? = nil) {
self.schema = schema
self.showGraphiQL = showGraphiQL
self.rootValue = rootValue
self.context = context
}
/// Handle an incoming HTTP request.
///
/// - Parameter request: The `RouterRequest` object used to get information
/// about the HTTP request.
/// - Parameter response: The `RouterResponse` object used to respond to the
/// HTTP request
/// - Parameter next: The closure to invoke to enable the Router to check for
/// other handlers or middleware to work with this request.
///
/// - Throws: Any `ErrorType`. If an error is thrown, processing of the request
/// is stopped, the error handlers, if any are defined, will be invoked,
/// and the user will get a response with a status code of 500.
public func handle(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws {
let params = GraphQLRequestParams(request: request)
switch request.method {
// GraphQL HTTP only supports GET and POST methods.
case .get:
if !showGraphiQL || (showGraphiQL && request.queryParameters["raw"] != nil) {
try executeGraphQLRequest(params: params, request: request, response: response)
} else {
if (showGraphiQL) {
let graphiql = renderGraphiQL(query: nil, variables: nil, operationName: nil, result: nil)
response.send(graphiql)
try response.end()
} else {
response.status(.badRequest)
try response.send("Must provide query string.").end()
}
}
case .post:
if let _ = request.accepts(type:"application/json") {
try executeGraphQLRequest(params: params, request: request, response: response)
} else {
response.status(.methodNotAllowed)
try response.end()
}
default:
response.headers.append("Allow",value: "GET, POST")
response.status(.methodNotAllowed)
try response.end()
}
next()
}
func executeGraphQLRequest(params: GraphQLRequestParams, request: RouterRequest, response: RouterResponse) throws {
guard let query = params.query else {
response.status(.badRequest)
try response.send("Must provide query string.").end()
return
}
do {
let result: Map
if let context = context {
result = try self.schema.execute(request: query, rootValue: rootValue, context: context, variables: params.variables, operationName: params.operationName)
} else {
result = try self.schema.execute(request: query, rootValue: rootValue, variables: params.variables, operationName: params.operationName)
}
try response.send(json: result.toJSON()).end()
} catch let error {
print(error)
try response.status(.badRequest).send(error.localizedDescription).end()
}
}
}
| mit | c982798bcd4c0fe75edde31c8d85d170 | 42.401515 | 295 | 0.643219 | 4.572227 | false | false | false | false |
abertelrud/swift-package-manager | Sources/SPMTestSupport/MockRegistry.swift | 2 | 16015 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import Foundation
import PackageFingerprint
import PackageGraph
import PackageLoading
import PackageModel
import PackageRegistry
import TSCBasic
public class MockRegistry {
private static let mockRegistryURL = URL(string: "http://localhost/registry/mock")!
private let fileSystem: FileSystem
private let identityResolver: IdentityResolver
private let checksumAlgorithm: HashAlgorithm
public var registryClient: RegistryClient!
private let jsonEncoder: JSONEncoder
private var packageVersions = [PackageIdentity: [String: InMemoryRegistryPackageSource]]()
private var packagesSourceControlURLs = [PackageIdentity: [URL]]()
private var sourceControlURLs = [URL: PackageIdentity]()
private let packagesLock = NSLock()
public init(
filesystem: FileSystem,
identityResolver: IdentityResolver,
checksumAlgorithm: HashAlgorithm,
fingerprintStorage: PackageFingerprintStorage
) {
self.fileSystem = filesystem
self.identityResolver = identityResolver
self.checksumAlgorithm = checksumAlgorithm
self.jsonEncoder = JSONEncoder.makeWithDefaults()
var configuration = RegistryConfiguration()
configuration.defaultRegistry = .init(url: Self.mockRegistryURL)
self.registryClient = RegistryClient(
configuration: configuration,
fingerprintStorage: fingerprintStorage,
fingerprintCheckingMode: .strict,
authorizationProvider: .none,
customHTTPClient: HTTPClient(handler: self.httpHandler),
customArchiverProvider: { fileSystem in MockRegistryArchiver(fileSystem: fileSystem) }
)
}
public func addPackage(identity: PackageIdentity, versions: [Version], sourceControlURLs: [URL]? = .none, source: InMemoryRegistryPackageSource) {
self.addPackage(identity: identity, versions: versions.map{ $0.description }, sourceControlURLs: sourceControlURLs, source: source)
}
public func addPackage(identity: PackageIdentity, versions: [String], sourceControlURLs: [URL]? = .none, source: InMemoryRegistryPackageSource) {
self.packagesLock.withLock {
// versions
var updatedVersions = self.packageVersions[identity] ?? [:]
for version in versions {
updatedVersions[version.description] = source
}
self.packageVersions[identity] = updatedVersions
// source control URLs
if let sourceControlURLs = sourceControlURLs {
var packageSourceControlURLs = self.packagesSourceControlURLs[identity] ?? []
packageSourceControlURLs.append(contentsOf: sourceControlURLs)
self.packagesSourceControlURLs[identity] = packageSourceControlURLs
// reverse index
for sourceControlURL in sourceControlURLs {
self.sourceControlURLs[sourceControlURL] = identity
}
}
}
}
func httpHandler(request: HTTPClient.Request, progress: HTTPClient.ProgressHandler?, completion: @escaping (Result<HTTPClient.Response, Error>) -> Void) {
do {
guard request.url.absoluteString.hasPrefix(Self.mockRegistryURL.absoluteString) else {
throw StringError("url outside mock registry \(Self.mockRegistryURL)")
}
switch request.kind {
case .generic:
let response = try self.handleRequest(request: request)
completion(.success(response))
case .download(let fileSystem, let destination):
let response = try self.handleDownloadRequest(
request: request,
progress: progress,
fileSystem: fileSystem,
destination: destination
)
completion(.success(response))
}
} catch {
completion(.failure(error))
}
}
private func handleRequest(request: HTTPClient.Request) throws -> HTTPClient.Response {
let routeComponents = request.url.absoluteString.dropFirst(Self.mockRegistryURL.absoluteString.count + 1).split(separator: "/")
switch routeComponents.count {
case _ where routeComponents[0].hasPrefix("identifiers?url="):
guard let query = request.url.query else {
throw StringError("invalid url: \(request.url)")
}
guard let sourceControlURL = URL(string: String(query.dropFirst(4))) else {
throw StringError("invalid url query: \(query)")
}
return try self.getIdentifiers(url: sourceControlURL)
case 2:
let package = PackageIdentity.plain(routeComponents.joined(separator: "."))
return try self.getPackageMetadata(packageIdentity: package)
case 3:
let package = PackageIdentity.plain(routeComponents[0...1].joined(separator: "."))
let version = String(routeComponents[2])
return try self.getVersionMetadata(packageIdentity: package, version: version)
case 4 where routeComponents[3] == "Package.swift":
let package = PackageIdentity.plain(routeComponents[0...1].joined(separator: "."))
let version = String(routeComponents[2])
guard let components = URLComponents(url: request.url, resolvingAgainstBaseURL: false) else {
throw StringError("invalid url: \(request.url)")
}
let toolsVersion = components.queryItems?.first(where: {$0.name == "swift-version"})?.value.flatMap(ToolsVersion.init(string:))
return try self.getManifest(packageIdentity: package, version: version, toolsVersion: toolsVersion)
default:
throw StringError("unknown request \(request.url)")
}
}
private func getPackageMetadata(packageIdentity: PackageIdentity) throws -> HTTPClientResponse {
guard let (scope, name) = packageIdentity.scopeAndName else {
throw StringError("invalid package identity \(packageIdentity)")
}
let versions = self.packageVersions[packageIdentity] ?? [:]
let metadata = RegistryClient.Serialization.PackageMetadata(
releases: versions.keys.reduce(into: [String: RegistryClient.Serialization.PackageMetadata.Release]()) { partial, item in
partial[item] = .init(url: "\(Self.mockRegistryURL.absoluteString)/\(scope)/\(name)/\(item)")
}
)
/*
<https://github.com/mona/LinkedList>; rel="canonical",
<ssh://[email protected]:mona/LinkedList.git>; rel="alternate"
*/
let sourceControlURLs = self.packagesSourceControlURLs[packageIdentity]
let links = sourceControlURLs?.map { url in
"<\(url.absoluteString)>; rel=alternate"
}.joined(separator: ", ")
var headers = HTTPClientHeaders()
headers.add(name: "Content-Version", value: "1")
headers.add(name: "Content-Type", value: "application/json")
if let links = links {
headers.add(name: "Link", value: links)
}
return try HTTPClientResponse(
statusCode: 200,
headers: headers,
body: self.jsonEncoder.encode(metadata)
)
}
private func getVersionMetadata(packageIdentity: PackageIdentity, version: String) throws -> HTTPClientResponse {
guard let package = self.packageVersions[packageIdentity]?[version] else {
return .notFound()
}
let zipfileContent = try self.zipFileContent(packageIdentity: packageIdentity, version: version, source: package)
let zipfileChecksum = self.checksumAlgorithm.hash(zipfileContent)
let metadata = RegistryClient.Serialization.VersionMetadata(
id: packageIdentity.description,
version: version,
resources: [
.init(
name: "source-archive",
type: "application/zip",
checksum: zipfileChecksum.hexadecimalRepresentation
)
],
metadata: .init(description: "\(packageIdentity) description")
)
var headers = HTTPClientHeaders()
headers.add(name: "Content-Version", value: "1")
headers.add(name: "Content-Type", value: "application/json")
return try HTTPClientResponse(
statusCode: 200,
headers: headers,
body: self.jsonEncoder.encode(metadata)
)
}
private func getManifest(packageIdentity: PackageIdentity, version: String, toolsVersion: ToolsVersion? = .none) throws -> HTTPClientResponse {
guard let package = self.packageVersions[packageIdentity]?[version] else {
return .notFound()
}
let filename: String
if let toolsVersion = toolsVersion {
filename = Manifest.basename + "@swift-\(toolsVersion).swift"
} else {
filename = Manifest.basename + ".swift"
}
let content: Data = try package.fileSystem.readFileContents(package.path.appending(component: filename))
var headers = HTTPClientHeaders()
headers.add(name: "Content-Version", value: "1")
headers.add(name: "Content-Type", value: "text/x-swift")
return HTTPClientResponse(
statusCode: 200,
headers: headers,
body: content
)
}
private func getIdentifiers(url: URL) throws -> HTTPClientResponse {
let identifiers = self.sourceControlURLs[url].map { [$0.description] } ?? []
let packageIdentifiers = RegistryClient.Serialization.PackageIdentifiers(
identifiers: identifiers
)
var headers = HTTPClientHeaders()
headers.add(name: "Content-Version", value: "1")
headers.add(name: "Content-Type", value: "application/json")
return HTTPClientResponse(
statusCode: 200,
headers: headers,
body: try self.jsonEncoder.encode(packageIdentifiers)
)
}
private func handleDownloadRequest(
request: HTTPClient.Request,
progress: HTTPClient.ProgressHandler?,
fileSystem: FileSystem,
destination: AbsolutePath
) throws -> HTTPClientResponse {
let routeComponents = request.url.absoluteString.dropFirst(Self.mockRegistryURL.absoluteString.count + 1).split(separator: "/")
guard routeComponents.count == 3, routeComponents[2].hasSuffix(".zip") else {
throw StringError("invalid request \(request.url), expecting zip suffix")
}
let packageIdentity = PackageIdentity.plain(routeComponents[0...1].joined(separator: "."))
let version = String(routeComponents[2].dropLast(4))
guard let package = self.packageVersions[packageIdentity]?[version] else {
return .notFound()
}
if !fileSystem.exists(destination.parentDirectory) {
try fileSystem.createDirectory(destination.parentDirectory, recursive: true)
}
let zipfileContent = try self.zipFileContent(packageIdentity: packageIdentity, version: version, source: package)
try fileSystem.writeFileContents(destination, string: zipfileContent)
var headers = HTTPClientHeaders()
headers.add(name: "Content-Version", value: "1")
headers.add(name: "Content-Type", value: "application/zip")
return HTTPClientResponse(
statusCode: 200,
headers: headers
)
}
private func zipFileContent(packageIdentity: PackageIdentity, version: String, source: InMemoryRegistryPackageSource) throws -> String {
var content = "\(packageIdentity)_\(version)\n"
content += source.path.pathString + "\n"
for file in try source.listFiles() {
content += file.pathString + "\n"
}
return content
}
}
public struct InMemoryRegistryPackageSource {
let fileSystem: FileSystem
public let path: AbsolutePath
public init(fileSystem: FileSystem, path: AbsolutePath, writeContent: Bool = true) {
self.fileSystem = fileSystem
self.path = path
}
public func writePackageContent(targets: [String] = [], toolsVersion: ToolsVersion = .current) throws {
try self.fileSystem.createDirectory(self.path, recursive: true)
let sourcesDir = self.path.appending(component: "Sources")
for target in targets {
let targetDir = sourcesDir.appending(component: target)
try self.fileSystem.createDirectory(targetDir, recursive: true)
try self.fileSystem.writeFileContents(targetDir.appending(component: "file.swift"), bytes: "")
}
let manifestPath = self.path.appending(component: Manifest.filename)
try self.fileSystem.writeFileContents(manifestPath, string: "// swift-tools-version:\(toolsVersion)")
}
public func listFiles(root: AbsolutePath? = .none) throws -> [AbsolutePath] {
var files = [AbsolutePath]()
let root = root ?? self.path
let entries = try self.fileSystem.getDirectoryContents(root)
for entry in entries.map({ root.appending(component: $0) }) {
if self.fileSystem.isDirectory(entry) {
let directoryFiles = try self.listFiles(root: entry)
files.append(contentsOf: directoryFiles)
} else if self.fileSystem.isFile(entry) {
files.append(entry)
} else {
throw StringError("invalid entry type")
}
}
return files
}
}
private struct MockRegistryArchiver: Archiver {
let supportedExtensions = Set<String>(["zip"])
let fileSystem: FileSystem
init(fileSystem: FileSystem) {
self.fileSystem = fileSystem
}
func extract(from archivePath: AbsolutePath, to destinationPath: AbsolutePath, completion: @escaping (Result<Void, Error>) -> Void) {
do {
let lines = try self.readFileContents(archivePath)
guard lines.count >= 2 else {
throw StringError("invalid mock zip format, not enough lines")
}
let rootPath = lines[1]
for path in lines[2..<lines.count] {
let relativePath = String(path.dropFirst(rootPath.count + 1))
let targetPath = try AbsolutePath(validating: relativePath, relativeTo: destinationPath.appending(component: "package"))
if !self.fileSystem.exists(targetPath.parentDirectory) {
try self.fileSystem.createDirectory(targetPath.parentDirectory, recursive: true)
}
try self.fileSystem.copy(from: try AbsolutePath(validating: path), to: targetPath)
}
completion(.success(()))
} catch {
completion(.failure(error))
}
}
func validate(path: AbsolutePath, completion: @escaping (Result<Bool, Error>) -> Void) {
do {
let lines = try self.readFileContents(path)
completion(.success(lines.count >= 2))
} catch {
completion(.failure(error))
}
}
private func readFileContents(_ path: AbsolutePath) throws -> [String] {
let content: String = try self.fileSystem.readFileContents(path)
return content.split(separator: "\n").map(String.init)
}
}
| apache-2.0 | bb8a6b90680a0678edd56656f6123671 | 41.593085 | 158 | 0.634031 | 5.061631 | false | false | false | false |
cdtschange/SwiftMKit | SwiftMKit/Data/DataStructure/MQueue.swift | 1 | 994 | //
// MQueue.swift
// SwiftMKitDemo
//
// Created by Mao on 8/16/16.
// Copyright © 2016 cdts. All rights reserved.
//
import Foundation
public struct MQueue<T> {
fileprivate var array = [T?]()
fileprivate var head = 0
public mutating func enqueue(_ element: T) {
array.append(element)
}
public mutating func dequeue() -> T? {
guard head < array.count, let element = array[head] else { return nil }
array[head] = nil
head += 1
let percentage = Double(head) / Double(array.count)
if array.count > 50 && percentage > 0.25 {
array.removeFirst(head)
head = 0
}
return element
}
public var isEmpty: Bool {
return count == 0
}
public var count: Int {
return array.count - head
}
public func peek() -> T? {
if isEmpty {
return nil
} else {
return array[head]
}
}
}
| mit | 0dc2cf81c1ff0d2d588494fe9ce33c0e | 20.586957 | 79 | 0.524673 | 4.1375 | false | false | false | false |
cdtschange/SwiftMKit | SwiftMKit/UI/View/SmarterView/CrashLogViewController.swift | 1 | 3162 | //
// CrashLogViewController.swift
// SwiftMKitDemo
//
// Created by Mao on 09/01/2017.
// Copyright © 2017 cdts. All rights reserved.
//
import UIKit
class CrashLogViewController: BaseListKitViewController {
struct InnerConst {
static let CellIdentifier = "CrashLogTableViewCell"
static let SegueToNextView = "CrashLogDetailViewController"
}
@IBOutlet weak var tableView: UITableView!
private var _viewModel = CrashLogViewModel()
override var viewModel: BaseKitViewModel!{
get { return _viewModel }
}
override var listViewType: ListViewType {
return .both
}
override var listView: UIScrollView! {
get { return tableView }
}
override func setupUI() {
super.setupUI()
title = "Crash Log"
tableView.tableFooterView = UIView()
loadData()
}
override func setupNavigation() {
super.setupNavigation()
let item = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(CrashLogViewController.clear))
self.navigationItem.rightBarButtonItem = item
}
override func loadData() {
super.loadData()
_viewModel.fetchData()
}
@objc func clear() {
let alert = UIAlertController(title: "确认", message: "确定要清空所有崩溃日志?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "清空", style: .destructive, handler: { [weak self] _ in
// LocalCrashLogReporter.shared.clean()
self?._viewModel.fetchData()
}))
alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
showAlert(alert, completion: nil)
}
override func getCell(withTableView tableView: UITableView, indexPath: IndexPath) -> UITableViewCell? {
var cell = tableView.dequeueReusableCell(withIdentifier: InnerConst.CellIdentifier)
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: InnerConst.CellIdentifier)
}
return cell
}
override func configureCell(_ tableViewCell: UITableViewCell, object: Any, indexPath: IndexPath) {
if let model = object as? CrashLogEntity {
tableViewCell.textLabel?.text = model.createTime?.toString(format: "yyyy-MM-dd HH:mm:ss")
tableViewCell.detailTextLabel?.text = model.message
}
}
override func didSelectCell(_ tableViewCell: UITableViewCell, object: Any, indexPath: IndexPath) {
if let model = object as? CrashLogEntity {
self.route(toName: InnerConst.SegueToNextView, params: ["title": model.createTime?.toString(format: "yyyy-MM-dd HH:mm:ss") ?? "Crash Log", "text": model.message ?? ""])
}
}
}
class CrashLogViewModel: BaseListKitViewModel {
override var listLoadNumber: UInt {
return 20
}
override func fetchData() {
// let array = LocalCrashLogReporter.shared.queryCrashLog(page: Int(dataIndex), number: Int(listLoadNumber))
// updateDataArray(array)
// listViewController.endListRefresh()
}
}
| mit | b15969e9d19089d8fe967d94c1b37a4f | 34.91954 | 180 | 0.65728 | 4.671151 | false | false | false | false |
lorentey/swift | test/ClangImporter/simd.swift | 8 | 3243 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name main -typecheck -verify %s
import c_simd
let char2_value: char2 = makes_char2()
let char64_value: char64 = makes_char64()
let uchar3_value: uchar3 = makes_uchar3()
let uchar32_value: uchar32 = makes_uchar32()
let short3_value: short3 = makes_short3()
let short8_value: short8 = makes_short8()
let ushort1_value: ushort1 = makes_ushort1()
let ushort16_value: ushort16 = makes_ushort16()
let int3_value: int3 = makes_int3()
let int32_value: int32 = makes_int32()
let uint4_value: uint4 = makes_uint4()
let uint2_value: uint2 = makes_uint2()
let long2_value: long2 = makes_long2()
let long8_value: long8 = makes_long8()
let ulong4_value: ulong4 = makes_ulong4()
let ulong1_value: ulong1 = makes_ulong1()
let ll3_value: ll3 = makes_ll3()
let ll8_value: ll8 = makes_ll8()
let ull4_value: ull4 = makes_ull4()
let ull16_value: ull16 = makes_ull16()
let float2_value: float2 = makes_float2()
let float3_value: float3 = makes_float3()
let float4_value: float4 = makes_float4()
let float8_value: float8 = makes_float8()
let float16_value: float16 = makes_float16()
let double2_value: double2 = makes_double2()
let double3_value: double3 = makes_double3()
let double4_value: double4 = makes_double4()
let double8_value: double8 = makes_double8()
takes_char2(char2_value)
takes_char64(char64_value)
takes_uchar3(uchar3_value)
takes_uchar32(uchar32_value)
takes_short3(short3_value)
takes_short8(short8_value)
takes_ushort1(ushort1_value)
takes_ushort16(ushort16_value)
takes_int3(int3_value)
takes_int32(int32_value)
takes_uint4(uint4_value)
takes_uint2(uint2_value)
takes_long2(long2_value)
takes_long8(long8_value)
takes_ulong4(ulong4_value)
takes_ulong1(ulong1_value)
takes_ll3(ll3_value)
takes_ll8(ll8_value)
takes_ull4(ull4_value)
takes_ull16(ull16_value)
takes_float2(float2_value)
takes_float3(float3_value)
takes_float4(float4_value)
takes_float8(float8_value)
takes_float16(float16_value)
takes_double2(double2_value)
takes_double3(double3_value)
takes_double4(double4_value)
takes_double8(double8_value)
// These shouldn't be imported, since there's no type to map them to.
let char17_value = makes_char17() // expected-error{{unresolved identifier 'makes_char17'}}
let uchar21_value = makes_uchar21() // expected-error{{unresolved identifier 'makes_uchar21'}}
let short5_value = makes_short5() // expected-error{{unresolved identifier 'makes_short5'}}
let ushort6_value = makes_ushort6() // expected-error{{unresolved identifier 'makes_ushort6'}}
let int128_value = makes_int128() // expected-error{{unresolved identifier 'makes_int128'}}
let uint20_value = makes_uint20() // expected-error{{unresolved identifier 'makes_uint20'}}
takes_char17(char17_value) // expected-error{{unresolved identifier 'takes_char17'}}
takes_uchar21(uchar21_value) // expected-error{{unresolved identifier 'takes_uchar21'}}
takes_short5(short5_value) // expected-error{{unresolved identifier 'takes_short5'}}
takes_ushort6(ushort6_value) // expected-error{{unresolved identifier 'takes_ushort6'}}
takes_int128(int128_value) // expected-error{{unresolved identifier 'takes_int128'}}
takes_uint20(uint20_value) // expected-error{{unresolved identifier 'takes_uint20'}}
| apache-2.0 | 0b2298ec84e7321ddf5e989c254ce359 | 40.050633 | 101 | 0.757323 | 2.822454 | false | false | false | false |
googleads/googleads-mobile-ios-examples | Swift/advanced/APIDemo/APIDemo/AdManagerCustomTargetingViewController.swift | 1 | 2569 | //
// Copyright (C) 2016 Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import GoogleMobileAds
import UIKit
/// AdManager - Custom Targeting
/// Demonstrates adding custom targeting information to a GAMRequest.
class AdManagerCustomTargetingViewController: UIViewController, UIPickerViewDataSource,
UIPickerViewDelegate
{
/// The constant for the customTargeting dictionary sport preference key.
let sportPreferenceKey = "sportpref"
/// The AdManager banner view.
@IBOutlet weak var bannerView: GAMBannerView!
/// The favorite sports view picker.
@IBOutlet weak var favoriteSportsPicker: UIPickerView!
/// The favorite sports options.
var favoriteSportsOptions: [String]!
override func viewDidLoad() {
super.viewDidLoad()
bannerView.adUnitID = Constants.AdManagerCustomTargetingAdUnitID
bannerView.rootViewController = self
favoriteSportsPicker.delegate = self
favoriteSportsPicker.dataSource = self
favoriteSportsOptions = [
"Baseball", "Basketball", "Bobsled", "Football", "Ice Hockey",
"Running", "Skiing", "Snowboarding", "Softball",
]
let favoriteSportsPickerMiddleRow = favoriteSportsOptions.count / 2
favoriteSportsPicker.selectRow(
favoriteSportsPickerMiddleRow, inComponent: 0,
animated: false)
}
// MARK: - UIPickerViewDelegate
func pickerView(
_ pickerView: UIPickerView, titleForRow row: Int,
forComponent component: Int
) -> String? {
return favoriteSportsOptions[row]
}
// MARK: - UIPickerViewDataSource
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return favoriteSportsOptions.count
}
// MARK: - Actions
@IBAction func loadAd(_ sender: AnyObject) {
let row = favoriteSportsPicker.selectedRow(inComponent: 0)
let request = GAMRequest()
request.customTargeting = [sportPreferenceKey: favoriteSportsOptions[row]]
bannerView.load(request)
}
}
| apache-2.0 | e143ce9adbf03b3786022d56cd7b4617 | 30.329268 | 94 | 0.734916 | 4.538869 | false | false | false | false |
skyfe79/SwiftImageProcessing | 01_MakeImageLibrary.playground/Sources/RGBAImage.swift | 1 | 3529 | import UIKit
public struct Pixel {
//각 색상 컴포넌트는 ABGR 순으로 저장되어 있다.
public var value: UInt32
//red
public var R: UInt8 {
get { return UInt8(value & 0xFF); }
set { value = UInt32(newValue) | (value & 0xFFFFFF00) }
}
//green
public var G: UInt8 {
get { return UInt8((value >> 8) & 0xFF) }
set { value = (UInt32(newValue) << 8) | (value & 0xFFFF00FF) }
}
//blue
public var B: UInt8 {
get { return UInt8((value >> 16) & 0xFF) }
set { value = (UInt32(newValue) << 16) | (value & 0xFF00FFFF) }
}
//alpha
public var A: UInt8 {
get { return UInt8((value >> 24) & 0xFF) }
set { value = (UInt32(newValue) << 24) | (value & 0x00FFFFFF) }
}
}
public struct RGBAImage {
class WrappedPixels {
public var pixels: UnsafeMutableBufferPointer<Pixel>
init() {
pixels = UnsafeMutableBufferPointer(start: nil, count: 0)
}
deinit {
pixels.deallocate()
}
}
let wrappedPixels = WrappedPixels()
public var width: Int
public var height: Int
public init?(image: UIImage) {
// CGImage로 변환이 가능해야 한다.
guard let cgImage = image.cgImage else {
return nil
}
// 주소 계산을 위해서 Float을 Int로 저장한다.
width = Int(image.size.width)
height = Int(image.size.height)
// 4 * width * height 크기의 버퍼를 생성한다.
let bytesPerRow = width * 4
let imageData = UnsafeMutablePointer<Pixel>.allocate(capacity: width * height)
//if we don't initialize it, the toUIImage() method will generate extra color.
imageData.initialize(repeating: Pixel(value: 0), count: width*height)
// 색상공간은 Device의 것을 따른다
let colorSpace = CGColorSpaceCreateDeviceRGB()
// BGRA로 비트맵을 만든다
var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue
bitmapInfo = bitmapInfo | CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
// 비트맵 생성
guard let imageContext = CGContext(data: imageData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
return nil
}
// cgImage를 imageData에 채운다.
imageContext.draw(cgImage, in: CGRect(origin: .zero, size: image.size))
wrappedPixels.pixels = UnsafeMutableBufferPointer<Pixel>(start: imageData, count: width * height)
}
public func toUIImage() -> UIImage? {
let colorSpace = CGColorSpaceCreateDeviceRGB()
var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue
let bytesPerRow = width * 4
bitmapInfo |= CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
guard let imageContext = CGContext(data: wrappedPixels.pixels.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo, releaseCallback: nil, releaseInfo: nil) else {
return nil
}
guard let cgImage = imageContext.makeImage() else {
return nil
}
let image = UIImage(cgImage: cgImage)
return image
}
}
| mit | e145f10a1e3135651066ea81822237ee | 32.69 | 249 | 0.601959 | 4.179901 | false | false | false | false |
LawrenceHan/iOS-project-playground | Dice/Dice/DieView.swift | 1 | 13224 | //
// DieView.swift
// Dice
//
// Created by Hanguang on 12/13/15.
// Copyright © 2015 Hanguang. All rights reserved.
//
import Cocoa
@IBDesignable class DieView: NSView, NSPasteboardItemDataProvider, NSDraggingSource {
var intValue: Int? = 5 {
didSet {
needsDisplay = true
}
}
var pressed: Bool = false {
didSet {
needsDisplay = true
}
}
var dieFacePath: NSBezierPath = NSBezierPath()
var mouseDownEvent: NSEvent?
var highlightForDragging: Bool = false {
didSet {
needsDisplay = true
}
}
var rollsRemaining: Int = 0
var color: NSColor = NSColor.whiteColor() {
didSet {
needsDisplay = true
}
}
var numberOfTimesToRoll: Int = 10
override var intrinsicContentSize: NSSize {
return NSSize(width: 20, height: 20)
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
self.registerForDraggedTypes([NSPasteboardTypeString])
}
override func drawRect(dirtyRect: NSRect) {
let backgroundColor = NSColor.lightGrayColor()
backgroundColor.set()
NSBezierPath.fillRect(bounds)
if highlightForDragging {
let gradient = NSGradient(startingColor: color,
endingColor: backgroundColor)!
gradient.drawInRect(bounds, relativeCenterPosition: NSZeroPoint)
}
else {
drawDieWithSize(bounds.size)
}
}
func metricksForSize(size: CGSize) -> (edgeLength: CGFloat, dieFrame: CGRect) {
let edgeLength = min(size.width, size.height)
let padding = edgeLength/10.0
let drawingBounds = CGRect(x: 0, y: 0, width: edgeLength, height: edgeLength)
var dieFrame = drawingBounds.insetBy(dx: padding, dy: padding)
if pressed {
dieFrame = dieFrame.offsetBy(dx: 0, dy: -edgeLength/40)
}
return (edgeLength, dieFrame)
}
func drawDieWithSize(size: CGSize) {
if let intValue = intValue {
let (edgeLength, dieFrame) = metricksForSize(size)
let cornerRadius: CGFloat = edgeLength / 5.0
let dotRadius = edgeLength/12.0
let dotFrame = dieFrame.insetBy(dx: dotRadius * 2.5, dy: dotRadius * 2.5)
NSGraphicsContext.saveGraphicsState()
let shadow = NSShadow()
shadow.shadowOffset = NSSize(width: 0, height: -1)
shadow.shadowBlurRadius = (pressed ? edgeLength/100 : edgeLength/20)
shadow.set()
// Draw the rounded shape of the die profile:
color.set()
dieFacePath = NSBezierPath(roundedRect: dieFrame, xRadius: cornerRadius, yRadius: cornerRadius)
dieFacePath.fill()
// NSColor.cyanColor().set()
// dieFacePath.lineWidth = edgeLength/10
// dieFacePath.stroke()
NSGraphicsContext.restoreGraphicsState()
// Shadow will not apply to subsequent drawing commands
// Draw gradient
// let gradient = NSGradient(startingColor: NSColor.whiteColor(), endingColor: NSColor.yellowColor())!
// gradient.drawInBezierPath(dieFacePath, angle: 90)
// Ready to draw the dots.
// The dot will be black:
NSColor.blackColor().set()
// Nested function to make drawing dots cleaner:
func drawDot(u: CGFloat, _ v: CGFloat) {
let dotOrigin = CGPoint(x: dotFrame.minX + dotFrame.width * u,
y: dotFrame.minY + dotFrame.height * v)
let dotRect = CGRect(origin: dotOrigin, size: CGSizeZero).insetBy(dx: -dotRadius, dy: -dotRadius)
let roundPath = NSBezierPath(ovalInRect: dotRect)
// NSColor.whiteColor().set()
// roundPath.lineWidth = dotRadius/5
// roundPath.stroke()
// let gradient = NSGradient(startingColor: NSColor.blueColor(), endingColor: NSColor.greenColor())!
// gradient.drawInBezierPath(roundPath, angle: -90)
// NSColor.blackColor().set()
roundPath.fill()
}
// If intValue is in range...
if (1...6).indexOf(intValue) != nil {
// Draw the dots:
if [1, 3, 5].indexOf(intValue) != nil {
drawDot(0.5, 0.5) // Center dot
}
if (2...6).indexOf(intValue) != nil {
drawDot(0, 1) // Upper left
drawDot(1, 0) // Lower right
}
if (4...6).indexOf(intValue) != nil {
drawDot(1, 1) // Upper right
drawDot(0, 0) // Lower left
}
if intValue == 6 {
drawDot(0, 0.5) // Mid left/right
drawDot(1, 0.5)
}
}
else {
let paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
paraStyle.alignment = .Center
let font = NSFont.systemFontOfSize(edgeLength * 0.5)
let attrs = [NSForegroundColorAttributeName: NSColor.blackColor(),
NSFontAttributeName: font,
NSParagraphStyleAttributeName: paraStyle]
let string = "\(intValue)" as NSString
string.drawCenteredInRect(dieFrame, attributes: attrs)
}
}
}
// MARK: - Private method
func roll() {
rollsRemaining = 10
NSTimer.scheduledTimerWithTimeInterval(0.15,
target: self,
selector: Selector("rollTick:"),
userInfo: nil,
repeats: true)
window?.makeFirstResponder(nil)
}
func rollTick(sender: NSTimer) {
let lastIntValue = intValue
while intValue == lastIntValue {
randomize()
}
rollsRemaining--
if rollsRemaining == 0 {
sender.invalidate()
window?.makeFirstResponder(self)
}
}
func randomize() {
intValue = Int(arc4random_uniform(5)) + 1
}
@IBAction func savePDF(sender: AnyObject!) {
let savePanel = NSSavePanel()
savePanel.allowedFileTypes = ["pdf"]
savePanel.beginSheetModalForWindow(window!) {
[unowned savePanel] (result) -> Void in
if result == NSModalResponseOK {
let data = self.dataWithPDFInsideRect(self.bounds)
do {
try data.writeToURL(savePanel.URL!, options: NSDataWritingOptions.DataWritingAtomic)
} catch let error as NSError {
let alert = NSAlert(error: error)
alert.runModal()
} catch {
fatalError("unknown error")
}
}
}
}
// MARK: - Pasteboard
func writeToPasteboad(pasteboard: NSPasteboard) {
if let intValue = intValue {
pasteboard.clearContents()
let item = NSPasteboardItem()
item.setDataProvider(self, forTypes: [NSPasteboardTypePDF])
pasteboard.writeObjects(["\(intValue)", item])
}
}
func readFromPasteboard(pasteboard: NSPasteboard) -> Bool {
let objects = pasteboard.readObjectsForClasses([NSString.self], options: [:]) as! [String]
if let str = objects.first {
intValue = Int(str)
return true
}
return false
}
@IBAction func cut(sender: AnyObject?) {
writeToPasteboad(NSPasteboard.generalPasteboard())
intValue = nil
}
@IBAction func copy(sender: AnyObject?) {
writeToPasteboad(NSPasteboard.generalPasteboard())
}
@IBAction func paste(sender: AnyObject?) {
readFromPasteboard(NSPasteboard.generalPasteboard())
}
// MARK: - Pasteboard delegate
func pasteboard(pasteboard: NSPasteboard?, item: NSPasteboardItem, provideDataForType type: String) {
if type == NSPasteboardTypePDF {
let data = self.dataWithPDFInsideRect(self.bounds)
item.setData(data, forType: NSPasteboardTypePDF)
}
}
// MARK: - Mouse Events
override func mouseDown(theEvent: NSEvent) {
Swift.print("mouseDown")
mouseDownEvent = theEvent
let pointInView = convertPoint(theEvent.locationInWindow, fromView: nil)
pressed = dieFacePath.containsPoint(pointInView)
}
override func mouseDragged(theEvent: NSEvent) {
Swift.print("mouseDragged location: \(theEvent.locationInWindow)")
let downPoint = mouseDownEvent!.locationInWindow
let dragPoint = theEvent.locationInWindow
let distanceDragged = hypot(downPoint.x - dragPoint.x, downPoint.y - dragPoint.y)
if distanceDragged < 3 {
return
}
pressed = false
if let intValue = intValue {
let imageSize = bounds.size
let image = NSImage(size: imageSize, flipped: false, drawingHandler: { (imageBounds) -> Bool in
self.drawDieWithSize(imageBounds.size)
return true
})
let draggingFrameOrigin = convertPoint(downPoint, fromView: nil)
let draggingFrame = NSRect(origin: draggingFrameOrigin, size: imageSize)
.insetBy(dx: -imageSize.width, dy: -imageSize.height/2)
let item = NSDraggingItem(pasteboardWriter: "\(intValue)")
item.draggingFrame = draggingFrame
item.imageComponentsProvider = {
let component = NSDraggingImageComponent(key: NSDraggingImageComponentIconKey)
component.contents = image
component.frame = NSRect(origin: NSPoint(), size: imageSize)
return [component]
}
beginDraggingSessionWithItems([item], event: mouseDownEvent!, source: self)
}
}
override func mouseUp(theEvent: NSEvent) {
Swift.print("mouseUp clickCount: \(theEvent.clickCount)")
if theEvent.clickCount == 2 && pressed {
roll()
}
pressed = false
}
// MARK: - First Responder
override var acceptsFirstResponder: Bool { return true }
override func becomeFirstResponder() -> Bool {
return true
}
override func resignFirstResponder() -> Bool {
return true
}
override func drawFocusRingMask() {
NSBezierPath.fillRect(bounds)
}
override var focusRingMaskBounds: NSRect {
return bounds
}
// MARK: - Keyboard Events
override func keyDown(theEvent: NSEvent) {
interpretKeyEvents([theEvent])
}
override func insertText(insertString: AnyObject) {
let text = insertString as! String
if let number = Int(text) {
intValue = number
}
}
override func insertTab(sender: AnyObject?) {
window?.selectNextKeyView(sender)
}
override func insertBacktab(sender: AnyObject?) {
window?.selectPreviousKeyView(sender)
}
// MARK: - Drag Source
func draggingSession(session: NSDraggingSession, sourceOperationMaskForDraggingContext context: NSDraggingContext)
-> NSDragOperation {
return [.Copy, .Delete]
}
func draggingSession(session: NSDraggingSession, endedAtPoint screenPoint: NSPoint, operation: NSDragOperation) {
if operation == .Delete {
intValue = nil
}
}
// MARK: - Drag Destination
override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation {
if sender.draggingSource() === self {
return .None
}
highlightForDragging = true
return sender.draggingSourceOperationMask()
}
override func draggingUpdated(sender: NSDraggingInfo) -> NSDragOperation {
Swift.print("operation mask = \(sender.draggingSourceOperationMask().rawValue)")
if sender.draggingSource() === self {
return .None
}
return [.Copy, .Delete]
}
override func draggingExited(sender: NSDraggingInfo?) {
highlightForDragging = false
}
override func prepareForDragOperation(sender: NSDraggingInfo) -> Bool {
return true
}
override func performDragOperation(sender: NSDraggingInfo) -> Bool {
let ok = readFromPasteboard(sender.draggingPasteboard())
return ok
}
override func concludeDragOperation(sender: NSDraggingInfo?) {
highlightForDragging = false
}
}
| mit | 5618803df48facfce1f23d6d0c0475ab | 32.560914 | 118 | 0.569009 | 5.139137 | false | false | false | false |
wyz5120/DrinkClock | DrinkClock/DrinkClock/Classes/TitleSwitchView.swift | 1 | 3498 | //
// TitleSwitchView.swift
// DrinkClock
//
// Created by wyz on 16/4/18.
// Copyright © 2016年 wyz. All rights reserved.
//
import UIKit
let TitleSwitchViewDidClickButtonNotifacation = "TitleSwitchViewDidClickButtonNotifacation"
class TitleSwitchView: UIView {
private var selectButton: UIButton?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.blackColor()
layer.cornerRadius = 18
layer.masksToBounds = true
addSubview(indicatorView)
addSubview(leftButton)
addSubview(rightButton)
indicatorView.snp_makeConstraints { (make) in
make.edges.equalTo(leftButton).inset(4)
}
leftButton.snp_makeConstraints { (make) in
make.left.top.bottom.equalTo(self)
make.right.equalTo(rightButton.snp_left)
make.width.equalTo(rightButton)
}
rightButton.snp_makeConstraints { (make) in
make.right.top.bottom.equalTo(self)
make.left.equalTo(leftButton.snp_right)
make.width.equalTo(leftButton)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - 懒加载
private lazy var leftButton: UIButton = {
let button = UIButton()
button.setTitle("时间", forState: UIControlState.Normal)
button.titleLabel?.font = UIFont(name: "GloberSemiBold", size: 15)
button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Disabled)
button.backgroundColor = UIColor.clearColor()
button.addTarget(self, action: #selector(TitleSwitchView.buttonAction), forControlEvents: UIControlEvents.TouchUpInside)
self.selectButton = button
button.enabled = false
button.tag = 101
return button
}()
private lazy var rightButton: UIButton = {
let button = UIButton()
button.setTitle("提醒", forState: UIControlState.Normal)
button.titleLabel?.font = UIFont(name: "GloberSemiBold", size: 15)
button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Disabled)
button.backgroundColor = UIColor.clearColor()
button.addTarget(self, action: #selector(TitleSwitchView.buttonAction), forControlEvents: UIControlEvents.TouchUpInside)
button.tag = 102
return button
}()
private lazy var indicatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.whiteColor()
view.layer.cornerRadius = 14
view.layer.masksToBounds = true
return view
}()
func buttonAction(button:UIButton) {
button.enabled = false
indicatorView.snp_remakeConstraints { (make) in
make.edges.equalTo(button).inset(4)
}
UIView.animateWithDuration(0.3, animations: {
self.layoutIfNeeded()
}) { (_) in
self.selectButton?.enabled = true
self.selectButton = button
}
NSNotificationCenter.defaultCenter().postNotificationName(TitleSwitchViewDidClickButtonNotifacation, object: self, userInfo: ["buttonTag":button.tag])
}
}
| mit | 074dbf92ad0be74cfe49c0aa51b401b7 | 32.796117 | 158 | 0.636886 | 4.965763 | false | false | false | false |
alexwillrock/PocketRocketNews | PocketRocketNews/Classes/UserStory/BaseModule/View/BaseViewController.swift | 1 | 1802 | //
// BaseViewController.swift
// PocketRocketNews
//
// Created by Алексей on 16.03.17.
// Copyright © 2017 Алексей. All rights reserved.
//
import UIKit
import Reusable
class BaseViewController: UIViewController {
var emptyView: EmptyView{
let frame = CGRect(x: 0, y: 0, width: 240, height: 240)
let _emptyview = EmptyView(frame: frame)
_emptyview.center = self.view.center
_emptyview.isHidden = true
return _emptyview;
}
var activityView: UIActivityIndicatorView {
let _activityView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
_activityView.center = self.view.center
_activityView.isHidden = true
return _activityView
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(emptyView)
self.view.addSubview(activityView)
}
}
extension BaseViewController: BaseViewControllerProtocol{
func didDismissEmptyView() {
self.emptyView.isHidden = true
}
func didShowError(message: String){
let alert = UIAlertController(title: "Ошибка", message: message, preferredStyle: .alert)
let cancell = UIAlertAction(title: "OK", style: .default) { (action) in
alert.dismiss(animated: true, completion: nil)
}
alert.addAction(cancell)
self.present(alert, animated: true, completion: nil)
}
func didShowEmptyView(){
self.emptyView.isHidden = false
}
func didShowActivityView() {
self.activityView.stopAnimating()
self.activityView.isHidden = true
}
func didDismissActivityView() {
self.activityView.startAnimating()
self.activityView.isHidden = false
}
}
| mit | 8e07b539e2b6d77c4065541fb486950a | 25.58209 | 96 | 0.64402 | 4.625974 | false | false | false | false |
zarochintsev/MotivationBox | Pods/Swinject/Sources/DebugHelper.swift | 1 | 1815 | //
// DebugHelper.swift
// Swinject
//
// Created by Jakub Vaňo on 26/09/16.
// Copyright © 2016 Swinject Contributors. All rights reserved.
//
internal protocol DebugHelper {
func resolutionFailed<Service>(
serviceType: Service.Type,
key: ServiceKey,
availableRegistrations: [ServiceKey: ServiceEntryProtocol]
)
}
internal final class LoggingDebugHelper: DebugHelper {
func resolutionFailed<Service>(
serviceType: Service.Type,
key: ServiceKey,
availableRegistrations: [ServiceKey: ServiceEntryProtocol]
) {
var output = [
"Swinject: Resolution failed. Expected registration:",
"\t{ \(description(serviceType: serviceType, serviceKey: key)) }",
"Available registrations:"
]
output += availableRegistrations
.filter { $0.1 is ServiceEntry<Service> }
.map { "\t{ " + $0.1.describeWithKey($0.0) + " }" }
Container.log(output.joined(separator: "\n"))
}
}
internal func description<Service>(
serviceType: Service.Type,
serviceKey: ServiceKey,
objectScope: ObjectScopeProtocol? = nil,
initCompleted: FunctionType? = nil
) -> String {
// The protocol order in "protocol<>" is non-deterministic.
let nameDescription = serviceKey.name.map { ", Name: \"\($0)\"" } ?? ""
let optionDescription = serviceKey.option.map { ", \($0)" } ?? ""
let initCompletedDescription = initCompleted.map { _ in ", InitCompleted: Specified" } ?? ""
let objectScopeDescription = objectScope.map { ", ObjectScope: \($0)" } ?? ""
return "Service: \(serviceType)"
+ nameDescription
+ optionDescription
+ ", Factory: \(serviceKey.factoryType)"
+ objectScopeDescription
+ initCompletedDescription
}
| mit | 4313c71b588f7c9055e26cf6d419a00c | 32.574074 | 96 | 0.633756 | 4.487624 | false | false | false | false |
airspeedswift/swift | test/IRGen/prespecialized-metadata/struct-inmodule-2argument-within-class-1argument-1distinct_use.swift | 3 | 4416 | // 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: @"$s4main9NamespaceC5ValueVySS_SiSdGWV" = linkonce_odr hidden constant %swift.vwtable {
// CHECK-SAME: i8* bitcast ({{(%swift.opaque\* \(\[[0-9]+ x i8\]\*, \[[0-9]+ x i8\]\*, %swift.type\*\)\* @"\$[a-zA-Z0-9_]+" to i8\*|[^@]+@__swift_memcpy[^[:space:]]+ to i8\*)}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@__swift_noop_void_return{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]+ to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]+ to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]+ to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]+ to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main9NamespaceC5ValueVySS_SiSdGwet{{[^@]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main9NamespaceC5ValueVySS_SiSdGwst{{[^@]+}} to i8*),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}}
// CHECK-SAME: },
// NOTE: ignore the COMDAT on PE/COFF platforms
// CHECK-SAME: align [[ALIGNMENT]]
// CHECK: @"$s4main9NamespaceC5ValueVySS_SiSdGMf" = linkonce_odr hidden constant {{.+}}$s4main9NamespaceC5ValueVMn{{.+}} to %swift.type_descriptor*), %swift.type* @"$sSSN", %swift.type* @"$sSiN", %swift.type* @"$sSdN", i32 0, i32 8, i64 3 }>, align [[ALIGNMENT]]
final class Namespace<Arg> {
struct Value<First, Second> {
let first: First
let second: Second
}
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main9NamespaceC5ValueVySS_SiSdGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: }
func doit() {
consume( Namespace<String>.Value(first: 13, second: 13.0) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceC5ValueVMa"([[INT]] %0, %swift.type* %1, %swift.type* %2, %swift.type* %3) #{{[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: [[ERASED_TYPE_3:%[0-9]+]] = bitcast %swift.type* %3 to i8*
// CHECK: br label %[[TYPE_COMPARISON_1:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_1]]:
// CHECK: [[EQUAL_TYPE_1_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSSN" to i8*), [[ERASED_TYPE_1]]
// CHECK: [[EQUAL_TYPES_1_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_1_1]]
// CHECK: [[EQUAL_TYPE_1_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_2]]
// CHECK: [[EQUAL_TYPES_1_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_1]], [[EQUAL_TYPE_1_2]]
// CHECK: [[EQUAL_TYPE_1_3:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSdN" to i8*), [[ERASED_TYPE_3]]
// CHECK: [[EQUAL_TYPES_1_3:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_2]], [[EQUAL_TYPE_1_3]]
// CHECK: br i1 [[EQUAL_TYPES_1_3]], label %[[EXIT_PRESPECIALIZED_1:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED_1]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main9NamespaceC5ValueVySS_SiSdGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE_1]], i8* [[ERASED_TYPE_2]], i8* [[ERASED_TYPE_3]], %swift.type_descriptor* bitcast ({{.+}}$s4main9NamespaceC5ValueVMn{{.+}} to %swift.type_descriptor*)) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | ede0e6470769a28dfcd6ac1752803876 | 64.910448 | 362 | 0.598053 | 2.886275 | false | false | false | false |
PerfectServers/APIDocumentationServer | Sources/APIDocumentationServer/Handlers/user/userDelete.swift | 1 | 1275 | //
// userDelete.swift
// ServerMonitor
//
// Created by Jonathan Guthrie on 2017-04-30.
//
//
import SwiftMoment
import PerfectHTTP
import PerfectLogger
import LocalAuthentication
extension WebHandlers {
static func userDelete(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
if (request.session?.userid ?? "").isEmpty { response.completed(status: .notAcceptable) }
let user = Account()
if let id = request.urlVariables["id"] {
try? user.get(id)
// cannot delete yourself
if user.id == (request.session?.userid ?? "") {
errorJSON(request, response, msg: "You cannot delete yourself.")
return
}
let usersCount = Account()
try? usersCount.findAll()
if usersCount.results.cursorData.totalRecords <= 1 {
errorJSON(request, response, msg: "You cannot delete yourself.")
return
}
if user.id.isEmpty {
errorJSON(request, response, msg: "Invalid User")
} else {
try? user.delete()
}
}
response.setHeader(.contentType, value: "application/json")
var resp = [String: Any]()
resp["error"] = "None"
do {
try response.setBody(json: resp)
} catch {
print("error setBody: \(error)")
}
response.completed()
return
}
}
}
| apache-2.0 | 2af8a1049364c808759a64d0314f0a82 | 19.901639 | 92 | 0.644706 | 3.474114 | false | false | false | false |
russbishop/swift | test/attr/attr_autoclosure.swift | 1 | 4692 | // RUN: %target-parse-verify-swift
// Simple case.
var fn : @autoclosure () -> Int = 4 // expected-error {{@autoclosure may only be used on parameters}} expected-error {{cannot convert value of type 'Int' to specified type '@noescape () -> Int'}}
@autoclosure func func1() {} // expected-error {{@autoclosure may only be used on 'parameter' declarations}}
func func1a(_ v1 : @autoclosure Int) {} // expected-error {{@autoclosure attribute only applies to function types}}
func func2(_ fp : @autoclosure () -> Int) { func2(4)}
func func3(fp fpx : @autoclosure () -> Int) {func3(fp: 0)}
func func4(fp : @autoclosure () -> Int) {func4(fp: 0)}
func func6(_: @autoclosure () -> Int) {func6(0)}
// multi attributes
func func7(_: @autoclosure @noreturn () -> Int) {func7(0)}
// autoclosure + inout don't make sense.
func func8(_ x: inout @autoclosure () -> Bool) -> Bool { // expected-error {{@autoclosure may only be used on parameters}}
}
// <rdar://problem/19707366> QoI: @autoclosure declaration change fixit
let migrate4 : (@autoclosure() -> ()) -> ()
struct SomeStruct {
@autoclosure let property : () -> Int // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{3-16=}}
init() {
}
}
class BaseClass {
@autoclosure var property : () -> Int // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{3-16=}}
init() {}
}
class DerivedClass {
var property : () -> Int { get {} set {} }
}
protocol P1 {
associatedtype Element
}
protocol P2 : P1 {
associatedtype Element
}
func overloadedEach<O: P1>(_ source: O, _ closure: () -> ()) {
}
func overloadedEach<P: P2>(_ source: P, _ closure: () -> ()) {
}
struct S : P2 {
typealias Element = Int
func each(_ closure: @autoclosure () -> ()) {
overloadedEach(self, closure) // expected-error {{invalid conversion from non-escaping function of type '@autoclosure () -> ()' to potentially escaping function type '() -> ()'}}
}
}
struct AutoclosureEscapeTest {
@autoclosure let delayed: () -> Int // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{3-16=}}
}
// @autoclosure(escaping)
// expected-error @+1 {{@autoclosure is now an attribute on a parameter type, instead of on the parameter itself}} {{13-34=}} {{38-38=@autoclosure(escaping) }}
func func10(@autoclosure(escaping _: () -> ()) { } // expected-error{{expected ')' in @autoclosure}}
// expected-note@-1{{to match this opening '('}}
func func11(_: @autoclosure(escaping) @noescape () -> ()) { } // expected-error{{@noescape conflicts with @autoclosure(escaping)}}
class Super {
func f1(_ x: @autoclosure(escaping) () -> ()) { }
func f2(_ x: @autoclosure(escaping) () -> ()) { } // expected-note {{potential overridden instance method 'f2' here}}
func f3(x: @autoclosure () -> ()) { }
}
class Sub : Super {
override func f1(_ x: @autoclosure(escaping)() -> ()) { }
override func f2(_ x: @autoclosure () -> ()) { } // expected-error{{does not override any method}}
override func f3(_ x: @autoclosure(escaping) () -> ()) { } // expected-error{{does not override any method}}
}
func func12_sink(_ x: () -> Int) { }
func func12a(_ x: @autoclosure () -> Int) {
func12_sink(x) // expected-error{{invalid conversion from non-escaping function of type '@autoclosure () -> Int' to potentially escaping function type '() -> Int'}}
}
func func12b(_ x: @autoclosure(escaping) () -> Int) {
func12_sink(x)
}
class TestFunc12 {
var x: Int = 5
func foo() -> Int { return 0 }
func test() {
func12a(x + foo()) // okay
func12b(x + foo())
// expected-error@-1{{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{13-13=self.}}
// expected-error@-2{{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{17-17=self.}}
}
}
enum AutoclosureFailableOf<T> {
case Success(@autoclosure () -> T) // expected-error {{@autoclosure may only be used on parameters}}
case Failure()
}
let _ : (@autoclosure () -> ()) -> ()
let _ : (@autoclosure(escaping) () -> ()) -> ()
// escaping is the name of param type
let _ : (@autoclosure(escaping) -> ()) -> () // expected-error {{use of undeclared type 'escaping'}}
// Migration
// expected-error @+1 {{@autoclosure is now an attribute on a parameter type, instead of on the parameter itself}} {{16-28=}} {{32-32=@autoclosure }}
func migrateAC(@autoclosure _: () -> ()) { }
// expected-error @+1 {{@autoclosure is now an attribute on a parameter type, instead of on the parameter itself}} {{17-39=}} {{43-43=@autoclosure(escaping) }}
func migrateACE(@autoclosure(escaping) _: () -> ()) { }
| apache-2.0 | b28d0dc590e45cf5db49717757bf65a3 | 34.816794 | 197 | 0.642157 | 3.677116 | false | false | false | false |
carabina/string-in-chain | Example/Tests/Tests.swift | 1 | 1180 | // https://github.com/Quick/Quick
import Quick
import Nimble
import StringInChain
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | da62b4c4f9cf0f94193ce5973bf64e5c | 22.48 | 63 | 0.365417 | 5.460465 | false | false | false | false |
laurentVeliscek/AudioKit | AudioKit/Common/Playgrounds/Analysis.playground/Pages/FFT Analysis.xcplaygroundpage/Contents.swift | 2 | 503 | //: ## FFT Analysis
//:
import XCPlayground
import AudioKit
let bundle = NSBundle.mainBundle()
let file = try AKAudioFile(readFileName: "leadloop.wav", baseDir: .Resources)
var player = try AKAudioPlayer(file: file)
player.looping = true
AudioKit.output = player
AudioKit.start()
player.play()
let fft = AKFFTTap(player)
AKPlaygroundLoop(every: 0.1) {
let max = fft.fftData.maxElement()!
let index = fft.fftData.indexOf(max)
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
| mit | 7f3fab57baff24f23bfffc447016138d | 19.958333 | 77 | 0.745527 | 3.753731 | false | false | false | false |
everlof/Various-Demos-iOS | VariousDemos/VariousDemos/AutoResizingMasksChildViewController.swift | 1 | 2228 | //
// AutoResizingMasksChildViewController.swift
// VariousDemos
//
// Created by David Everlöf on 29/05/16.
// Copyright © 2016 The Yelllow Ampersand. All rights reserved.
//
import UIKit
class AutoResizingMasksChildViewController: UIViewController {
var index = 0
var sampleView = UIView()
var sampleLabel = UILabel()
var resizing: UIViewAutoresizing!
var descLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
/* Main view */
view.backgroundColor = UIColor.lightGrayColor()
/* Describes this specific autoResizingMask */
descLabel.font = UIFont.systemFontOfSize(16.0)
descLabel.textAlignment = .Center
descLabel.numberOfLines = 0
/* Lable, contained in sample view */
sampleLabel.text = "Foo, Bar"
sampleLabel.sizeToFit()
sampleLabel.backgroundColor = UIColor.yellowColor().colorWithAlphaComponent(0.5)
sampleLabel.autoresizingMask = resizing // [ .FlexibleWidth, .FlexibleHeight ]
/* Sample view, animates */
sampleView.backgroundColor = UIColor.redColor()
sampleView.addSubview(sampleLabel)
view.addSubview(sampleView)
view.addSubview(descLabel)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UIView.animateKeyframesWithDuration(2, delay: 0, options: [ .Autoreverse, .Repeat ], animations: {
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.5, animations: {
self.sampleView.transform = CGAffineTransformMakeScale(0.25, 0.25)
})
UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.5, animations: {
self.sampleView.transform = CGAffineTransformIdentity
})
}, completion: nil)
}
override func viewDidLayoutSubviews() {
sampleView.frame = CGRectMake(0, 0, 200, 200)
sampleView.center = self.view.center
descLabel.sizeToFit()
descLabel.frame = CGRectMake(0, 0, view.frame.size.width, descLabel.frame.size.height)
}
}
| mit | 7b8a7609c0b05f9b7ce2747e48f1547a | 31.26087 | 106 | 0.636568 | 5.024831 | false | false | false | false |
gregomni/swift | benchmark/single-source/DropWhile.swift | 10 | 7078 | //===--- DropWhile.swift --------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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
//
//===----------------------------------------------------------------------===//
////////////////////////////////////////////////////////////////////////////////
// WARNING: This file is manually generated from .gyb template and should not
// be directly modified. Instead, make changes to DropWhile.swift.gyb and run
// scripts/generate_harness/generate_harness.py to regenerate this file.
////////////////////////////////////////////////////////////////////////////////
import TestsUtils
let sequenceCount = 4096
let dropCount = 1024
let suffixCount = sequenceCount - dropCount
let sumCount = suffixCount * (2 * sequenceCount - suffixCount - 1) / 2
let array: [Int] = Array(0..<sequenceCount)
public let benchmarks = [
BenchmarkInfo(
name: "DropWhileCountableRange",
runFunction: run_DropWhileCountableRange,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileSequence",
runFunction: run_DropWhileSequence,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnySequence",
runFunction: run_DropWhileAnySequence,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnySeqCntRange",
runFunction: run_DropWhileAnySeqCntRange,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnySeqCRangeIter",
runFunction: run_DropWhileAnySeqCRangeIter,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnyCollection",
runFunction: run_DropWhileAnyCollection,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileArray",
runFunction: run_DropWhileArray,
tags: [.validation, .api, .Array],
setUpFunction: { blackHole(array) }),
BenchmarkInfo(
name: "DropWhileCountableRangeLazy",
runFunction: run_DropWhileCountableRangeLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileSequenceLazy",
runFunction: run_DropWhileSequenceLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnySequenceLazy",
runFunction: run_DropWhileAnySequenceLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnySeqCntRangeLazy",
runFunction: run_DropWhileAnySeqCntRangeLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnySeqCRangeIterLazy",
runFunction: run_DropWhileAnySeqCRangeIterLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnyCollectionLazy",
runFunction: run_DropWhileAnyCollectionLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileArrayLazy",
runFunction: run_DropWhileArrayLazy,
tags: [.validation, .api, .Array],
setUpFunction: { blackHole(array) }),
]
@inline(never)
public func run_DropWhileCountableRange(_ n: Int) {
let s = 0..<sequenceCount
for _ in 1...20*n {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropWhileSequence(_ n: Int) {
let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }
for _ in 1...20*n {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnySequence(_ n: Int) {
let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })
for _ in 1...20*n {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnySeqCntRange(_ n: Int) {
let s = AnySequence(0..<sequenceCount)
for _ in 1...20*n {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnySeqCRangeIter(_ n: Int) {
let s = AnySequence((0..<sequenceCount).makeIterator())
for _ in 1...20*n {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnyCollection(_ n: Int) {
let s = AnyCollection(0..<sequenceCount)
for _ in 1...20*n {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropWhileArray(_ n: Int) {
let s = array
for _ in 1...20*n {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropWhileCountableRangeLazy(_ n: Int) {
let s = (0..<sequenceCount).lazy
for _ in 1...20*n {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropWhileSequenceLazy(_ n: Int) {
let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy
for _ in 1...20*n {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnySequenceLazy(_ n: Int) {
let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy
for _ in 1...20*n {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnySeqCntRangeLazy(_ n: Int) {
let s = (AnySequence(0..<sequenceCount)).lazy
for _ in 1...20*n {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnySeqCRangeIterLazy(_ n: Int) {
let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy
for _ in 1...20*n {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnyCollectionLazy(_ n: Int) {
let s = (AnyCollection(0..<sequenceCount)).lazy
for _ in 1...20*n {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropWhileArrayLazy(_ n: Int) {
let s = (array).lazy
for _ in 1...20*n {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
check(result == sumCount)
}
}
// Local Variables:
// eval: (read-only-mode 1)
// End:
| apache-2.0 | 0f21b1df7952bd720dd4d83a419125eb | 27.889796 | 91 | 0.619101 | 3.969714 | false | false | false | false |
jfrowies/coolblue | coolblue/AppDelegate.swift | 1 | 6910 | //
// AppDelegate.swift
// coolblue
//
// Created by Fer Rowies on 3/24/16.
// Copyright © 2016 Fernando Rowies. All rights reserved.
//
import UIKit
import CoreData
import AlamofireNetworkActivityIndicator
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let articlesFeedViewController = storyboard.instantiateViewControllerWithIdentifier("ArticlesFeedViewController") as! ArticlesFeedViewController
articlesFeedViewController.viewModel = ArticlesFeedViewModel(articlesFeedService: AlamofireArticlesService(), imageDownloader: AlamofireImageDownloader())
let initialNavigationController = UINavigationController(rootViewController: articlesFeedViewController)
self.window?.rootViewController = initialNavigationController
self.window?.makeKeyAndVisible()
NetworkActivityIndicatorManager.sharedManager.isEnabled = true
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.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.rowiesfer.coolblue" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("coolblue", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 98e5d6581ec80755dd3b347e97cb309b | 54.717742 | 291 | 0.726444 | 6.013055 | false | false | false | false |
gregomni/swift | test/decl/protocol/special/JSExport.swift | 2 | 1013 | // RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=on -requirement-machine-inferred-signatures=on
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/abi %s -emit-ir -requirement-machine-protocol-signatures=on -requirement-machine-inferred-signatures=on | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
@objc protocol JSExport { }
@objc protocol RootJSExport : JSExport { }
// CHECK: @_PROTOCOL_PROTOCOLS__TtP8JSExport4Sub1_ = weak hidden constant{{.*}}_PROTOCOL__TtP8JSExport8JSExport_{{.*}}_PROTOCOL__TtP8JSExport12RootJSExport_
@objc protocol Sub1 : JSExport, RootJSExport { }
// CHECK: @_PROTOCOL_PROTOCOLS__TtP8JSExport4Sub2_{{.*}}_PROTOCOL__TtP8JSExport4Sub1_{{.*}}_PROTOCOL__TtP8JSExport8JSExport_
@objc protocol Sub2 : Sub1, JSExport { }
// CHECK: @_PROTOCOL_PROTOCOLS__TtP8JSExport4Sub3_ = weak hidden constant{{.*}}@_PROTOCOL__TtP8JSExport4Sub2_
@objc protocol Sub3 : Sub2 { }
protocol ReexportJSExport : RootJSExport, JSExport { }
| apache-2.0 | e3c599d955563874bbbc813f58910425 | 47.238095 | 194 | 0.754195 | 3.630824 | false | false | false | false |
thomasvl/swift-protobuf | Sources/SwiftProtobufCore/Google_Protobuf_Value+Extensions.swift | 2 | 5556 | // Sources/SwiftProtobuf/Google_Protobuf_Value+Extensions.swift - Value extensions
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Value is a well-known message type that can be used to parse or encode
/// arbitrary JSON without a predefined schema.
///
// -----------------------------------------------------------------------------
extension Google_Protobuf_Value: ExpressibleByIntegerLiteral {
public typealias IntegerLiteralType = Int64
/// Creates a new `Google_Protobuf_Value` from an integer literal.
public init(integerLiteral value: Int64) {
self.init(kind: .numberValue(Double(value)))
}
}
extension Google_Protobuf_Value: ExpressibleByFloatLiteral {
public typealias FloatLiteralType = Double
/// Creates a new `Google_Protobuf_Value` from a floating point literal.
public init(floatLiteral value: Double) {
self.init(kind: .numberValue(value))
}
}
extension Google_Protobuf_Value: ExpressibleByBooleanLiteral {
public typealias BooleanLiteralType = Bool
/// Creates a new `Google_Protobuf_Value` from a boolean literal.
public init(booleanLiteral value: Bool) {
self.init(kind: .boolValue(value))
}
}
extension Google_Protobuf_Value: ExpressibleByStringLiteral {
public typealias StringLiteralType = String
public typealias ExtendedGraphemeClusterLiteralType = String
public typealias UnicodeScalarLiteralType = String
/// Creates a new `Google_Protobuf_Value` from a string literal.
public init(stringLiteral value: String) {
self.init(kind: .stringValue(value))
}
/// Creates a new `Google_Protobuf_Value` from a Unicode scalar literal.
public init(unicodeScalarLiteral value: String) {
self.init(kind: .stringValue(value))
}
/// Creates a new `Google_Protobuf_Value` from a character literal.
public init(extendedGraphemeClusterLiteral value: String) {
self.init(kind: .stringValue(value))
}
}
extension Google_Protobuf_Value: ExpressibleByNilLiteral {
/// Creates a new `Google_Protobuf_Value` from the nil literal.
public init(nilLiteral: ()) {
self.init(kind: .nullValue(.nullValue))
}
}
extension Google_Protobuf_Value: _CustomJSONCodable {
internal func encodedJSONString(options: JSONEncodingOptions) throws -> String {
var jsonEncoder = JSONEncoder()
try serializeJSONValue(to: &jsonEncoder, options: options)
return jsonEncoder.stringResult
}
internal mutating func decodeJSON(from decoder: inout JSONDecoder) throws {
let c = try decoder.scanner.peekOneCharacter()
switch c {
case "n":
if !decoder.scanner.skipOptionalNull() {
throw JSONDecodingError.failure
}
kind = .nullValue(.nullValue)
case "[":
var l = Google_Protobuf_ListValue()
try l.decodeJSON(from: &decoder)
kind = .listValue(l)
case "{":
var s = Google_Protobuf_Struct()
try s.decodeJSON(from: &decoder)
kind = .structValue(s)
case "t", "f":
let b = try decoder.scanner.nextBool()
kind = .boolValue(b)
case "\"":
let s = try decoder.scanner.nextQuotedString()
kind = .stringValue(s)
default:
let d = try decoder.scanner.nextDouble()
kind = .numberValue(d)
}
}
internal static func decodedFromJSONNull() -> Google_Protobuf_Value? {
return Google_Protobuf_Value(kind: .nullValue(.nullValue))
}
}
extension Google_Protobuf_Value {
/// Creates a new `Google_Protobuf_Value` with the given kind.
fileprivate init(kind: OneOf_Kind) {
self.init()
self.kind = kind
}
/// Creates a new `Google_Protobuf_Value` whose `kind` is `numberValue` with
/// the given floating-point value.
public init(numberValue: Double) {
self.init(kind: .numberValue(numberValue))
}
/// Creates a new `Google_Protobuf_Value` whose `kind` is `stringValue` with
/// the given string value.
public init(stringValue: String) {
self.init(kind: .stringValue(stringValue))
}
/// Creates a new `Google_Protobuf_Value` whose `kind` is `boolValue` with the
/// given boolean value.
public init(boolValue: Bool) {
self.init(kind: .boolValue(boolValue))
}
/// Creates a new `Google_Protobuf_Value` whose `kind` is `structValue` with
/// the given `Google_Protobuf_Struct` value.
public init(structValue: Google_Protobuf_Struct) {
self.init(kind: .structValue(structValue))
}
/// Creates a new `Google_Protobuf_Value` whose `kind` is `listValue` with the
/// given `Google_Struct_ListValue` value.
public init(listValue: Google_Protobuf_ListValue) {
self.init(kind: .listValue(listValue))
}
/// Writes out the JSON representation of the value to the given encoder.
internal func serializeJSONValue(
to encoder: inout JSONEncoder,
options: JSONEncodingOptions
) throws {
switch kind {
case .nullValue?: encoder.putNullValue()
case .numberValue(let v)?: encoder.putDoubleValue(value: v)
case .stringValue(let v)?: encoder.putStringValue(value: v)
case .boolValue(let v)?: encoder.putNonQuotedBoolValue(value: v)
case .structValue(let v)?: encoder.append(text: try v.jsonString(options: options))
case .listValue(let v)?: encoder.append(text: try v.jsonString(options: options))
case nil: throw JSONEncodingError.missingValue
}
}
}
| apache-2.0 | 1dd603183eb23c553fd67804afdfe584 | 33.08589 | 87 | 0.688985 | 4.296984 | false | false | false | false |
lennet/proNotes | app/proNotes/Document/Settings Container/SketchSettingsViewController.swift | 1 | 3884 | //
// SketchSettingsViewController.swift
// proNotes
//
// Created by Leo Thomas on 29/11/15.
// Copyright © 2015 leonardthomas. All rights reserved.
//
import UIKit
protocol SketchSettingsDelegate: class {
func clearSketch()
func didSelectColor(_ color: UIColor)
func didSelectDrawingObject(_ object: Pen)
func didSelectLineWidth(_ width: CGFloat)
func removeLayer()
}
enum SketchType {
case pen
case marker
case eraser
}
class SketchSettingsViewController: SettingsBaseViewController {
weak static var delegate: SketchSettingsDelegate?
let defaultTopConstant: CGFloat = -20
var currentType = SketchType.pen {
didSet {
if oldValue != currentType {
switch oldValue {
case .pen:
penTopConstraint.constant = defaultTopConstant
break
case .marker:
markerTopConstraint.constant = defaultTopConstant
break
case .eraser:
eraserTopConstraint.constant = defaultTopConstant
break
}
var object: Pen?
// -1 instead of 0 to avoid whitespaces during spring animation
switch currentType {
case .pen:
penTopConstraint.constant = -1
object = Pencil()
break
case .marker:
markerTopConstraint.constant = -1
object = Marker()
break
case .eraser:
eraserTopConstraint.constant = -1
object = Eraser()
break
}
UIView.animate(withDuration: standardAnimationDuration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 5, options: UIViewAnimationOptions(), animations: {
() -> Void in
self.lineWidthCircleView.radius = object?.lineWidth ?? self.lineWidthCircleView.radius
self.lineWidthSlider.value = Float(self.lineWidthCircleView.radius)
self.view.layoutIfNeeded()
}, completion: nil)
SketchSettingsViewController.delegate?.didSelectDrawingObject(object!)
}
}
}
@IBOutlet weak var penTopConstraint: NSLayoutConstraint!
@IBOutlet weak var markerTopConstraint: NSLayoutConstraint!
@IBOutlet weak var eraserTopConstraint: NSLayoutConstraint!
@IBOutlet weak var lineWidthSlider: UISlider!
@IBOutlet weak var lineWidthCircleView: CircleView!
// MARK: - Actions
@IBAction func handlePenButtonPressed(_ sender: AnyObject) {
currentType = .pen
}
@IBAction func handleMarkerButtonPressed(_ sender: AnyObject) {
currentType = .marker
}
@IBAction func handleEraserButtonPressed(_ sender: AnyObject) {
currentType = .eraser
}
@IBAction func handleClearButtonPressed(_ sender: AnyObject) {
SketchSettingsViewController.delegate?.clearSketch()
}
@IBAction func handleDeleteButtonPressed(_ sender: AnyObject) {
SketchSettingsViewController.delegate?.removeLayer()
}
@IBAction func handleLineWidthSliderValueChanged(_ sender: UISlider) {
lineWidthCircleView.radius = CGFloat(sender.value)
SketchSettingsViewController.delegate?.didSelectLineWidth(lineWidthCircleView.radius)
}
// MARK: - ColorPickerDelegate
override func didSelectColor(_ colorPicker: ColorPickerViewController, color: UIColor) {
SketchSettingsViewController.delegate?.didSelectColor(color)
}
override func canSelectClearColor(_ colorPicker: ColorPickerViewController) -> Bool {
return false
}
}
| mit | 8b1fe4ca372b1ded5c948321c59b11aa | 29.81746 | 185 | 0.611383 | 5.821589 | false | false | false | false |
wayfinders/WRCalendarView | WRCalendarView/Helpers/Constants.swift | 1 | 1331 | //
// Constants.swift
// Pods
//
// Created by wayfinder on 2017. 4. 26..
//
//
import Foundation
public enum SupplementaryViewKinds {
static let columnHeader = "ColumnHeader"
static let rowHeader = "RowHeader"
static let defaultCell = "DefaultCell"
}
public enum DecorationViewKinds {
static let todayBackground = "TodayBackground"
static let columnHeaderBackground = "ColumnHeaderBackground"
static let rowHeaderBackground = "RowHeaderBackground"
static let currentTimeIndicator = "CurrentTimeIndicator"
static let currentTimeGridline = "CurrentTimeGridline"
static let verticalGridline = "VerticalGridline"
static let horizontalGridline = "HorizontalGridline"
static let cornerHeader = "CornerHeader"
}
public enum ReuseIdentifiers {
static let columnHeader = WRColumnHeader.className
static let rowHeader = WRRowHeader.className
static let defaultCell = WREventCell.className
}
public enum CalendarType {
case week
case day
}
public enum HourGridDivision: Int {
case none = 0
case minutes_5 = 5
case minutes_10 = 10
case minutes_15 = 15
case minutes_20 = 20
case minutes_30 = 30
}
enum ScrollDirection {
case none
case crazy
case left
case right
case up
case down
case horizontal
case vertical
}
| mit | eb9560f5f176656697e956f314002a9c | 21.948276 | 64 | 0.718257 | 4.293548 | false | false | false | false |
BareFeetWare/BFWControls | BFWControls Demo/Modules/Transition/Controller/TransitionViewController.swift | 2 | 2108 | //
// TransitionViewController.swift
// BFWControls
//
// Created by Andy Kim on 12/5/17.
// Copyright © 2017 BareFeetWare. All rights reserved.
//
import UIKit
import BFWControls
class TransitionViewController: UIViewController, SegueHandlerType {
let interactiveTransition = TranslationAnimationController()
enum SegueIdentifier: String {
case interactive
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let identifier = segue.identifier,
let segueIdentifier = SegueIdentifier(rawValue: identifier)
else { return }
switch segueIdentifier {
case .interactive:
let viewController = segue.destination
viewController.transitioningDelegate = interactiveTransition
}
}
@IBAction func handlePanGesture(_ pan: UIPanGestureRecognizer) {
let translation = pan.translation(in: pan.view!)
let progress = translation.y / pan.view!.bounds.height
switch pan.state {
case .began:
interactiveTransition.isInteractive = true
interactiveTransition.direction = .down
performSegue(.interactive, sender: pan.view)
break
case .changed:
// update progress of the transition
interactiveTransition.update(progress)
break
default: // .ended, .cancelled, .failed ...
// return flag to false and finish the transition
interactiveTransition.isInteractive = false
if progress > 0.2 {
// threshold crossed: finish
interactiveTransition.finish()
}
else {
// threshold not met: cancel
interactiveTransition.cancel()
}
}
}
@IBAction func unwindToTransitionWithSegue(_ segue: UIStoryboardSegue) {
// unwind to this view controller
}
}
| mit | 8044faf5cb21b4d8e97a3fe3c9e1b554 | 31.921875 | 106 | 0.621737 | 5.820442 | false | false | false | false |
ibhupi/cksapp | ios-app/cksapp/Classes/Libraries/UIImageViewNetwork/UIImageViewNetwork.swift | 1 | 6430 | //
// MagicImageView.swift
// swift2
//
// Created by Singh, Bhupendra | Bhupi | NEWSD on 7/9/15.
// Copyright © 2015 Bhupendra Singh. All rights reserved.
//
import UIKit
private var kImageUrlAssociationKey: UInt8 = 0
private var kErrorImageAssociationKey: UInt8 = 0
private let kCachedImageLimitCount: NSInteger = 100
/**
Image cache, so need to download it again once it downloaded.
*/
struct ImageCache {
static var cacheDictionary:NSMutableDictionary?
/// TODO: Better cache purging with memory warning from APP
static var cacheArrayForPurging:NSMutableArray?
}
extension UIImageView {
/**
Error Image, this image will be used when there is any error in downloading image from network.
*/
public var errorImage: UIImage? {
get {
return objc_getAssociatedObject(self, &kErrorImageAssociationKey) as? UIImage
}
set {
objc_setAssociatedObject(self, &kErrorImageAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
/**
Set Image from imgage URL, This will asynchronoulsy fetch
image from network. And set it after loading. Images will
be set with fadeIn animation.
If image url was changed during loading, then it will
gracefully ignore previously fetched image.
- parameter imageUrlString: image url string to download image
*/
public func setImageFromUrl(imageUrlString : NSString) {
self.setImageFromUrl(imageUrlString, animated: true)
}
/**
Set Image from imgage URL, This will asynchronoulsy fetch
image from network. And set it after loading.
If image url was changed during loading then it will
gracefully ignore previously fetched image.
- parameter imageUrlString: image url string
- parameter animated: boolean value(true) to show image with animation
*/
public func setImageFromUrl(imageUrlString : NSString, animated : Bool) {
if (self.image != nil && self.imageUrlString != nil && self.imageUrlString.length > 0 && self.imageUrlString.isEqualToString(imageUrlString as String)) {
return;
}
self.imageUrlString = imageUrlString
if (imageUrlString.length < 1) {
return;
}
if(ImageCache.cacheDictionary == nil) {
ImageCache.cacheDictionary = NSMutableDictionary()
ImageCache.cacheArrayForPurging = NSMutableArray()
}
self.image = nil
let imagesDict = ImageCache.cacheDictionary
if let imageCached = imagesDict?.objectForKey(imageUrlString) as? UIImage {
self.setImage(imageCached, animated: false)
return
}
downloadImage(imageUrlString) { (urlString, image) -> Void in
// Cache Image for downloaded URL
ImageCache.cacheDictionary?.setValue(image, forKey: urlString as String)
ImageCache.cacheArrayForPurging?.addObject(urlString)
if(ImageCache.cacheDictionary?.count > kCachedImageLimitCount) {
let firstImageInCache : NSString = (ImageCache.cacheArrayForPurging?.firstObject) as! NSString
ImageCache.cacheDictionary?.removeObjectForKey(firstImageInCache)
ImageCache.cacheArrayForPurging?.removeObject(firstImageInCache)
}
if (urlString != self.imageUrlString) {
return;
}
var imageToShow : UIImage? = image
if(image == nil) {
imageToShow = self.errorImage
}
self.setImage(imageToShow, animated: animated)
}
}
/**
Set already Image with or without animaiton
- parameter image: UIImage? An optional UIImage
- parameter animated: boolean value(true) to show image with animation
*/
public func setImage(image : UIImage?, animated : Bool) {
if (animated == true) {
UIView.transitionWithView(self, duration: 0.2, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { () -> Void in
self.image = image
}, completion: { (stop) -> Void in
})
} else {
self.image = image
}
}
/**
Function to download image from network. Downloaded image will
be cached. Cached image will be used for same url
- parameter urlString: Image url string to download image from
- parameter completion: Completion block will be called in main
thread after image is dowloaded or found in cache
*/
func downloadImage(urlString : NSString, completion:(urlString : NSString, image : UIImage?) -> Void) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) { () -> Void in
let url = NSURL(string: urlString as String)
if (url == nil) {
self.imageDownloaded(urlString, image: nil, completion: completion)
return
}
let data = NSData(contentsOfURL: url!)
if (data?.length > 0), let image = UIImage(data: data!) {
self.imageDownloaded(urlString, image: image, completion: completion)
}
else {
self.imageDownloaded(urlString, image: nil, completion: completion)
}
}
}
/**
Helper function to call completion block in main thread
(Reduing just few lines of code in downloadImage())
*/
func imageDownloaded(urlString : NSString, image : UIImage?, completion:(urlString : NSString, image : UIImage?) -> Void) {
dispatch_async(dispatch_get_main_queue()) { () -> Void in
completion(urlString: urlString, image: image)
}
}
/**
Custom image url property, to check when download asynchronous
image is same as latest set image url.
If different then downloaded image will not be set in image view.
Because image might has been removed or new image is being downloaded from different url
*/
var imageUrlString: NSString! {
get {
return objc_getAssociatedObject(self, &kImageUrlAssociationKey) as? NSString
}
set {
objc_setAssociatedObject(self, &kImageUrlAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
} | apache-2.0 | a69c8260beeb63e9dd4e7023c27bc58c | 35.534091 | 161 | 0.636024 | 5.026583 | false | false | false | false |
judi0713/TouTiao | TouTiao/Network/NetWorkFetcher.swift | 2 | 2556 | //
// NetWorkFetcher.swift
// TouTiao
//
// Created by tesths on 4/11/16.
// Copyright © 2016 tesths. All rights reserved.
//
import Cocoa
import Alamofire
import Fuzi
class NetWorkFetcher: NSObject {
let url = "https://toutiao.io/"
let Hoturl = "https://toutiao.io/posts/hot/7"
let Javaurl = "https://toutiao.io/c/java"
let iOSurl = "https://toutiao.io/c/ios"
let Weburl = "https://toutiao.io/c/fe"
func getReleases(url: String, _ done: @escaping (_ model: [TTModel]?) -> ()) {
Alamofire.request(url, method: .get )
.responseString { response in
guard let html = response.result.value else {
return done(nil)
}
let document = try? XMLDocument(string: html)
let body = document!.xpath("//div[@class='post']")
let releases = body.map { return self.release($0) }.flatMap { return $0 }
done(releases)
}
}
func release(_ element: Fuzi.XMLElement) -> [TTModel] {
var model = [TTModel]()
var url = String()
var href = String()
var title = String()
var like = String()
var comment = String()
let pth = element.xpath(".//div[@class='btn-group-vertical upvote']")
pth.forEach {tt in
for (index, element) in tt.xpath(".//span").enumerated() {
if index == 0 {
like = element.stringValue
break
}
}
}
let pth1 = element.xpath(".//div[@class='meta']/span")
pth1.forEach {tt in
let value = tt.stringValue
comment = value.trimmingCharacters(in: .whitespacesAndNewlines)
}
let pth2 = element.xpath(".//div[@class='meta']")
pth2.forEach {tt in
let value = tt.stringValue.components(separatedBy: "\n")
url = value[1].trimmingCharacters(in: .whitespacesAndNewlines)
}
let pth3 = element.xpath(".//h3[@class='title']/a")
pth3.forEach {tt in
pth3.forEach { pth in
href = pth["href"]!
title = pth.stringValue
}
}
model.append(
TTModel(
title: title,
url: url,
href: href,
like: like,
comment: comment
)
)
return model
}
}
| mit | 18724d4d5c0aea1303d4014eeb32d687 | 27.707865 | 89 | 0.488454 | 4.244186 | false | false | false | false |
andrew8712/DCKit | DCKit/UIViews/DCDashedBorderedView.swift | 2 | 2883 | //
// DCDashedBorderedView.swift
// DCKitSample
//
// Created by Andrey Gordeev on 5/10/15.
// Copyright (c) 2015 Andrey Gordeev. All rights reserved.
//
import UIKit
/// UIView with dashed border.
@IBDesignable open class DCDashedBorderedView: DCBaseView {
/// The control's border color.
@IBInspectable open var borderColor: UIColor = UIColor.lightGray {
didSet {
borderLayer.strokeColor = borderColor.cgColor
}
}
/// The control's border width. Gets automatically scaled with using UIScreen.main.scale.
@IBInspectable open var borderWidth: CGFloat = 1.0 {
didSet {
borderLayer.lineWidth = borderWidth / UIScreen.main.scale
}
}
/// The control's corner radius.
@IBInspectable open var cornerRadius: CGFloat = 0.0 {
didSet {
layoutSubviews()
}
}
/// Dash length (in points).
@IBInspectable open var dashLength: CGFloat = 4.0 {
didSet {
borderLayer.lineDashPattern = [NSNumber(value: Float(dashLength)), NSNumber(value: Float(dashSpace))]
}
}
/// Space between two dashes (in points).
@IBInspectable open var dashSpace: CGFloat = 2.0 {
didSet {
borderLayer.lineDashPattern = [NSNumber(value: Float(dashLength)), NSNumber(value: Float(dashSpace))]
}
}
// MARK: - Initializers
// IBDesignables require both of these inits, otherwise we'll get an error: IBDesignable View Rendering times out.
// http://stackoverflow.com/questions/26772729/ibdesignable-view-rendering-times-out
override public init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// A layer, where we actually draw a dashed border.
private let borderLayer = CAShapeLayer()
open override func layoutSubviews() {
super.layoutSubviews()
borderLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
borderLayer.frame = bounds
}
// MARK: - Build control
override open func customInit() {
super.customInit()
addBorder()
}
/// Adds a dashed border to the control.
open func addBorder() {
borderLayer.strokeColor = borderColor.cgColor
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.lineDashPattern = [NSNumber(value: Float(dashLength)), NSNumber(value: Float(dashSpace))]
borderLayer.lineWidth = borderWidth / UIScreen.main.scale
// http://stackoverflow.com/questions/4735623/uilabel-layer-cornerradius-negatively-impacting-performance
borderLayer.masksToBounds = true
borderLayer.rasterizationScale = UIScreen.main.scale
borderLayer.shouldRasterize = true
layer.addSublayer(borderLayer)
}
}
| mit | d974b8149731f6ad2ab00db079a64ede | 29.347368 | 118 | 0.66077 | 4.665049 | false | false | false | false |
Raizlabs/Geode | Example/Common/NavBarExtension.swift | 1 | 4868 | //
// NavBarExtension.swift
// Example
//
// Created by John Watson on 1/30/16.
//
// Copyright © 2016 Raizlabs. All rights reserved.
// http://raizlabs.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 CoreLocation
import UIKit
final class NavBarExtension: UIView {
var coordinate = kCLLocationCoordinate2DInvalid {
didSet {
if coordinate == kCLLocationCoordinate2DInvalid {
stackView.isHidden = true
noLocationLabel.isHidden = false
}
else {
lonLabel.text = String(format: "Lon: %.5f", coordinate.longitude)
latLabel.text = String(format: "Lat: %.5f", coordinate.latitude)
stackView.isHidden = false
noLocationLabel.isHidden = true
}
}
}
fileprivate let hairline = UIView()
fileprivate let stackView = UIStackView()
fileprivate let lonLabel = UILabel()
fileprivate let latLabel = UILabel()
fileprivate let noLocationLabel = UILabel()
init() {
hairline.backgroundColor = UIColor(named: .black)
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.distribution = .fillEqually
lonLabel.textColor = UIColor(named: .white)
lonLabel.textAlignment = .center
latLabel.textColor = UIColor(named: .white)
latLabel.textAlignment = .center
noLocationLabel.text = "Location not available"
noLocationLabel.textColor = UIColor(named: .white)
noLocationLabel.textAlignment = .center
super.init(frame: CGRect.zero)
backgroundColor = UIColor(named: .purple)
addSubview(hairline)
addSubview(stackView)
addSubview(noLocationLabel)
stackView.addArrangedSubview(lonLabel)
stackView.addArrangedSubview(latLabel)
configureConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Private
private extension NavBarExtension {
func configureConstraints() {
// The hairline view sits at the bottom of the view, has a fixed
// height, and fills the width of the view.
hairline.translatesAutoresizingMaskIntoConstraints = false
hairline.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
hairline.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
hairline.heightAnchor.constraint(equalToConstant: 1.0 / UIScreen.main.scale).isActive = true
// The stack view is pinned to the top of the view, sits above the
// hairline, and fills the width of the view.
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: hairline.topAnchor).isActive = true
stackView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
// The longitude label is pinned to the left of the stack view.
lonLabel.translatesAutoresizingMaskIntoConstraints = false
lonLabel.leftAnchor.constraint(equalTo: stackView.leftAnchor).isActive = true
// The latitude label is pinned to the right of the stack view.
latLabel.translatesAutoresizingMaskIntoConstraints = false
latLabel.rightAnchor.constraint(equalTo: stackView.rightAnchor).isActive = true
// The no location label fills the view, in the same position as the
// stack view.
noLocationLabel.translatesAutoresizingMaskIntoConstraints = false
noLocationLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
noLocationLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
}
| mit | 2e27f1297f59fa174cb6a73b42574535 | 37.322835 | 100 | 0.696322 | 4.886546 | false | false | false | false |
OscarSwanros/swift | test/SILGen/partial_apply_super.swift | 2 | 23627 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule -module-name resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift
// RUN: %target-swift-frontend -enable-resilience -emit-silgen -parse-as-library -I %t %s | %FileCheck %s
import resilient_class
func doFoo(_ f: () -> ()) {
f()
}
public class Parent {
public init() {}
public func method() {}
public final func finalMethod() {}
public class func classMethod() {}
public final class func finalClassMethod() {}
}
public class GenericParent<A> {
let a: A
public init(a: A) {
self.a = a
}
public func method() {}
public final func finalMethod() {}
public class func classMethod() {}
public final class func finalClassMethod() {}
}
class Child : Parent {
// CHECK-LABEL: sil hidden @_T019partial_apply_super5ChildC6methodyyF : $@convention(method) (@guaranteed Child) -> ()
// CHECK: bb0([[SELF:%.*]] : $Child):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $Child to $Parent
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super6ParentC6methodyyFTcTd : $@convention(thin) (@owned Parent) -> @owned @callee_owned () -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(thin) (@owned Parent) -> @owned @callee_owned () -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super5ChildC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super5ChildC11classMethodyyFZ : $@convention(method) (@thick Child.Type) -> () {
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick Child.Type to $@thick Parent.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super6ParentC11classMethodyyFZTcTd : $@convention(thin) (@thick Parent.Type) -> @owned @callee_owned () -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(thin) (@thick Parent.Type) -> @owned @callee_owned () -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super5ChildC20callFinalSuperMethodyyF : $@convention(method) (@guaranteed Child) -> ()
// CHECK: bb0([[SELF:%.*]] : $Child):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $Child to $Parent
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super6ParentC11finalMethodyyFTc : $@convention(thin) (@owned Parent) -> @owned @callee_owned () -> ()
// CHECK: [[APPLIED_SELF:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(thin) (@owned Parent) -> @owned @callee_owned () -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[APPLIED_SELF]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super5ChildC20callFinalSuperMethodyyF'
func callFinalSuperMethod() {
doFoo(super.finalMethod)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super5ChildC25callFinalSuperClassMethodyyFZ : $@convention(method) (@thick Child.Type) -> ()
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick Child.Type to $@thick Parent.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super6ParentC16finalClassMethodyyFZTc : $@convention(thin) (@thick Parent.Type) -> @owned @callee_owned () -> ()
// CHECK: [[APPLIED_SELF:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(thin) (@thick Parent.Type) -> @owned @callee_owned () -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[APPLIED_SELF]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
class func callFinalSuperClassMethod() {
doFoo(super.finalClassMethod)
}
}
class GenericChild<A> : GenericParent<A> {
override init(a: A) {
super.init(a: a)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super12GenericChildC6methodyyF : $@convention(method) <A> (@guaranteed GenericChild<A>) -> ()
// CHECK: bb0([[SELF:%.*]] : $GenericChild<A>):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $GenericChild<A> to $GenericParent<A>
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super13GenericParentC6methodyyFTcTd : $@convention(thin) <τ_0_0> (@owned GenericParent<τ_0_0>) -> @owned @callee_owned () -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]<A>([[CASTED_SELF_COPY]]) : $@convention(thin) <τ_0_0> (@owned GenericParent<τ_0_0>) -> @owned @callee_owned () -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super12GenericChildC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super12GenericChildC11classMethodyyFZ : $@convention(method) <A> (@thick GenericChild<A>.Type) -> ()
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GenericChild<A>.Type to $@thick GenericParent<A>.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super13GenericParentC11classMethodyyFZTcTd : $@convention(thin) <τ_0_0> (@thick GenericParent<τ_0_0>.Type) -> @owned @callee_owned () -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply %4<A>(%3) : $@convention(thin) <τ_0_0> (@thick GenericParent<τ_0_0>.Type) -> @owned @callee_owned () -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply %2([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class ChildToFixedOutsideParent : OutsideParent {
// CHECK-LABEL: sil hidden @_T019partial_apply_super25ChildToFixedOutsideParentC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $ChildToFixedOutsideParent):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $ChildToFixedOutsideParent to $OutsideParent
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $ChildToFixedOutsideParent, #OutsideParent.method!1 : (OutsideParent) -> () -> (), $@convention(method) (@guaranteed OutsideParent) -> ()
// CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed OutsideParent) -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super25ChildToFixedOutsideParentC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super25ChildToFixedOutsideParentC11classMethodyyFZ
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick ChildToFixedOutsideParent.Type to $@thick OutsideParent.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick ChildToFixedOutsideParent.Type, #OutsideParent.classMethod!1 : (OutsideParent.Type) -> () -> (), $@convention(method) (@thick OutsideParent.Type) -> (){{.*}} // user: %5
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick OutsideParent.Type) -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class ChildToResilientOutsideParent : ResilientOutsideParent {
// CHECK-LABEL: sil hidden @_T019partial_apply_super29ChildToResilientOutsideParentC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $ChildToResilientOutsideParent):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $ChildToResilientOutsideParent to $ResilientOutsideParent
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $ChildToResilientOutsideParent, #ResilientOutsideParent.method!1 : (ResilientOutsideParent) -> () -> (), $@convention(method) (@guaranteed ResilientOutsideParent) -> ()
// CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed ResilientOutsideParent) -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super29ChildToResilientOutsideParentC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super29ChildToResilientOutsideParentC11classMethodyyFZ
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick ChildToResilientOutsideParent.Type to $@thick ResilientOutsideParent.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick ChildToResilientOutsideParent.Type, #ResilientOutsideParent.classMethod!1 : (ResilientOutsideParent.Type) -> () -> (), $@convention(method) (@thick ResilientOutsideParent.Type) -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick ResilientOutsideParent.Type) -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class GrandchildToFixedOutsideChild : OutsideChild {
// CHECK-LABEL: sil hidden @_T019partial_apply_super29GrandchildToFixedOutsideChildC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $GrandchildToFixedOutsideChild):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $GrandchildToFixedOutsideChild to $OutsideChild
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $GrandchildToFixedOutsideChild, #OutsideChild.method!1 : (OutsideChild) -> () -> (), $@convention(method) (@guaranteed OutsideChild) -> ()
// CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed OutsideChild) -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super29GrandchildToFixedOutsideChildC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super29GrandchildToFixedOutsideChildC11classMethodyyFZ
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GrandchildToFixedOutsideChild.Type to $@thick OutsideChild.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GrandchildToFixedOutsideChild.Type, #OutsideChild.classMethod!1 : (OutsideChild.Type) -> () -> (), $@convention(method) (@thick OutsideChild.Type) -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply %4(%3) : $@convention(method) (@thick OutsideChild.Type) -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class GrandchildToResilientOutsideChild : ResilientOutsideChild {
// CHECK-LABEL: sil hidden @_T019partial_apply_super33GrandchildToResilientOutsideChildC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $GrandchildToResilientOutsideChild):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $GrandchildToResilientOutsideChild to $ResilientOutsideChild
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $GrandchildToResilientOutsideChild, #ResilientOutsideChild.method!1 : (ResilientOutsideChild) -> () -> (), $@convention(method) (@guaranteed ResilientOutsideChild) -> ()
// CHEC: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed ResilientOutsideChild) -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super33GrandchildToResilientOutsideChildC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super33GrandchildToResilientOutsideChildC11classMethodyyFZ
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GrandchildToResilientOutsideChild.Type to $@thick ResilientOutsideChild.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GrandchildToResilientOutsideChild.Type, #ResilientOutsideChild.classMethod!1 : (ResilientOutsideChild.Type) -> () -> (), $@convention(method) (@thick ResilientOutsideChild.Type) -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick ResilientOutsideChild.Type) -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class GenericChildToFixedGenericOutsideParent<A> : GenericOutsideParent<A> {
// CHECK-LABEL: sil hidden @_T019partial_apply_super019GenericChildToFixedD13OutsideParentC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $GenericChildToFixedGenericOutsideParent<A>):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $GenericChildToFixedGenericOutsideParent<A> to $GenericOutsideParent<A>
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $GenericChildToFixedGenericOutsideParent<A>, #GenericOutsideParent.method!1 : <A> (GenericOutsideParent<A>) -> () -> (), $@convention(method) <τ_0_0> (@guaranteed GenericOutsideParent<τ_0_0>) -> ()
// CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]<A>([[CASTED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed GenericOutsideParent<τ_0_0>) -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super019GenericChildToFixedD13OutsideParentC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super019GenericChildToFixedD13OutsideParentC11classMethodyyFZ
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GenericChildToFixedGenericOutsideParent<A>.Type to $@thick GenericOutsideParent<A>.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GenericChildToFixedGenericOutsideParent<A>.Type, #GenericOutsideParent.classMethod!1 : <A> (GenericOutsideParent<A>.Type) -> () -> (), $@convention(method) <τ_0_0> (@thick GenericOutsideParent<τ_0_0>.Type) -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(method) <τ_0_0> (@thick GenericOutsideParent<τ_0_0>.Type) -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class GenericChildToResilientGenericOutsideParent<A> : ResilientGenericOutsideParent<A> {
// CHECK-LABEL: sil hidden @_T019partial_apply_super023GenericChildToResilientD13OutsideParentC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $GenericChildToResilientGenericOutsideParent<A>):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $GenericChildToResilientGenericOutsideParent<A> to $ResilientGenericOutsideParent<A>
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $GenericChildToResilientGenericOutsideParent<A>, #ResilientGenericOutsideParent.method!1 : <A> (ResilientGenericOutsideParent<A>) -> () -> (), $@convention(method) <τ_0_0> (@guaranteed ResilientGenericOutsideParent<τ_0_0>) -> ()
// CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]<A>([[CASTED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed ResilientGenericOutsideParent<τ_0_0>) -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super023GenericChildToResilientD13OutsideParentC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super023GenericChildToResilientD13OutsideParentC11classMethodyyFZ
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GenericChildToResilientGenericOutsideParent<A>.Type to $@thick ResilientGenericOutsideParent<A>.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GenericChildToResilientGenericOutsideParent<A>.Type, #ResilientGenericOutsideParent.classMethod!1 : <A> (ResilientGenericOutsideParent<A>.Type) -> () -> (), $@convention(method) <τ_0_0> (@thick ResilientGenericOutsideParent<τ_0_0>.Type) -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(method) <τ_0_0> (@thick ResilientGenericOutsideParent<τ_0_0>.Type) -> ()
// CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
| apache-2.0 | c0f3d4c12217fa1b78a9e6e908aa196f | 80.109966 | 325 | 0.654663 | 3.614548 | false | false | false | false |
brynbellomy/Funky | src/Operators.Misc.swift | 2 | 2875 | //
// Operators.misc.swift
// Funky
//
// Created by bryn austin bellomy on 2015 Jan 6.
// Copyright (c) 2014 bryn austin bellomy. All rights reserved.
//
infix operator =?? { associativity left precedence 99 }
infix operator ??= { associativity left precedence 99 }
infix operator ?± { associativity right precedence 110 }
// look, i made a face operator!
// prefix operator °¿° {}
/**
The set-if-non-nil operator. Will only set `lhs` to `rhs` if `rhs` is non-nil.
*/
public func =?? <T>(inout lhs:T, maybeRhs: T?) {
if let rhs = maybeRhs {
lhs = rhs
}
}
/**
The set-if-non-nil operator. Will only set `lhs` to `rhs` if `rhs` is non-nil.
*/
public func =?? <T>(inout lhs:T?, maybeRhs: T?) {
if let rhs = maybeRhs {
lhs = rhs
}
}
/**
The set-if-non-failure operator. Will only set `lhs` to `rhs` if `rhs` is not a `Result<T>.Failure`.
*/
public func =?? <T, E: ErrorType> (inout lhs:T, result: Result<T, E>) {
lhs =?? result.value
}
/**
The set-if-non-failure operator. Will only set `lhs` to `rhs` if `rhs` is not a `Result<T>.Failure`.
*/
public func =?? <T, E: ErrorType> (inout lhs:T?, result: Result<T, E>) {
lhs =?? result.value
}
/**
The initialize-if-nil operator. Will only set `lhs` to `rhs` if `lhs` is nil.
*/
public func ??= <T: Any> (inout lhs:T?, @autoclosure rhs: () -> T)
{
if lhs == nil {
lhs = rhs()
}
}
/**
The initialize-if-nil operator. Will only set `lhs` to `rhs` if `lhs` is nil.
*/
public func ??= <T: Any> (inout lhs:T?, @autoclosure rhs: () -> T?)
{
if lhs == nil {
lhs = rhs()
}
}
//public func |> <T, U> (lhs: T -> Result<U>, rhs: U -> Void) -> T -> Result<U> {
// return { arg in lhs(arg).map { rhs($0); return $0 } }
//}
/**
Nil coalescing operator for `Result<T, E>`.
*/
public func ?± <T, E: ErrorType>
(lhs: T?, @autoclosure rhs: () -> Result<T, E>) -> Result<T, E>
{
if let lhs = lhs {
return success(lhs)
}
else {
return rhs()
}
}
public func ?± <T, E: ErrorType>
(lhs: Result<T, E>, @autoclosure rhs: () -> Result<T, E>) -> Result<T, E>
{
switch lhs {
case .Success: return lhs
case .Failure: return rhs()
}
}
postfix operator ‡ {}
/**
The reverse-args-and-curry operator (type shift+option+7). Useful in bringing the Swift stdlib collection functions into use in functional pipelines.
For example: `let lowercaseStrings = someStrings |> mapTo { $0.lowercaseString }`
*/
//public postfix func ‡
// <T, U, V, R>
// (f: (T, U, V) -> R) -> V -> ((T, U) -> R) {
// return { v in { t, u in f(t, u, v) }}
//}
public postfix func ‡
<T, U, R>
(f: (T, U) -> R) -> U -> T -> R {
// @@XYZZY
// return currySwap(f)
return { x in { y in f(y, x) }}
}
| mit | aef9a3e9bb7922498ed57c8def52f827 | 17.835526 | 153 | 0.547677 | 2.991641 | false | false | false | false |
zeroc-ice/ice | swift/src/Ice/ObjectAdapterI.swift | 4 | 8269 | //
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import IceImpl
class ObjectAdapterI: LocalObject<ICEObjectAdapter>, ObjectAdapter, ICEBlobjectFacade, Hashable {
private let communicator: Communicator
let servantManager: ServantManager
init(handle: ICEObjectAdapter, communicator: Communicator) {
self.communicator = communicator
servantManager = ServantManager(adapterName: handle.getName(), communicator: communicator)
super.init(handle: handle)
handle.registerDefaultServant(self)
}
func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self).hashValue)
}
static func == (lhs: ObjectAdapterI, rhs: ObjectAdapterI) -> Bool {
return lhs === rhs
}
func getName() -> String {
return handle.getName()
}
func getCommunicator() -> Communicator {
return communicator
}
func activate() throws {
try autoreleasepool {
try handle.activate()
}
}
func hold() {
handle.hold()
}
func waitForHold() {
handle.waitForHold()
}
func deactivate() {
handle.deactivate()
}
func waitForDeactivate() {
handle.waitForDeactivate()
}
func isDeactivated() -> Bool {
return handle.isDeactivated()
}
func destroy() {
return handle.destroy()
}
func add(servant: Disp, id: Identity) throws -> ObjectPrx {
return try addFacet(servant: servant, id: id, facet: "")
}
func addFacet(servant: Disp, id: Identity, facet: String) throws -> ObjectPrx {
precondition(!id.name.isEmpty, "Identity cannot have an empty name")
try servantManager.addServant(servant: servant, id: id, facet: facet)
return try createProxy(id).ice_facet(facet)
}
func addWithUUID(_ servant: Disp) throws -> ObjectPrx {
return try addFacetWithUUID(servant: servant, facet: "")
}
func addFacetWithUUID(servant: Disp, facet: String) throws -> ObjectPrx {
return try addFacet(servant: servant, id: Identity(name: UUID().uuidString, category: ""), facet: facet)
}
func addDefaultServant(servant: Disp, category: String) throws {
try servantManager.addDefaultServant(servant: servant, category: category)
}
func remove(_ id: Identity) throws -> Disp {
return try removeFacet(id: id, facet: "")
}
func removeFacet(id: Identity, facet: String) throws -> Disp {
precondition(!id.name.isEmpty, "Identity cannot have an empty name")
return try servantManager.removeServant(id: id, facet: facet)
}
func removeAllFacets(_ id: Identity) throws -> FacetMap {
precondition(!id.name.isEmpty, "Identity cannot have an empty name")
return try servantManager.removeAllFacets(id: id)
}
func removeDefaultServant(_ category: String) throws -> Disp {
return try servantManager.removeDefaultServant(category: category)
}
func find(_ id: Identity) -> Disp? {
return findFacet(id: id, facet: "")
}
func findFacet(id: Identity, facet: String) -> Disp? {
return servantManager.findServant(id: id, facet: facet)
}
func findAllFacets(_ id: Identity) -> FacetMap {
return servantManager.findAllFacets(id: id)
}
func findByProxy(_ proxy: ObjectPrx) -> Disp? {
return findFacet(id: proxy.ice_getIdentity(), facet: proxy.ice_getFacet())
}
func addServantLocator(locator: ServantLocator, category: String) throws {
try servantManager.addServantLocator(locator: locator, category: category)
}
func removeServantLocator(_ category: String) throws -> ServantLocator {
return try servantManager.removeServantLocator(category: category)
}
func findServantLocator(_ category: String) -> ServantLocator? {
return servantManager.findServantLocator(category: category)
}
func findDefaultServant(_ category: String) -> Disp? {
return servantManager.findDefaultServant(category: category)
}
func createProxy(_ id: Identity) throws -> ObjectPrx {
precondition(!id.name.isEmpty, "Identity cannot have an empty name")
return try autoreleasepool {
try ObjectPrxI(handle: handle.createProxy(name: id.name, category: id.category),
communicator: communicator)
}
}
func createDirectProxy(_ id: Identity) throws -> ObjectPrx {
precondition(!id.name.isEmpty, "Identity cannot have an empty name")
return try autoreleasepool {
try ObjectPrxI(handle: handle.createDirectProxy(name: id.name, category: id.category),
communicator: communicator)
}
}
func createIndirectProxy(_ id: Identity) throws -> ObjectPrx {
precondition(!id.name.isEmpty, "Identity cannot have an empty name")
return try autoreleasepool {
try ObjectPrxI(handle: handle.createIndirectProxy(name: id.name, category: id.category),
communicator: communicator)
}
}
func setLocator(_ locator: LocatorPrx?) {
let l = locator as? LocatorPrxI
handle.setLocator(l?.handle ?? nil)
}
func getLocator() -> LocatorPrx? {
guard let locatorHandle = handle.getLocator() else {
return nil
}
return LocatorPrxI.fromICEObjectPrx(handle: locatorHandle)
}
func getEndpoints() -> EndpointSeq {
return handle.getEndpoints().fromObjc()
}
func refreshPublishedEndpoints() throws {
try autoreleasepool {
try handle.refreshPublishedEndpoints()
}
}
func getPublishedEndpoints() -> EndpointSeq {
return handle.getPublishedEndpoints().fromObjc()
}
func setPublishedEndpoints(_ newEndpoints: EndpointSeq) throws {
try autoreleasepool {
try handle.setPublishedEndpoints(newEndpoints.toObjc())
}
}
func getDispatchQueue() throws -> DispatchQueue {
return try autoreleasepool {
try handle.getDispatchQueue()
}
}
func facadeInvoke(_ adapter: ICEObjectAdapter,
inEncapsBytes: UnsafeMutableRawPointer,
inEncapsCount: Int,
con: ICEConnection?,
name: String,
category: String,
facet: String,
operation: String,
mode: UInt8,
context: [String: String],
requestId: Int32,
encodingMajor: UInt8,
encodingMinor: UInt8,
response: @escaping ICEBlobjectResponse,
exception: @escaping ICEBlobjectException) {
precondition(handle == adapter)
let connection = con?.getSwiftObject(ConnectionI.self) { ConnectionI(handle: con!) } ?? nil
let current = Current(adapter: self,
con: connection,
id: Identity(name: name, category: category),
facet: facet,
operation: operation,
mode: OperationMode(rawValue: mode)!,
ctx: context,
requestId: requestId,
encoding: EncodingVersion(major: encodingMajor, minor: encodingMinor))
let incoming = Incoming(istr: InputStream(communicator: communicator,
encoding: EncodingVersion(major: encodingMajor,
minor: encodingMinor),
bytes: Data(bytesNoCopy: inEncapsBytes, count: inEncapsCount,
deallocator: .none)),
response: response,
exception: exception,
current: current)
incoming.invoke(servantManager)
}
func facadeRemoved() {
servantManager.destroy()
}
}
| gpl-2.0 | f8c5ac117d12163cc935e3db0c7d7c2b | 33.028807 | 112 | 0.590277 | 4.963385 | false | false | false | false |
artursDerkintis/Starfly | Starfly/SFHistoryCell.swift | 1 | 4505 | //
// SFHistoryCell.swift
// Starfly
//
// Created by Arturs Derkintis on 12/12/15.
// Copyright © 2015 Starfly. All rights reserved.
//
import UIKit
class SFHistoryCell : SWTableViewCell {
var titleLabel : UILabel?
var urlLabel : UILabel?
var icon : UIImageView?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .clearColor()
icon = UIImageView(frame: CGRect.zero)
contentView.addSubview(icon!)
contentView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(1)
make.right.equalTo(0)
make.left.equalTo(0)
make.bottom.equalTo(-1)
}
contentView.backgroundColor = UIColor(white: 0.9, alpha: 0.5)
icon?.snp_makeConstraints {(make) -> Void in
make.width.height.equalTo(30)
make.centerY.equalTo(self.snp_centerY)
make.left.equalTo(10)
}
titleLabel = UILabel(frame: CGRect.zero)
titleLabel?.textColor = UIColor.blackColor()
titleLabel?.font = UIFont.systemFontOfSize(16, weight: UIFontWeightRegular)
contentView.addSubview(titleLabel!)
titleLabel?.snp_makeConstraints {(make) -> Void in
make.left.equalTo(self.icon!.snp_rightMargin).offset(20)
make.height.equalTo(self.contentView).multipliedBy(0.5)
make.top.equalTo(4)
make.right.equalTo(0)
}
urlLabel = UILabel(frame: CGRect.zero)
urlLabel?.textColor = UIColor.grayColor()
urlLabel?.font = UIFont.systemFontOfSize(14, weight: UIFontWeightRegular)
contentView.addSubview(urlLabel!)
urlLabel!.snp_makeConstraints {(make) -> Void in
make.left.equalTo(self.icon!.snp_rightMargin).offset(20)
make.bottom.equalTo(-4)
make.top.equalTo(25)
make.right.equalTo(0)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class SFHistoryHeader : UITableViewHeaderFooterView {
var dayLabel : UILabel?
var csView : SFView?
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
csView = SFView(frame: bounds)
csView!.userInteractionEnabled = false
addSubview(csView!)
csView?.snp_makeConstraints {(make) -> Void in
make.top.equalTo(0)
make.bottom.equalTo(-1)
make.right.left.equalTo(0)
make.center.equalTo(self)
}
dayLabel = UILabel(frame: CGRect.zero)
dayLabel?.textAlignment = .Center
dayLabel?.textColor = UIColor.whiteColor()
dayLabel?.font = UIFont.systemFontOfSize(16, weight: UIFontWeightMedium)
addSubview(dayLabel!)
dayLabel?.snp_makeConstraints {(make) -> Void in
make.top.bottom.equalTo(0)
make.left.equalTo(0)
make.width.equalTo(self)
}
}
override func layoutSubviews() {
super.layoutSubviews()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class SFHistoryCellSearch : SWTableViewCell {
var titleLabel : UILabel?
var urlLabel : UILabel?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .clearColor()
contentView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(1)
make.right.equalTo(0)
make.left.equalTo(0)
make.bottom.equalTo(-1)
}
titleLabel = UILabel(frame: CGRect.zero)
titleLabel?.textColor = UIColor.blackColor()
titleLabel?.font = UIFont.systemFontOfSize(16, weight: UIFontWeightRegular)
contentView.addSubview(titleLabel!)
titleLabel?.snp_makeConstraints {(make) -> Void in
make.left.equalTo(20)
make.height.equalTo(self.contentView).multipliedBy(0.5)
make.top.equalTo(4)
make.right.equalTo(0)
}
urlLabel = UILabel(frame: CGRect.zero)
urlLabel?.textColor = UIColor.grayColor()
urlLabel?.font = UIFont.systemFontOfSize(14, weight: UIFontWeightRegular)
contentView.addSubview(urlLabel!)
urlLabel!.snp_makeConstraints {(make) -> Void in
make.left.equalTo(20)
make.bottom.equalTo(-4)
make.top.equalTo(25)
make.right.equalTo(0)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 10fbb4cb1836ab53a5b5bc83bf676cf3 | 29.849315 | 83 | 0.65897 | 4.021429 | false | false | false | false |
mathewsanders/Mustard | Tests/LiteralTokenTests.swift | 1 | 3868 | // InternalStateTokenTests.swift
//
// Copyright (c) 2017 Mathew Sanders
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import XCTest
import Mustard
// implementing as class rather than struct since `canTake(_:)` will have mutating effect.
final class LiteralTokenizer: TokenizerType {
private let target: String
private var position: String.UnicodeScalarIndex
// instead, we should initalize instance with the target String we're looking for
init(target: String) {
self.target = target
self.position = target.unicodeScalars.startIndex
}
// instead of looking at a set of scalars, the order that the scalar occurs
// is relevent for the token
func tokenCanTake(_ scalar: UnicodeScalar) -> Bool {
guard position < target.unicodeScalars.endIndex else {
return false
}
// if the scalar matches the target scalar in the current position, then advance
// the position and return true
if scalar == target.unicodeScalars[position] {
position = target.unicodeScalars.index(after: position)
return true
}
else {
return false
}
}
// this token is only complete when we've called `canTake(_:)` with the correct sequence
// of scalars such that `position` has advanced to the endIndex of the target
func tokenIsComplete() -> Bool {
return position == target.unicodeScalars.endIndex
}
// if we've matched the token completely, it should be invalid if the next scalar
// matches a letter, this means that literal match of "cat" will not match "catastrophe"
func completeTokenIsInvalid(whenNextScalarIs scalar: UnicodeScalar?) -> Bool {
if let next = scalar {
return CharacterSet.letters.contains(next)
}
else {
return false
}
}
// token instances are re-used, in most cases this doesn't matter, but because we keep
// an internal state, we need to reset this instance to start matching again
func prepareForReuse() {
position = target.unicodeScalars.startIndex
}
}
extension String {
// a convenience to allow us to use `"cat".literalToken` instead of `LiteralToken("cat")`
var literalTokenizer: LiteralTokenizer {
return LiteralTokenizer(target: self)
}
}
class LiteralTokenTests: XCTestCase {
func testGetCatAndDuck() {
let input = "the cat and the catastrophe duck"
let tokens = input.tokens(matchedWith: "cat".literalTokenizer, "duck".literalTokenizer)
XCTAssert(tokens.count == 2, "Unexpected number of tokens [\(tokens.count)]")
XCTAssert(tokens[0].text == "cat")
XCTAssert(tokens[1].text == "duck")
}
}
| mit | e88c33511908aa8a187c5a84dc957fb6 | 37.29703 | 95 | 0.679938 | 4.781211 | false | false | false | false |
StephenMIMI/U17Comics | U17Comics/U17Comics/classes/HomePage/main/Controllers/HomePageViewController.swift | 1 | 7628 | //
// HomePageViewController.swift
// U17Comics
//
// Created by qianfeng on 16/10/21.
// Copyright © 2016年 zhb. All rights reserved.
//
import UIKit
class HomePageViewController: BaseViewController {
//滚动视图
private var scrollView: UIScrollView?
//选择控件
private var segCtrl: CustomSegCtrl?
//推荐视图
var recommendView: HomePageRecommendView?
//VIP视图
var VIPView: HomeVIPView?
//订阅视图
var subscribeView: HomeVIPView?
//排行视图
var rankView: HomeRankView?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = customBgColor
automaticallyAdjustsScrollViewInsets = false
//选择控件
let frame = CGRectMake(0, 0, screenWidth-120, 44)
segCtrl = CustomSegCtrl(frame: frame, titleArray: ["推荐","VIP","订阅","排行"])
segCtrl!.delegate = self
navigationItem.titleView = segCtrl
createHomePage()//创建滚动视图
downloadRecommendData()//下载首页的推荐数据
downloadVIPData()//下载VIP页面的数据
downloadSubscribeData()//下载订阅页面的数据
}
//创建首页滚动视图
func createHomePage() {
scrollView = UIScrollView()
scrollView?.backgroundColor = customBgColor
scrollView?.pagingEnabled = true
scrollView?.showsHorizontalScrollIndicator = false
scrollView?.delegate = self
view.addSubview(scrollView!)
scrollView?.snp_makeConstraints { (make) in
make.edges.equalTo(self.view).inset(UIEdgeInsetsMake(64, 0, 49, 0))
}
//容器视图
let containerView = UIView.createView()
scrollView!.addSubview(containerView)
containerView.snp_makeConstraints { (make) in
make.edges.equalTo(scrollView!)
make.height.equalTo(scrollView!)
}
//添加子视图
//1.推荐视图
recommendView = HomePageRecommendView()
containerView.addSubview(recommendView!)
recommendView?.snp_makeConstraints(closure: { (make) in
make.left.top.bottom.equalTo(containerView)
make.width.equalTo(screenWidth)
})
//2.VIP视图
VIPView = HomeVIPView()
containerView.addSubview(VIPView!)
VIPView?.snp_makeConstraints(closure: { (make) in
make.left.equalTo((recommendView?.snp_right)!)
make.top.bottom.equalTo(containerView)
make.width.equalTo(screenWidth)
})
//3.订阅视图
subscribeView = HomeVIPView()
containerView.addSubview(subscribeView!)
subscribeView?.snp_makeConstraints(closure: { (make) in
make.left.equalTo((VIPView?.snp_right)!)
make.top.bottom.equalTo(containerView)
make.width.equalTo(screenWidth)
})
//3.排行视图
rankView = HomeRankView()
//将当前视图控制器传递过去
rankView?.viewController = self
containerView.addSubview(rankView!)
rankView?.snp_makeConstraints(closure: { (make) in
make.left.equalTo((subscribeView?.snp_right)!)
make.top.bottom.equalTo(containerView)
make.width.equalTo(screenWidth)
})
//修改容器视图的大小
containerView.snp_makeConstraints { (make) in
make.right.equalTo(rankView!)
}
}
//下载首页的推荐数据
func downloadRecommendData() {
let downloader = U17Download()
downloader.delegate = self
downloader.downloadType = HomeDownloadType.HomeRecommend
downloader.getWithUrl(homeRecommendUrl)
}
func downloadVIPData() {
let downloader = U17Download()
downloader.delegate = self
downloader.downloadType = HomeDownloadType.HomeVIP
let tmpUrl = String(format: homeMoreUrl, 14,"topic",2)
downloader.getWithUrl(tmpUrl+"1")
}
func downloadSubscribeData() {
let downloader = U17Download()
downloader.delegate = self
downloader.downloadType = HomeDownloadType.HomeSubscribe
let tmpUrl = String(format: homeMoreUrl, 12,"topic",2)
downloader.getWithUrl(tmpUrl+"1")
}
func handleClickEvent(urlString: String, ticketUrl: String?, title: String? = nil) {
HomePageService.handleEvent(urlString, comicTicket: ticketUrl, title: title, onViewController: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
//MARK: 网址请求代理
extension HomePageViewController: U17DownloadDelegate {
//下载失败
func downloader(downloader: U17Download, didFailWithError error: NSError) {
print(error)
}
//下载成功
func downloader(downloader: U17Download, didFinishWithData data: NSData?) {
if let tmpData = data {
if downloader.downloadType == HomeDownloadType.HomeRecommend {
//1.json解析
let model = HomeRecommend.parseData(tmpData)
recommendView!.model = model
recommendView!.jumpClosure = {
[weak self](jumpUrl,ticketUrl,title) in
self!.handleClickEvent(jumpUrl, ticketUrl: ticketUrl, title: title)
}
}else if downloader.downloadType == HomeDownloadType.HomeVIP {
//VIP页面
if let model = HomeVIPModel.parseData(tmpData).data?.returnData?.comics {
VIPView?.model = model
VIPView?.downloadType = .HomeVIP
VIPView?.viewType = ViewType.VIP
VIPView!.jumpClosure = {
[weak self](jumpUrl,ticketUrl,title) in
self!.handleClickEvent(jumpUrl, ticketUrl: ticketUrl)
}
}
}else if downloader.downloadType == HomeDownloadType.HomeSubscribe {
//分类页面
if let model = HomeVIPModel.parseData(tmpData).data?.returnData?.comics {
subscribeView?.model = model
VIPView?.downloadType = .HomeSubscribe
subscribeView?.viewType = ViewType.Subscribe
subscribeView!.jumpClosure = {
[weak self](jumpUrl,ticketUrl,title) in
self!.handleClickEvent(jumpUrl, ticketUrl: ticketUrl)
}
}
}
}else {
print(data)
}
}
}
//MARK: CustomSegCtrl代理
extension HomePageViewController: CustomSegCtrlDelegate {
func segmentCtrl(segCtrl: CustomSegCtrl, didClickBtnAtIndex index: Int) {
scrollView?.setContentOffset(CGPointMake(CGFloat(index)*screenWidth, 0), animated: true)
if index == 1 {
VIPView?.downloadType = .HomeVIP
}else if index == 2 {
subscribeView?.downloadType = .HomeSubscribe
}
}
}
//MARK: UIScrollView的代理
extension HomePageViewController: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let index = scrollView.contentOffset.x / scrollView.bounds.width
segCtrl?.selectedIndex = Int(index)
if index == 1 {
VIPView?.downloadType = .HomeVIP
}else if index == 2 {
subscribeView?.downloadType = .HomeSubscribe
}
}
} | mit | 2dd35d759c857622ee7af2ef9dacbba7 | 33.224299 | 108 | 0.600983 | 4.872255 | false | false | false | false |
bigL055/Routable | Example/Routable/ViewController.swift | 1 | 5357 | //
// ViewController.swift
// Routable
//
// Created by linhay on 06/10/2017.
// Copyright (c) 2017 linhay. All rights reserved.
//
import UIKit
import SPRoutable
import BModules
import RoutableAssist
import SPKit
//import AModules
class ViewController: UITableViewController {
struct CellUnit {
let title = ""
let leftURL = ""
let rightURL = ""
}
var resultTests = [(title: "获取 int 类型返回值",
objc: "sp://objc/int",
swift: "sp://swift/int"),
(title: "获取 double 类型返回值",
objc: "sp://objc/double",
swift: "sp://swift/double"),
(title: "获取 string/NSString 类型返回值",
objc: "sp://objc/string",
swift: "sp://swift/string"),
(title: "获取 cgfloat 类型返回值",
objc: "sp://objc/cgfloat",
swift: "sp://swift/cgfloat"),
(title: "获取 bool 类型返回值",
objc: "sp://objc/boolValue",
swift: "sp://swift/boolValue"),
(title: "获取 dictionary 类型返回值",
objc: "sp://objc/dictionary",
swift: "sp://swift/dictionary"),
(title: "获取 selector 类型返回值",
objc: "sp://objc/selector",
swift: "sp://swift/selector"),
(title: "获取 viewcontroller 类型返回值",
objc: "sp://objc/vc",
swift: "sp://swift/vc"),
(title: "获取 asyncWithoutReturn/异步 返回值",
objc: "sp://objc/async",
swift: "sp://swift/async?title=title"),
(title: "获取 asyncWithReturn/异步 返回值",
objc: "sp://objc/async",
swift: "sp://swift/async?title=title")]
var rewriteRule = ["http://rewrite/vc?title=rewrite&test=1" : "http://web/vc?url=https://m.baidu.com/s&word=$title&title=vcName"]
override func viewDidLoad() {
super.viewDidLoad()
title = "Routable"
Routable.configs.set(scheme: "*", classPrefix: "Router_", funcPrefix: "", remark: "")
// Routable.rewrite(rules:rewriteRule)
tableView.sp.register(URLReturnValueCell.self)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultTests.count + 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.sp.dequeueCell(indexPath) as URLReturnValueCell
switch indexPath.item {
case 0..<resultTests.count:
let item = resultTests[indexPath.item]
cell.label.text = item.title
cell.leftBtn.setTitle(item.objc, for: .normal)
cell.rightBtn.setTitle(item.swift, for: .normal)
cell.leftBtn.add(for: .touchUpInside) {
let value = Routable.object(str: item.objc,params: ["param1" : "title"]) { (result) in
self.alert(title: item.title, message: String(describing: result))
}
guard let result = value else { return }
self.alert(title: item.title, message: String(describing: result))
}
cell.rightBtn.add(for: .touchUpInside) {
let value = Routable.object(str: item.swift,params: ["param1" : "title"]) { (result) in
self.alert(title: item.title, message: String(describing: result))
}
guard let result = value else { return }
self.alert(title: item.title, message: String(describing: result))
}
default:
cell.label.text =
"""
RewriteRule:
http://rewrite/vc?title=rewrite&test=1
http://web/vc?url=https://m.baidu.com/s&word=$title&title=vcName
[先执行覆盖: title=vcName, 后执行新增: word=$title]
RewriteAfter:
http://web/vc
?url=https://m.baidu.com/s
&word=vcName
&title=vcName
&test=1
"""
cell.leftBtn.setTitle(self.rewriteRule.keys.first!, for: .normal)
cell.rightBtn.setTitle(self.rewriteRule.keys.first!, for: .normal)
cell.leftBtn.add(for: .touchUpInside) {
// Routable.rewrite(rules: self.rewriteRule)
guard let vc = Routable.viewController(str: self.rewriteRule.keys.first!) else { return }
self.navigationController?.pushViewController(vc, animated: true)
}
cell.rightBtn.add(for: .touchUpInside) {
// Routable.rewrite(rules: [:])
guard let vc = Routable.viewController(str: self.rewriteRule.keys.first!) else { return }
self.navigationController?.pushViewController(vc, animated: true)
}
}
return cell
}
func alert(title: String, message: String) {
let alert = UIAlertController(title: title,
message: message,
preferredStyle: .alert)
let action = UIAlertAction(title: "done",
style: .cancel,
handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
}
| mit | 9cdccb129661ff61e1679620b122c87e | 34.114865 | 131 | 0.552627 | 4.211507 | false | false | false | false |
OSzhou/MyTestDemo | 18_GCD_Test/GCD_Test/Classes/FMRootViewController.swift | 1 | 3946 | //
// FMRootViewController.swift
// GCD_Test
//
// Created by Zhouheng on 2020/8/5.
// Copyright © 2020 tataUFO. All rights reserved.
//
import UIKit
// MARK: 屏幕高度
let screenHeight: CGFloat = UIScreen.main.bounds.height
// MARK: 屏幕宽度
let screenWidth: CGFloat = UIScreen.main.bounds.width
class FMRootViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .gray
setupUI()
}
private func setupUI() {
view.addSubview(magnifyButton)
view.addSubview(cameraButton)
view.addSubview(albumButton)
view.addSubview(otherButton)
// view.addSubview(popButton)
// view.addSubview(reminderButton)
}
/// MARK: --- action
@objc private func toMagnifyView(_ sender: UIButton) {
self.navigationController?.pushViewController(FMQuestionsViewController(), animated: true)
}
@objc private func customCamera(_ sender: UIButton) {
self.navigationController?.pushViewController(FMPrintViewController(), animated: true)
}
@objc private func customAlbum(_ sender: UIButton) {
self.navigationController?.pushViewController(FMGroupViewController(), animated: true)
}
@objc private func other(_ sender: UIButton) {
self.navigationController?.pushViewController(FMBarrierViewController(), animated: true)
}
@objc private func popAction(_ sender: UIButton) {
}
@objc private func reminderAction(_ sender: UIButton) {
// self.navigationController?.pushViewController(FMCalendarAndReminderViewController(), animated: true)
}
/// MARK: --- lazy loading
lazy var magnifyButton: UIButton = {
let button = UIButton(frame: CGRect(x: (screenWidth - 200) / 2, y: 88 + 50, width: 200, height: 50))
button.setTitle("? ? ?", for: .normal)
button.addTarget(self, action: #selector(toMagnifyView(_:)), for: .touchUpInside)
button.backgroundColor = .gray
return button
}()
lazy var cameraButton: UIButton = {
let button = UIButton(frame: CGRect(x: (screenWidth - 200) / 2, y: 88 + 110, width: 200, height: 50))
button.setTitle("print", for: .normal)
button.addTarget(self, action: #selector(customCamera(_:)), for: .touchUpInside)
button.backgroundColor = .gray
return button
}()
lazy var albumButton: UIButton = {
let button = UIButton(frame: CGRect(x: (screenWidth - 200) / 2, y: 88 + 170, width: 200, height: 50))
button.setTitle("group", for: .normal)
button.addTarget(self, action: #selector(customAlbum(_:)), for: .touchUpInside)
button.backgroundColor = .gray
return button
}()
lazy var otherButton: UIButton = {
let button = UIButton(frame: CGRect(x: (screenWidth - 200) / 2, y: 88 + 230, width: 200, height: 50))
button.setTitle("barrier", for: .normal)
button.addTarget(self, action: #selector(other(_:)), for: .touchUpInside)
button.backgroundColor = .gray
return button
}()
lazy var popButton: UIButton = {
let button = UIButton(frame: CGRect(x: (screenWidth - 200) / 2, y: 88 + 290, width: 200, height: 50))
button.setTitle("弹框", for: .normal)
button.addTarget(self, action: #selector(popAction(_:)), for: .touchUpInside)
button.backgroundColor = .gray
return button
}()
lazy var reminderButton: UIButton = {
let button = UIButton(frame: CGRect(x: (screenWidth - 200) / 2, y: 88 + 360, width: 200, height: 50))
button.setTitle("提醒", for: .normal)
button.addTarget(self, action: #selector(reminderAction(_:)), for: .touchUpInside)
button.backgroundColor = .gray
return button
}()
}
| apache-2.0 | 227dd37f3f2beda758e742d53b55778a | 34.645455 | 110 | 0.633512 | 4.376116 | false | false | false | false |
buscarini/JMSSwiftParse | Source/parseAny.swift | 1 | 17134 | //
// parseAny.swift
// JMSSwiftParse
//
// Created by Jose Manuel Sánchez Peñarroja on 18/11/14.
// Copyright (c) 2014 José Manuel Sánchez. All rights reserved.
//
import Foundation
// MARK: T <-> AnyObject
public func parse<T: Hashable>(inout property: T?, value: AnyObject,validate: (T)->Bool) -> Bool {
var converted : T?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse<T: Hashable>(inout property: T?, value: AnyObject) -> Bool {
var converted : T?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse<T: Hashable>(inout property: T, value: AnyObject,validate: (T)->Bool) -> Bool {
var converted : T?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse<T: Hashable>(inout property: T, value: AnyObject) -> Bool {
var converted : T?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse<T: Hashable>(inout property: T?, value: AnyObject?,validate: (T)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : T?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse<T: Hashable>(inout property: T?, value: AnyObject?) -> Bool {
if let validValue : AnyObject = value {
var converted : T?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse<T: Hashable>(inout property: T, value: AnyObject?,validate: (T)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : T?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse<T: Hashable>(inout property: T, value: AnyObject?) -> Bool {
if let validValue : AnyObject = value {
var converted : T?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: NSDate <-> AnyObject
public func parse(inout property: NSDate?, value: AnyObject, format: String,validate: (NSDate)->Bool) -> Bool {
var converted : NSDate?
downcast(&converted, value, format)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSDate?, value: AnyObject, format: String) -> Bool {
var converted : NSDate?
downcast(&converted, value, format)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSDate, value: AnyObject, format: String,validate: (NSDate)->Bool) -> Bool {
var converted : NSDate?
downcast(&converted, value, format)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSDate, value: AnyObject, format: String) -> Bool {
var converted : NSDate?
downcast(&converted, value, format)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSDate?, value: AnyObject?, format: String,validate: (NSDate)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : NSDate?
downcast(&converted, value, format)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSDate?, value: AnyObject?, format: String) -> Bool {
if let validValue : AnyObject = value {
var converted : NSDate?
downcast(&converted, value, format)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSDate, value: AnyObject?, format: String,validate: (NSDate)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : NSDate?
downcast(&converted, value, format)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSDate, value: AnyObject?, format: String) -> Bool {
if let validValue : AnyObject = value {
var converted : NSDate?
downcast(&converted, value, format)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: String <-> AnyObject
public func parse(inout property: String?, value: AnyObject,validate: (String)->Bool) -> Bool {
var converted : String?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: String?, value: AnyObject) -> Bool {
var converted : String?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: String, value: AnyObject,validate: (String)->Bool) -> Bool {
var converted : String?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: String, value: AnyObject) -> Bool {
var converted : String?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: String?, value: AnyObject?,validate: (String)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : String?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: String?, value: AnyObject?) -> Bool {
if let validValue : AnyObject = value {
var converted : String?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: String, value: AnyObject?,validate: (String)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : String?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: String, value: AnyObject?) -> Bool {
if let validValue : AnyObject = value {
var converted : String?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: NSString <-> AnyObject
public func parse(inout property: NSString?, value: AnyObject,validate: (NSString)->Bool) -> Bool {
var converted : NSString?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSString?, value: AnyObject) -> Bool {
var converted : NSString?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSString, value: AnyObject,validate: (NSString)->Bool) -> Bool {
var converted : NSString?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSString, value: AnyObject) -> Bool {
var converted : NSString?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSString?, value: AnyObject?,validate: (NSString)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : NSString?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSString?, value: AnyObject?) -> Bool {
if let validValue : AnyObject = value {
var converted : NSString?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSString, value: AnyObject?,validate: (NSString)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : NSString?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSString, value: AnyObject?) -> Bool {
if let validValue : AnyObject = value {
var converted : NSString?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: NSURL <-> AnyObject
public func parse(inout property: NSURL?, value: AnyObject,validate: (NSURL)->Bool) -> Bool {
var converted : NSURL?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSURL?, value: AnyObject) -> Bool {
var converted : NSURL?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSURL, value: AnyObject,validate: (NSURL)->Bool) -> Bool {
var converted : NSURL?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSURL, value: AnyObject) -> Bool {
var converted : NSURL?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSURL?, value: AnyObject?,validate: (NSURL)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : NSURL?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSURL?, value: AnyObject?) -> Bool {
if let validValue : AnyObject = value {
var converted : NSURL?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSURL, value: AnyObject?,validate: (NSURL)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : NSURL?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSURL, value: AnyObject?) -> Bool {
if let validValue : AnyObject = value {
var converted : NSURL?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: Bool <-> AnyObject
public func parse(inout property: Bool?, value: AnyObject,validate: (Bool)->Bool) -> Bool {
var converted : Bool?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Bool?, value: AnyObject) -> Bool {
var converted : Bool?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Bool, value: AnyObject,validate: (Bool)->Bool) -> Bool {
var converted : Bool?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Bool, value: AnyObject) -> Bool {
var converted : Bool?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Bool?, value: AnyObject?,validate: (Bool)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : Bool?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Bool?, value: AnyObject?) -> Bool {
if let validValue : AnyObject = value {
var converted : Bool?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: Bool, value: AnyObject?,validate: (Bool)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : Bool?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Bool, value: AnyObject?) -> Bool {
if let validValue : AnyObject = value {
var converted : Bool?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: Int <-> AnyObject
public func parse(inout property: Int?, value: AnyObject,validate: (Int)->Bool) -> Bool {
var converted : Int?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Int?, value: AnyObject) -> Bool {
var converted : Int?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Int, value: AnyObject,validate: (Int)->Bool) -> Bool {
var converted : Int?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Int, value: AnyObject) -> Bool {
var converted : Int?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Int?, value: AnyObject?,validate: (Int)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : Int?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Int?, value: AnyObject?) -> Bool {
if let validValue : AnyObject = value {
var converted : Int?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: Int, value: AnyObject?,validate: (Int)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : Int?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Int, value: AnyObject?) -> Bool {
if let validValue : AnyObject = value {
var converted : Int?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: NSNumber <-> AnyObject
public func parse(inout property: NSNumber?, value: AnyObject,validate: (NSNumber)->Bool) -> Bool {
var converted : NSNumber?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSNumber?, value: AnyObject) -> Bool {
var converted : NSNumber?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSNumber, value: AnyObject,validate: (NSNumber)->Bool) -> Bool {
var converted : NSNumber?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSNumber, value: AnyObject) -> Bool {
var converted : NSNumber?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSNumber?, value: AnyObject?,validate: (NSNumber)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : NSNumber?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSNumber?, value: AnyObject?) -> Bool {
if let validValue : AnyObject = value {
var converted : NSNumber?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSNumber, value: AnyObject?,validate: (NSNumber)->Bool) -> Bool {
if let validValue : AnyObject = value {
var converted : NSNumber?
downcast(&converted, value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSNumber, value: AnyObject?) -> Bool {
if let validValue : AnyObject = value {
var converted : NSNumber?
downcast(&converted, value)
if let valid = converted {
property = valid
return true
}
}
return false
}
| mit | 89c278cd6091dd3b03edfd355cb29bd3 | 20.574307 | 112 | 0.678225 | 3.44668 | false | false | false | false |
zalando/zmon-ios | zmon/persistence/Team.swift | 1 | 2929 | //
// Team.swift
// zmon
//
// Created by Andrej Kincel on 17/12/15.
// Copyright © 2015 Zalando Tech. All rights reserved.
//
import Foundation
class Team: NSObject, NSCoding {
//MARK: Persistence names
static let teamListPropertyName = "zmon.team.teamList"
static let namePropertyName = "zmon.team.name"
static let observedPropertyName = "zmon.team.observed"
private static var teamList: [Team] = {
//If teamList was previously persisted on disk, fetch it, otherwise return an empty array
let defaults = NSUserDefaults.standardUserDefaults()
let teamListData = defaults.objectForKey(Team.teamListPropertyName)
if teamListData != nil {
let teamList = NSKeyedUnarchiver.unarchiveObjectWithData(teamListData as! NSData)
return teamList as! [Team]
}
return []
}()
//MARK: Properties
var name: String
var observed: Bool
//MARK: Initialization
init(name: String, observed: Bool) {
self.name = name
self.observed = observed
}
//MARK: NSCoding
required convenience init?(coder decoder: NSCoder) {
let observed = decoder.decodeBoolForKey(Team.observedPropertyName)
guard let name = decoder.decodeObjectForKey(Team.namePropertyName) as? String
else {
return nil;
}
self.init(name: name, observed: observed)
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.name, forKey:Team.namePropertyName)
coder.encodeBool(self.observed, forKey: Team.observedPropertyName)
}
func save() {
let idx = Team.teamList.indexOf { (team: Team) -> Bool in
return team.name == self.name
}
if (idx == nil) {
Team.teamList.append(self)
}
else {
Team.teamList.removeAtIndex(idx!)
Team.teamList.append(self)
}
self.persistObservedTeams()
}
func persistObservedTeams() {
let defaults = NSUserDefaults.standardUserDefaults()
let data = NSKeyedArchiver.archivedDataWithRootObject(Team.teamList)
defaults.setObject(data, forKey: Team.teamListPropertyName);
}
static func findByName(name name: String) -> Team? {
let idx = Team.teamList.indexOf { (team: Team) -> Bool in
return team.name == name
}
if (idx != nil) {
return Team.teamList[idx!]
}
else {
return nil
}
}
static func allObservedTeamNames() -> [String] {
return Team.teamList
.filter({ (team: Team) -> Bool in
return (team.observed) ? true: false
})
.map({ (team: Team) -> String in
return team.name
})
}
}
| mit | d5106f7f3ad6143b4bef7dd189b06486 | 27.427184 | 97 | 0.579235 | 4.611024 | false | false | false | false |
dexafree/SayCheese | SayCheese/PreferencesWindowController.swift | 2 | 3866 | //
// PreferencesViewController.swift
// SayCheese
//
// Created by Arasthel on 15/06/14.
// Copyright (c) 2014 Jorge Martín Espinosa. All rights reserved.
//
import Cocoa
class PreferencesWindowController: NSWindowController, ReceivedImgurAuthenticationDelegate {
var imgurClient: ImgurClient?
@IBOutlet var signInButton: NSButton!
@IBOutlet var pinCodeTextField: NSTextField!
@IBOutlet var savePinButton: NSButton!
@IBOutlet var hotKeyTextField: HotkeyTextField!
@IBOutlet var stateTextField: NSTextField!
@IBOutlet var launchLoginCheckBox: NSButton!
@IBOutlet var versionLabel: NSTextField!
override init(window: NSWindow?) {
super.init(window: window)
if self.window != nil {
self.window!.releasedWhenClosed = false
window!.level = 20
}
}
required init?(coder aDecoder: NSCoder){
super.init(coder: aDecoder)
}
override func showWindow(sender: AnyObject!) {
super.showWindow(sender)
if self.window != nil {
NSBundle.mainBundle().loadNibNamed("PreferencesWindowController", owner: self, topLevelObjects: nil)
}
self.window?.level = 20
self.window?.makeKeyAndOrderFront(self)
self.window?.makeFirstResponder(launchLoginCheckBox!)
NSApplication.sharedApplication().activateIgnoringOtherApps(true)
println("HasAccount: \(imgurClient!.hasAccount()!)")
if imgurClient!.hasAccount()! {
pinCodeTextField!.enabled = false
stateTextField.stringValue = "Logged successfully into Imgur."
signInButton.title = "Sign out"
} else {
stateTextField.stringValue = "You haven't logged into Imgur yet."
}
let startUpUtil = StartUpUtils()
if startUpUtil.isAppALoginItem() {
if launchLoginCheckBox != nil {
launchLoginCheckBox!.state = NSOnState
}
} else {
if launchLoginCheckBox != nil {
launchLoginCheckBox!.state = NSOffState
}
}
if versionLabel != nil {
let version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
versionLabel!.stringValue = "SayCheese \(version)"
}
}
@IBAction func toggleImgurAccount(sender: AnyObject) {
if imgurClient!.hasAccount()! {
signOut()
} else {
pinCodeTextField.enabled = true
stateTextField.stringValue = "You haven't logged into Imgur yet."
imgurClient!.authenticate(false)
}
}
@IBAction func codeWritten(sender: AnyObject?) {
let code = pinCodeTextField.stringValue
savePinButton!.enabled = false
NSLog(code)
imgurClient!.imgurSession!.authenticateWithCode(code)
}
func authenticationInImgurSuccessful() {
pinCodeTextField.enabled = false
signInButton.title = "Sign out"
stateTextField.stringValue = "Logged successfully into Imgur."
}
@IBAction func toggleLaunchOnBoot(sender: NSButton?) {
let startUpUtil = StartUpUtils()
if startUpUtil.isAppALoginItem() == false {
startUpUtil.addAppAsLoginItem()
} else {
startUpUtil.deleteAppFromLoginItem()
}
}
func signOut(){
pinCodeTextField.enabled = false
stateTextField.stringValue = "You haven't logged into Imgur yet."
signInButton.title = "Sign in"
imgurClient!.signOut()
}
func activatePinButton() {
savePinButton!.enabled = true
}
}
| apache-2.0 | 5bb08a076669e3ce5254e93cda94c26b | 28.06015 | 115 | 0.600776 | 5.272851 | false | false | false | false |
NathanE73/Blackboard | Sources/BlackboardFramework/Extensions/Dictionary.swift | 1 | 1567 | //
// Copyright (c) 2022 Nathan E. Walczak
//
// MIT License
//
// 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
extension Dictionary where Key == String, Value == String {
@inlinable
init(_ dictionary: NSDictionary) {
var results: [String: String] = [:]
dictionary.forEach { key, value in
if let key = key as? String,
let value = value as? String {
results[key] = value
}
}
self = results
}
}
| mit | e101debafed486f3ca7f7e19b0f3f1a3 | 35.44186 | 80 | 0.685386 | 4.649852 | false | false | false | false |
golfiti/KWBannerSwift | KWBannerSwift/ViewController.swift | 1 | 1095 | //
// ViewController.swift
// KWBannerSwift
//
// Created by Kridsanapong Wongthongdee on 7/8/2559 BE.
// Copyright © 2559 Kridsanapong Wongthongdee. All rights reserved.
//
import UIKit
class ViewController: UIViewController, KWBannerViewDelegate{
@IBOutlet weak var bannerView: KWBannerView!
override func viewDidLoad() {
super.viewDidLoad()
bannerView.delegate = self;
bannerView.imagesName = ["image2","image1","image2","image1"]
bannerView.isAutoScroll = true
bannerView.drawBanner()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
func didTapBannerAtIndex(bannerIndex:CGFloat) {
print("Tap Banner at Index \(bannerIndex)")
bannerView.imagesName = ["image1","image1","image1","image1"]
bannerView.isAutoScroll = true
bannerView.drawBanner()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 7d8c7aa4b4e546639fd23c778f86cf46 | 25.047619 | 69 | 0.651737 | 4.539419 | false | false | false | false |
phatblat/Nimble | Sources/Nimble/Matchers/Match.swift | 47 | 954 | import Foundation
/// A Nimble matcher that succeeds when the actual string satisfies the regular expression
/// described by the expected string.
public func match(_ expectedValue: String?) -> Predicate<String> {
return Predicate.simple("match <\(stringify(expectedValue))>") { actualExpression in
if let actual = try actualExpression.evaluate() {
if let regexp = expectedValue {
let bool = actual.range(of: regexp, options: .regularExpression) != nil
return PredicateStatus(bool: bool)
}
}
return .fail
}
}
#if canImport(Darwin)
extension NMBObjCMatcher {
@objc public class func matchMatcher(_ expected: NSString) -> NMBMatcher {
return NMBPredicate { actualExpression in
let actual = actualExpression.cast { $0 as? String }
return try match(expected.description).satisfies(actual).toObjectiveC()
}
}
}
#endif
| apache-2.0 | 7dbe1e000419f970f5aa629303b8510b | 31.896552 | 90 | 0.65304 | 5.047619 | false | false | false | false |
mitochrome/complex-gestures-demo | apps/GestureRecognizer/Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/UITextField+RxTests.swift | 12 | 1210 | //
// UITextField+RxTests.swift
// Tests
//
// Created by Krunoslav Zaher on 5/13/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import XCTest
// UITextField
final class UITextFieldTests : RxTest {
func test_TextCompletesOnDealloc() {
ensurePropertyDeallocated({ UITextField() }, "a", comparer: { $0 == $1 }) { (view: UITextField) in view.rx.text }
}
func test_ValueCompletesOnDealloc() {
ensurePropertyDeallocated({ UITextField() }, "a", comparer: { $0 == $1 }) { (view: UITextField) in view.rx.value }
}
func testSettingTextDoesntClearMarkedText() {
let textField = UITextFieldSubclass(frame: CGRect.zero)
textField.text = "Text1"
textField.set = false
textField.rx.text.on(.next("Text1"))
XCTAssertTrue(!textField.set)
textField.rx.text.on(.next("Text2"))
XCTAssertTrue(textField.set)
}
}
final class UITextFieldSubclass : UITextField {
var set: Bool = false
override var text: String? {
get {
return super.text
}
set {
set = true
super.text = newValue
}
}
}
| mit | be2fa5bc5f8b561a90923364250866e6 | 24.723404 | 122 | 0.618693 | 4.098305 | false | true | false | false |
VladiMihaylenko/omim | iphone/Maps/UI/Appearance/ThemeManager.swift | 1 | 1879 | @objc(MWMThemeManager)
final class ThemeManager: NSObject {
private static let autoUpdatesInterval: TimeInterval = 30 * 60 // 30 minutes in seconds
private static let instance = ThemeManager()
private weak var timer: Timer?
private override init() { super.init() }
private func update(theme: MWMTheme) {
let actualTheme: MWMTheme = { theme in
let isVehicleRouting = MWMRouter.isRoutingActive() && (MWMRouter.type() == .vehicle)
switch theme {
case .day: fallthrough
case .vehicleDay: return isVehicleRouting ? .vehicleDay : .day
case .night: fallthrough
case .vehicleNight: return isVehicleRouting ? .vehicleNight : .night
case .auto:
guard isVehicleRouting else { return .day }
switch FrameworkHelper.daytime() {
case .day: return .vehicleDay
case .night: return .vehicleNight
}
}
}(theme)
let nightMode = UIColor.isNightMode()
let newNightMode: Bool = { theme in
switch theme {
case .day: fallthrough
case .vehicleDay: return false
case .night: fallthrough
case .vehicleNight: return true
case .auto: assert(false); return false
}
}(actualTheme)
FrameworkHelper.setTheme(actualTheme)
if nightMode != newNightMode {
UIColor.setNightMode(newNightMode)
(UIViewController.topViewController() as! MWMController).mwm_refreshUI()
}
}
@objc static func invalidate() {
instance.update(theme: MWMSettings.theme())
}
@objc static var autoUpdates: Bool {
get {
return instance.timer != nil
}
set {
if newValue {
instance.timer = Timer.scheduledTimer(timeInterval: autoUpdatesInterval, target: self, selector: #selector(invalidate), userInfo: nil, repeats: true)
} else {
instance.timer?.invalidate()
}
invalidate()
}
}
}
| apache-2.0 | 3bd7e049120f2c18774a6132ce50fb08 | 28.825397 | 157 | 0.656732 | 4.410798 | false | false | false | false |
studyYF/YueShiJia | YueShiJia/YueShiJia/Classes/Home/Views/YFItemCollectionCell.swift | 1 | 870 | //
// YFItemCollectionCell.swift
// YueShiJia
//
// Created by YangFan on 2017/5/11.
// Copyright © 2017年 YangFan. All rights reserved.
//
import UIKit
class YFItemCollectionCell: UICollectionViewCell {
//MARK: 属性
/// 图片
@IBOutlet weak var iconImageView: UIImageView!
/// 标题
@IBOutlet weak var titleLabel: UILabel!
/// 价格
@IBOutlet weak var priceLabel: UILabel!
var item: Goods_Special_List? {
didSet {
iconImageView.kf.setImage(with: URL(string: (item?.goods_img!)!))
titleLabel.text = item?.goods_name
priceLabel.text = "¥\((item?.goods_price)!)"
}
}
override func awakeFromNib() {
super.awakeFromNib()
priceLabel.textColor = kColor
layer.borderWidth = 0.3
layer.borderColor = kColor.cgColor
}
}
| apache-2.0 | 2f099ef50357832632c7a2aaa1aae8aa | 21.945946 | 77 | 0.60424 | 4.161765 | false | false | false | false |
jarrroo/MarkupKitLint | Tools/Pods/Nimble/Sources/Nimble/Adapters/NMBExpectation.swift | 28 | 6323 | import Foundation
#if _runtime(_ObjC)
fileprivate func from(objcPredicate: NMBPredicate) -> Predicate<NSObject> {
return Predicate { actualExpression in
let result = objcPredicate.satisfies(({ try! actualExpression.evaluate() }),
location: actualExpression.location)
return result.toSwift()
}
}
internal struct ObjCMatcherWrapper: Matcher {
let matcher: NMBMatcher
func matches(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
return matcher.matches(
({ try! actualExpression.evaluate() }),
failureMessage: failureMessage,
location: actualExpression.location)
}
func doesNotMatch(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
return matcher.doesNotMatch(
({ try! actualExpression.evaluate() }),
failureMessage: failureMessage,
location: actualExpression.location)
}
}
// Equivalent to Expectation, but for Nimble's Objective-C interface
public class NMBExpectation: NSObject {
internal let _actualBlock: () -> NSObject!
internal var _negative: Bool
internal let _file: FileString
internal let _line: UInt
internal var _timeout: TimeInterval = 1.0
public init(actualBlock: @escaping () -> NSObject!, negative: Bool, file: FileString, line: UInt) {
self._actualBlock = actualBlock
self._negative = negative
self._file = file
self._line = line
}
private var expectValue: Expectation<NSObject> {
return expect(_file, line: _line) {
self._actualBlock() as NSObject?
}
}
public var withTimeout: (TimeInterval) -> NMBExpectation {
return ({ timeout in self._timeout = timeout
return self
})
}
public var to: (NMBMatcher) -> Void {
return ({ matcher in
if let pred = matcher as? NMBPredicate {
self.expectValue.to(from(objcPredicate: pred))
} else {
self.expectValue.to(ObjCMatcherWrapper(matcher: matcher))
}
})
}
public var toWithDescription: (NMBMatcher, String) -> Void {
return ({ matcher, description in
if let pred = matcher as? NMBPredicate {
self.expectValue.to(from(objcPredicate: pred), description: description)
} else {
self.expectValue.to(ObjCMatcherWrapper(matcher: matcher), description: description)
}
})
}
public var toNot: (NMBMatcher) -> Void {
return ({ matcher in
if let pred = matcher as? NMBPredicate {
self.expectValue.toNot(from(objcPredicate: pred))
} else {
self.expectValue.toNot(ObjCMatcherWrapper(matcher: matcher))
}
})
}
public var toNotWithDescription: (NMBMatcher, String) -> Void {
return ({ matcher, description in
if let pred = matcher as? NMBPredicate {
self.expectValue.toNot(from(objcPredicate: pred), description: description)
} else {
self.expectValue.toNot(ObjCMatcherWrapper(matcher: matcher), description: description)
}
})
}
public var notTo: (NMBMatcher) -> Void { return toNot }
public var notToWithDescription: (NMBMatcher, String) -> Void { return toNotWithDescription }
public var toEventually: (NMBMatcher) -> Void {
return ({ matcher in
if let pred = matcher as? NMBPredicate {
self.expectValue.toEventually(
from(objcPredicate: pred),
timeout: self._timeout,
description: nil
)
} else {
self.expectValue.toEventually(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: nil
)
}
})
}
public var toEventuallyWithDescription: (NMBMatcher, String) -> Void {
return ({ matcher, description in
if let pred = matcher as? NMBPredicate {
self.expectValue.toEventually(
from(objcPredicate: pred),
timeout: self._timeout,
description: description
)
} else {
self.expectValue.toEventually(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: description
)
}
})
}
public var toEventuallyNot: (NMBMatcher) -> Void {
return ({ matcher in
if let pred = matcher as? NMBPredicate {
self.expectValue.toEventuallyNot(
from(objcPredicate: pred),
timeout: self._timeout,
description: nil
)
} else {
self.expectValue.toEventuallyNot(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: nil
)
}
})
}
public var toEventuallyNotWithDescription: (NMBMatcher, String) -> Void {
return ({ matcher, description in
if let pred = matcher as? NMBPredicate {
self.expectValue.toEventuallyNot(
from(objcPredicate: pred),
timeout: self._timeout,
description: description
)
} else {
self.expectValue.toEventuallyNot(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: description
)
}
})
}
public var toNotEventually: (NMBMatcher) -> Void { return toEventuallyNot }
public var toNotEventuallyWithDescription: (NMBMatcher, String) -> Void { return toEventuallyNotWithDescription }
public class func failWithMessage(_ message: String, file: FileString, line: UInt) {
fail(message, location: SourceLocation(file: file, line: line))
}
}
#endif
| mit | 04317502aaa3e916c230ce1278a284a7 | 33.551913 | 117 | 0.559861 | 5.625445 | false | false | false | false |
multinerd/Mia | Mia/Toolkits/UpdateKit/UpdateKitWBObjC.swift | 1 | 6190 | //
// UpdateKitWBObjC.swift
// Mia
//
// Created by Michael Hedaitulla on 2/8/18.
//
import Foundation
import Alamofire
private let versionKey: String = "Multinerd.UpdateKitWB.CurrentVersion"
// This class has a very specific use case. Not for public use.
@objcMembers
@available(iOS 10.0, *)
public class UpdateKitWBObjC: NSObject {
// MARK: - *** Shared ***
public static let shared = UpdateKitWBObjC()
// MARK: - *** Configurations ***
public var isLoggingEnabled: Bool = true
/// FOR DEBUGGING ONLY. Setting this to false will ensure the current version will not be saved.
/// Use to test 'onFreshInstall' and 'onUpdate'
public var willSaveCurrentVersion: Bool = true {
didSet {
if willSaveCurrentVersion == false {
UserDefaults.standard.set(nil, forKey: versionKey)
}
}
}
/// Set the update type.
public var updateType: UpdateType = .normal
// MARK: - *** Properties ***
private var currentVersion: String {
return Application.BundleInfo.version.description
}
private var bundleIdentifier: String {
return Application.BundleInfo.identifier.description
}
// MARK: - *** Init/Deinit Methods ***
private override init() {}
// MARK: - *** Public Methods ***
/// Check for updates OTA
public func checkForUpdates(url: String) {
let postHeaders: HTTPHeaders = [ "Content-Type": "application/x-www-form-urlencoded" ]
let encoding: JSONEncoding = JSONEncoding.default
let parameters: [String: Any] = [ "BundleId": bundleIdentifier, "Version": currentVersion ]
let oldDecodeDate = CodableKit.Configurations.Decoding.dateStrategy
CodableKit.Configurations.Decoding.dateStrategy = .datetimeDotNet
log(message: "Checking for updates...")
Alamofire.request(url, method: .post, parameters: parameters, encoding: encoding, headers: postHeaders).responseData { (response) in
switch response.result {
case .failure(let error):
self.log(message: "Error \(error)")
case .success(let value):
if !value.isEmpty, let entities = AppStore_Apps_Version.decode(data: value) {
self.log(message: "Update Available | New: \(entities.versionString) | Cur: \(self.currentVersion)")
DispatchQueue.main.async(execute: { self.showAlert(url: entities.PList_URL) })
} else {
self.log(message: "No Updates Available")
}
CodableKit.Configurations.Decoding.dateStrategy = oldDecodeDate
}
}
}
// /// Compares the last ran version with the current version.
// ///
// /// - Returns: A LastRunType value.
// public func checkLastAppVersion() -> LastRunType {
//
// if let lastSavedVersion = UserDefaults.standard.string(forKey: versionKey) {
//
// if currentVersion.compare(lastSavedVersion, options: .numeric) == .orderedSame { return .noChanges }
// if currentVersion.compare(lastSavedVersion, options: .numeric) == .orderedDescending { return .updated }
// if currentVersion.compare(lastSavedVersion, options: .numeric) == .orderedAscending { return .downgraded }
//
// return .unknown
// } else {
// return .freshInstall
// }
// }
//
// /// Checks if the app was a fresh install.
// ///
// /// - Parameter completion: The callback block.
// public func onFreshInstall(_ completion: CheckBlock) {
//
// if self.checkLastAppVersion() == .freshInstall {
// if Configurations.willSaveCurrentVersion { saveCurrentVersion() }
// completion()
// }
// }
//
// /// Checks if the app was a updated.
// ///
// /// - Parameter completion: The callback block.
// public func onUpdate(_ completion: CheckBlock) {
//
// if self.checkLastAppVersion() == .updated {
// if Configurations.willSaveCurrentVersion { saveCurrentVersion() }
// completion()
// }
// }
// MARK: - *** Private Methods ***
private func showAlert(url: String) {
let title: String = "New Update Available!"
let message: String = "Would you like to install the new update?"
let okButtonTitle: String = "Update Now!"
let cancelButtonTitle: String = "Later..."
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: okButtonTitle, style: .default, handler: { Void in
guard let url = URL(string: self.createDownloadLink(url: url)) else { return }
UIApplication.shared.open(url, options: [:]) { if ($0 == true) { exit(0) } }
}))
if updateType == .normal {
alert.addAction(UIAlertAction(title: cancelButtonTitle, style: .cancel, handler: nil))
}
getTopMostController()?.present(alert, animated: true, completion: nil)
}
// MARK: - *** Helper Methods ***
private func saveCurrentVersion() {
UserDefaults.standard.set(currentVersion, forKey: versionKey)
}
private func createDownloadLink(url: String) -> String {
let urlPrefix = "https://s3.amazonaws.com/cactusappstore/"
var urlPath = url.replacingOccurrences(of: urlPrefix, with: "")
urlPath = urlPath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let newUrl = "\(urlPrefix)\(urlPath)"
return "itms-services://?action=download-manifest&url=\(newUrl)"
}
private func log(message: String) {
if isLoggingEnabled {
Rosewood.Framework.print(framework: String(describing: self), message: message)
}
}
}
| mit | 23ba000eae7c1b7f9e4f301da3356dda | 35.411765 | 140 | 0.586107 | 4.728801 | false | false | false | false |
jum/Charts | Source/Charts/Data/Implementations/Standard/CombinedChartData.swift | 8 | 7418 | //
// CombinedChartData.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
open class CombinedChartData: BarLineScatterCandleBubbleChartData
{
private var _lineData: LineChartData!
private var _barData: BarChartData!
private var _scatterData: ScatterChartData!
private var _candleData: CandleChartData!
private var _bubbleData: BubbleChartData!
public override init()
{
super.init()
}
public override init(dataSets: [IChartDataSet]?)
{
super.init(dataSets: dataSets)
}
@objc open var lineData: LineChartData!
{
get
{
return _lineData
}
set
{
_lineData = newValue
notifyDataChanged()
}
}
@objc open var barData: BarChartData!
{
get
{
return _barData
}
set
{
_barData = newValue
notifyDataChanged()
}
}
@objc open var scatterData: ScatterChartData!
{
get
{
return _scatterData
}
set
{
_scatterData = newValue
notifyDataChanged()
}
}
@objc open var candleData: CandleChartData!
{
get
{
return _candleData
}
set
{
_candleData = newValue
notifyDataChanged()
}
}
@objc open var bubbleData: BubbleChartData!
{
get
{
return _bubbleData
}
set
{
_bubbleData = newValue
notifyDataChanged()
}
}
open override func calcMinMax()
{
_dataSets.removeAll()
_yMax = -Double.greatestFiniteMagnitude
_yMin = Double.greatestFiniteMagnitude
_xMax = -Double.greatestFiniteMagnitude
_xMin = Double.greatestFiniteMagnitude
_leftAxisMax = -Double.greatestFiniteMagnitude
_leftAxisMin = Double.greatestFiniteMagnitude
_rightAxisMax = -Double.greatestFiniteMagnitude
_rightAxisMin = Double.greatestFiniteMagnitude
let allData = self.allData
for data in allData
{
data.calcMinMax()
let sets = data.dataSets
_dataSets.append(contentsOf: sets)
if data.yMax > _yMax
{
_yMax = data.yMax
}
if data.yMin < _yMin
{
_yMin = data.yMin
}
if data.xMax > _xMax
{
_xMax = data.xMax
}
if data.xMin < _xMin
{
_xMin = data.xMin
}
for dataset in sets
{
if dataset.axisDependency == .left
{
if dataset.yMax > _leftAxisMax
{
_leftAxisMax = dataset.yMax
}
if dataset.yMin < _leftAxisMin
{
_leftAxisMin = dataset.yMin
}
}
else
{
if dataset.yMax > _rightAxisMax
{
_rightAxisMax = dataset.yMax
}
if dataset.yMin < _rightAxisMin
{
_rightAxisMin = dataset.yMin
}
}
}
}
}
/// All data objects in row: line-bar-scatter-candle-bubble if not null.
@objc open var allData: [ChartData]
{
var data = [ChartData]()
if lineData !== nil
{
data.append(lineData)
}
if barData !== nil
{
data.append(barData)
}
if scatterData !== nil
{
data.append(scatterData)
}
if candleData !== nil
{
data.append(candleData)
}
if bubbleData !== nil
{
data.append(bubbleData)
}
return data
}
@objc open func dataByIndex(_ index: Int) -> ChartData
{
return allData[index]
}
open func dataIndex(_ data: ChartData) -> Int?
{
return allData.firstIndex(of: data)
}
open override func removeDataSet(_ dataSet: IChartDataSet) -> Bool
{
return allData.contains { $0.removeDataSet(dataSet) }
}
open override func removeDataSetByIndex(_ index: Int) -> Bool
{
print("removeDataSet(index) not supported for CombinedData", terminator: "\n")
return false
}
open override func removeEntry(_ entry: ChartDataEntry, dataSetIndex: Int) -> Bool
{
print("removeEntry(entry, dataSetIndex) not supported for CombinedData", terminator: "\n")
return false
}
open override func removeEntry(xValue: Double, dataSetIndex: Int) -> Bool
{
print("removeEntry(xValue, dataSetIndex) not supported for CombinedData", terminator: "\n")
return false
}
open override func notifyDataChanged()
{
if _lineData !== nil
{
_lineData.notifyDataChanged()
}
if _barData !== nil
{
_barData.notifyDataChanged()
}
if _scatterData !== nil
{
_scatterData.notifyDataChanged()
}
if _candleData !== nil
{
_candleData.notifyDataChanged()
}
if _bubbleData !== nil
{
_bubbleData.notifyDataChanged()
}
super.notifyDataChanged() // recalculate everything
}
/// Get the Entry for a corresponding highlight object
///
/// - Parameters:
/// - highlight:
/// - Returns: The entry that is highlighted
open override func entryForHighlight(_ highlight: Highlight) -> ChartDataEntry?
{
if highlight.dataIndex >= allData.count
{
return nil
}
let data = dataByIndex(highlight.dataIndex)
if highlight.dataSetIndex >= data.dataSetCount
{
return nil
}
// The value of the highlighted entry could be NaN - if we are not interested in highlighting a specific value.
let entries = data.getDataSetByIndex(highlight.dataSetIndex).entriesForXValue(highlight.x)
return entries.first { $0.y == highlight.y || highlight.y.isNaN }
}
/// Get dataset for highlight
///
/// - Parameters:
/// - highlight: current highlight
/// - Returns: dataset related to highlight
@objc open func getDataSetByHighlight(_ highlight: Highlight) -> IChartDataSet!
{
if highlight.dataIndex >= allData.count
{
return nil
}
let data = dataByIndex(highlight.dataIndex)
if highlight.dataSetIndex >= data.dataSetCount
{
return nil
}
return data.dataSets[highlight.dataSetIndex]
}
}
| apache-2.0 | 525a606f4de2dd97377f961c5f441114 | 23.644518 | 119 | 0.498787 | 5.590053 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/LanguageCode.swift | 1 | 6156 | //
// LanguageCode.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. 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 Foundation
extension Storefront {
/// ISO 639-1 language codes supported by Shopify.
public enum LanguageCode: String {
/// Afrikaans.
case af = "AF"
/// Akan.
case ak = "AK"
/// Amharic.
case am = "AM"
/// Arabic.
case ar = "AR"
/// Assamese.
case `as` = "AS"
/// Azerbaijani.
case az = "AZ"
/// Belarusian.
case be = "BE"
/// Bulgarian.
case bg = "BG"
/// Bambara.
case bm = "BM"
/// Bangla.
case bn = "BN"
/// Tibetan.
case bo = "BO"
/// Breton.
case br = "BR"
/// Bosnian.
case bs = "BS"
/// Catalan.
case ca = "CA"
/// Chechen.
case ce = "CE"
/// Czech.
case cs = "CS"
/// Church Slavic.
case cu = "CU"
/// Welsh.
case cy = "CY"
/// Danish.
case da = "DA"
/// German.
case de = "DE"
/// Dzongkha.
case dz = "DZ"
/// Ewe.
case ee = "EE"
/// Greek.
case el = "EL"
/// English.
case en = "EN"
/// Esperanto.
case eo = "EO"
/// Spanish.
case es = "ES"
/// Estonian.
case et = "ET"
/// Basque.
case eu = "EU"
/// Persian.
case fa = "FA"
/// Fulah.
case ff = "FF"
/// Finnish.
case fi = "FI"
/// Faroese.
case fo = "FO"
/// French.
case fr = "FR"
/// Western Frisian.
case fy = "FY"
/// Irish.
case ga = "GA"
/// Scottish Gaelic.
case gd = "GD"
/// Galician.
case gl = "GL"
/// Gujarati.
case gu = "GU"
/// Manx.
case gv = "GV"
/// Hausa.
case ha = "HA"
/// Hebrew.
case he = "HE"
/// Hindi.
case hi = "HI"
/// Croatian.
case hr = "HR"
/// Hungarian.
case hu = "HU"
/// Armenian.
case hy = "HY"
/// Interlingua.
case ia = "IA"
/// Indonesian.
case id = "ID"
/// Igbo.
case ig = "IG"
/// Sichuan Yi.
case ii = "II"
/// Icelandic.
case `is` = "IS"
/// Italian.
case it = "IT"
/// Japanese.
case ja = "JA"
/// Javanese.
case jv = "JV"
/// Georgian.
case ka = "KA"
/// Kikuyu.
case ki = "KI"
/// Kazakh.
case kk = "KK"
/// Kalaallisut.
case kl = "KL"
/// Khmer.
case km = "KM"
/// Kannada.
case kn = "KN"
/// Korean.
case ko = "KO"
/// Kashmiri.
case ks = "KS"
/// Kurdish.
case ku = "KU"
/// Cornish.
case kw = "KW"
/// Kyrgyz.
case ky = "KY"
/// Luxembourgish.
case lb = "LB"
/// Ganda.
case lg = "LG"
/// Lingala.
case ln = "LN"
/// Lao.
case lo = "LO"
/// Lithuanian.
case lt = "LT"
/// Luba-Katanga.
case lu = "LU"
/// Latvian.
case lv = "LV"
/// Malagasy.
case mg = "MG"
/// Māori.
case mi = "MI"
/// Macedonian.
case mk = "MK"
/// Malayalam.
case ml = "ML"
/// Mongolian.
case mn = "MN"
/// Marathi.
case mr = "MR"
/// Malay.
case ms = "MS"
/// Maltese.
case mt = "MT"
/// Burmese.
case my = "MY"
/// Norwegian (Bokmål).
case nb = "NB"
/// North Ndebele.
case nd = "ND"
/// Nepali.
case ne = "NE"
/// Dutch.
case nl = "NL"
/// Norwegian Nynorsk.
case nn = "NN"
/// Norwegian.
case no = "NO"
/// Oromo.
case om = "OM"
/// Odia.
case or = "OR"
/// Ossetic.
case os = "OS"
/// Punjabi.
case pa = "PA"
/// Polish.
case pl = "PL"
/// Pashto.
case ps = "PS"
/// Portuguese.
case pt = "PT"
/// Portuguese (Brazil).
case ptBr = "PT_BR"
/// Portuguese (Portugal).
case ptPt = "PT_PT"
/// Quechua.
case qu = "QU"
/// Romansh.
case rm = "RM"
/// Rundi.
case rn = "RN"
/// Romanian.
case ro = "RO"
/// Russian.
case ru = "RU"
/// Kinyarwanda.
case rw = "RW"
/// Sindhi.
case sd = "SD"
/// Northern Sami.
case se = "SE"
/// Sango.
case sg = "SG"
/// Sinhala.
case si = "SI"
/// Slovak.
case sk = "SK"
/// Slovenian.
case sl = "SL"
/// Shona.
case sn = "SN"
/// Somali.
case so = "SO"
/// Albanian.
case sq = "SQ"
/// Serbian.
case sr = "SR"
/// Sundanese.
case su = "SU"
/// Swedish.
case sv = "SV"
/// Swahili.
case sw = "SW"
/// Tamil.
case ta = "TA"
/// Telugu.
case te = "TE"
/// Tajik.
case tg = "TG"
/// Thai.
case th = "TH"
/// Tigrinya.
case ti = "TI"
/// Turkmen.
case tk = "TK"
/// Tongan.
case to = "TO"
/// Turkish.
case tr = "TR"
/// Tatar.
case tt = "TT"
/// Uyghur.
case ug = "UG"
/// Ukrainian.
case uk = "UK"
/// Urdu.
case ur = "UR"
/// Uzbek.
case uz = "UZ"
/// Vietnamese.
case vi = "VI"
/// Volapük.
case vo = "VO"
/// Wolof.
case wo = "WO"
/// Xhosa.
case xh = "XH"
/// Yiddish.
case yi = "YI"
/// Yoruba.
case yo = "YO"
/// Chinese.
case zh = "ZH"
/// Chinese (Simplified).
case zhCn = "ZH_CN"
/// Chinese (Traditional).
case zhTw = "ZH_TW"
/// Zulu.
case zu = "ZU"
case unknownValue = ""
}
}
| mit | 828ea6d18c310e5808ca6b540b0955e3 | 12.826966 | 81 | 0.514546 | 2.596203 | false | false | false | false |
alphatroya/KeyboardManager | Tests/KeyboardManagerTests/KeyboardObserverTests.swift | 1 | 2390 | //
// MIT License
//
// Copyright (c) 2021
//
// 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
@testable import KeyboardManager
import XCTest
class KeyboardObserverTests: XCTestCase {
var notificationCenter: NotificationCenterMock!
override func setUp() {
super.setUp()
notificationCenter = NotificationCenterMock()
}
override func tearDown() {
notificationCenter = nil
super.tearDown()
}
func testKeyboardObserverSubscription() {
_ = KeyboardObserver.addObserver(notificationCenter) { _ in }
XCTAssertTrue(notificationCenter.isWillShow)
XCTAssertTrue(notificationCenter.isDidShow)
XCTAssertTrue(notificationCenter.isWillHide)
XCTAssertTrue(notificationCenter.isDidHide)
XCTAssertTrue(notificationCenter.isWillChangeFrame)
XCTAssertTrue(notificationCenter.isDidChangeFrame)
}
func testKeyboardObserverUnsubscriptionOnDeallocation() {
var token: KeyboardObserverToken? = KeyboardObserver.addObserver(notificationCenter) { _ in }
token?.doNothing()
XCTAssertFalse(notificationCenter.isUnsubscribed)
token = nil
XCTAssertTrue(notificationCenter.isUnsubscribed)
}
}
extension KeyboardObserverToken {
/// this method does nothing to remove warning in L52
func doNothing() {}
}
| mit | 9ae7d0e623e5273a4041c48c7c46ee31 | 36.936508 | 101 | 0.741423 | 5.161987 | false | true | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Gutenberg/Layout Picker/LayoutPickerAnalyticsEvent.swift | 2 | 2627 | import Foundation
class LayoutPickerAnalyticsEvent {
typealias PreviewDevice = PreviewDeviceSelectionViewController.PreviewDevice
private static let templateTrackingKey = "template"
private static let errorTrackingKey = "error"
private static let previewModeTrackingKey = "preview_mode"
static func previewErrorShown(_ template: PageTemplateLayout, _ error: Error) {
WPAnalytics.track(.layoutPickerPreviewErrorShown, withProperties: commonProperties(template, error))
}
static func previewLoaded(_ device: PreviewDevice, _ template: PageTemplateLayout) {
WPAnalytics.track(.layoutPickerPreviewLoaded, withProperties: commonProperties(device, template))
}
static func previewLoading(_ device: PreviewDevice, _ template: PageTemplateLayout) {
WPAnalytics.track(.layoutPickerPreviewLoading, withProperties: commonProperties(device, template))
}
static func previewModeButtonTapped(_ device: PreviewDevice, _ template: PageTemplateLayout) {
WPAnalytics.track(.layoutPickerPreviewModeButtonTapped, withProperties: commonProperties(device, template))
}
static func previewModeChanged(_ device: PreviewDevice, _ template: PageTemplateLayout? = nil) {
WPAnalytics.track(.layoutPickerPreviewModeChanged, withProperties: commonProperties(device, template))
}
static func previewViewed(_ device: PreviewDevice, _ template: PageTemplateLayout) {
WPAnalytics.track(.layoutPickerPreviewViewed, withProperties: commonProperties(device, template))
}
static func thumbnailModeButtonTapped(_ device: PreviewDevice) {
WPAnalytics.track(.layoutPickerThumbnailModeButtonTapped, withProperties: commonProperties(device))
}
static func templateApplied(_ template: PageTemplateLayout) {
WPAnalytics.track(.editorSessionTemplateApply, withProperties: commonProperties(template))
}
// MARK: - Common
private static func commonProperties(_ properties: Any?...) -> [AnyHashable: Any] {
var result: [AnyHashable: Any] = [:]
for property: Any? in properties {
if let template = property as? PageTemplateLayout {
result.merge([templateTrackingKey: template.slug]) { (_, new) in new }
}
if let previewMode = property as? PreviewDevice {
result.merge([previewModeTrackingKey: previewMode.rawValue]) { (_, new) in new }
}
if let error = property as? Error {
result.merge([errorTrackingKey: error]) { (_, new) in new }
}
}
return result
}
}
| gpl-2.0 | 0b13d80741621dca6d9ac2c080ee598d | 42.783333 | 115 | 0.707271 | 5.1409 | false | false | false | false |
John-Connolly/SwiftQ | Sources/SwiftQ/Queues/ScheduledQueue.swift | 1 | 1746 | //
// ScheduledQueue.swift
// SwiftQ
//
// Created by John Connolly on 2017-07-04.
//
//
import Foundation
final class ScheduledQueue: Monitorable {
private let redisAdaptor: Adaptor
private let queue: String
init(config: RedisConfig, queue: String = "default") throws {
self.queue = queue
self.redisAdaptor = try RedisAdaptor(config: config, connections: 1)
}
func enqueue(_ boxedTask: ZSettable) throws {
try redisAdaptor.pipeline {
return [
.multi,
.zadd(queue: RedisKey.scheduledQ.name, score: boxedTask.score, value: boxedTask.uuid),
.set(key: boxedTask.uuid, value: boxedTask.task),
.exec
]
}
}
private func zrangeByScore() throws -> [Foundation.Data]? {
let ids = try redisAdaptor.execute(.zrangebyscore(
key: RedisKey.scheduledQ.name,
min: "-inf",
max: Date().unixTime.description)).array
return ids
}
/// Pushs multiple tasks onto the work queue from the scheduled queue
private func transfer(tasks: [Foundation.Data]) throws {
try redisAdaptor.pipeline {
return [
.multi,
.zrem(key: RedisKey.scheduledQ.name, values: tasks),
.lpush(key: RedisKey.workQ(queue).name, values: tasks),
.exec
]
}
}
func monitor() {
do {
guard let data = try zrangeByScore(), data.count > 0 else {
return
}
try transfer(tasks: data)
} catch {
Logger.log(error)
}
}
}
| mit | 671e82fc786dc3596949262f2e2c16fc | 25.059701 | 102 | 0.528637 | 4.37594 | false | true | false | false |
lemberg/connfa-ios | Connfa/Common/Extensions/DateFormatter+Default.swift | 1 | 451 | //
// DateFormatter+default.swift
// ConnfaCore
//
// Created by Marian Fedyk on 8/28/17.
//
import Foundation
let defaultFormatter = DateFormatter.default
extension DateFormatter {
static var `default`: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
formatter.locale = Locale(identifier: "en_US")
formatter.timeZone = TimeZone(abbreviation: "UTC")
return formatter
}
}
| apache-2.0 | 1526211e9a34bcd133fc18df614565fd | 19.5 | 54 | 0.7051 | 3.696721 | false | false | false | false |
chenyunguiMilook/VisualDebugger | Sources/VisualDebugger/data/AffineTransform.swift | 1 | 1469 | //
// AffineTransform.swift
// VisualDebugger
//
// Created by chenyungui on 2018/3/19.
//
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
#else
import Cocoa
#endif
public struct AffineTransform {
public var rect: AffineRect
public var image: CGImage?
public var transform: CGAffineTransform
public var elements: [Debuggable] = []
public init(rect: AffineRect, image: CGImage?, transform: CGAffineTransform) {
self.rect = rect
self.image = image
self.transform = transform
self.elements = getDebugElements()
}
private func getDebugElements() -> [Debuggable] {
let rectFrom = self.rect
let rectTo = self.rect * self.transform
if let image = self.image {
let start = AffineImage(image: image, rect: rectFrom, opacity: 0.4)
let end = AffineImage(image: image, rect: rectTo, opacity: 0.8)
return [start, end]
} else {
return [rectFrom, rectTo]
}
}
}
extension AffineTransform : Debuggable {
public var bounds: CGRect {
let result = elements[0].bounds
return elements.reduce(result, { $0.union($1.bounds) })
}
public func debug(in coordinate: CoordinateSystem, color: AppColor?) {
let color = color ?? coordinate.getNextColor()
for element in self.elements {
element.debug(in: coordinate, color: color)
}
}
}
| mit | cfb4d177d1b3c8bc85af40da2c31fbb9 | 22.693548 | 82 | 0.611981 | 4.197143 | false | false | false | false |
cpageler93/RAML-Swift | Sources/ResourceMethod.swift | 1 | 5808 | //
// ResourceMethod.swift
// RAML
//
// Created by Christoph on 30.06.17.
//
import Foundation
import Yaml
import PathKit
public enum ResourceMethodType: String {
case get
case patch
case put
case post
case delete
case options
case head
}
public class ResourceMethod: HasHeaders, HasAnnotations, HasTraitUsages, HasMethodResponses, HasSecuritySchemeUsages, HasQueryParameters {
public var type: ResourceMethodType
public var displayName: String?
public var description: String?
public var annotations: [Annotation]?
public var queryParameters: [URIParameter]?
public var headers: [Header]?
public var queryString: QueryString?
public var responses: [MethodResponse]?
public var body: Body?
public var protocols: Protocols?
public var traitUsages: [TraitUsage]?
public var securedBy: [SecuritySchemeUsage]?
public init(type: ResourceMethodType) {
self.type = type
}
internal init() {
self.type = .get
}
}
// MARK: ResourceMethod Parsing
internal extension RAML {
internal func parseResourceMethods(_ input: ParseInput) throws -> [ResourceMethod]? {
guard let yaml = input.yaml else { return nil }
var resourceMethods: [ResourceMethod] = []
let availableMethods = [
"get",
"patch",
"put",
"post",
"delete",
"options",
"head"
]
for (key, value) in yaml.dictionary ?? [:] {
if let keyString = key.string,
availableMethods.contains(keyString),
let resourceMethod = try parseResourceMethod(keyString, fromYaml: value, parentFilePath: input.parentFilePath) {
resourceMethods.append(resourceMethod)
}
}
if resourceMethods.count > 0 {
return resourceMethods
} else {
return nil
}
}
private func parseResourceMethod(_ method: String, fromYaml yaml: Yaml, parentFilePath: Path?) throws -> ResourceMethod? {
guard let methodType = ResourceMethodType(rawValue: method) else { return nil }
let resourceMethod = ResourceMethod(type: methodType)
resourceMethod.displayName = yaml["displayName"].string
resourceMethod.description = yaml["description"].string
resourceMethod.annotations = try parseAnnotations(ParseInput(yaml, parentFilePath))
resourceMethod.queryParameters = try parseURIParameters(ParseInput(yaml["queryParameters"], parentFilePath))
resourceMethod.headers = try parseHeaders(ParseInput(yaml["headers"], parentFilePath))
resourceMethod.queryString = try parseQueryString(ParseInput(yaml["queryString"], parentFilePath))
resourceMethod.responses = try parseResponses(ParseInput(yaml["responses"], parentFilePath))
resourceMethod.body = try parseBody(ParseInput(yaml["body"], parentFilePath))
resourceMethod.protocols = try parseProtocols(ParseInput(yaml["protocols"], parentFilePath))
resourceMethod.traitUsages = try parseTraitUsages(ParseInput(yaml["is"], parentFilePath))
resourceMethod.securedBy = try parseSecuritySchemeUsages(ParseInput(yaml["securedBy"], parentFilePath))
return resourceMethod
}
}
public protocol HasResourceMethods {
var methods: [ResourceMethod]? { get set }
}
public extension HasResourceMethods {
public func methodWith(type: ResourceMethodType) -> ResourceMethod? {
for method in methods ?? [] {
if method.type == type {
return method
}
}
return nil
}
public func hasMethodWith(type: ResourceMethodType) -> Bool {
return methodWith(type: type) != nil
}
}
// MARK: Default Values
public extension ResourceMethod {
internal func responsesOrDefault(raml: RAML) -> [MethodResponse]? {
if let responses = responses { return responses.map { $0.applyDefaults(raml: raml) } }
let defaultMethodResponse = MethodResponse(code: 200)
defaultMethodResponse.description = description
defaultMethodResponse.annotations = annotations
defaultMethodResponse.headers = headers
defaultMethodResponse.body = body
return [defaultMethodResponse.applyDefaults(raml: raml)]
}
public convenience init(initWithDefaultsBasedOn resourceMethod: ResourceMethod, raml: RAML) {
self.init()
self.type = resourceMethod.type
self.displayName = resourceMethod.displayName
self.description = resourceMethod.description
self.annotations = resourceMethod.annotations?.map { $0.applyDefaults() }
self.queryParameters = resourceMethod.queryParameters?.map { $0.applyDefaults() }
self.headers = resourceMethod.headers?.map { $0.applyDefaults() }
self.queryString = resourceMethod.queryString?.applyDefaults()
self.responses = resourceMethod.responsesOrDefault(raml: raml)
self.body = resourceMethod.body?.applyDefaults(raml: raml)
self.protocols = resourceMethod.protocols ?? Protocols.defaultProtocols()
self.traitUsages = resourceMethod.traitUsages?.map { $0.applyDefaults() }
self.securedBy = resourceMethod.securedBy?.map { $0.applyDefaults() }
}
public func applyDefaults(raml: RAML) -> ResourceMethod {
return ResourceMethod(initWithDefaultsBasedOn: self, raml: raml)
}
}
| mit | fcc7041132d88dc0e3407e267dc12866 | 33.366864 | 138 | 0.637569 | 4.819917 | false | false | false | false |
radvansky-tomas/NutriFacts | nutri-facts/nutri-facts/Libraries/Persei/MenuView.swift | 1 | 4388 | // For License please refer to LICENSE file in the root of Persei project
import Foundation
import UIKit
private let CellIdentifier = "MenuCell"
private let DefaultContentHeight: CGFloat = 97.0
public class MenuView: StickyHeaderView {
// MARK: - Init
override func commonInit() {
super.commonInit()
if backgroundColor == nil {
backgroundColor = UIColor(red: 51 / 255, green: 51 / 255, blue: 76 / 255, alpha: 1)
}
contentHeight = DefaultContentHeight
updateContentLayout()
}
// MARK: - FlowLayout
private lazy var collectionLayout: UICollectionViewFlowLayout = { [unowned self] in
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .Horizontal
return layout
}()
// MARK: - CollectionView
private lazy var collectionView: UICollectionView = { [unowned self] in
let view = UICollectionView(frame: CGRectZero, collectionViewLayout: self.collectionLayout)
view.clipsToBounds = false
view.backgroundColor = UIColor.clearColor()
view.showsHorizontalScrollIndicator = false
view.registerClass(MenuCell.self, forCellWithReuseIdentifier: CellIdentifier)
view.delegate = self
view.dataSource = self
self.contentView = view
return view
}()
// MARK: - Delegate
@IBOutlet
public weak var delegate: MenuViewDelegate?
//MARK: Radvansky
public var shouldCloseMenu:Bool = true
// TODO: remove explicit type declaration when compiler error will be fixed
public var items: [MenuItem] = [] {
didSet {
collectionView.reloadData()
selectedIndex = items.count > 0 ? 0 : nil
}
}
public var selectedIndex: Int? = 0 {
didSet {
var indexPath: NSIndexPath?
if let index = self.selectedIndex {
indexPath = NSIndexPath(forItem: index, inSection: 0)
}
self.collectionView.selectItemAtIndexPath(indexPath,
animated: self.revealed,
scrollPosition: .CenteredHorizontally
)
}
}
// MARK: - ContentHeight & Layout
public override var contentHeight: CGFloat {
didSet {
updateContentLayout()
}
}
private func updateContentLayout() {
let inset = ceil(contentHeight / 6.0)
let spacing = floor(inset / 2.0)
collectionLayout.minimumLineSpacing = spacing
collectionLayout.minimumInteritemSpacing = spacing
collectionView.contentInset = UIEdgeInsets(top: 0.0, left: inset, bottom: 0.0, right: inset)
collectionLayout.itemSize = CGSize(width: contentHeight - inset * 2, height: contentHeight - inset * 2)
}
}
extension MenuView {
public func frameOfItemAtIndex(index: Int) -> CGRect {
let indexPath = NSIndexPath(forItem: index, inSection: 0)
let layoutAttributes = collectionLayout.layoutAttributesForItemAtIndexPath(indexPath)
return self.convertRect(layoutAttributes.frame, fromView: collectionLayout.collectionView)
}
}
extension MenuView: UICollectionViewDataSource {
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
CellIdentifier,
forIndexPath: indexPath
) as? MenuCell
// compatibility with Swift 1.1 & 1.2
cell?.object = items[indexPath.item]
return cell!
}
}
extension MenuView: UICollectionViewDelegate {
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
selectedIndex = indexPath.item
delegate?.menu(self, didSelectItemAtIndex: selectedIndex!)
if shouldCloseMenu
{
UIView.animateWithDuration(0.2, delay: 0.4, options: nil, animations: {
self.revealed = false
}, completion: nil)
}
}
}
| gpl-2.0 | 621e30f9eda27d5bf7eac801be62b2b8 | 31.992481 | 137 | 0.634686 | 5.676585 | false | false | false | false |
alvaromb/EventBlankApp | EventBlank/EventBlank/ViewControllers/Speakers/SpeakerDetailsViewController.swift | 1 | 13181 | //
// SpeakerDetailsViewController.swift
// EventBlank
//
// Created by Marin Todorov on 6/22/15.
// Copyright (c) 2015 Underplot ltd. All rights reserved.
//
import UIKit
import SQLite
class SpeakerDetailsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var speaker: Row! //set from the previous view controller
var favorites: [Int]! //set from the previous view controller
let twitter = TwitterController()
var tweets: [TweetModel]? = nil
let newsCtr = NewsController()
let userCtr = UserController()
@IBOutlet weak var tableView: UITableView!
var user: Row?
var database: Database {
return DatabaseProvider.databases[appDataFileName]!
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 100.0
tableView.rowHeight = UITableViewAutomaticDimension
//fetch new tweets
if let twitterHandle = speaker[Speaker.twitter] where count(twitterHandle) > 0 {
backgroundQueue(fetchTweets)
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
title = speaker[Speaker.name]
}
//MARK: - table view methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if let twitterHandle = speaker[Speaker.twitter] where count(twitterHandle) > 0 {
return 2
}
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return 1;
case 1 where tweets == nil: return 1
case 1 where tweets != nil && tweets!.count == 0: return 0
case 1 where tweets != nil && tweets!.count > 0: return tweets!.count
default: return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
//speaker details
let cell = tableView.dequeueReusableCellWithIdentifier("SpeakerDetailsCell") as! SpeakerDetailsCell
cell.nameLabel.text = speaker[Speaker.name]
if let twitterHandle = speaker[Speaker.twitter] where count(twitterHandle) > 0 {
cell.twitterLabel.text = twitterHandle.hasPrefix("@") ? twitterHandle : "@"+twitterHandle
cell.didTapTwitter = {
let twitterUrl = NSURL(string: "https://twitter.com/" + twitterHandle)!
let webVC = self.storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController
webVC.initialURL = twitterUrl
self.navigationController!.pushViewController(webVC, animated: true)
}
cell.btnIsFollowing.hidden = false
cell.btnIsFollowing.username = cell.twitterLabel.text
cell.didTapFollow = {
self.twitter.authorize({success in
if success {
cell.btnIsFollowing.followState = .SendingRequest
self.twitter.followUser(twitterHandle, completion: {following in
cell.btnIsFollowing.followState = following ? .Following : .Follow
cell.btnIsFollowing.animateSelect(scale: 0.8, completion: nil)
})
} else {
cell.btnIsFollowing.hidden = true
}
})
}
//check if already following speaker
twitter.authorize({success in
if success {
self.twitter.isFollowingUser(twitterHandle, completion: {following in
if let following = following {
cell.btnIsFollowing.followState = following ? .Following : .Follow
} else {
cell.btnIsFollowing.hidden = true
}
})
} else {
cell.btnIsFollowing.hidden = true
}
})
} else {
mainQueue {
cell.btnIsFollowing.hidden = true
cell.twitterLabel.text = ""
cell.didTapTwitter = nil
}
}
cell.websiteLabel.text = speaker[Speaker.url]
cell.btnToggleIsFavorite.selected = find(favorites, speaker[Speaker.idColumn]) != nil
cell.bioTextView.text = speaker[Speaker.bio]
let userImage = speaker[Speaker.photo]?.imageValue ?? UIImage(named: "empty")!
userImage.asyncToSize(.FillSize(cell.userImage.bounds.size), cornerRadius: 5, completion: {result in
cell.userImage.image = result
})
backgroundQueue({
if self.speaker[Speaker.photo]?.imageValue == nil {
self.userCtr.lookupUserImage(self.speaker, completion: {userImage in
userImage?.asyncToSize(.FillSize(cell.userImage.bounds.size), cornerRadius: 5, completion: {result in
cell.userImage.image = result
})
if let userImage = userImage {
cell.didTapPhoto = {
PhotoPopupView.showImage(userImage, inView: self.view)
}
}
})
} else {
cell.didTapPhoto = {
PhotoPopupView.showImage(cell.userImage.image!, inView: self.view)
}
}
})
cell.indexPath = indexPath
cell.didSetIsFavoriteTo = {setIsFavorite, indexPath in
//TODO: update all this to Swift 2.0
let id = self.speaker[Speaker.idColumn]
let isInFavorites = find(self.favorites, id) != nil
if setIsFavorite && !isInFavorites {
self.favorites.append(id)
Favorite.saveSpeakerId(id)
} else if !setIsFavorite && isInFavorites {
self.favorites.removeAtIndex(find(self.favorites, id)!)
Favorite.removeSpeakerId(id)
}
self.notification(kFavoritesChangedNotification, object: nil)
}
if let urlString = speaker[Speaker.url], let url = NSURL(string: urlString) {
cell.speakerUrl = url
} else {
cell.speakerUrl = nil
}
cell.didTapURL = {tappedUrl in
let webVC = self.storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController
webVC.initialURL = tappedUrl
self.navigationController!.pushViewController(webVC, animated: true)
}
return cell
}
if indexPath.section == 1, let tweets = tweets where tweets.count > 0 {
let cell = self.tableView.dequeueReusableCellWithIdentifier("TweetCell") as! TweetCell
let row = indexPath.row
let tweet = tweets[indexPath.row]
cell.message.text = tweet.text
cell.timeLabel.text = tweet.created.relativeTimeToString()
cell.message.selectedRange = NSRange(location: 0, length: 0)
if let attachmentUrl = tweet.imageUrl {
cell.attachmentImage.hnk_setImageFromURL(attachmentUrl, placeholder: nil, format: nil, failure: nil, success: {image in
image.asyncToSize(.Fill(cell.attachmentImage.bounds.width, 150), cornerRadius: 5.0, completion: {result in
cell.attachmentImage.image = result
})
})
cell.didTapAttachment = {
PhotoPopupView.showImageWithUrl(attachmentUrl, inView: self.view)
}
cell.attachmentHeight.constant = 148.0
}
cell.nameLabel.text = speaker[Speaker.name]
if user == nil {
let usersTable = database[UserConfig.tableName]
user = usersTable.filter(User.idColumn == tweet.userId).first
}
if let userImage = user?[User.photo]?.imageValue {
userImage.asyncToSize(.FillSize(cell.userImage.bounds.size), cornerRadius: 5, completion: {result in
cell.userImage.image = result
})
} else {
if !fetchingUserImage {
fetchUserImage()
}
cell.userImage.image = UIImage(named: "empty")
}
cell.didTapURL = {tappedUrl in
let webVC = self.storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController
webVC.initialURL = tappedUrl
self.navigationController!.pushViewController(webVC, animated: true)
}
return cell
}
if indexPath.section == 1 && tweets == nil {
return tableView.dequeueReusableCellWithIdentifier("LoadingCell") as! UITableViewCell
}
return tableView.dequeueReusableCellWithIdentifier("") as! UITableViewCell
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0: return "Speaker Details"
case 1: return (tweets?.count < 1) ? "No tweets available" : "Latest tweets"
default: return nil
}
}
func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == 1, let tweets = tweets where tweets.count == 0 {
return "We couldn't load any tweets"
} else {
return nil
}
}
//add some space at the end of the tweet list
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
switch section {
case 1: return 50
default: return 0
}
}
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
switch section {
case 1: return UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
default: return nil
}
}
//MARK: - fetching data
func fetchTweets() {
twitter.authorize({success in
if success, let username = self.speaker[Speaker.twitter] {
self.twitter.getTimeLineForUsername(username, completion: {tweetList, user in
if let user = user where tweetList.count > 0 {
self.userCtr.persistUsers([user])
self.didFetchTweets(tweetList)
} else {
self.tweets = []
mainQueue {
self.tableView.reloadSections(NSIndexSet(index: 1),
withRowAnimation: .Automatic)
}
}
})
} else {
//TODO: no auth - show message?
self.tweets = []
mainQueue({ self.tableView.reloadData() })
}
})
}
func didFetchTweets(tweetList: [TweetModel]) {
tweets = tweetList
//reload table
//TODO: remove delay when it's working
delay(seconds: 0.1, {
self.tableView.reloadSections(NSIndexSet(index: 1),
withRowAnimation: UITableViewRowAnimation.Bottom)
})
}
var fetchingUserImage = false
func fetchUserImage() {
fetchingUserImage = true
if let imageUrlString = self.user![User.photoUrl],
let imageUrl = NSURL(string: imageUrlString) {
self.twitter.getImageWithUrl(imageUrl, completion: {image in
if let image = image, let user = self.user {
//update table cell
mainQueue({
self.userCtr.persistUserImage(image, userId: user[User.idColumn])
self.user = nil
self.fetchingUserImage = false
self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Automatic)
})
}
})
}
}
}
| mit | eccbc7f299f0cbc690f3bbb411074e3d | 38.346269 | 135 | 0.525302 | 5.750873 | false | false | false | false |
superk589/CGSSGuide | DereGuide/Controller/BaseModelTableViewController.swift | 2 | 2939 | //
// BaseModelTableViewController.swift
// DereGuide
//
// Created by zzk on 2017/5/1.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
class BaseModelTableViewController: RefreshableTableViewController {
lazy var searchBar: CGSSSearchBar = {
let bar = CGSSSearchBar()
bar.delegate = self
return bar
}()
lazy var searchBarWrapper: UIView = {
let wrapper = SearchBarWrapper(searchBar: self.searchBar)
return wrapper
}()
private var needsReloadData = true
private var isShowing = false
// called after search text changed, must to be overrided
func updateUI() {}
// called if needsReloadData is true when text changed, must to be overrided
func reloadData() {}
@objc func setNeedsReloadData() {
needsReloadData = true
if isShowing {
reloadDataIfNeeded()
}
}
func reloadDataIfNeeded() {
if needsReloadData {
reloadData()
needsReloadData = false
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
isShowing = true
reloadDataIfNeeded()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isShowing = false
searchBar.resignFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView(frame: CGRect.zero)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { (context) in
self.navigationController?.navigationBar.setNeedsLayout()
self.navigationController?.navigationBar.layoutIfNeeded()
}, completion: nil)
super.viewWillTransition(to: size, with: coordinator)
}
}
// MARK: UISearchBarDelegate
extension BaseModelTableViewController: UISearchBarDelegate {
// 文字改变时
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
updateUI()
}
// // 开始编辑时
// func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
// return true
// }
//
// 点击搜索按钮时
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
// // 点击searchbar自带的取消按钮时
// func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
//
// }
}
// MARK: UIScrollViewDelegate
extension BaseModelTableViewController {
override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
// 滑动时取消输入框的第一响应者
if searchBar.isFirstResponder {
searchBar.resignFirstResponder()
}
}
}
| mit | 02093c0621c5a6feac81e741776e87ea | 25.691589 | 112 | 0.639706 | 5.398866 | false | false | false | false |
Karumi/Alamofire-Result | Source/ResponseSerialization.swift | 1 | 13711 | // ResponseSerialization.swift
//
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Result
// MARK: ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializerType`.
typealias SerializedObject
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
typealias ErrorObject: ErrorType
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get }
}
// MARK: -
/**
A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
*/
public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = Value
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
public typealias ErrorObject = Error
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>
/**
Initializes the `ResponseSerializer` instance with the given serialize response closure.
- parameter serializeResponse: The closure used to serialize the response.
- returns: The new generic response serializer instance.
*/
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) {
self.serializeResponse = serializeResponse
}
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response(
queue queue: dispatch_queue_t? = nil,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
}
}
return self
}
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
and data.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response<T: ResponseSerializerType>(
queue queue: dispatch_queue_t? = nil,
responseSerializer: T,
completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
dispatch_async(queue ?? dispatch_get_main_queue()) {
let response = Response<T.SerializedObject, T.ErrorObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result
)
completionHandler(response)
}
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
- returns: A data response serializer.
*/
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSData()) }
guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
return .Success(validData)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified
string encoding.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
response, falling back to the default HTTP default character set, ISO-8859-1.
- returns: A string response serializer.
*/
public static func stringResponseSerializer(
var encoding encoding: NSStringEncoding? = nil)
-> ResponseSerializer<String, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success("") }
guard let validData = data else {
let failureReason = "String could not be serialized. Input data was nil."
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName)
)
}
let actualEncoding = encoding ?? NSISOLatin1StringEncoding
if let string = String(data: validData, encoding: actualEncoding) {
return .Success(string)
} else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
server response, falling back to the default HTTP default character set,
ISO-8859-1.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseString(
encoding encoding: NSStringEncoding? = nil,
completionHandler: Response<String, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using
`NSJSONSerialization` with the specified reading options.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(
options options: NSJSONReadingOptions = .AllowFragments)
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
guard let validData = data where validData.length > 0 else {
let failureReason = "JSON could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
return .Success(JSON)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseJSON(
options options: NSJSONReadingOptions = .AllowFragments,
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using
`NSPropertyListSerialization` with the specified reading options.
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
- returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
guard let validData = data where validData.length > 0 else {
let failureReason = "Property list could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
return .Success(plist)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The property list reading options. `0` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response, the server data and the result
produced while creating the property list.
- returns: The request.
*/
public func responsePropertyList(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
| mit | 2264a3bdb1f3c9a0853f50f61b1266f7 | 37.508427 | 130 | 0.644102 | 5.584114 | false | false | false | false |
chenchangqing/travelMapMvvm | travelMapMvvm/travelMapMvvm/General/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallPulse.swift | 66 | 1842 | //
// NVActivityIndicatorAnimationBallPulse.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/23/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
class NVActivityIndicatorAnimationBallPulse: NVActivityIndicatorAnimationDelegate {
func setUpAnimationInLayer(layer: CALayer, size: CGSize, color: UIColor) {
let circleSpacing: CGFloat = 2
let circleSize: CGFloat = (size.width - 2 * circleSpacing) / 3
let x: CGFloat = (layer.bounds.size.width - size.width) / 2
let y: CGFloat = (layer.bounds.size.height - circleSize) / 2
let duration: CFTimeInterval = 0.75
let beginTime = CACurrentMediaTime()
let beginTimes: [CFTimeInterval] = [0.12, 0.24, 0.36]
let timingFunction = CAMediaTimingFunction(controlPoints: 0.2, 0.68, 0.18, 1.08)
let animation = CAKeyframeAnimation(keyPath: "transform.scale")
// Animation
animation.keyTimes = [0, 0.3, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.3, 1]
animation.duration = duration
animation.repeatCount = HUGE
animation.removedOnCompletion = false
// Draw circles
for var i = 0; i < 3; i++ {
let circle = NVActivityIndicatorShape.Circle.createLayerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: x + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
y: y,
width: circleSize,
height: circleSize)
animation.beginTime = beginTime + beginTimes[i]
circle.frame = frame
circle.addAnimation(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
}
| apache-2.0 | 5d2bc8197a95f9649eb2ca9998857539 | 39.933333 | 139 | 0.62975 | 4.651515 | false | false | false | false |
jvesala/teknappi | teknappi/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift | 27 | 5531 | //
// ConcurrentDispatchQueueScheduler.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/5/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Abstracts the work that needs to be peformed on a specific `dispatch_queue_t`. You can also pass a serial dispatch queue, it shouldn't cause any problems.
This scheduler is suitable when some work needs to be performed in background.
*/
public class ConcurrentDispatchQueueScheduler: SchedulerType {
public typealias TimeInterval = NSTimeInterval
public typealias Time = NSDate
private let queue : dispatch_queue_t
public var now : NSDate {
get {
return NSDate()
}
}
// leeway for scheduling timers
var leeway: Int64 = 0
/**
Constructs new `ConcurrentDispatchQueueScheduler` that wraps `queue`.
- parameter queue: Target dispatch queue.
*/
public init(queue: dispatch_queue_t) {
self.queue = queue
}
/**
Convenience init for scheduler that wraps one of the global concurrent dispatch queues.
- parameter globalConcurrentQueuePriority: Target global dispatch queue.
*/
public convenience init(globalConcurrentQueuePriority: DispatchQueueSchedulerPriority) {
var priority: Int = 0
switch globalConcurrentQueuePriority {
case .High:
priority = DISPATCH_QUEUE_PRIORITY_HIGH
case .Default:
priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
case .Low:
priority = DISPATCH_QUEUE_PRIORITY_LOW
}
self.init(queue: dispatch_get_global_queue(priority, UInt(0)))
}
class func convertTimeIntervalToDispatchInterval(timeInterval: NSTimeInterval) -> Int64 {
return Int64(timeInterval * Double(NSEC_PER_SEC))
}
class func convertTimeIntervalToDispatchTime(timeInterval: NSTimeInterval) -> dispatch_time_t {
return dispatch_time(DISPATCH_TIME_NOW, convertTimeIntervalToDispatchInterval(timeInterval))
}
/**
Schedules an action to be executed immediatelly.
- parameter state: State passed to the action to be executed.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public final func schedule<StateType>(state: StateType, action: StateType -> Disposable) -> Disposable {
return self.scheduleInternal(state, action: action)
}
func scheduleInternal<StateType>(state: StateType, action: StateType -> Disposable) -> Disposable {
let cancel = SingleAssignmentDisposable()
dispatch_async(self.queue) {
if cancel.disposed {
return
}
cancel.disposable = action(state)
}
return cancel
}
/**
Schedules an action to be executed.
- parameter state: State passed to the action to be executed.
- parameter dueTime: Relative time after which to execute the action.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public final func scheduleRelative<StateType>(state: StateType, dueTime: NSTimeInterval, action: (StateType) -> Disposable) -> Disposable {
let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue)
let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchTime(dueTime)
let compositeDisposable = CompositeDisposable()
dispatch_source_set_timer(timer, dispatchInterval, DISPATCH_TIME_FOREVER, 0)
dispatch_source_set_event_handler(timer, {
if compositeDisposable.disposed {
return
}
compositeDisposable.addDisposable(action(state))
})
dispatch_resume(timer)
compositeDisposable.addDisposable(AnonymousDisposable {
dispatch_source_cancel(timer)
})
return compositeDisposable
}
/**
Schedules a periodic piece of work.
- parameter state: State passed to the action to be executed.
- parameter startAfter: Period after which initial work should be run.
- parameter period: Period for running the work periodically.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public func schedulePeriodic<StateType>(state: StateType, startAfter: TimeInterval, period: TimeInterval, action: (StateType) -> StateType) -> Disposable {
let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue)
let initial = MainScheduler.convertTimeIntervalToDispatchTime(startAfter)
let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchInterval(period)
var timerState = state
let validDispatchInterval = dispatchInterval < 0 ? 0 : UInt64(dispatchInterval)
dispatch_source_set_timer(timer, initial, validDispatchInterval, 0)
let cancel = AnonymousDisposable {
dispatch_source_cancel(timer)
}
dispatch_source_set_event_handler(timer, {
if cancel.disposed {
return
}
timerState = action(timerState)
})
dispatch_resume(timer)
return cancel
}
} | gpl-3.0 | 2e8edcb80692471261368fd6a109d89f | 34.690323 | 159 | 0.657024 | 5.31316 | false | false | false | false |
xuzhuoxi/SearchKit | Source/cs/cacheconfig/CacheInfo.swift | 1 | 3186 | //
// CacheInfo.swift
// SearchKit
//
// Created by 许灼溪 on 15/12/18.
//
//
import Foundation
/**
* 缓存信息
*
* @author xuzhuoxi
*
*/
public struct CacheInfo {
/**
* cache名称
*/
public let cacheName : String
/**
* 缓存实例的反射信息
*/
public let cacheReflectionInfo: ReflectionInfo
/**
* 是否为单例<br>
* 是:实例化后加入到缓存池中。{@link CachePool}<br>
* 否:实例化后不加入到缓存池中。<br>
*/
public let isSingleton : Bool
/**
* 哈希表初始容量
*/
public let initialCapacity : UInt
/**
* 缓存初始化时使用资源的路径 多个资源可使用""相隔
*/
public let resourceURLs : [URL]?
/**
* 字符文件编码类型,如UTF-8等
*/
public let charsetName : String?
/**
* 资源的值实例的反射信息
*/
public let valueCodingReflectionInfo: ReflectionInfo?
/**
* @return 是否需要资源作为初始化,当resourcePath{@link #resourcePath}无效时返回false。
*/
public let isNeedResource : Bool
public init(_ cacheName: String, _ cacheClassName: String, _ isSingleton: Bool, _ initialCapacity: UInt, _ resourceURLs: [URL]?, _ charsetName: String?, valueCodingType: ValueCodingType?) {
self.cacheName = cacheName
self.cacheReflectionInfo = ReflectionInfo(className: cacheClassName)
self.isSingleton = isSingleton
self.initialCapacity = initialCapacity
self.resourceURLs = resourceURLs
self.charsetName = charsetName
self.valueCodingReflectionInfo = nil == valueCodingType ? nil : ReflectionInfo(className: valueCodingType!.associatedClassName)
self.isNeedResource = nil != resourceURLs && !resourceURLs!.isEmpty
}
public init(_ cacheName: String, _ cacheClassName: String, _ isSingleton: Bool, _ initialCapacity: UInt, _ resourceURLs: [URL]?, _ charsetName: String?, valueCodingClassName: String?) {
self.cacheName = cacheName
self.cacheReflectionInfo = ReflectionInfo(className: cacheClassName)
self.isSingleton = isSingleton
self.initialCapacity = initialCapacity
self.resourceURLs = resourceURLs
self.charsetName = charsetName
self.valueCodingReflectionInfo = nil == valueCodingClassName ? nil : ReflectionInfo(className: valueCodingClassName!)
self.isNeedResource = nil != resourceURLs && !resourceURLs!.isEmpty
}
public init(cacheName: String, reflectClassName: String, isSingleton: Bool, initialCapacity: UInt, resourceURLs: [URL]?, valueCodingType: ValueCodingType?) {
self.init(cacheName, reflectClassName, isSingleton, initialCapacity, resourceURLs, "UTF-8", valueCodingType: valueCodingType)
}
public init(cacheName: String, reflectClassName: String, isSingleton: Bool, initialCapacity: UInt, resourceURLs: [URL]?, valueCodingClassName: String?) {
self.init(cacheName, reflectClassName, isSingleton, initialCapacity, resourceURLs, "UTF-8", valueCodingClassName: valueCodingClassName)
}
}
| mit | ddd78a093fc8c2d27f2cad2102a15b56 | 32.05618 | 194 | 0.667233 | 4.167139 | false | false | false | false |
clonezer/FreeForm | FreeForm/Classes/FreeFormTextViewCell.swift | 1 | 1487 | //
// FreeFormTextViewCell.swift
// FreeForm
//
// Created by Peerasak Unsakon on 11/28/16.
// Copyright © 2016 Peerasak Unsakon. All rights reserved.
//
import UIKit
import Validator
public class FreeFormTextViewRow: FreeFormRow {
override public init(tag: String, title: String, value: AnyObject?) {
super.init(tag: tag, title: title, value: value)
self.cellType = String(describing: FreeFormTextViewCell.self)
self.height = 110
}
}
public class FreeFormTextViewCell: FreeFormCell {
@IBOutlet weak public var titleLabel: UILabel!
@IBOutlet weak public var textView: UITextView!
override public func awakeFromNib() {
super.awakeFromNib()
self.textView.delegate = self
}
override public func update() {
super.update()
self.titleLabel.text = row.title
guard let value = row.value as? String else { return }
self.textView.text = value
}
}
extension FreeFormTextViewCell: UITextViewDelegate {
public func textViewDidEndEditing(_ textView: UITextView) {
guard let row = self.row else { return }
row.value = textView.text as AnyObject?
guard let block = row.didChanged else { return }
block(textView.text as AnyObject, row)
self.update()
}
public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
guard let row = self.row else { return false }
return !row.disable
}
}
| mit | b973cf7a3ad26743baa0d1e6a82ffc3a | 26.518519 | 76 | 0.659489 | 4.357771 | false | false | false | false |
davidstump/SwiftPhoenixClient | Sources/SwiftPhoenixClient/Defaults.swift | 1 | 3431 | // Copyright (c) 2021 David Stump <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// A collection of default values and behaviors used accross the Client
public class Defaults {
/// Default timeout when sending messages
public static let timeoutInterval: TimeInterval = 10.0
/// Default interval to send heartbeats on
public static let heartbeatInterval: TimeInterval = 30.0
/// Default reconnect algorithm for the socket
public static let reconnectSteppedBackOff: (Int) -> TimeInterval = { tries in
return tries > 9 ? 5.0 : [0.01, 0.05, 0.1, 0.15, 0.2, 0.25, 0.5, 1.0, 2.0][tries - 1]
}
/** Default rejoin algorithm for individual channels */
public static let rejoinSteppedBackOff: (Int) -> TimeInterval = { tries in
return tries > 3 ? 10 : [1, 2, 5][tries - 1]
}
public static let vsn = "2.0.0"
/// Default encode function, utilizing JSONSerialization.data
public static let encode: (Any) -> Data = { json in
return try! JSONSerialization
.data(withJSONObject: json,
options: JSONSerialization.WritingOptions())
}
/// Default decode function, utilizing JSONSerialization.jsonObject
public static let decode: (Data) -> Any? = { data in
guard
let json = try? JSONSerialization
.jsonObject(with: data,
options: JSONSerialization.ReadingOptions())
else { return nil }
return json
}
public static let heartbeatQueue: DispatchQueue
= DispatchQueue(label: "com.phoenix.socket.heartbeat")
}
/// Represents the multiple states that a Channel can be in
/// throughout it's lifecycle.
public enum ChannelState: String {
case closed = "closed"
case errored = "errored"
case joined = "joined"
case joining = "joining"
case leaving = "leaving"
}
/// Represents the different events that can be sent through
/// a channel regarding a Channel's lifecycle.
public struct ChannelEvent {
public static let heartbeat = "heartbeat"
public static let join = "phx_join"
public static let leave = "phx_leave"
public static let reply = "phx_reply"
public static let error = "phx_error"
public static let close = "phx_close"
static func isLifecyleEvent(_ event: String) -> Bool {
switch event {
case join, leave, reply, error, close: return true
default: return false
}
}
}
| mit | dae4f0b7dc59463d8e1718b743cf17c9 | 36.293478 | 89 | 0.707374 | 4.304893 | false | false | false | false |
nathawes/swift | test/ModuleInterface/ModuleCache/force-module-loading-mode-archs.swift | 22 | 9981 | // RUN: %empty-directory(%t)
// 1. Not finding things is okay.
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// (default)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// 2. Only interface is present.
// RUN: %empty-directory(%t/Lib.swiftmodule)
// RUN: cp %S/Inputs/force-module-loading-mode/Lib.swiftinterface %t/Lib.swiftmodule/%module-target-triple.swiftinterface
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// (default)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -I %t %s 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// 3. Only module is present.
// RUN: %empty-directory(%t/Lib.swiftmodule)
// RUN: sed -e 's/FromInterface/FromSerialized/g' %S/Inputs/force-module-loading-mode/Lib.swiftinterface | %target-swift-frontend -parse-stdlib -module-cache-path %t/MCP -emit-module-path %t/Lib.swiftmodule/%target-swiftmodule-name - -module-name Lib
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-SERIALIZED %s
// RUN: %empty-directory(%t/MCP)
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-SERIALIZED %s
// RUN: %empty-directory(%t/MCP)
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: %empty-directory(%t/MCP)
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-SERIALIZED %s
// RUN: %empty-directory(%t/MCP)
// (default)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -I %t %s 2>&1 | %FileCheck -check-prefix=FROM-SERIALIZED %s
// RUN: %empty-directory(%t/MCP)
// 4. Both are present.
// RUN: cp %S/Inputs/force-module-loading-mode/Lib.swiftinterface %t/Lib.swiftmodule/%module-target-triple.swiftinterface
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: %empty-directory(%t/MCP)
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-SERIALIZED %s
// RUN: %empty-directory(%t/MCP)
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: %empty-directory(%t/MCP)
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-SERIALIZED %s
// (default)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -I %t %s 2>&1 | %FileCheck -check-prefix=FROM-SERIALIZED %s
// RUN: %empty-directory(%t/MCP)
// 5. Both are present but the module is invalid.
// RUN: rm %t/Lib.swiftmodule/%target-swiftmodule-name && touch %t/Lib.swiftmodule/%target-swiftmodule-name
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=BAD-MODULE %s
// (default)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -I %t %s 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// 6. Both are present but the module can't be opened.
// RUN: %{python} %S/../Inputs/make-unreadable.py %t/Lib.swiftmodule/%target-swiftmodule-name
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: %empty-directory(%t/MCP)
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: %empty-directory(%t/MCP)
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: %empty-directory(%t/MCP)
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: %empty-directory(%t/MCP)
// (default)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -I %t %s 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: %empty-directory(%t/MCP)
// 7. Both are present but for the wrong architecture.
// RUN: %empty-directory(%t/Lib.swiftmodule)
// RUN: touch %t/Lib.swiftmodule/garbage.swiftmodule
// RUN: touch %t/Lib.swiftmodule/garbage.swiftinterface
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=WRONG-ARCH -DARCH=%module-target-triple %s
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=WRONG-ARCH -DARCH=%module-target-triple %s
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=WRONG-ARCH -DARCH=%module-target-triple %s
// (default)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -I %t %s 2>&1 | %FileCheck -check-prefix=WRONG-ARCH -DARCH=%module-target-triple %s
// 8. Only the interface is present but for the wrong architecture.
// (Diagnostics for the module only are tested elsewhere.)
// FIXME: We should improve this to not just say NO-SUCH-MODULE.
// RUN: rm %t/Lib.swiftmodule/garbage.swiftmodule
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: env SWIFT_FORCE_MODULE_LOADING=prefer-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-parseable not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: env SWIFT_FORCE_MODULE_LOADING=only-serialized not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// (default)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -I %t %s 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
import Lib
// NO-SUCH-MODULE: [[@LINE-1]]:8: error: no such module 'Lib'
// BAD-MODULE: [[@LINE-2]]:8: error: malformed compiled module: {{.*}}Lib.swiftmodule
// WRONG-ARCH: [[@LINE-3]]:8: error: could not find module 'Lib' for target '[[ARCH]]'; found: garbage
struct X {}
let _: X = Lib.testValue
// FROM-INTERFACE: [[@LINE-1]]:16: error: cannot convert value of type 'FromInterface' to specified type 'X'
// FROM-SERIALIZED: [[@LINE-2]]:16: error: cannot convert value of type 'FromSerialized' to specified type 'X'
| apache-2.0 | 584ab20fbaa5c9697e9a6140f7215cfc | 96.852941 | 250 | 0.730288 | 3.105476 | false | false | false | false |
imjerrybao/FutureKit | FutureKit-2. Promise.playground/Contents.swift | 1 | 3432 | //: # Welcome to FutureKit!
//: Make sure you opened this inside the FutureKit workspace. Opening the playground file directly, usually means it can't import FutureKit module correctly.
import FutureKit
#if os(iOS)
import UIKit
#else
import Cocoa
typealias UIImage = NSImage
#endif
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely(true)
//: # Promises.
//: Promises are used to create your own Futures.
//: When you want to write a function or method that returns a Future, you will most likely want to create a Promise.
//:This is a **promise**. It helps you return Futures when you need to. When you create a Promise object, you are also creating a "promise" to complete a Future. It's contract. Don't break your promises, or you will have code that hangs.
let namesPromise = Promise<[String]>()
//: the promise has a var `future`. we can now return this future to others.
let namesFuture :Future<[String]> = namesPromise.future
var timeCounter = 0
namesFuture.onSuccess(.Main) { (names : [String]) -> Void in
for name in names {
let timeCount = timeCounter++
let greeting = "Happy Future Day \(name)!"
}
}
//: so we have a nice routine that wants to greet all the names, but someone has to actually SUPPLY the names. Where are they?
let names = ["Skyer","David","Jess"]
let t = timeCounter++
namesPromise.completeWithSuccess(names)
//: Notice how the timeCounter shows us that the logic inside onSuccess() is executing after we execute completeWithSuccess().
//: A more typical case if you need to perform something inside a background queue.
//: I need a cat Picture. I want to see my cats! So go get me some!
//: Let's write a function that returns an Image. But since I might have to go to the internet to retrieve it, we will define a function that returns Future instead
func getCoolCatPic(url: NSURL) -> Future<UIImage> {
// We will use a promise, so we can return a Future<Image>
let catPicturePromise = Promise<UIImage>()
// go get data from this URL.
let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
if let e = error {
// if this is failing, make sure you aren't running this as an iOS Playground. It works when running as an OSX Playground.
catPicturePromise.completeWithFail(e)
}
else {
// parsing the data from the server into an Image.
if let d = data,
let image = UIImage(data: d) {
let i = image
catPicturePromise.completeWithSuccess(i)
}
else {
catPicturePromise.completeWithFail("couldn't understand the data returned from the server \(url) - \(response)")
}
}
// make sure to keep your promises!
// promises are promises!
assert(catPicturePromise.isCompleted)
})
// start downloading.
task.resume()
// return the promise's future.
return catPicturePromise.future
}
let catIFoundOnTumblr = NSURL(string: "http://25.media.tumblr.com/tumblr_m7zll2bkVC1rcyf04o1_500.gif")!
getCoolCatPic(catIFoundOnTumblr).onComplete { (completion) -> Void in
switch completion.state {
case .Success:
let i = completion.result
case .Fail:
let e = completion.error
case .Cancelled:
break
}
}
| mit | cec8190119fbd7373fa72fc57bbf7ba4 | 38.906977 | 243 | 0.676282 | 4.263354 | false | false | false | false |
zhangliangzhi/iosStudyBySwift | xxcolor/xxcolor/ShopViewController.swift | 1 | 13968 | //
// ShopViewController.swift
// xxcolor
//
// Created by ZhangLiangZhi on 2017/4/5.
// Copyright © 2017年 xigk. All rights reserved.
//
import UIKit
import SnapKit
import StoreKit
import SwiftyStoreKit
class ShopViewController: UIViewController {
var contactShop:UIView! // 正在连接商店的提示
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.white
self.title = NSLocalizedString("Buy Diamond", comment: "")
addDiamonView()
// shopJS()
}
func addDiamonView() -> Void {
let btn60 = UIButton(type: .custom)
self.view.addSubview(btn60)
btn60.addTarget(self, action: #selector(btnBuyDiamond60), for: .touchUpInside)
let btn320 = UIButton()
self.view.addSubview(btn320)
btn320.addTarget(self, action: #selector(btnBuyDiamond320), for: .touchUpInside)
let btn3800 = UIButton()
self.view.addSubview(btn3800)
btn3800.addTarget(self, action: #selector(btnBuyDiamond3800), for: .touchUpInside)
btn60.setTitleColor(UIColor.white, for: .normal)
btn60.layer.borderColor = UIColor(red: 80/255, green: 183/255, blue: 221/255, alpha: 1).cgColor
btn60.layer.borderWidth = 1.0
btn60.backgroundColor = UIColor(red: 233/255, green: 152/255, blue: 0/255, alpha: 1)
btn320.setTitleColor(UIColor.white, for: .normal)
btn320.layer.borderColor = UIColor(red: 80/255, green: 183/255, blue: 221/255, alpha: 1).cgColor
btn320.layer.borderWidth = 1.0
btn320.backgroundColor = UIColor(red: 233/255, green: 152/255, blue: 0/255, alpha: 1)
btn3800.setTitleColor(UIColor.white, for: .normal)
btn3800.layer.borderColor = UIColor(red: 80/255, green: 183/255, blue: 221/255, alpha: 1).cgColor
btn3800.layer.borderWidth = 1.0
btn3800.backgroundColor = UIColor(red: 233/255, green: 152/255, blue: 0/255, alpha: 1)
btn320.snp.makeConstraints { (make) in
make.width.equalTo(self.view).multipliedBy(0.88)
make.height.equalTo(self.view).multipliedBy(0.2)
make.center.equalTo(self.view)
}
btn60.snp.makeConstraints { (make) in
make.bottom.equalTo(btn320.snp.top).offset(-30)
make.width.equalTo(self.view).multipliedBy(0.88)
make.height.equalTo(self.view).multipliedBy(0.2)
make.centerX.equalTo(self.view)
}
btn3800.snp.makeConstraints { (make) in
make.top.equalTo(btn320.snp.bottom).offset(30)
make.width.equalTo(self.view).multipliedBy(0.88)
make.height.equalTo(self.view).multipliedBy(0.2)
make.centerX.equalTo(self.view)
}
// 钻石的图片
let img60 = UIImageView(image: UIImage(named: "diamond"))
btn60.addSubview(img60)
img60.snp.makeConstraints { (make) in
make.centerX.equalTo(btn60)
make.centerY.equalTo(btn60).offset(-10)
}
// 320钻
let img320 = UIImageView(image: UIImage(named: "diamond"))
btn320.addSubview(img320)
img320.snp.makeConstraints { (make) in
make.centerX.equalTo(btn320).offset(-25)
make.centerY.equalTo(btn320).offset(-10)
}
let img320b = UIImageView(image: UIImage(named: "diamond"))
btn320.addSubview(img320b)
img320b.snp.makeConstraints { (make) in
make.centerX.equalTo(btn320).offset(25)
make.centerY.equalTo(btn320).offset(-10)
}
// 3800钻
let img3a = UIImageView(image: UIImage(named: "diamond"))
btn3800.addSubview(img3a)
img3a.snp.makeConstraints { (make) in
make.center.equalTo(btn3800).offset(0)
make.centerY.equalTo(btn3800).offset(-10)
}
let img3b = UIImageView(image: UIImage(named: "diamond"))
btn3800.addSubview(img3b)
img3b.snp.makeConstraints { (make) in
make.centerX.equalTo(btn3800).offset(-50)
make.centerY.equalTo(btn3800).offset(-10)
}
let img3c = UIImageView(image: UIImage(named: "diamond"))
btn3800.addSubview(img3c)
img3c.snp.makeConstraints { (make) in
make.centerX.equalTo(btn3800).offset(50)
make.centerY.equalTo(btn3800).offset(-10)
}
// 文本
let lbl60 = UILabel()
btn60.addSubview(lbl60)
lbl60.text = NSLocalizedString("money1", comment: "")
lbl60.textColor = UIColor.white
lbl60.font = UIFont(name: "Arial-BoldMT", size: 25)
lbl60.textAlignment = .center //文字中心对齐
lbl60.snp.makeConstraints { (make) in
make.centerX.equalTo(btn60)
make.centerY.equalTo(btn60).offset(25)
}
let lbl320 = UILabel()
btn320.addSubview(lbl320)
lbl320.text = NSLocalizedString("money5", comment: "")
lbl320.textColor = UIColor.white
lbl320.font = UIFont(name: "Arial-BoldMT", size: 25)
lbl320.textAlignment = .center //文字中心对齐
lbl320.snp.makeConstraints { (make) in
make.centerX.equalTo(btn320)
make.centerY.equalTo(btn320).offset(25)
}
let lbl3800 = UILabel()
btn3800.addSubview(lbl3800)
lbl3800.text = NSLocalizedString("money50", comment: "")
lbl3800.textColor = UIColor.white
lbl3800.font = UIFont(name: "Arial-BoldMT", size: 25)
lbl3800.textAlignment = .center //文字中心对齐
lbl3800.snp.makeConstraints { (make) in
make.centerX.equalTo(btn3800)
make.centerY.equalTo(btn3800).offset(25)
}
// 钻石数量
let lblnum60 = UILabel()
btn60.addSubview(lblnum60)
lblnum60.text = "60"
lblnum60.textColor = UIColor.white
lblnum60.font = UIFont(name: "Arial-BoldMT", size: 25)
lblnum60.textAlignment = .center //文字中心对齐
lblnum60.snp.makeConstraints { (make) in
make.right.equalTo(img60.snp.left).offset(-5)
make.centerY.equalTo(img60)
}
let lblnum320 = UILabel()
btn320.addSubview(lblnum320)
lblnum320.text = "320"
lblnum320.textColor = UIColor.white
lblnum320.font = UIFont(name: "Arial-BoldMT", size: 25)
lblnum320.textAlignment = .center //文字中心对齐
lblnum320.snp.makeConstraints { (make) in
make.right.equalTo(img320.snp.left).offset(-5)
make.centerY.equalTo(img320)
}
let lblnum3800 = UILabel()
btn3800.addSubview(lblnum3800)
lblnum3800.text = "3800"
lblnum3800.textColor = UIColor.white
lblnum3800.font = UIFont(name: "Arial-BoldMT", size: 25)
lblnum3800.textAlignment = .center //文字中心对齐
lblnum3800.snp.makeConstraints { (make) in
make.right.equalTo(img3b.snp.left).offset(-5)
make.centerY.equalTo(img3b)
}
// 钻石, 在右侧添加一个按钮
let barButtonItem = UIBarButtonItem(title: "0 "+strzs, style: UIBarButtonItemStyle.plain, target: self, action: #selector(descDiamon))
self.navigationItem.rightBarButtonItem = barButtonItem
}
override func viewWillAppear(_ animated: Bool) {
reSetDiamond()
}
func reSetDiamond() {
let dia = String(format: "%d", (gGlobalSet?.diamon)!) + " "
self.navigationItem.rightBarButtonItem?.title = dia + strzs
}
func descDiamon() {
let dia = " " + String(format: "%d", (gGlobalSet?.diamon)!) + " "
let strShow = NSLocalizedString("You have", comment: "") + dia + strzs
TipsSwift.showTopWithText(strShow)
}
func callbackBuyDiamond60() {
gGlobalSet?.diamon += 60
appDelegate.saveContext()
reSetDiamond()
MobClick.event("UMSHOPBUY60")
}
func callbackBuyDiamond320() {
gGlobalSet?.diamon += 320
appDelegate.saveContext()
reSetDiamond()
MobClick.event("UMSHOPBUY320")
}
func callbackBuyDiamond3800() {
gGlobalSet?.diamon += 3800
appDelegate.saveContext()
reSetDiamond()
MobClick.event("UMSHOPBUY3800")
}
func shopJS() -> Void {
SwiftyStoreKit.retrieveProductsInfo(["2"]) { result in
if let product = result.retrievedProducts.first {
let priceString = product.localizedPrice!
print("Product: \(product.localizedDescription), price: \(priceString)")
}
else if let invalidProductId = result.invalidProductIDs.first {
print("Could not retrieve product info")
return
}
else {
print("Error: \(result.error)")
}
}
}
func btnBuyDiamond60() {
MobClick.event("UMSHOPWANTBUY60")
showConDec()
SwiftyStoreKit.purchaseProduct("2", atomically: true) { result in
switch result {
case .success(let product):
print("Purchase Success: \(product.productId)")
self.callbackBuyDiamond60()
case .error(let error):
switch error.code {
case .unknown: print("Unknown error. Please contact support")
case .clientInvalid: print("Not allowed to make the payment")
case .paymentCancelled: break
case .paymentInvalid: print("The purchase identifier was invalid")
case .paymentNotAllowed: print("The device is not allowed to make the payment")
case .storeProductNotAvailable: print("The product is not available in the current storefront")
case .cloudServicePermissionDenied: print("Access to cloud service information is not allowed")
case .cloudServiceNetworkConnectionFailed: print("Could not connect to the network")
default:break
}
}
}
}
func btnBuyDiamond320() {
MobClick.event("UMSHOPWANTBUY320")
showConDec()
SwiftyStoreKit.purchaseProduct("3", atomically: true) { result in
switch result {
case .success(let product):
print("Purchase Success: \(product.productId)")
self.callbackBuyDiamond320()
case .error(let error):
switch error.code {
case .unknown: print("Unknown error. Please contact support")
case .clientInvalid: print("Not allowed to make the payment")
case .paymentCancelled: break
case .paymentInvalid: print("The purchase identifier was invalid")
case .paymentNotAllowed: print("The device is not allowed to make the payment")
case .storeProductNotAvailable: print("The product is not available in the current storefront")
case .cloudServicePermissionDenied: print("Access to cloud service information is not allowed")
case .cloudServiceNetworkConnectionFailed: print("Could not connect to the network")
default:break
}
}
}
}
static func buy320() {
MobClick.event("UMSHOPWANTBUY320")
SwiftyStoreKit.purchaseProduct("3", atomically: true) { result in
switch result {
case .success(let product):
print("Purchase Success: \(product.productId)")
gGlobalSet?.diamon += 320
appDelegate.saveContext()
MobClick.event("UMSHOPBUY320")
TipsSwift.showCenterWithText(NSLocalizedString("Sucess", comment: ""), duration: 3)
case .error(let error):
break
}
}
}
func btnBuyDiamond3800() {
MobClick.event("UMSHOPWANTBUY3800")
showConDec()
SwiftyStoreKit.purchaseProduct("4", atomically: true) { result in
switch result {
case .success(let product):
print("Purchase Success: \(product.productId)")
self.callbackBuyDiamond3800()
case .error(let error):
switch error.code {
case .unknown: print("Unknown error. Please contact support")
case .clientInvalid: print("Not allowed to make the payment")
case .paymentCancelled: break
case .paymentInvalid: print("The purchase identifier was invalid")
case .paymentNotAllowed: print("The device is not allowed to make the payment")
case .storeProductNotAvailable: print("The product is not available in the current storefront")
case .cloudServicePermissionDenied: print("Access to cloud service information is not allowed")
case .cloudServiceNetworkConnectionFailed: print("Could not connect to the network")
default:break
}
}
}
}
func showConDec() {
TipsSwift.showCenterWithText(NSLocalizedString("content shop", comment: ""), duration: 2)
}
func showContactShop() {
contactShop = UIView()
self.view.addSubview(contactShop)
contactShop.snp.makeConstraints { (make) in
make.center.equalTo(self.view)
make.width.equalTo(self.view).multipliedBy(0.8)
make.height.equalTo(self.view).multipliedBy(0.5)
}
}
func closeContactShop() {
if contactShop != nil {
contactShop.removeFromSuperview()
contactShop = nil
}
}
}
| mit | ff2cccddaf42acd2937533e35787daed | 38.28125 | 142 | 0.594344 | 4.215549 | false | false | false | false |
qidafang/iOS_427studio | studio427/Favorite.swift | 1 | 339 | //
// Favorite.swift
// studio427
//
// Created by 祁达方 on 15/10/27.
// Copyright © 2015年 祁达方. All rights reserved.
//
import UIKit
class Favorite: NSObject {
var id:String = "";
var title:String = "";
var link:String = "";
var desc:String = "";
var weight:String = "";
var group:String = "";
}
| apache-2.0 | 28f23a200a9d977d0d23ddef6995b31b | 17 | 47 | 0.580247 | 3.085714 | false | false | false | false |
ChenJian345/realm-cocoa | RealmSwift-swift2.0/Tests/ObjectAccessorTests.swift | 4 | 7301 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import RealmSwift
import Foundation
class ObjectAccessorTests: TestCase {
func setAndTestAllProperties(object: SwiftObject) {
object.boolCol = true
XCTAssertEqual(object.boolCol, true)
object.boolCol = false
XCTAssertEqual(object.boolCol, false)
object.intCol = -1
XCTAssertEqual(object.intCol, -1)
object.intCol = 0
XCTAssertEqual(object.intCol, 0)
object.intCol = 1
XCTAssertEqual(object.intCol, 1)
object.floatCol = 20
XCTAssertEqual(object.floatCol, 20 as Float)
object.floatCol = 20.2
XCTAssertEqual(object.floatCol, 20.2 as Float)
object.floatCol = 16777217
XCTAssertEqual(Double(object.floatCol), 16777216.0 as Double)
object.doubleCol = 20
XCTAssertEqual(object.doubleCol, 20)
object.doubleCol = 20.2
XCTAssertEqual(object.doubleCol, 20.2)
object.doubleCol = 16777217
XCTAssertEqual(object.doubleCol, 16777217)
object.stringCol = ""
XCTAssertEqual(object.stringCol, "")
let utf8TestString = "值значен™👍☞⎠‱௹♣︎☐▼❒∑⨌⧭иеمرحبا"
object.stringCol = utf8TestString
XCTAssertEqual(object.stringCol, utf8TestString)
let data = "b".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
object.binaryCol = data
XCTAssertEqual(object.binaryCol, data)
let date = NSDate(timeIntervalSinceReferenceDate: 2) as NSDate
object.dateCol = date
XCTAssertEqual(object.dateCol, date)
object.objectCol = SwiftBoolObject(value: [true])
XCTAssertEqual(object.objectCol.boolCol, true)
}
func testStandaloneAccessors() {
let object = SwiftObject()
setAndTestAllProperties(object)
}
func testPersistedAccessors() {
let object = SwiftObject()
try! Realm().beginWrite()
try! Realm().create(SwiftObject)
setAndTestAllProperties(object)
try! Realm().commitWrite()
}
func testIntSizes() {
let realm = realmWithTestPath()
let v8 = Int8(1) << 6
let v16 = Int16(1) << 12
let v32 = Int32(1) << 30
// 1 << 40 doesn't auto-promote to Int64 on 32-bit platforms
let v64 = Int64(1) << 40
realm.write {
let obj = SwiftAllIntSizesObject()
let testObject: Void -> Void = {
obj.objectSchema.properties.map { $0.name }.map { obj[$0] = 0 }
obj["int8"] = Int(v8)
XCTAssertEqual(obj["int8"]! as! Int, Int(v8))
obj["int16"] = Int(v16)
XCTAssertEqual(obj["int16"]! as! Int, Int(v16))
obj["int32"] = Int(v32)
XCTAssertEqual(obj["int32"]! as! Int, Int(v32))
obj["int64"] = NSNumber(longLong: v64)
XCTAssertEqual(obj["int64"]! as! NSNumber, NSNumber(longLong: v64))
obj.objectSchema.properties.map { $0.name }.map { obj[$0] = 0 }
obj.setValue(Int(v8), forKey: "int8")
XCTAssertEqual(obj.valueForKey("int8")! as! Int, Int(v8))
obj.setValue(Int(v16), forKey: "int16")
XCTAssertEqual(obj.valueForKey("int16")! as! Int, Int(v16))
obj.setValue(Int(v32), forKey: "int32")
XCTAssertEqual(obj.valueForKey("int32")! as! Int, Int(v32))
obj.setValue(NSNumber(longLong: v64), forKey: "int64")
XCTAssertEqual(obj.valueForKey("int64")! as! NSNumber, NSNumber(longLong: v64))
obj.objectSchema.properties.map { $0.name }.map { obj[$0] = 0 }
obj.int8 = v8
XCTAssertEqual(obj.int8, v8)
obj.int16 = v16
XCTAssertEqual(obj.int16, v16)
obj.int32 = v32
XCTAssertEqual(obj.int32, v32)
obj.int64 = v64
XCTAssertEqual(obj.int64, v64)
}
testObject()
realm.add(obj)
testObject()
}
let obj = realm.objects(SwiftAllIntSizesObject).first!
XCTAssertEqual(obj.int8, v8)
XCTAssertEqual(obj.int16, v16)
XCTAssertEqual(obj.int32, v32)
XCTAssertEqual(obj.int64, v64)
}
func testLongType() {
let longNumber: Int64 = 17179869184
let intNumber: Int64 = 2147483647
let negativeLongNumber: Int64 = -17179869184
let updatedLongNumber: Int64 = 8589934592
let realm = realmWithTestPath()
realm.beginWrite()
realm.create(SwiftLongObject.self, value: [NSNumber(longLong: longNumber)])
realm.create(SwiftLongObject.self, value: [NSNumber(longLong: intNumber)])
realm.create(SwiftLongObject.self, value: [NSNumber(longLong: negativeLongNumber)])
realm.commitWrite()
let objects = realm.objects(SwiftLongObject)
XCTAssertEqual(objects.count, Int(3), "3 rows expected")
XCTAssertEqual(objects[0].longCol, longNumber, "2 ^ 34 expected")
XCTAssertEqual(objects[1].longCol, intNumber, "2 ^ 31 - 1 expected")
XCTAssertEqual(objects[2].longCol, negativeLongNumber, "-2 ^ 34 expected")
realm.beginWrite()
objects[0].longCol = updatedLongNumber
realm.commitWrite()
XCTAssertEqual(objects[0].longCol, updatedLongNumber, "After update: 2 ^ 33 expected")
}
func testListsDuringResultsFastEnumeration() {
let realm = realmWithTestPath()
let object1 = SwiftObject()
let object2 = SwiftObject()
let trueObject = SwiftBoolObject()
trueObject.boolCol = true
let falseObject = SwiftBoolObject()
falseObject.boolCol = false
object1.arrayCol.append(trueObject)
object1.arrayCol.append(falseObject)
object2.arrayCol.append(trueObject)
object2.arrayCol.append(falseObject)
realm.write {
realm.add(object1)
realm.add(object2)
}
let objects = realm.objects(SwiftObject)
let firstObject = objects.first
XCTAssertEqual(2, firstObject!.arrayCol.count)
let lastObject = objects.last
XCTAssertEqual(2, lastObject!.arrayCol.count)
// let generator = objects.generate()
// let next = generator.next()!
// XCTAssertEqual(next.arrayCol.count, 2)
for obj in objects {
XCTAssertEqual(2, obj.arrayCol.count)
}
}
}
| apache-2.0 | 26a0dcd246049f31c36c610850b694f1 | 33.889423 | 95 | 0.600386 | 4.301719 | false | true | false | false |
mylifeasdog/Pictures | Sources/Pictures.swift | 1 | 5271 | //
// Pictures.swift
// Pictures
//
// Created by Wipoo Shinsirikul on 12/28/16.
// Copyright © 2016 Wipoo Shinsirikul. All rights reserved.
//
import UIKit
open class Pictures<T: UICollectionViewCell>: UICollectionViewController where T: PicturesImageProviderType
{
fileprivate let picturesCollectionViewDataSource = PicturesCollectionViewDataSource<T>()
// private let picturesCollectionViewDataSourcePrefetching = PicturesCollectionViewDataSourcePrefetching()
fileprivate let picturesCollectionViewDelegate = PicturesCollectionViewDelegate<T>()
public init()
{
super.init(collectionViewLayout: UICollectionViewFlowLayout())
}
required public init?(coder aDecoder: NSCoder)
{
super.init(collectionViewLayout: UICollectionViewFlowLayout())
}
override open func viewDidLoad()
{
super.viewDidLoad()
if #available(iOS 9.0, *)
{
installsStandardGestureForInteractiveMovement = false
}
if collectionViewLayout is UICollectionViewFlowLayout
{
// ;
}
else
{
collectionView?.collectionViewLayout = UICollectionViewFlowLayout()
}
picturesCollectionViewDataSource.collectionView = collectionView
picturesCollectionViewDataSource.picturesCollectionViewDelegate = picturesCollectionViewDelegate
picturesCollectionViewDelegate.collectionViewLayout = collectionView?.collectionViewLayout
picturesCollectionViewDelegate.picturesCollectionViewDataSource = picturesCollectionViewDataSource
collectionView?.dataSource = picturesCollectionViewDataSource
// collectionView?.prefetchDataSource = picturesCollectionViewDataSourcePrefetching
collectionView?.delegate = picturesCollectionViewDelegate
collectionView?.allowsMultipleSelection = true
collectionView?.backgroundColor = .white
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(Pictures.refreshControlValueDidChange(refreshControl:)), for: .valueChanged)
collectionView?.addSubview(refreshControl)
reloadData()
}
// MARK: -
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
{
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(
alongsideTransition: { [weak self] _ in
self?.picturesCollectionViewDelegate.size = CGSize(width: UIScreen.main.bounds.width / 3.0, height: UIScreen.main.bounds.width / 3.0) },
completion: nil)
}
// MARK: - Action
@objc
private func refreshControlValueDidChange(refreshControl: UIRefreshControl)
{
reloadData { refreshControl.endRefreshing() }
}
}
extension Pictures
{
func reloadData(_ completion: (() -> Void)? = nil)
{
guard let needsNewPicturesHandler = needsNewPicturesHandler else
{
return
}
picturesCollectionViewDataSource.isLoading = true
picturesCollectionViewDataSource.isLoadAll = false
picturesCollectionViewDelegate.clearSelectedImages()
needsNewPicturesHandler(true) { [weak self] (newPictures, isLoadAll) in
self?.picturesCollectionViewDataSource.pictures.removeAll()
self?.picturesCollectionViewDataSource.pictures += newPictures
self?.picturesCollectionViewDataSource.isLoadAll = isLoadAll
self?.picturesCollectionViewDataSource.isLoading = false
self?.collectionView?.reloadData()
completion?() }
}
}
extension Pictures
{
open var size: CGSize {
get { return picturesCollectionViewDelegate.size }
set { picturesCollectionViewDelegate.size = newValue } }
open var inset: UIEdgeInsets {
get { return picturesCollectionViewDelegate.inset }
set { picturesCollectionViewDelegate.inset = newValue } }
open var minimumLineSpacing: CGFloat {
get { return picturesCollectionViewDelegate.minimumLineSpacing }
set { picturesCollectionViewDelegate.minimumLineSpacing = newValue } }
open var minimumInteritemSpacing: CGFloat {
get { return picturesCollectionViewDelegate.minimumInteritemSpacing }
set { picturesCollectionViewDelegate.minimumInteritemSpacing = newValue } }
open var needsNewPicturesHandler: ((_ isFromRefreshControl: Bool, _ callback: @escaping ((newPictures: [Any], isLoadAll: Bool)) -> Void) -> Void)? {
get { return picturesCollectionViewDelegate.needsNewPicturesHandler }
set { picturesCollectionViewDelegate.needsNewPicturesHandler = newValue } }
open var didSelectPicturesHandler: (([(index: UInt, picture: Any)]) -> Void)? {
get { return picturesCollectionViewDelegate.didSelectPicturesHandler }
set { picturesCollectionViewDelegate.didSelectPicturesHandler = newValue } }
open var selectionLimit: UInt {
get { return picturesCollectionViewDelegate.selectionLimit }
set { picturesCollectionViewDelegate.selectionLimit = newValue } }
}
| mit | cfec7752b0561f17152e301e9905fda9 | 38.924242 | 152 | 0.701139 | 6.092486 | false | false | false | false |
teaxus/TSAppEninge | StandardProject/Controller/Basic/SideBarViewController.swift | 1 | 11830 | //
// SideBarViewController.swift
// StandardProject
//
// Created by teaxus on 15/12/8.
// Copyright © 2015年 teaxus. All rights reserved.
//
import UIKit
class SideBarViewController: UIViewController,UIGestureRecognizerDelegate {
static var share:SideBarViewController?
let speedf = CGFloat(0.7)
let kMainPageDistance = Screen_width*0.2//打开左侧窗时,中视图(右视图)露出的宽度
let kMainPageScale = CGFloat(0.8)
let kLeftCenterX = CGFloat(30.0) //左侧初始偏移量
let kLeftScale = CGFloat(0.6) //左侧初始缩放比例
let kLeftAlpha = CGFloat(0.7) //左侧蒙版的最大值 0.9是最好的
let kMainPageCenter = CGPoint(x: Screen_width + Screen_width * CGFloat(0.8) / 2.0 - (Screen_width*0.2),y: Screen_height / 2.0) //打开左侧窗时,中视图中心点
let vCouldChangeDeckStateDistance = (Screen_width - (Screen_width*2)) / 2.0 - 40.0 //滑动距离大于此数时,状态改变(关--》开,或者开--》关)
var sideslipTapGes:UITapGestureRecognizer?
var closed:Bool
var leftVC:UIViewController
var mainVC:UIViewController
var contentView:UIView?
var pan:UIPanGestureRecognizer?;//侧滑手势
var leftTableview:UITableView?
var scalef:CGFloat//实时横向位移
let bool_need_scale = false //是否要缩放 这个地方是可以配置
var bool_sideable = true //是可以侧滑
//MARK:方法---------------------------------
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
@brief 初始化侧滑控制器
@param leftVC 左视图控制器
mainVC 中间视图控制器
@result instancetype 初始化生成的对象
*/
required init(leftVC:UIViewController,mainVC:UIViewController) {
self.closed = true
self.leftVC = leftVC
self.mainVC = mainVC
self.scalef = 0.0
super.init(nibName:nil,bundle:nil)
//滑动手势
#if swift(>=2.2)
self.pan = UIPanGestureRecognizer(target: self, action: #selector(SideBarViewController.handlePan(rec:)))
#else
self.pan = UIPanGestureRecognizer(target: self, action: "handlePan:")
#endif
self.mainVC.view .addGestureRecognizer(self.pan!)
self.pan?.delegate = self
self.view .addSubview(self.leftVC.view)
self.view.frame = CGRect(x: 0,y: 0,width: Screen_width,height: Screen_height)
//蒙版
let view = UIView()
view.frame = self.leftVC.view.bounds
view.backgroundColor = UIColor.black
view.alpha = 0
self.contentView = view
self.mainVC.view.addSubview(view)
//获取左侧tableview
for object in self.leftVC.view.subviews{
if object is UITableView{
self.leftTableview = object as? UITableView
}
}
self.leftTableview?.backgroundColor = UIColor.clear
self.leftTableview?.frame = CGRect(x: 0,y: 0,
width: Screen_width - kMainPageDistance,
height: Screen_height)
//设置左侧tableview的初始位置和缩放系数
self.leftTableview?.transform = CGAffineTransform(scaleX: kLeftCenterX, y: kLeftScale)
self.leftTableview?.center = CGPoint(x: Screen_width/2.0,y: Screen_height * 0.5)
self.view.addSubview(self.mainVC.view)//初始时侧滑窗关闭
}
//MARK:滑动手势
func handlePan(rec:UIPanGestureRecognizer){
if !bool_sideable{
return
}
let point = rec.translation(in: self.view)
self.scalef = point.x * self.speedf + scalef
var needMoveWithTap = true //是否还需要跟随手指移动
if (((self.mainVC.view.x_origin <= 0.0) && (self.scalef <= 0.0)) ||
((self.mainVC.view.x_origin >= (Screen_width - kMainPageDistance)) &&
(self.scalef >= 0))){
//边界值管控
scalef = 0
needMoveWithTap = false
}
//根据视图位置判断是左滑还是右边滑动
if ((needMoveWithTap && (rec.view!.frame.origin.x >= 0.0) &&
(rec.view!.frame.origin.x <= (Screen_width - kMainPageDistance)))){
var recCenterX = rec.view!.center.x + point.x * self.speedf
if (recCenterX < Screen_width * 0.5 - 2.0) {
recCenterX = Screen_width * 0.5;
}
let recCenterY = rec.view?.center.y
rec.view?.center = CGPoint(x: recCenterX,y: recCenterY!)
//scale 1.0~kMainPageScale
let scale = 1.0 - (1.0 - kMainPageScale) * (rec.view!.frame.origin.x / (Screen_width - kMainPageDistance))
rec.setTranslation(CGPoint(x: 0.0,y: 0.0), in: self.view)
let leftTabCenterX = kLeftCenterX + ((Screen_width - kMainPageDistance) * 0.5 - kLeftCenterX) * (rec.view!.frame.origin.x / (Screen_width - kMainPageDistance))
//leftScale kLeftScale~1.0
let leftScale = kLeftScale + (1.0 - kLeftScale) * (rec.view!.frame.origin.x / (Screen_width - kMainPageDistance))
self.leftTableview?.center = CGPoint(x: leftTabCenterX,y: Screen_height * 0.5)
if bool_need_scale{
//rec.view?.transform = CGAffineTransformScale(CGAffineTransformIdentity, scale, scale)
//self.leftTableview?.transform = CGAffineTransformScale(CGAffineTransformIdentity, leftScale,leftScale)
rec.view?.transform = CGAffineTransform(scaleX: scale, y: scale)
self.leftTableview?.transform = CGAffineTransform(scaleX: leftScale, y: leftScale)
}
//tempAlpha kLeftAlpha~0
let tempAlpha = kLeftAlpha - kLeftAlpha * (rec.view!.frame.origin.x / (Screen_width - kMainPageDistance))
self.contentView?.alpha = 1-tempAlpha;
}
else{
//超出范围,
if self.mainVC.view.x_origin < 0
{
self.closeLeftView()
scalef = 0;
}
else if (self.mainVC.view.x_origin > (Screen_width - kMainPageDistance))
{
self.openLeftView()
scalef = 0;
}
}
//手势结束后修正位置,超过约一半时向多出的一半偏移
if (rec.state == UIGestureRecognizerState.ended){
if (fabs(scalef) > self.vCouldChangeDeckStateDistance){
if (self.closed){
self.openLeftView()
}
else
{
self.closeLeftView()
}
}
else{
if (self.closed){
self.closeLeftView()
}
else{
self.openLeftView()
}
}
scalef = 0
}
}
internal func closeLeftView(){
let view_mask = UIView(frame: CGRect(x: 0,y: 0,width: self.view.frame.size.width,height: self.view.frame.size.height))
self.view.addSubview(view_mask)
UIView.animate(withDuration: 0.5) { () -> Void in
self.mainVC.view.center = CGPoint(x: Screen_width / 2.0,y: Screen_height / 2.0)
self.closed = true
self.leftTableview?.center = CGPoint(x: self.kLeftCenterX,y: Screen_height * 0.5)
if self.bool_need_scale{
//self.mainVC.view.transform = CGAffineTransformScale(CGAffineTransformIdentity,1.0,1.0)
//self.leftTableview?.transform = CGAffineTransformScale(CGAffineTransformIdentity,self.kLeftScale,self.kLeftScale)
self.mainVC.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.leftTableview?.transform = CGAffineTransform(scaleX: self.kLeftScale, y: self.kLeftScale)
}
self.contentView?.alpha = 0
self.removeSingleTap()
}
DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
view_mask.removeFromSuperview()
}
}
//关闭行为收敛
func removeSingleTap(){
for tempButton in self.mainVC.view.subviews{
tempButton.isUserInteractionEnabled = true
}
if self.sideslipTapGes != nil{
self.mainVC.view.removeGestureRecognizer(self.sideslipTapGes!)
self.sideslipTapGes = nil
}
}
//MARK:打开左视图
func openLeftView(){
UIView.animate(withDuration: 0.5) { () -> Void in
self.mainVC.view.center = self.kMainPageCenter
self.closed = false
self.leftTableview?.center = CGPoint(x: (Screen_width - self.kMainPageDistance) * 0.5,y: Screen_height * 0.5)
if self.bool_need_scale{
//self.leftTableview?.transform = CGAffineTransformScale(CGAffineTransformIdentity,1.0,1.0)
//self.mainVC.view.transform = CGAffineTransformScale(CGAffineTransformIdentity,self.kMainPageScale,self.kMainPageScale)
self.leftTableview?.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.mainVC.view.transform = CGAffineTransform(scaleX: self.kMainPageScale, y: self.kMainPageScale)
}
self.contentView?.alpha = self.kLeftAlpha;
}
self.disableTapButton()
}
func disableTapButton(){
for tempButton in self.mainVC.view.subviews{
tempButton.isUserInteractionEnabled = false
}
//单击
if self.sideslipTapGes == nil{
//单击手势
#if swift(>=2.2)
self.sideslipTapGes = UITapGestureRecognizer(target: self, action: #selector(SideBarViewController.handeTap(tap:)))
#else
self.sideslipTapGes = UITapGestureRecognizer(target: self, action: "handeTap:")
#endif
self.sideslipTapGes?.numberOfTapsRequired = 1
self.mainVC.view.addGestureRecognizer(self.sideslipTapGes!)
self.sideslipTapGes?.cancelsTouchesInView = true//点击事件盖住其它响应事件,但盖不住Button
}
}
func handeTap(tap:UITapGestureRecognizer){
if ((!self.closed) && (tap.state == UIGestureRecognizerState.ended)){
UIView.animate(withDuration: 0.5, animations: { () -> Void in
tap.view!.center = CGPoint(x: Screen_width/2.0,y: Screen_height/2.0)
self.closed = true
self.leftTableview?.center = CGPoint(x: self.kLeftCenterX,y: Screen_height * 0.5);
if self.bool_need_scale{
//self.leftTableview?.transform = CGAffineTransformScale(CGAffineTransformIdentity,self.kLeftScale,self.kLeftScale)
//tap.view!.transform = CGAffineTransformScale(CGAffineTransformIdentity,1.0,1.0)
self.leftTableview?.transform = CGAffineTransform(scaleX: self.kLeftScale, y: self.kLeftScale)
tap.view!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}
self.contentView?.alpha = 0;
})
self.scalef = 0
self.removeSingleTap()
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
let vDeckCanNotPanViewTag = 987654
if touch.view?.tag == vDeckCanNotPanViewTag{
return false
}
return true
}
}
| mit | fdec05259fb507c6bd87148054a386eb | 37.9 | 171 | 0.577165 | 4.162731 | false | false | false | false |
tamadon/nassi | ios/nassi/AppDelegate.swift | 1 | 3946 | //
// AppDelegate.swift
// nassi
//
// Created by Hideaki Tamai on 2017/08/06.
// Copyright © 2017年 tamadon. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
loadEnv()
var viewControllers: [UIViewController] = []
let firstVC = EventViewController.initialViewController()
let navigationController = UINavigationController(rootViewController: firstVC)
navigationController.tabBarItem = UITabBarItem(title: "Record", image: UIImage.Asset.ic_mode_edit_36pt, tag: 1)
viewControllers.append(navigationController)
let secondVC = YouTubeListViewController.initialViewController()
secondVC.tabBarItem = UITabBarItem(title: "Movie", image: UIImage.Asset.ic_play_circle_outline_36pt, tag: 2)
viewControllers.append(secondVC)
let tabBarController = UITabBarController()
tabBarController.setViewControllers(viewControllers, animated: false)
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.rootViewController = tabBarController
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func loadEnv() {
guard let path = Bundle.main.path(forResource: ".env", ofType: nil) else {
fatalError("Not found: '/path/to/.env'.\nPlease create .env file reference from .env.sample")
}
let url = URL(fileURLWithPath: path)
do {
let data = try Data(contentsOf: url)
let str = String(data: data, encoding: .utf8) ?? "Empty File"
let clean = str.replacingOccurrences(of: "\"", with: "").replacingOccurrences(of: "'", with: "")
let envVars = clean.components(separatedBy:"\n")
for envVar in envVars {
let keyVal = envVar.components(separatedBy:"=")
if keyVal.count == 2 {
setenv(keyVal[0], keyVal[1], 1)
}
}
} catch {
fatalError(error.localizedDescription)
}
}
}
| mit | bcc0bd420da6095f29ad525656d7f8f7 | 45.388235 | 285 | 0.693381 | 5.278447 | false | false | false | false |
DTVD/APIKitExt | Example/Pods/JASON/Source/JSON.swift | 2 | 4638 | //
// JSON.swift
//
// Copyright (c) 2015-2016 Damien (http://delba.io)
//
// 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.
//
// MARK: - Initializers
public struct JSON {
/// The date formatter used for date conversions
public static var dateFormatter = DateFormatter()
/// The object on which any subsequent method operates
public let object: AnyObject?
/**
Creates an instance of JSON from AnyObject.
- parameter object: An instance of any class
- returns: the created JSON
*/
public init(_ object: Any?) {
self.init(object: object)
}
/**
Creates an instance of JSON from NSData.
- parameter data: An instance of NSData
- returns: the created JSON
*/
public init(_ data: Data?) {
self.init(object: JSON.objectWithData(data))
}
/**
Creates an instance of JSON from a string.
- parameter data: A string
- returns: the created JSON
*/
public init(_ string: String?) {
self.init(string?.data(using: String.Encoding.utf8))
}
/**
Creates an instance of JSON from AnyObject.
Takes an explicit parameter name to prevent calls to init(_:) with NSData? when nil is passed.
- parameter object: An instance of any class
- returns: the created JSON
*/
internal init(object: Any?) {
self.object = object as AnyObject?
}
}
// MARK: - Subscript
extension JSON {
/**
Creates a new instance of JSON.
- parameter index: A string
- returns: a new instance of JSON or itself if its object is nil.
*/
public subscript(index: String) -> JSON {
if object == nil { return self }
if let nsDictionary = nsDictionary {
return JSON(nsDictionary[index])
}
return JSON(object: nil)
}
/**
Creates a new instance of JSON.
- parameter index: A string
- returns: a new instance of JSON or itself if its object is nil.
*/
public subscript(index: Int) -> JSON {
if object == nil { return self }
if let nsArray = nsArray {
return JSON(nsArray[safe: index])
}
return JSON(object: nil)
}
/**
Creates a new instance of JSON.
- parameter indexes: Any
- returns: a new instance of JSON or itself if its object is nil
*/
public subscript(path indexes: Any...) -> JSON {
return self[indexes]
}
internal subscript(indexes: [Any]) -> JSON {
if object == nil { return self }
var json = self
for index in indexes {
if let string = index as? String, let object = json.nsDictionary?[string] {
json = JSON(object)
continue
}
if let int = index as? Int, let object = json.nsArray?[safe: int] {
json = JSON(object)
continue
}
else {
json = JSON(object: nil)
break
}
}
return json
}
}
// MARK: - Private extensions
private extension JSON {
/**
Converts an instance of NSData to AnyObject.
- parameter data: An instance of NSData or nil
- returns: An instance of AnyObject or nil
*/
static func objectWithData(_ data: Data?) -> Any? {
guard let data = data else { return nil }
return try? JSONSerialization.jsonObject(with: data)
}
}
| mit | b2fba2a0842fc69855b91a42e97065dc | 26.282353 | 102 | 0.599612 | 4.703854 | false | false | false | false |
alblue/com.packtpub.swift.essentials | CustomViews/CustomViews/SampleTable.swift | 1 | 4684 | // Copyright (c) 2016, Alex Blewitt, Bandlem Ltd
// Copyright (c) 2016, Packt Publishing Ltd
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class SampleTable: UITableViewController {
var items = [
("First", "A first item"),
("Second", "A second item"),
]
required init?(coder: NSCoder) {
super.init(coder:coder)
}
override func viewDidLoad() {
let xib = UINib(nibName:"CounterView",bundle:nil)
let objects = xib.instantiateWithOwner(self, options:nil)
let counter = objects.first as? UIView
tableView.tableHeaderView = counter
let footer = UITableViewHeaderFooterView()
footer.contentView.addSubview(TwoLabels(frame:CGRect.zero))
tableView.tableFooterView = footer
let url = NSURL(string: "https://raw.githubusercontent.com/alblue/com.packtpub.swift.essentials/master/CustomViews/CustomViews/SampleTable.json")!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {data,response,error -> Void in
guard error == nil else {
self.items += [("Error",error!.localizedDescription)]
return
}
let statusCode = (response as! NSHTTPURLResponse).statusCode
guard statusCode < 500 else {
self.items += [("Server error \(statusCode)",
url.absoluteString)]
return
}
guard statusCode < 400 else {
self.items += [("Client error \(statusCode)",
url.absoluteString)]
return
}
if let parsed = try? NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as! NSArray {
for entry in parsed {
switch (entry["title"], entry["content"]) {
case (let title as String, let content as String):
self.items += [(title,content)]
default:
self.items += [("Error", "Missing unknown entry")]
}
}
} else {
self.items += [("Error", "JSON is not an array")]
}
self.runOnUIThread {
self.tableView.backgroundColor = UIColor.redColor()
self.tableView.reloadData()
self.tableView.backgroundColor = UIColor.greenColor()
}
})
task.resume()
session.dataTaskWithURL(NSURL(string:"http://alblue.bandlem.com/Tag/swift/atom.xml")!, completionHandler: {data,response,error -> Void in
if let data = data {
self.items += FeedParser(data).items
self.runOnUIThread(self.tableView.reloadData)
}
}).resume()
runOnBackgroundThread {
let repo = RemoteGitRepository(host: "github.com", repo: "/alblue/com.packtpub.swift.essentials.git")
// way of forcing true without compiler warnings of unused code
let async = arc4random() >= 0
if async {
repo.lsRemoteAsync() { (ref:String,hash:String) in
self.items += [(ref,hash)]
self.runOnUIThread(self.tableView.reloadData)
}
} else {
for (ref,hash) in repo.lsRemote() {
self.items += [(ref,hash)]
}
self.runOnUIThread(self.tableView.reloadData)
}
}
}
func runOnBackgroundThread(fn:()->()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),fn)
}
func runOnUIThread(fn:()->()) {
if NSThread.isMainThread() {
fn()
} else {
dispatch_async(dispatch_get_main_queue(), fn)
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let (title,subtitle) = items[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("prototypeCell")!
let titleLabel = cell.viewWithTag(1) as! UILabel
let subtitleLabel = cell.viewWithTag(2) as! UILabel
titleLabel.text = title
subtitleLabel.text = subtitle
return cell
}
}
| mit | ab4c0560ddf2c31d9b7be181a0255a00 | 37.393443 | 148 | 0.712852 | 3.826797 | false | false | false | false |
tndatacommons/Compass-iOS | Compass/src/Cell/AwardCell.swift | 1 | 1077 | //
// AwardCell.swift
// Compass
//
// Created by Ismael Alonso on 7/14/16.
// Copyright © 2016 Tennessee Data Commons. All rights reserved.
//
import UIKit
import Nuke
class AwardCell: UITableViewCell{
@IBOutlet weak var container: UIView!
@IBOutlet weak var badgeImage: UIImageView!
@IBOutlet weak var badgeName: UILabel!
@IBOutlet weak var badgeDescription: UILabel!
func bind(badge: Badge){
badgeImage.layoutIfNeeded();
if (badge.getImageUrl().characters.count != 0){
Nuke.taskWith(NSURL(string: badge.getImageUrl())!){
let image = $0.image;
self.badgeImage.image = image;
}.resume();
}
badgeName.text = badge.getName();
badgeDescription.text = badge.getDescription();
if (badge.isNew){
container.backgroundColor = UIColor(colorLiteralRed: 0.9, green: 0.9, blue: 0.9, alpha: 1);
}
else{
container.backgroundColor = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 1);
}
}
}
| mit | 380e82f96d8ccd07d93e73d8d37a16b0 | 28.081081 | 103 | 0.607807 | 4.15444 | false | false | false | false |
mozilla-mobile/focus-ios | Shared/Settings.swift | 1 | 3223 | /* 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
enum SettingsToggle: String, Equatable {
case trackingProtection = "TrackingProtection"
case biometricLogin = "BiometricLogin"
case blockAds = "BlockAds"
case blockAnalytics = "BlockAnalytics"
case blockSocial = "BlockSocial"
case blockOther = "BlockOther"
case blockFonts = "BlockFonts"
case showHomeScreenTips = "HomeScreenTips"
case safari = "Safari"
case sendAnonymousUsageData = "SendAnonymousUsageData"
case studies = "Studies"
case enableDomainAutocomplete = "enableDomainAutocomplete"
case enableCustomDomainAutocomplete = "enableCustomDomainAutocomplete"
case enableSearchSuggestions = "enableSearchSuggestions"
case displaySecretMenu = "displaySecretMenu"
}
extension SettingsToggle {
var trackerChanged: String {
switch self {
case .trackingProtection:
return ""
case .blockAds:
return "Advertising"
case .blockAnalytics:
return "Analytics"
case .blockSocial:
return "Social"
case .blockOther:
return "Content"
default:
return ""
}
}
}
struct Settings {
private static let prefs = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)!
private static let customDomainSettingKey = "customDomains"
private static let siriRequestsEraseKey = "siriRequestsErase"
private static func defaultForToggle(_ toggle: SettingsToggle) -> Bool {
switch toggle {
case .trackingProtection: return true
case .biometricLogin: return false
case .blockAds: return true
case .blockAnalytics: return true
case .blockSocial: return true
case .blockOther: return false
case .blockFonts: return false
case .showHomeScreenTips: return true
case .safari: return true
case .sendAnonymousUsageData: return AppInfo.isKlar ? false : true
case .studies: return AppInfo.isKlar ? false : true
case .enableDomainAutocomplete: return true
case .enableCustomDomainAutocomplete: return true
case .enableSearchSuggestions: return false
case .displaySecretMenu: return false
}
}
static func getToggle(_ toggle: SettingsToggle) -> Bool {
return prefs.object(forKey: toggle.rawValue) as? Bool ?? defaultForToggle(toggle)
}
static func getCustomDomainSetting() -> [String] {
return prefs.array(forKey: customDomainSettingKey) as? [String] ?? []
}
static func setCustomDomainSetting(domains: [String]) {
prefs.set(domains, forKey: customDomainSettingKey)
}
static func set(_ value: Bool, forToggle toggle: SettingsToggle) {
prefs.set(value, forKey: toggle.rawValue)
}
static func siriRequestsErase() -> Bool {
return prefs.bool(forKey: siriRequestsEraseKey)
}
static func setSiriRequestErase(to value: Bool) {
prefs.set(value, forKey: siriRequestsEraseKey)
}
}
| mpl-2.0 | 0c343fcff285a783447c2f7dbad4d38e | 33.655914 | 90 | 0.680112 | 4.664255 | false | false | false | false |
marcioarantes/EasyViewLayout | EasyViewLayout/EasyViewLayout.swift | 1 | 3781 | //
// EasyViewLayout.swift
// Yoke
//
// Created by Marcio R. Arantes on 2/23/15.
// Copyright (c) 2015 Creative Lenses. All rights reserved.
//
//Operators
/*
>= GreaterThanOrEqual relation
<= LessThanOrEqual relation
== Equal relation
= Used to set width or height
*/
import UIKit
infix operator + {}
infix operator |>=| {}
infix operator |<=| {}
infix operator |==| {}
infix operator |=| {}
func height (v: UIView) -> (UIView, NSLayoutAttribute) { return (v, .Height) }
func width (v: UIView) -> (UIView, NSLayoutAttribute) { return (v, .Width) }
func left (v: UIView) -> (UIView, NSLayoutAttribute) { return (v, .Left) }
func right (v: UIView) -> (UIView, NSLayoutAttribute) { return (v, .Right) }
func centerX (v:UIView) -> (UIView, NSLayoutAttribute) { return (v, .CenterX) }
func centerY (v:UIView) -> (UIView, NSLayoutAttribute) { return (v, .CenterY) }
func top (v:UIView) -> (UIView, NSLayoutAttribute) { return (v, .Top) }
func bottom (v:UIView) -> (UIView, NSLayoutAttribute) { return (v, .Bottom) }
func +(tuple:(UIView, NSLayoutAttribute), c:CGFloat) -> (UIView, NSLayoutAttribute, CGFloat) {
return (tuple.0, tuple.1, c)
}
func |==|(lhs:(UIView, NSLayoutAttribute), rhs:(UIView, NSLayoutAttribute, CGFloat)) {
if applyToSuperView(lhs.0, rhs.0){
if let superView = rhs.0.superview{
superView.addConstraint(NSLayoutConstraint(
item:lhs.0,
attribute:lhs.1,
relatedBy:.Equal,
toItem:rhs.0,
attribute:rhs.1,
multiplier:1,
constant:rhs.2 ))
}
}
else {
rhs.0.addConstraint(NSLayoutConstraint(
item:lhs.0,
attribute:lhs.1,
relatedBy:.Equal,
toItem:rhs.0,
attribute:rhs.1,
multiplier:1,
constant:rhs.2 ))
}
}
func |>=|(lhs:(UIView, NSLayoutAttribute), rhs:(UIView, NSLayoutAttribute, CGFloat)) {
if applyToSuperView(lhs.0, rhs.0){
if let superView = rhs.0.superview{
superView.addConstraint(NSLayoutConstraint(
item:lhs.0,
attribute:lhs.1,
relatedBy:.GreaterThanOrEqual,
toItem:rhs.0,
attribute:rhs.1,
multiplier:1,
constant:rhs.2 ))
}
}
else {
rhs.0.addConstraint(NSLayoutConstraint(
item:lhs.0,
attribute:lhs.1,
relatedBy:.GreaterThanOrEqual,
toItem:rhs.0,
attribute:rhs.1,
multiplier:1,
constant:rhs.2 ))
}
}
func |<=|(lhs:(UIView, NSLayoutAttribute), rhs:(UIView, NSLayoutAttribute, CGFloat)) {
if applyToSuperView(lhs.0, rhs.0){
if let superView = rhs.0.superview{
superView.addConstraint(NSLayoutConstraint(
item:lhs.0,
attribute:lhs.1,
relatedBy:.LessThanOrEqual,
toItem:rhs.0,
attribute:rhs.1,
multiplier:1,
constant:rhs.2 ))
}
}
else {
rhs.0.addConstraint(NSLayoutConstraint(
item:lhs.0,
attribute:lhs.1,
relatedBy:.LessThanOrEqual,
toItem:rhs.0,
attribute:rhs.1,
multiplier:1,
constant:rhs.2 ))
}
}
func |=|(lhs:(UIView, NSLayoutAttribute), rhs:(CGFloat)) {
lhs.0.addConstraint(NSLayoutConstraint(
item:lhs.0,
attribute:lhs.1,
relatedBy:.Equal,
toItem:nil,
attribute:lhs.1,
multiplier:1,
constant:rhs.0 ))
}
private func applyToSuperView(firstView: UIView, secondView: UIView) -> Bool{
return firstView.superview == secondView.superview
} | mit | b33d0fe20bab154196d14696ff7a6d9b | 28.779528 | 94 | 0.567839 | 4.074353 | false | false | false | false |
taka0125/TAKUUID | Examples/TAKUUIDSample/TAKViewController.swift | 1 | 1124 | //
// TAKViewController.swift
//
// Created by Takahiro Oishi
// Copyright (c) 2016年 Takahiro Ooishi. All rights reserved.
//
import UIKit
final class TAKViewController: UIViewController {
override func viewDidLoad() {
guard let accessGroup = Bundle.main.object(forInfoDictionaryKey: "KeychainAccessGroup") as? String else { return }
TAKUUIDStorage.sharedInstance().accessGroup = accessGroup
TAKUUIDStorage.sharedInstance().migrate()
}
@IBAction func remove() {
let result = TAKUUIDStorage.sharedInstance().remove()
print("remove = \(result)")
print("lastErrorStatus = \(TAKUUIDStorage.sharedInstance().lastErrorStatus)")
}
@IBAction func findOrCreate() {
guard let uuid = TAKUUIDStorage.sharedInstance().findOrCreate() else { return }
print("uuid = \(uuid)")
print("lastErrorStatus = \(TAKUUIDStorage.sharedInstance().lastErrorStatus)")
}
@IBAction func renew() {
guard let uuid = TAKUUIDStorage.sharedInstance().renew() else { return }
print("uuid = \(uuid)")
print("lastErrorStatus = \(TAKUUIDStorage.sharedInstance().lastErrorStatus)")
}
}
| mit | c80e693c70a55af0b502718e843f73ce | 32 | 118 | 0.708556 | 4.54251 | false | false | false | false |
moray95/MCChat | Pod/Classes/ChatViewController.swift | 1 | 18597 | //
// ViewController.swift
// BluetoothChat
//
// Created by Moray on 22/06/15.
// Copyright © 2015 Moray. All rights reserved.
//
import UIKit
import MultipeerConnectivity
import JSQMessagesViewController
import JSQSystemSoundPlayer
import CoreLocation
var serviceTypeSet = false
public var serviceType = ""
{
willSet
{
assert(!serviceTypeSet, "You shouldn't change serviceType once set. This might break MCChat's functionality.")
serviceTypeSet = true
}
}
let avatarDictionaryInfo = "AvatarDictionaryInfo"
var connectedUserInfo = [String : UserInfo]()
var locations = [String : CLLocation]()
public class MCChatLoader
{
public class func instantiateChatViewController() -> UIViewController
{
assert(serviceType.length > 0 && serviceType.length < 16,
"Your should set serviceType variable to a unique value for MCChat to work properly.")
let bundle = NSBundle(forClass: self)
let storyboard = UIStoryboard(name: "Main", bundle: bundle)
let viewController = storyboard.instantiateInitialViewController() as! UIViewController
return viewController
}
}
class ChatViewController: JSQMessagesViewController,
UINavigationControllerDelegate,
UIImagePickerControllerDelegate,
UIActionSheetDelegate,
MCSessionDelegate,
MCNearbyServiceBrowserDelegate,
MCNearbyServiceAdvertiserDelegate,
UITableViewDataSource,
CLLocationManagerDelegate
{
// MARK: Instance variables
var session : MCSession?
var messages = [Message]()
let timeout = 20.0
var browser : MCNearbyServiceBrowser?
var connectedUsers = [String]()
var shouldDisconnect = true
var imageMessage = true
var advertiser : MCNearbyServiceAdvertiser?
var locationManager = CLLocationManager()
// MARK: View load/unload
override func viewDidLoad()
{
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Settings", style: .Plain, target: self, action: "showSettings:")
collectionView!.delegate = self
NSUserDefaults.sessionDate = NSDate()
title = "Chat (0)"
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined
{
locationManager.requestWhenInUseAuthorization()
}
locationManager.delegate = self
locationManager.startUpdatingLocation()
}
override func viewWillAppear(animated: Bool)
{
shouldDisconnect = true
session = MCSession(peer: MCPeerID(displayName: NSUserDefaults.displayName))
session!.delegate = self
senderDisplayName = session!.myPeerID.displayName
senderId = session!.myPeerID.displayName
browser = MCNearbyServiceBrowser(peer: session!.myPeerID, serviceType: serviceType)
browser!.delegate = self
browser!.startBrowsingForPeers()
collectionView?.collectionViewLayout.springinessEnabled = true
advertiser = MCNearbyServiceAdvertiser(peer: session!.myPeerID, discoveryInfo: nil, serviceType: serviceType)
advertiser!.delegate = self
advertiser!.startAdvertisingPeer()
super.viewWillAppear(animated)
}
override func viewWillDisappear(animated : Bool)
{
super.viewWillDisappear(animated)
if shouldDisconnect
{
session!.disconnect()
browser?.stopBrowsingForPeers()
locationManager.stopUpdatingLocation()
}
}
// MARK: Actions
func showSettings(sender : AnyObject?)
{
let settings = storyboard!.instantiateViewControllerWithIdentifier("Settings") as! SettingsViewController
shouldDisconnect = false
settings.connectedPeers = session!.connectedPeers as! [MCPeerID]
navigationController?.pushViewController(settings, animated: true)
//presentViewController(settings, animated: true, completion: nil)
}
func simulateMessage(sender : AnyObject?)
{
let message = Message(sender: "Message Simulator", body: imageMessage ? "" : "Test message")
message.image = imageMessage ? UIImage(named: "test") : nil
imageMessage = !imageMessage
messages.append(message)
dispatch_async(dispatch_get_main_queue())
{
if NSUserDefaults.enableSounds
{
JSQSystemSoundPlayer.jsq_playMessageReceivedSound()
}
self.finishReceivingMessageAnimated(true)
}
}
override func didPressSendButton(button: UIButton!,
withMessageText text: String!,
senderId: String!,
senderDisplayName: String!,
date: NSDate!)
{
println("sending: \(text) to:")
for peer in session!.connectedPeers
{
println(peer.displayName)
}
let message = Message(sender: senderDisplayName, body: text)
var error : NSError? = nil
session!.sendData(NSData.dataForTextMessage(text),
toPeers: session!.connectedPeers as! [MCPeerID],
withMode: MCSessionSendDataMode.Reliable,
error: &error)
if session!.connectedPeers.count != 0 && error != nil
{
println("error sending message : \(error)")
}
messages.append(message)
if NSUserDefaults.enableSounds
{
JSQSystemSoundPlayer.jsq_playMessageSentSound()
}
dispatch_async(dispatch_get_main_queue())
{
self.finishSendingMessageAnimated(true)
}
}
override func didPressAccessoryButton(sender: UIButton!)
{
let alert = UIAlertController(title: "Send Photo",
message: "Where do you want to send your photo from?",
preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Photo Library", style: UIAlertActionStyle.Default, handler:
{
(alert) in
self.selectPhoto(.PhotoLibrary)
}))
alert.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default, handler:
{
(alert) in
self.selectPhoto(.Camera)
}))
shouldDisconnect = false
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler:nil))
presentViewController(alert, animated: true, completion: nil)
}
func selectPhoto(sourceType : UIImagePickerControllerSourceType)
{
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = false
imagePicker.sourceType = sourceType
self.navigationController?.presentViewController(imagePicker, animated: true, completion: nil)
}
// MARK: UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController,
didFinishPickingImage image: UIImage!, info: [NSObject : AnyObject]!)
{
picker.dismissViewControllerAnimated(true, completion: nil)
shouldDisconnect = true
dispatch_async(dispatch_get_global_queue(0, 0))
{
var error : NSError? = nil
self.session?.sendData(NSData.dataForImageMessage(image),
toPeers: self.session!.connectedPeers,
withMode: .Reliable,
error: &error)
if self.session!.connectedPeers.count != 0 && error != nil
{
println("Sending image failed with error: \(error)")
}
let message = Message(sender: self.senderDisplayName, body: "")
message.image = image
self.messages.append(message)
dispatch_async(dispatch_get_main_queue())
{
if NSUserDefaults.enableSounds
{
JSQSystemSoundPlayer.jsq_playMessageSentSound()
}
self.finishSendingMessage()
}
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController)
{
picker.dismissViewControllerAnimated(true, completion: nil)
shouldDisconnect = true
}
// MARK: JSQMessagesCollectionViewDataSource
override func collectionView(collectionView: JSQMessagesCollectionView!,
messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData!
{
return messages[indexPath.row].jsqMessage
}
override func collectionView(collectionView: JSQMessagesCollectionView!,
messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource!
{
if messages[indexPath.item].isSystemMessage
{
return JSQMessagesBubbleImageFactory.systemMessageBubble
}
if messages[indexPath.item].senderDisplayName() != session!.myPeerID.displayName
{
return JSQMessagesBubbleImageFactory.incomingMessageBubble
}
return JSQMessagesBubbleImageFactory.outgoingMessageBubble
}
override func collectionView(collectionView: JSQMessagesCollectionView!,
avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!)
-> JSQMessageAvatarImageDataSource!
{
let avatar : JSQMessageAvatarImageDataSource
if session!.myPeerID.displayName == messages[indexPath.row].senderId()
{
if NSUserDefaults.avatar == nil
{
// Initials
avatar = JSQMessagesAvatarImageFactory.avatarImageWithUserInitials(
messages[indexPath.row].initials,
backgroundColor: UIColor.grayColor(),
textColor: UIColor.whiteColor(),
font: UIFont.systemFontOfSize(14),
diameter: 34)
}
else
{
// Avatar
avatar = JSQMessagesAvatarImageFactory.avatarImageWithImage(NSUserDefaults.avatar, diameter: 34)
}
}
else
{
if connectedUserInfo[messages[indexPath.row].senderId()]?.avatar == nil
{
// Initials
avatar = JSQMessagesAvatarImageFactory.avatarImageWithUserInitials(
messages[indexPath.row].initials,
backgroundColor: UIColor.grayColor(),
textColor: UIColor.whiteColor(),
font: UIFont.systemFontOfSize(14),
diameter: 34)
}
else
{
// Avatar
avatar = JSQMessagesAvatarImageFactory.avatarImageWithImage(connectedUserInfo[messages[indexPath.row].sender]?.avatar, diameter: 34)
}
}
return avatar
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return messages.count
}
override func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
var cell = super.collectionView(collectionView, cellForItemAtIndexPath:indexPath) as? JSQMessagesCollectionViewCell
if cell == nil
{
cell = JSQMessagesCollectionViewCell()
}
if messages[indexPath.item].senderId() != senderId
{
cell!.textView?.textColor = UIColor.blackColor()
}
return cell!
}
// MARK: MCBrowserViewControllerDelegate
func browserViewControllerDidFinish(browserViewController: MCBrowserViewController)
{
browserViewController.dismissViewControllerAnimated(true, completion: nil)
}
func browserViewControllerWasCancelled(browserViewController: MCBrowserViewController)
{
browserViewController.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: MCSessionDelegate
func session(session: MCSession,
didReceiveData data: NSData,
fromPeer peerID: MCPeerID)
{
let (type, messageObject : AnyObject?) = NSData.messageData(data)
if type == .UserInfo
{
// Got UserInfo
let userInfo = messageObject as! UserInfo
connectedUserInfo[peerID.displayName] = userInfo
collectionView?.reloadData()
return
}
if type == .Location
{
// Got location
let location = messageObject as! CLLocation
println("Received location from \(peerID.displayName)")
locations[peerID.displayName] = location
return
}
var message : Message
if type == .TextMessage
{
// Got text message
message = Message(sender: peerID.displayName, body: messageObject as! NSString as String)
println("Received message: \(message.body)")
messages.append(message)
}
if type == .ImageMessage
{
// Got image message
println("received image from \(peerID.displayName)")
message = Message(sender: peerID.displayName, body: "")
message.image = messageObject as? UIImage
messages.append(message)
}
if NSUserDefaults.enableSounds
{
JSQSystemSoundPlayer.jsq_playMessageReceivedSound()
}
dispatch_async(dispatch_get_main_queue())
{
self.finishReceivingMessageAnimated(false)
}
}
func session(session: MCSession,
didStartReceivingResourceWithName resourceName: String,
fromPeer peerID: MCPeerID,
withProgress progress: NSProgress)
{
}
func session(session: MCSession,
didFinishReceivingResourceWithName resourceName: String,
fromPeer peerID: MCPeerID,
atURL localURL: NSURL,
withError error: NSError)
{
}
func session(session: MCSession,
didReceiveStream stream: NSInputStream,
withName streamName: String,
fromPeer peerID: MCPeerID)
{
}
func session(session: MCSession,
peer peerID: MCPeerID,
didChangeState state: MCSessionState)
{
switch state
{
case .Connected:
println("\(peerID.displayName) is now conected.")
if find(connectedUsers, peerID.displayName) == nil
{
connectedUsers.append(peerID.displayName)
}
let userInfo = NSUserDefaults.userInfo
var error : NSError? = nil
session.sendData(NSData.dataForUserInfo(userInfo),
toPeers: [peerID],
withMode: .Reliable,
error: &error)
if session.connectedPeers.count > 0
{
println("Error sending info to \(peerID.displayName): \(error)")
}
let message = Message(systemMessage: peerID.displayName, body: peerID.displayName + " has connected.")
messages.append(message)
dispatch_async(dispatch_get_main_queue())
{
self.finishReceivingMessageAnimated(true)
}
title = "Chat (\(session.connectedPeers.count))"
case .Connecting:
println("\(peerID.displayName) is now connecting.")
case .NotConnected:
println("\(peerID.displayName) has disconnected.")
if contains(connectedUsers, peerID.displayName) && !contains(session.connectedPeers as! [MCPeerID], peerID)
{
connectedUsers.removeAtIndex(find(connectedUsers, peerID.displayName)!)
let message = Message(systemMessage: peerID.displayName, body: peerID.displayName + " has disconnected.")
messages.append(message)
dispatch_async(dispatch_get_main_queue())
{
self.finishReceivingMessageAnimated(true)
}
title = "Chat (\(session.connectedPeers.count))"
}
locations[peerID.displayName] = nil
connectedUserInfo[peerID.displayName] = nil
}
}
// MARK: MCNearbyServiceAdvertiserDelegate
func advertiser(advertiser: MCNearbyServiceAdvertiser!, didReceiveInvitationFromPeer peerID: MCPeerID!, withContext context: NSData!, invitationHandler: ((Bool, MCSession!) -> Void)!)
{
let date = NSKeyedUnarchiver.unarchiveObjectWithData(context!) as! NSDate
if date.compare(NSUserDefaults.sessionDate) == .OrderedAscending
{
println("Joining older session")
invitationHandler(true, session!)
NSUserDefaults.sessionDate = date
for peer in session!.connectedPeers
{
browser?.invitePeer(peer as! MCPeerID, toSession: session!, withContext: NSKeyedArchiver.archivedDataWithRootObject(date), timeout: timeout)
}
}
}
// MARK: MCNearbyServiceBrowserDelegate
func browser(browser: MCNearbyServiceBrowser!, foundPeer peerID: MCPeerID!, withDiscoveryInfo info: [NSObject : AnyObject]!)
{
println("Inviting \(peerID.displayName)")
browser.invitePeer(peerID, toSession: session!,
withContext: NSKeyedArchiver.archivedDataWithRootObject(NSUserDefaults.sessionDate),
timeout: timeout)
}
func browser(browser: MCNearbyServiceBrowser!, lostPeer peerID: MCPeerID!)
{
println("Lost peer: \(peerID.displayName)")
}
// MARK: UITableViewDataSource (DetailsViewController)
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("detailCell") as? UITableViewCell ?? UITableViewCell()
cell.textLabel!.text = connectedUsers[indexPath.row]
return cell
}
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int
{
return connectedUsers.count
}
// Mark: CLLocationManagerDelegate
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
MCChat.locations[NSUserDefaults.displayName] = locations.last! as? CLLocation
println("Location updated")
var error : NSError? = nil
session?.sendData(NSData.dataForLocation(locations.last! as! CLLocation),
toPeers: session!.connectedPeers,
withMode: MCSessionSendDataMode.Reliable,
error: &error)
if session?.connectedPeers.count > 0
{
println("Error sending location data: \(error)")
}
}
}
| mit | 7da1085ad4e372d299a475f8ca222583 | 32.088968 | 184 | 0.63519 | 5.68859 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/EditAvatarVC.swift | 1 | 6324 | //
// EditAvatarVC.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 30.3.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import UIKit
// This view controller is used for editing and creation of new project avatars
class EditAvatarVC: UIViewController
{
// OUTLETS ------------------
@IBOutlet weak var createAvatarView: CreateAvatarView!
@IBOutlet weak var errorLabel: UILabel!
@IBOutlet weak var saveButton: BasicButton!
@IBOutlet weak var contentView: KeyboardReactiveView!
@IBOutlet weak var contentTopConstraint: NSLayoutConstraint!
@IBOutlet weak var contentBottomConstraint: NSLayoutConstraint!
// ATTRIBUTES --------------
static let identifier = "EditAvatar"
private var editedInfo: (Avatar, AvatarInfo)?
private var completionHandler: ((Avatar, AvatarInfo) -> ())?
private var presetName: String?
// LOAD ----------------------
override func viewDidLoad()
{
super.viewDidLoad()
errorLabel.text = nil
// If in editing mode, some fields cannot be edited
if let (avatar, info) = editedInfo
{
createAvatarView.avatarImage = info.image
createAvatarView.avatarName = avatar.name
createAvatarView.isShared = info.isShared
// Sharing can be enabled / disabled for non-shared accounts only
// (Shared account avatars have always sharing enabled)
do
{
if let account = try AgricolaAccount.get(avatar.accountId)
{
createAvatarView.mustBeShared = account.isShared
}
}
catch
{
print("ERROR: Failed to read account data. \(error)")
}
}
// If creating a new avatar, those created for shared accounts must be shared
else
{
if let presetName = presetName
{
createAvatarView.avatarName = presetName
}
do
{
guard let accountId = Session.instance.accountId, let account = try AgricolaAccount.get(accountId) else
{
print("ERROR: No account selected")
return
}
createAvatarView.mustBeShared = account.isShared
}
catch
{
print("ERROR: Failed to check whether account is shared. \(error)")
}
}
createAvatarView.viewController = self
contentView.configure(mainView: view, elements: [createAvatarView, errorLabel, saveButton], topConstraint: contentTopConstraint, bottomConstraint: contentBottomConstraint, style: .squish)
}
override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
contentView.startKeyboardListening()
}
override func viewDidDisappear(_ animated: Bool)
{
super.viewDidDisappear(animated)
contentView.endKeyboardListening()
}
// ACTIONS ------------------
@IBAction func cancelButtonPressed(_ sender: Any)
{
dismiss(animated: true)
}
@IBAction func backgroundTapped(_ sender: Any)
{
dismiss(animated: true)
}
@IBAction func saveButtonPressed(_ sender: Any)
{
// Checks that all necessary fields are filled
guard createAvatarView.allFieldsFilled else
{
errorLabel.text = NSLocalizedString("Please fill in the required fields", comment: "An error message displayed when trying to create new avatar without first filling all required fields")
return
}
// Makes sure the passwords match
guard createAvatarView.passwordsMatch else
{
errorLabel.text = NSLocalizedString("The passwords don't match!", comment: "An error message displayed when new avatar password is not repeated correctly")
return
}
do
{
// Makes the necessary modifications to the avatar
if let (avatar, info) = editedInfo
{
if let newImage = createAvatarView.avatarImage?.scaledToFit(CGSize(width: 320, height: 320)), info.image != newImage
{
try info.setImage(newImage)
}
if let newPassword = createAvatarView.offlinePassword
{
info.setPassword(newPassword)
}
avatar.name = createAvatarView.avatarName
try DATABASE.tryTransaction
{
try avatar.push()
try info.push()
}
dismiss(animated: true, completion: { self.completionHandler?(avatar, info) })
}
// Or creates a new avatar entirely
else
{
guard let accountId = Session.instance.accountId else
{
print("ERROR: No account selected")
return
}
guard let projectId = Session.instance.projectId, let project = try Project.get(projectId) else
{
print("ERROR: No project selected")
return
}
let avatarName = createAvatarView.avatarName
// Makes sure there is no avatar with the same name yet
/*
guard try Avatar.get(projectId: projectId, avatarName: avatarName) == nil else
{
errorLabel.text = "Avatar with the provided name already exists!"
return
}*/
// Checks whether admin rights should be given to the new avatar
// (must be the owner of the project, and the first avatar if account is shared)
var makeAdmin = false
if project.ownerId == accountId, let account = try AgricolaAccount.get(accountId)
{
if try (!account.isShared || AvatarView.instance.avatarQuery(projectId: projectId, accountId: accountId).firstResultRow() == nil)
{
makeAdmin = true
}
}
// Creates the new information
let avatar = Avatar(name: avatarName, projectId: projectId, accountId: accountId, isAdmin: makeAdmin)
let info = AvatarInfo(avatarId: avatar.idString, password: createAvatarView.offlinePassword, isShared: createAvatarView.isShared)
// Saves the changes to the database (inlcuding image attachment)
try DATABASE.tryTransaction
{
try avatar.push()
try info.push()
if let image = self.createAvatarView.avatarImage
{
try info.setImage(image)
}
}
dismiss(animated: true, completion: { self.completionHandler?(avatar, info) })
}
}
catch
{
print("ERROR: Failed to perform the required database operations. \(error)")
}
}
// OTHER METHODS --------------
func configureForEdit(avatar: Avatar, avatarInfo: AvatarInfo, successHandler: ((Avatar, AvatarInfo) -> ())? = nil)
{
self.editedInfo = (avatar, avatarInfo)
self.completionHandler = successHandler
}
func configureForCreate(avatarName: String? = nil, successHandler: ((Avatar, AvatarInfo) -> ())? = nil)
{
self.presetName = avatarName
self.completionHandler = successHandler
}
}
| mit | e4f5d8cefd90e381a20b161fe8794799 | 26.137339 | 190 | 0.686225 | 4.045425 | false | false | false | false |
niunaruto/DeDaoAppSwift | DeDaoSwift/Pods/ReactiveSwift/Sources/Atomic.swift | 1 | 7779 | //
// Atomic.swift
// ReactiveSwift
//
// Created by Justin Spahr-Summers on 2014-06-10.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Foundation
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import MachO
#endif
/// Represents a finite state machine that can transit from one state to
/// another.
internal protocol AtomicStateProtocol {
associatedtype State: RawRepresentable
/// Try to transit from the expected current state to the specified next
/// state.
///
/// - parameters:
/// - expected: The expected state.
///
/// - returns:
/// `true` if the transition succeeds. `false` otherwise.
func tryTransiting(from expected: State, to next: State) -> Bool
}
/// A simple, generic lock-free finite state machine.
///
/// - warning: `deinitialize` must be called to dispose of the consumed memory.
internal struct UnsafeAtomicState<State: RawRepresentable>: AtomicStateProtocol where State.RawValue == Int32 {
internal typealias Transition = (expected: State, next: State)
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
private let value: UnsafeMutablePointer<Int32>
/// Create a finite state machine with the specified initial state.
///
/// - parameters:
/// - initial: The desired initial state.
internal init(_ initial: State) {
value = UnsafeMutablePointer<Int32>.allocate(capacity: 1)
value.initialize(to: initial.rawValue)
}
/// Deinitialize the finite state machine.
internal func deinitialize() {
value.deinitialize()
value.deallocate(capacity: 1)
}
/// Compare the current state with the specified state.
///
/// - parameters:
/// - expected: The expected state.
///
/// - returns:
/// `true` if the current state matches the expected state. `false`
/// otherwise.
@inline(__always)
internal func `is`(_ expected: State) -> Bool {
return OSAtomicCompareAndSwap32Barrier(expected.rawValue,
expected.rawValue,
value)
}
/// Try to transit from the expected current state to the specified next
/// state.
///
/// - parameters:
/// - expected: The expected state.
///
/// - returns:
/// `true` if the transition succeeds. `false` otherwise.
@inline(__always)
internal func tryTransiting(from expected: State, to next: State) -> Bool {
return OSAtomicCompareAndSwap32Barrier(expected.rawValue,
next.rawValue,
value)
}
#else
private let value: Atomic<Int32>
/// Create a finite state machine with the specified initial state.
///
/// - parameters:
/// - initial: The desired initial state.
internal init(_ initial: State) {
value = Atomic(initial.rawValue)
}
/// Deinitialize the finite state machine.
internal func deinitialize() {}
/// Compare the current state with the specified state.
///
/// - parameters:
/// - expected: The expected state.
///
/// - returns:
/// `true` if the current state matches the expected state. `false`
/// otherwise.
internal func `is`(_ expected: State) -> Bool {
return value.modify { $0 == expected.rawValue }
}
/// Try to transit from the expected current state to the specified next
/// state.
///
/// - parameters:
/// - expected: The expected state.
///
/// - returns:
/// `true` if the transition succeeds. `false` otherwise.
internal func tryTransiting(from expected: State, to next: State) -> Bool {
return value.modify { value in
if value == expected.rawValue {
value = next.rawValue
return true
}
return false
}
}
#endif
}
final class PosixThreadMutex: NSLocking {
private var mutex = pthread_mutex_t()
init() {
let result = pthread_mutex_init(&mutex, nil)
precondition(result == 0, "Failed to initialize mutex with error \(result).")
}
deinit {
let result = pthread_mutex_destroy(&mutex)
precondition(result == 0, "Failed to destroy mutex with error \(result).")
}
func lock() {
let result = pthread_mutex_lock(&mutex)
precondition(result == 0, "Failed to lock \(self) with error \(result).")
}
func unlock() {
let result = pthread_mutex_unlock(&mutex)
precondition(result == 0, "Failed to unlock \(self) with error \(result).")
}
}
/// An atomic variable.
public final class Atomic<Value>: AtomicProtocol {
private let lock: PosixThreadMutex
private var _value: Value
/// Initialize the variable with the given initial value.
///
/// - parameters:
/// - value: Initial value for `self`.
public init(_ value: Value) {
_value = value
lock = PosixThreadMutex()
}
/// Atomically modifies the variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
public func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result {
lock.lock()
defer { lock.unlock() }
return try action(&_value)
}
/// Atomically perform an arbitrary action using the current value of the
/// variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
public func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result {
lock.lock()
defer { lock.unlock() }
return try action(_value)
}
}
/// An atomic variable which uses a recursive lock.
internal final class RecursiveAtomic<Value>: AtomicProtocol {
private let lock: NSRecursiveLock
private var _value: Value
private let didSetObserver: ((Value) -> Void)?
/// Initialize the variable with the given initial value.
///
/// - parameters:
/// - value: Initial value for `self`.
/// - name: An optional name used to create the recursive lock.
/// - action: An optional closure which would be invoked every time the
/// value of `self` is mutated.
internal init(_ value: Value, name: StaticString? = nil, didSet action: ((Value) -> Void)? = nil) {
_value = value
lock = NSRecursiveLock()
lock.name = name.map(String.init(describing:))
didSetObserver = action
}
/// Atomically modifies the variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result {
lock.lock()
defer {
didSetObserver?(_value)
lock.unlock()
}
return try action(&_value)
}
/// Atomically perform an arbitrary action using the current value of the
/// variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result {
lock.lock()
defer { lock.unlock() }
return try action(_value)
}
}
/// A protocol used to constraint convenience `Atomic` methods and properties.
public protocol AtomicProtocol: class {
associatedtype Value
@discardableResult
func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result
@discardableResult
func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result
}
extension AtomicProtocol {
/// Atomically get or set the value of the variable.
public var value: Value {
get {
return withValue { $0 }
}
set(newValue) {
swap(newValue)
}
}
/// Atomically replace the contents of the variable.
///
/// - parameters:
/// - newValue: A new value for the variable.
///
/// - returns: The old value.
@discardableResult
public func swap(_ newValue: Value) -> Value {
return modify { (value: inout Value) in
let oldValue = value
value = newValue
return oldValue
}
}
}
| mit | d4ba8fecaad7bc5298d2698a31493384 | 26.10453 | 111 | 0.661396 | 3.690228 | false | false | false | false |
PurpleSweetPotatoes/SwiftKit | SwiftKit/control/BQRefresh/BQRefreshView.swift | 1 | 3308 | //
// BQRefreshView.swift
// BQRefresh
//
// Created by baiqiang on 2017/7/5.
// Copyright © 2017年 baiqiang. All rights reserved.
//
import UIKit
enum RefreshStatus: Int {
case idle //闲置
case pull //拖拽
case refreshing //刷新
case willRefresh //即将刷新
case noMoreData //无更多数据
}
enum ObserverName: String {
case scrollerOffset = "contentOffset"
case scrollerSize = "contentSize"
}
typealias CallBlock = ()->()
class BQRefreshView: UIView {
//MARK: - ***** Ivars *****
var origiOffsetY: CGFloat = 0
public var scrollViewOriginalInset: UIEdgeInsets = .zero
public var status: RefreshStatus = .idle
public weak var scrollView: UIScrollView!
public var refreshBlock: CallBlock!
//MARK: - ***** public Method *****
public class func refreshLab() -> UILabel {
let lab = UILabel()
lab.font = UIFont.systemFont(ofSize: 14)
lab.textAlignment = .center
return lab
}
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
if !(newSuperview is UIScrollView) {
return
}
self.removeObservers()
self.sizeW = newSuperview?.sizeW ?? 0
self.left = 0
self.scrollView = newSuperview as! UIScrollView
self.scrollViewOriginalInset = self.scrollView.contentInset
self.addObservers()
//初始化状态(防止第一次无数据tableView下拉时出现异常)
self.scrollView.contentOffset = CGPoint.zero
}
override func removeFromSuperview() {
self.removeObservers()
super.removeFromSuperview()
}
//MARK: - ***** private Method *****
private func addObservers() {
let options: NSKeyValueObservingOptions = [.new, .old]
self.scrollView.addObserver(self, forKeyPath: ObserverName.scrollerOffset.rawValue, options: options, context: nil)
self.scrollView.addObserver(self, forKeyPath: ObserverName.scrollerSize.rawValue, options: options, context: nil)
}
private func removeObservers() {
self.superview?.removeObserver(self, forKeyPath: ObserverName.scrollerOffset.rawValue)
self.superview?.removeObserver(self, forKeyPath: ObserverName.scrollerSize.rawValue)
}
//MARK: - ***** respond event Method *****
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if !self.isUserInteractionEnabled {
return
}
if self.isHidden {
return
}
if let key = keyPath {
let value = ObserverName(rawValue: key)!
switch value {
case .scrollerOffset:
self.contentOffsetDidChange(change: change)
case .scrollerSize:
self.contentSizeDidChange(change: change)
}
}
}
func contentOffsetDidChange(change: [NSKeyValueChangeKey : Any]?) {
if self.status == .idle && !self.scrollView.isDragging {
origiOffsetY = self.scrollView.contentOffset.y
self.status = .pull
}
}
func contentSizeDidChange(change: [NSKeyValueChangeKey : Any]?) {
}
}
| apache-2.0 | 0599c50cc84581972244e04d6fae2a46 | 30.407767 | 151 | 0.633385 | 4.792593 | false | false | false | false |
mentalfaculty/impeller | Sources/MonolithicRepository.swift | 1 | 4739 | //
// MonolithicRepository
// Impeller
//
// Created by Drew McCormack on 08/12/2016.
// Copyright © 2016 Drew McCormack. All rights reserved.
//
import Foundation
/// All data is in memory. This class does not persist data to disk,
/// but other classes can be used to do that.
public class MonolithicRepository: LocalRepository, Exchangable {
public var uniqueIdentifier: UniqueIdentifier = uuid()
private let queue = DispatchQueue(label: "impeller.monolithicRepository")
private var forest = Forest()
private var commitTimestamp = Date.distantPast.timeIntervalSinceReferenceDate
public init() {}
public func load(from url:URL, with serializer: ForestSerializer) throws {
try queue.sync {
try forest = serializer.load(from:url)
}
}
public func save(to url:URL, with serializer: ForestSerializer) throws {
try queue.sync {
try serializer.save(forest, to:url)
}
}
/// Resolves conflicts and commits, and sets the value on out to resolved value.
public func commit<T:Repositable>(_ value: inout T, resolvingConflictsWith conflictResolver: ConflictResolver = ConflictResolver()) {
queue.sync {
performCommit(&value, resolvingConflictsWith: conflictResolver)
}
}
private func performCommit<T:Repositable>(_ value: inout T, resolvingConflictsWith conflictResolver: ConflictResolver) {
// Plant
let planter = ForestPlanter(withRoot: value)
let commitForest = planter.forest
let rootRef = ValueTreePlanter(repositable: value).valueTree.valueTreeReference
let plantedTree = PlantedValueTree(forest: commitForest, root: rootRef)
// Merge into forest
forest.merge(plantedTree, resolvingConflictsWith: conflictResolver)
// Harvest
let newValueTree = forest.valueTree(at: rootRef)!
let harvester = ForestHarvester(forest: forest)
value = harvester.harvest(newValueTree)
}
public func delete<T:Repositable>(_ root: inout T, resolvingConflictsWith conflictResolver: ConflictResolver = ConflictResolver()) {
queue.sync {
// First merge in-memory and repo values, then delete
self.performCommit(&root, resolvingConflictsWith: conflictResolver)
self.performDelete(&root)
}
}
private func performDelete<T:Repositable>(_ root: inout T) {
let rootTree = ValueTreePlanter(repositable: root).valueTree
forest.deleteValueTrees(descendentFrom: rootTree.valueTreeReference)
}
public func fetchValue<T:Repositable>(identifiedBy uniqueIdentifier:UniqueIdentifier) -> T? {
var result: T?
queue.sync {
let ref = ValueTreeReference(uniqueIdentifier: uniqueIdentifier, repositedType: T.repositedType)
if let valueTree = forest.valueTree(at: ref), !valueTree.metadata.isDeleted {
let harvester = ForestHarvester(forest: forest)
let repositable:T = harvester.harvest(valueTree)
result = repositable
}
}
return result
}
public func push(changesSince cursor: Cursor?, completionHandler completion: @escaping (Error?, [ValueTree], Cursor?)->Void) {
queue.async {
let timestampCursor = cursor as? TimestampCursor
var maximumTimestamp = timestampCursor?.timestamp ?? Date.distantPast.timeIntervalSinceReferenceDate
var valueTrees = [ValueTree]()
for valueTree in self.forest {
let time = valueTree.metadata.timestamp
if timestampCursor == nil || timestampCursor!.timestamp <= time {
valueTrees.append(valueTree)
maximumTimestamp = max(maximumTimestamp, time)
}
}
DispatchQueue.main.async {
completion(nil, valueTrees, TimestampCursor(timestamp: maximumTimestamp))
}
}
}
public func pull(_ valueTrees: [ValueTree], completionHandler completion: @escaping CompletionHandler) {
queue.async {
for newTree in valueTrees {
let reference = ValueTreeReference(uniqueIdentifier: newTree.metadata.uniqueIdentifier, repositedType: newTree.repositedType)
let mergedTree = newTree.merged(with: self.forest.valueTree(at: reference))
self.forest.update(mergedTree)
}
DispatchQueue.main.async {
completion(nil)
}
}
}
public func makeCursor(fromData data: Data) -> Cursor? {
return TimestampCursor(data: data)
}
}
| mit | a061c697880ca2f71b16e3e973e65445 | 38.815126 | 141 | 0.647531 | 4.6588 | false | false | false | false |
wallflyrepo/Ject | Example/Sources/LogManager.swift | 1 | 1832 | //
// LogManager.swift
// Pods
//
// Created by Williams, Joshua on 9/25/17.
//
//
import Foundation
/**
* Allows for a `String` to be logged using NSLog in debug mode only.
**/
internal class LogManager {
/**
* Typically the class that instantiated this LogManager instance.
**/
private let parentClass: AnyObject
/**
* Ideally, passing the parent class object allows for us to easily trace where each statement comes from.
**/
init(_ parentClass: AnyObject) {
self.parentClass = parentClass
}
/**
* Allows to print numbers using the same print() function for a `String`. Also logs the function name for tracing.
**/
func print(_ log: Int, functionName: String = #function) {
self.printLog(log: String(log), functionName: functionName)
}
/**
* Allows to print a `String`. Also logs the function name for tracing.
**/
func print(_ log:String, functionName: String = #function) {
self.printLog(log: log, functionName: functionName)
}
/**
* Prints the log statement with the function that it was called in if the build is a Debug build. If not,
* it prints a log stating that something was logged.
**/
fileprivate func printLog(log : String, functionName: String = #function) {
#if DEBUG
let className = String(describing: type(of: parentClass)).components(separatedBy: ".").last!
printLogToSystem("[\(className).\(functionName)] - \(log) \n")
#else
printLogToSystem("Statement logged. App is in production. Use Debug build to see log statements")
#endif
}
/**
* Uses NSLog to print a statement.
**/
fileprivate func printLogToSystem(_ log: String) {
NSLog(log)
}
}
| apache-2.0 | 599e14c521ba9fac82a5d11ee551d557 | 28.079365 | 119 | 0.619541 | 4.512315 | false | false | false | false |
gregomni/swift | test/Distributed/distributed_actor_accessor_section_elf.swift | 9 | 6678 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift
// RUN: %target-swift-frontend -emit-irgen -module-name distributed_actor_accessors -disable-availability-checking -I %t 2>&1 %s | %IRGenFileCheck %s --dump-input=always
// UNSUPPORTED: back_deploy_concurrency
// REQUIRES: concurrency
// REQUIRES: distributed
// REQUIRES: OS=linux-gnu
import Distributed
import FakeDistributedActorSystems
@available(SwiftStdlib 5.5, *)
typealias DefaultDistributedActorSystem = FakeActorSystem
enum SimpleE : Codable {
case a
}
enum E : Codable {
case a, b, c
}
enum IndirectE : Codable {
case empty
indirect case test(_: Int)
}
final class Obj : Codable, Sendable {
let x: Int
init(x: Int) {
self.x = x
}
}
struct LargeStruct : Codable {
var a: Int
var b: Int
var c: String
var d: Double
}
@available(SwiftStdlib 5.7, *)
public distributed actor MyActor {
distributed func simple1(_: Int) {
}
// `String` would be a direct result as a struct type
distributed func simple2(_: Int) -> String {
return ""
}
// `String` is an object that gets exploded into two parameters
distributed func simple3(_: String) -> Int {
return 42
}
// Enum with a single case are special because they have an empty
// native schema so they are dropped from parameters/result.
distributed func single_case_enum(_ e: SimpleE) -> SimpleE {
return e
}
distributed func with_indirect_enums(_: IndirectE, _: Int) -> IndirectE {
return .empty
}
// Combination of multiple arguments, reference type and indirect result
//
// Note: Tuple types cannot be used here is either position because they
// cannot conform to protocols.
distributed func complex(_: [Int], _: Obj, _: String?, _: LargeStruct) -> LargeStruct {
fatalError()
}
// Make sure that Sendable doesn't show up in the mangled name
distributed func generic<T: Codable & Sendable>(_: T) {
}
}
@available(SwiftStdlib 5.7, *)
public distributed actor MyOtherActor {
distributed func empty() {
}
}
/// ---> Let's check that distributed accessors and thunks are emitted as accessible functions
/// -> `MyActor.simple1`
// CHECK: @"$s27distributed_actor_accessors7MyActorC7simple1yySiYaKFTEHF" = private constant
// CHECK-SAME: @"symbolic Si___________pIetMHygzo_ 27distributed_actor_accessors7MyActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7simple1yySiYaKFTETFTu" to i{{32|64}})
// CHECK-SAME: , section "swift5_accessible_functions", {{.*}}
/// -> `MyActor.simple2`
// CHECK: @"$s27distributed_actor_accessors7MyActorC7simple2ySSSiYaKFTEHF" = private constant
// CHECK-SAME: @"symbolic Si_____SS______pIetMHygozo_ 27distributed_actor_accessors7MyActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7simple2ySSSiYaKFTETFTu" to i{{32|64}})
// CHECK-SAME: , section "swift5_accessible_functions", {{.*}}
/// -> `MyActor.simple3`
// CHECK: @"$s27distributed_actor_accessors7MyActorC7simple3ySiSSYaKFTEHF" = private constant
// CHECK-SAME: @"symbolic SS_____Si______pIetMHggdzo_ 27distributed_actor_accessors7MyActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7simple3ySiSSYaKFTETFTu" to i{{32|64}})
// CHECK-SAME: , section "swift5_accessible_functions", {{.*}}
/// -> `MyActor.single_case_enum`
// CHECK: @"$s27distributed_actor_accessors7MyActorC16single_case_enumyAA7SimpleEOAFYaKFTEHF" = private constant
// CHECK-SAME: @"symbolic __________AA______pIetMHygdzo_ 27distributed_actor_accessors7SimpleEO AA7MyActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC16single_case_enumyAA7SimpleEOAFYaKFTETFTu" to i{{32|64}})
// CHECK-SAME: , section "swift5_accessible_functions", {{.*}}
/// -> `MyActor.with_indirect_enums`
// CHECK: @"$s27distributed_actor_accessors7MyActorC19with_indirect_enumsyAA9IndirectEOAF_SitYaKFTEHF" = private constant
// CHECK-SAME: @"symbolic _____Si_____AA______pIetMHgygozo_ 27distributed_actor_accessors9IndirectEO AA7MyActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC19with_indirect_enumsyAA9IndirectEOAF_SitYaKFTETFTu" to i{{32|64}})
// CHECK-SAME: , section "swift5_accessible_functions", {{.*}}
/// -> `MyActor.complex`
// CHECK: @"$s27distributed_actor_accessors7MyActorC7complexyAA11LargeStructVSaySiG_AA3ObjCSSSgAFtYaKFTEHF" = private constant
// CHECK-SAME: @"symbolic SaySiG_____SSSg__________AD______pIetMHgggngrzo_ 27distributed_actor_accessors3ObjC AA11LargeStructV AA7MyActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7complexyAA11LargeStructVSaySiG_AA3ObjCSSSgAFtYaKFTETFTu" to i{{32|64}})
// CHECK-SAME: , section "swift5_accessible_functions", {{.*}}
/// -> `MyActor.generic`
// CHECK: @"$s27distributed_actor_accessors7MyActorC7genericyyxYaKSeRzSERzlFTEHF" = private constant
// CHECK-SAME: @"symbolic x___________pSeRzSERzlIetMHngzo_ 27distributed_actor_accessors7MyActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7genericyyxYaKSeRzSERzlFTETFTu" to i{{32|64}})
// CHECK-SAME: , section "swift5_accessible_functions", {{.*}}
/// -> `MyOtherActor.empty`
// CHECK: @"$s27distributed_actor_accessors12MyOtherActorC5emptyyyYaKFTEHF" = private constant
// CHECK-SAME: @"symbolic ___________pIetMHgzo_ 27distributed_actor_accessors12MyOtherActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors12MyOtherActorC5emptyyyYaKFTETFTu" to i{{32|64}})
// CHECK-SAME: , section "swift5_accessible_functions", {{.*}}
// CHECK: @llvm.compiler.used = appending global [{{.*}} x i8*] [
// CHECK-SAME: @"$s27distributed_actor_accessors7MyActorC7simple1yySiYaKFTEHF"
// CHECK-SAME: @"$s27distributed_actor_accessors7MyActorC7simple2ySSSiYaKFTEHF"
// CHECK-SAME: @"$s27distributed_actor_accessors7MyActorC7simple3ySiSSYaKFTEHF"
// CHECK-SAME: @"$s27distributed_actor_accessors7MyActorC16single_case_enumyAA7SimpleEOAFYaKFTEHF"
// CHECK-SAME: @"$s27distributed_actor_accessors7MyActorC19with_indirect_enumsyAA9IndirectEOAF_SitYaKFTEHF"
// CHECK-SAME: @"$s27distributed_actor_accessors7MyActorC7complexyAA11LargeStructVSaySiG_AA3ObjCSSSgAFtYaKFTEHF"
// CHECK-SAME: @"$s27distributed_actor_accessors12MyOtherActorC5emptyyyYaKFTEHF"
// CHECK-SAME: ], section "llvm.metadata"
| apache-2.0 | 7ffd7a5766184a0bf711aee5f0c0222b | 44.121622 | 219 | 0.739742 | 3.588393 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.