repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fengnanyue/ios | OC Share Sheet/Managers.swift | 8 | 1648 | //
// Managers.swift
// Owncloud iOs Client
//
// Created by Gonzalo Gonzalez on 10/3/15.
//
/*
Copyright (C) 2015, ownCloud, Inc.
This code is covered by the GNU Public License Version 3.
For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/
You should have received a copy of this license
along with this program. If not, see <http://www.gnu.org/licenses/gpl-3.0.en.html>.
*/
import UIKit
class Managers: NSObject {
//MARK: FMDataBase
class var sharedDatabase: FMDatabaseQueue {
struct Static {
static var sharedDatabase: FMDatabaseQueue?
static var tokenDatabase: dispatch_once_t = 0
}
dispatch_once(&Static.tokenDatabase) {
Static.sharedDatabase = FMDatabaseQueue()
let documentsDir = UtilsUrls.getOwnCloudFilePath()
let dbPath = documentsDir.stringByAppendingPathComponent("DB.sqlite")
Static.sharedDatabase = FMDatabaseQueue(path: dbPath, flags: SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE|SQLITE_OPEN_FILEPROTECTION_NONE)
}
return Static.sharedDatabase!
}
//MARK: OCCommunication
class var sharedOCCommunication: OCCommunication {
struct Static {
static var sharedOCCommunication: OCCommunication?
static var tokenCommunication: dispatch_once_t = 0
}
dispatch_once(&Static.tokenCommunication) {
Static.sharedOCCommunication = OCCommunication()
}
return Static.sharedOCCommunication!
}
}
| gpl-3.0 | 4071824f4b3918ab8fb5d26d56d9fef9 | 26.932203 | 146 | 0.650485 | 4.616246 | false | false | false | false |
elkanaoptimove/OptimoveSDK | OptimoveSDK/Tenant Config/Parameter.swift | 1 | 965 | //
// Parameter.swift
// WeAreOptimove
//
// Created by Elkana Orbach on 10/05/2018.
// Copyright © 2018 Optimove. All rights reserved.
//
import Foundation
struct Parameter:Decodable
{
let mandatory:Bool
let name: String
let id: Int
let type : String
let optiTrackDimensionId: Int
enum CodingKeys:String, CodingKey
{
case name
case id
case type
case optiTrackDimensionId
case optional
}
init(from decoder: Decoder) throws
{
let values = try decoder.container(keyedBy: CodingKeys.self)
let optional = try values.decode(Bool.self, forKey: .optional)
mandatory = !optional
name = try values.decode(String.self, forKey: .name)
id = try values.decode(Int.self, forKey: .id)
type = try values.decode(String.self, forKey: .type)
optiTrackDimensionId = try values.decode(Int.self, forKey: .optiTrackDimensionId)
}
}
| mit | b87e231ca776908df9c064c308e243ff | 25.054054 | 89 | 0.642116 | 3.918699 | false | false | false | false |
idomizrachi/Regen | regen/General Models/CommandLineParameter.swift | 1 | 1011 | //
// CommandLineParameter.swift
// regen
//
// Created by Ido Mizrachi on 17/07/2019.
// Copyright © 2019 Ido Mizrachi. All rights reserved.
//
import Foundation
enum CommandLineParameter: String {
case searchPath = "--search-path"
case template = "--template"
case outputFilename = "--output-filename"
case outputClassName = "--output-class-name"
case baseLanguageCode = "--base-language-code"
case whitelist = "--whitelist-filename"
case parameterStartRegex = "--parameter-start-regex"
case parameterEndRegex = "--parameter-end-regex"
case parameterStartOffset = "--parameter-start-offset"
case parameterEndOffset = "--parameter-end-offset"
case assetsFile = "--assets"
}
func tryParse<T: CanBeInitializedWithString>(_ parameter: CommandLineParameter, from arguments: [String]) -> T? {
if let index = arguments.firstIndex(of: parameter.rawValue), index+1 < arguments.count {
return T(arguments[index+1])
} else {
return nil
}
}
| mit | aab1e1284aff6e66b1179f56d3e5d469 | 31.580645 | 113 | 0.691089 | 4.089069 | false | false | false | false |
xnitech/nopeekgifts | NoPeekGifts/FriendsViewController.swift | 1 | 1382 | //
// SecondViewController.swift
// NoPeekGifts
//
// Created by Mark Gruetzner on 10/31/15.
// Copyright © 2015 XNI Technologies, LLC. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
class FriendsViewController: UIViewController, FBSDKLoginButtonDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if (FBSDKAccessToken.currentAccessToken() == nil)
{
print("Not logged in")
}
else {
print("Logged in")
}
let loginButton = FBSDKLoginButton()
loginButton.readPermissions = ["public_profile", "email", "user_friends"]
loginButton.center = self.view.center
loginButton.delegate = self
self.view.addSubview(loginButton)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
if (error == nil)
{
print("Login complete")
}
else {
print(error.localizedDescription)
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
print("User logged out")
}
}
| mit | f018f4bb8872ce0337a91c3567948586 | 23.660714 | 132 | 0.655322 | 4.949821 | false | false | false | false |
alexaubry/HTMLString | Sources/HTMLString/HTMLString.swift | 1 | 8224 | import Foundation
// MARK: Escaping
extension String {
///
/// Returns a copy of the current `String` where every character incompatible with HTML Unicode
/// encoding (UTF-16 or UTF-8) is replaced by a decimal HTML entity.
///
/// ### Examples
///
/// | String | Result | Format |
/// |--------|--------|--------|
/// | `&` | `&` | Decimal entity (part of the Unicode special characters) |
/// | `Σ` | `Σ` | Not escaped (Unicode compliant) |
/// | `🇺🇸` | `🇺🇸` | Not escaped (Unicode compliant) |
/// | `a` | `a` | Not escaped (alphanumerical) |
///
public var addingUnicodeEntities: String {
return self.addUnicodeEntities()
}
///
/// Replaces every character incompatible with HTML Unicode encoding (UTF-16 or UTF-8) by a decimal HTML entity.
///
/// ### Examples
///
/// | String | Result | Format |
/// |--------|--------|--------|
/// | `&` | `&` | Decimal entity (part of the Unicode special characters) |
/// | `Σ` | `Σ` | Not escaped (Unicode compliant) |
/// | `🇺🇸` | `🇺🇸` | Not escaped (Unicode compliant) |
/// | `a` | `a` | Not escaped (alphanumerical) |
///
public func addUnicodeEntities() -> String {
let requiredEscapes: Set<Character> = ["!", "\"", "$", "%", "&", "'", "+", ",", "<", "=", ">", "@", "[", "]", "`", "{", "}"]
var result = ""
for character in self {
if requiredEscapes.contains(character) {
// One of the required escapes for security reasons
result.append(contentsOf: "&#\(character.asciiValue!);")
} else {
// Not a required escape, no need to replace the character
result.append(character)
}
}
return result
}
///
/// Returns a copy of the current `String` where every character incompatible with HTML ASCII
/// encoding is replaced by a decimal HTML entity.
///
/// ### Examples
///
/// | String | Result | Format |
/// |--------|--------|--------|
/// | `&` | `&` | Decimal entity |
/// | `Σ` | `Σ` | Decimal entity |
/// | `🇺🇸` | `🇺🇸` | Combined decimal entities (extented grapheme cluster) |
/// | `a` | `a` | Not escaped (alphanumerical) |
///
/// ### Performance
///
/// If your webpage is unicode encoded (UTF-16 or UTF-8) use `addingUnicodeEntities` instead,
/// as it is faster and produces a less bloated and more readable HTML.
///
public var addingASCIIEntities: String {
return self.addASCIIEntities()
}
///
/// Replaces every character incompatible with HTML Unicode (UTF-16 or UTF-8) with a decimal HTML entity.
///
/// ### Examples
///
/// | String | Result | Format |
/// |--------|--------|--------|
/// | `&` | `&` | Decimal entity (part of the Unicode special characters) |
/// | `Σ` | `Σ` | Not escaped (Unicode compliant) |
/// | `🇺🇸` | `🇺🇸` | Not escaped (Unicode compliant) |
/// | `a` | `a` | Not escaped (alphanumerical) |
///
public func addASCIIEntities() -> String {
let requiredEscapes: Set<Character> = ["!", "\"", "$", "%", "&", "'", "+", ",", "<", "=", ">", "@", "[", "]", "`", "{", "}"]
var result = ""
for character in self {
if let asciiiValue = character.asciiValue {
if requiredEscapes.contains(character) {
// One of the required escapes for security reasons
result.append(contentsOf: "&#\(asciiiValue);")
} else {
// Not a required escape, no need to replace the character
result.append(character)
}
} else {
// Not an ASCII Character, we need to escape.
let escape = character.unicodeScalars.reduce(into: "") { $0 += "&#\($1.value);" }
result.append(contentsOf: escape)
}
}
return result
}
}
// MARK: - Unescaping
extension String {
///
/// Replaces every HTML entity in the receiver with the matching Unicode character.
///
/// ### Examples
///
/// | String | Result | Format |
/// |--------|--------|--------|
/// | `&` | `&` | Keyword entity |
/// | `Σ` | `Σ` | Decimal entity |
/// | `č` | `č` | Hexadecimal entity |
/// | `🇺🇸` | `🇺🇸` | Combined decimal entities (extented grapheme cluster) |
/// | `a` | `a` | Not an entity |
/// | `&` | `&` | Not an entity |
///
public func removeHTMLEntities() -> String {
var result = ""
var currentIndex = startIndex
while let delimiterIndex = self[currentIndex...].firstIndex(of: "&") {
// Avoid unnecessary operations
var semicolonIndex = self.index(after: delimiterIndex)
// Parse the last sequence (ex: Fish & chips & sauce -> "&" instead of "& chips &")
var lastDelimiterIndex = delimiterIndex
while semicolonIndex != endIndex, self[semicolonIndex] != ";" {
if self[semicolonIndex] == "&" {
lastDelimiterIndex = semicolonIndex
}
semicolonIndex = self.index(after: semicolonIndex)
}
// Fast path if semicolon doesn't exists in current range
if semicolonIndex == endIndex {
result.append(contentsOf: self[currentIndex..<semicolonIndex])
return result
}
let escapableRange = index(after: lastDelimiterIndex) ..< semicolonIndex
let escapableContent = self[escapableRange]
result.append(contentsOf: self[currentIndex..<lastDelimiterIndex])
let cursorPosition: Index
if let unescapedNumber = escapableContent.unescapeAsNumber() {
result.append(contentsOf: unescapedNumber)
cursorPosition = self.index(semicolonIndex, offsetBy: 1)
} else if let unescapedCharacter = HTMLStringMappings.shared.unescapingTable[String(escapableContent)] {
result.append(contentsOf: unescapedCharacter)
cursorPosition = self.index(semicolonIndex, offsetBy: 1)
} else {
result.append(self[lastDelimiterIndex])
cursorPosition = self.index(after: lastDelimiterIndex)
}
currentIndex = cursorPosition
}
result.append(contentsOf: self[currentIndex...])
return result
}
///
/// Returns a copy of the current `String` where every HTML entity is replaced with the matching
/// Unicode character.
///
/// ### Examples
///
/// | String | Result | Format |
/// |--------|--------|--------|
/// | `&` | `&` | Keyword entity |
/// | `Σ` | `Σ` | Decimal entity |
/// | `č` | `č` | Hexadecimal entity |
/// | `🇺🇸` | `🇺🇸` | Combined decimal entities (extented grapheme cluster) |
/// | `a` | `a` | Not an entity |
/// | `&` | `&` | Not an entity |
///
public var removingHTMLEntities: String {
return removeHTMLEntities()
}
}
// MARK: - Helpers
extension StringProtocol {
/// Unescapes the receives as a number if possible.
fileprivate func unescapeAsNumber() -> String? {
guard hasPrefix("#") else { return nil }
let unescapableContent = self.dropFirst()
let isHexadecimal = unescapableContent.hasPrefix("x") || hasPrefix("X")
let radix = isHexadecimal ? 16 : 10
guard let numberStartIndex = unescapableContent.index(unescapableContent.startIndex, offsetBy: isHexadecimal ? 1 : 0, limitedBy: unescapableContent.endIndex) else {
return nil
}
let numberString = unescapableContent[numberStartIndex ..< endIndex]
guard let codePoint = UInt32(numberString, radix: radix), let scalar = UnicodeScalar(codePoint) else {
return nil
}
return String(scalar)
}
}
| mit | a242aa038ea9a6dfcf63422d5baacf0c | 34.320346 | 172 | 0.534502 | 4.339894 | false | false | false | false |
ra1028/FloatingActionSheetController | FloatingActionSheetController/FloatingActionSheetController.swift | 1 | 18494 | //
// FloatingActionSheetController.swift
// FloatingActionSheetController
//
// Created by Ryo Aoyama on 10/25/15.
// Copyright © 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
open class FloatingActionSheetController: UIViewController, UIViewControllerTransitioningDelegate {
// MARK: Public
public enum AnimationStyle {
case slideUp
case slideDown
case slideLeft
case slideRight
case pop
}
open var animationStyle = AnimationStyle.slideUp
open var itemTintColor = UIColor(red:0.13, green:0.13, blue:0.17, alpha:1)
open var font = UIFont.boldSystemFont(ofSize: 14)
open var textColor = UIColor.white
open var dimmingColor = UIColor(white: 0, alpha: 0.7)
open var pushBackScale: CGFloat = 0.85
public convenience init(animationStyle: AnimationStyle) {
self.init(nibName: nil, bundle: nil)
self.animationStyle = animationStyle
}
public convenience init(actionGroup: FloatingActionGroup..., animationStyle: AnimationStyle = .slideUp) {
self.init(nibName: nil, bundle: nil)
self.animationStyle = animationStyle
actionGroup.forEach { add(actionGroup: $0) }
}
public convenience init(actionGroups: [FloatingActionGroup], animationStyle: AnimationStyle = .slideUp) {
self.init(nibName: nil, bundle: nil)
self.animationStyle = animationStyle
add(actionGroups: actionGroups)
}
public convenience init(actions: [FloatingAction], animationStyle: AnimationStyle = .slideUp) {
self.init(nibName: nil, bundle: nil)
self.animationStyle = animationStyle
add(actions: actions)
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
configure()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
open override var prefersStatusBarHidden: Bool {
return UIApplication.shared.isStatusBarHidden
}
open override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .fade
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if !isShowing {
showActionSheet()
}
if originalStatusBarStyle == nil {
originalStatusBarStyle = UIApplication.shared.statusBarStyle
}
UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
}
open override func viewWillDisappear(_ animated: Bool) {
if let style = originalStatusBarStyle {
UIApplication.shared.setStatusBarStyle(style, animated: true)
}
}
@discardableResult
public func present(in inViewController: UIViewController, completion: (() -> Void)? = nil) -> Self {
inViewController.present(self, animated: true, completion: completion)
return self
}
@discardableResult
public func dismiss() -> Self {
dismissActionSheet()
return self
}
@discardableResult
public func add(actionGroup: FloatingActionGroup...) -> Self {
actionGroups += actionGroup
return self
}
@discardableResult
public func add(actionGroups: [FloatingActionGroup]) -> Self {
self.actionGroups += actionGroups
return self
}
@discardableResult
public func add(action: FloatingAction..., newGroup: Bool = false) -> Self {
if let lastGroup = actionGroups.last, !newGroup {
action.forEach { lastGroup.add(action: $0) }
} else {
let actionGroup = FloatingActionGroup()
action.forEach { actionGroup.add(action: $0) }
add(actionGroup: actionGroup)
}
return self
}
@discardableResult
public func add(actions: [FloatingAction], newGroup: Bool = false) -> Self {
if let lastGroup = actionGroups.last, !newGroup {
lastGroup.add(actions: actions)
} else {
let actionGroup = FloatingActionGroup(actions: actions)
add(actionGroup: actionGroup)
}
return self
}
// MARK: Private
fileprivate class ActionButton: UIButton {
fileprivate var action: FloatingAction?
private var defaultBackgroundColor: UIColor?
override fileprivate var isHighlighted: Bool {
didSet {
guard oldValue != isHighlighted else { return }
if isHighlighted {
defaultBackgroundColor = backgroundColor
backgroundColor = highlightedColor(defaultBackgroundColor)
} else {
backgroundColor = defaultBackgroundColor
defaultBackgroundColor = nil
}
}
}
func configure(_ action: FloatingAction) {
self.action = action
setTitle(action.title, for: .normal)
if let color = action.tintColor {
backgroundColor = color
}
if let color = action.textColor {
setTitleColor(color, for: .normal)
}
if let font = action.font {
titleLabel?.font = font
}
}
private func highlightedColor(_ originalColor: UIColor?) -> UIColor? {
guard let originalColor = originalColor else { return nil }
var hue: CGFloat = 0, saturatioin: CGFloat = 0,
brightness: CGFloat = 0, alpha: CGFloat = 0
if originalColor.getHue(
&hue,
saturation: &saturatioin,
brightness: &brightness,
alpha: &alpha) {
return UIColor(hue: hue, saturation: saturatioin, brightness: brightness * 0.75, alpha: alpha)
}
return originalColor
}
}
private var actionGroups = [FloatingActionGroup]()
private var actionButtons = [ActionButton]()
private var isShowing = false
private var originalStatusBarStyle: UIStatusBarStyle?
fileprivate weak var dimmingView: UIControl!
private func showActionSheet() {
isShowing = true
dimmingView.backgroundColor = dimmingColor
let itemHeight: CGFloat = 50
let itemSpacing: CGFloat = 10
let groupSpacing: CGFloat = 30
var previousGroupLastButton: ActionButton?
actionGroups.reversed().forEach {
var previousButton: ActionButton?
$0.actions.reversed().forEach {
let button = createSheetButton($0)
view.addSubview(button)
var constraints = NSLayoutConstraint.constraints(
withVisualFormat: "H:|-(spacing)-[button]-(spacing)-|",
options: [],
metrics: ["spacing": itemSpacing],
views: ["button": button]
)
if let previousButton = previousButton {
constraints +=
NSLayoutConstraint.constraints(
withVisualFormat: "V:[button(height)]-spacing-[previous]",
options: [],
metrics: ["height": itemHeight,"spacing": itemSpacing],
views: ["button": button, "previous": previousButton]
)
} else if let previousGroupLastButton = previousGroupLastButton {
constraints +=
NSLayoutConstraint.constraints(
withVisualFormat: "V:[button(height)]-spacing-[previous]",
options: [],
metrics: ["height": itemHeight, "spacing": groupSpacing],
views: ["button": button, "previous": previousGroupLastButton]
)
} else {
if #available(iOS 11.0, *) {
constraints += [button.heightAnchor.constraint(equalToConstant: itemHeight),
button.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -itemSpacing)
]
} else {
constraints +=
NSLayoutConstraint.constraints(
withVisualFormat: "V:[button(height)]-spacing-|",
options: [],
metrics: ["height": itemHeight,"spacing": itemSpacing],
views: ["button": button]
)
}
}
view.addConstraints(constraints)
previousButton = button
previousGroupLastButton = button
actionButtons.append(button)
}
}
view.layoutIfNeeded()
if let topButton = actionButtons.last {
let buttons: [ActionButton]
let preTransform: CATransform3D
let transform: CATransform3D
let topButtonY = topButton.frame.origin.y
assert(topButtonY > 0, "[FloatingActionSheetController] Too many action items error.")
switch animationStyle {
case .slideUp:
let bottomPad = view.bounds.height - topButtonY
buttons = actionButtons.reversed()
preTransform = CATransform3DMakeTranslation(0, bottomPad, 0)
transform = CATransform3DMakeTranslation(0, -10, 0)
case .slideDown:
let topPad = actionButtons[0].frame.maxY
buttons = actionButtons
preTransform = CATransform3DMakeTranslation(0, -topPad, 0)
transform = CATransform3DMakeTranslation(0, 10, 0)
case .slideLeft:
let rightPad = view.bounds.width - topButton.frame.origin.x
buttons = actionButtons.reversed()
preTransform = CATransform3DMakeTranslation(rightPad, 0, 0)
transform = CATransform3DMakeTranslation(-10, 0, 0)
case .slideRight:
let leftPad = topButton.frame.maxX
buttons = actionButtons.reversed()
preTransform = CATransform3DMakeTranslation(-leftPad, 0, 0)
transform = CATransform3DMakeTranslation(10, 0, 0)
case .pop:
buttons = actionButtons.reversed()
preTransform = CATransform3DMakeScale(0, 0, 1)
transform = CATransform3DMakeScale(1.1, 1.1, 1)
}
buttons.enumerated().forEach { index, button in
button.layer.transform = preTransform
UIView.animate(withDuration: 0.25, delay: TimeInterval(index) * 0.05 + 0.05,
options: .beginFromCurrentState,
animations: {
button.layer.transform = transform
}) { _ in
UIView.animate(withDuration: 0.2, delay: 0,
options: [.beginFromCurrentState, .curveEaseOut],
animations: {
button.layer.transform = CATransform3DIdentity
}, completion: nil)
}
}
}
}
private func dismissActionSheet(_ completion: (() -> Void)? = nil) {
self.dismiss(animated: true, completion: completion)
if let topButton = actionButtons.last {
let buttons: [ActionButton]
let transform: CATransform3D
var completion: ((ActionButton) -> Void)?
switch animationStyle {
case .slideUp:
let bottomPad = view.bounds.height - topButton.frame.origin.y
buttons = actionButtons
transform = CATransform3DMakeTranslation(0, bottomPad, 0)
case .slideDown:
let topPad = actionButtons[0].frame.maxY
buttons = actionButtons.reversed()
transform = CATransform3DMakeTranslation(0, -topPad, 0)
case .slideLeft:
let leftPad = topButton.frame.maxX
buttons = actionButtons.reversed()
transform = CATransform3DMakeTranslation(-leftPad, 0, 0)
case .slideRight:
let rightPad = view.bounds.width - topButton.frame.origin.x
buttons = actionButtons.reversed()
transform = CATransform3DMakeTranslation(rightPad, 0, 0)
case .pop:
buttons = actionButtons
transform = CATransform3DMakeScale(0.01, 0.01, 1) // 0.01 = Swift bug
completion = { $0.layer.transform = CATransform3DMakeScale(0, 0, 1) }
}
buttons.enumerated().forEach { index, button in
UIView.animate(withDuration: 0.2, delay: TimeInterval(index) * 0.05 + 0.05,
options: .beginFromCurrentState,
animations: {
button.layer.transform = transform
}) { _ in
completion?(button)
}
}
}
}
private func createSheetButton(_ action: FloatingAction) -> ActionButton {
let button = ActionButton(type: .custom)
button.layer.cornerRadius = 4
button.backgroundColor = itemTintColor
button.titleLabel?.textAlignment = .center
button.titleLabel?.font = font
button.setTitleColor(textColor, for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.configure(action)
button.addTarget(self, action: #selector(FloatingActionSheetController.didSelectItem(_:)), for: .touchUpInside)
return button
}
@objc private dynamic func didSelectItem(_ button: ActionButton) {
guard let action = button.action else { return }
if action.handleImmediately {
action.handler?(action)
}
dismissActionSheet {
if !action.handleImmediately {
action.handler?(action)
}
}
}
private func configure() {
view.backgroundColor = .clear
modalPresentationStyle = .custom
transitioningDelegate = self
let dimmingView = UIControl()
dimmingView.addTarget(self, action: #selector(FloatingActionSheetController.handleTapDimmingView), for: .touchUpInside)
dimmingView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(dimmingView)
self.dimmingView = dimmingView
view.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[dimmingView]-0-|",
options: [],
metrics: nil,
views: ["dimmingView": dimmingView]
)
+ NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[dimmingView]-0-|",
options: [],
metrics: nil,
views: ["dimmingView": dimmingView]
)
)
}
@objc private dynamic func handleTapDimmingView() {
dismissActionSheet()
}
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return FloatingTransitionAnimator(dimmingView: dimmingView, pushBackScale: pushBackScale)
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let delay = TimeInterval(actionButtons.count) * 0.03
return FloatingTransitionAnimator(dimmingView: dimmingView, pushBackScale: pushBackScale, delay: delay, forwardTransition: false)
}
}
private final class FloatingTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
var forwardTransition = true
let dimmingView: UIView
let pushBackScale: CGFloat
var delay: TimeInterval = 0
init(dimmingView: UIView, pushBackScale: CGFloat, delay: TimeInterval = 0, forwardTransition: Bool = true) {
self.dimmingView = dimmingView
self.pushBackScale = pushBackScale
super.init()
self.delay = delay
self.forwardTransition = forwardTransition
}
@objc func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
@objc func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from),
let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
else { return }
let containerView = transitionContext.containerView
let duration = transitionDuration(using: transitionContext)
if forwardTransition {
containerView.addSubview(toVC.view)
UIView.animate(withDuration: duration, delay: 0,
usingSpringWithDamping: 1, initialSpringVelocity: 0,
options: .beginFromCurrentState,
animations: {
fromVC.view.layer.transform = CATransform3DMakeScale(self.pushBackScale, self.pushBackScale, 1)
self.dimmingView.alpha = 0
self.dimmingView.alpha = 1
}) { _ in
transitionContext.completeTransition(true)
}
} else {
UIView.animate(withDuration: duration, delay: delay,
usingSpringWithDamping: 1, initialSpringVelocity: 0,
options: .beginFromCurrentState,
animations: {
toVC.view.layer.transform = CATransform3DIdentity
self.dimmingView.alpha = 0
}) { _ in
transitionContext.completeTransition(true)
}
}
}
}
| mit | 9ea5ad35e61fa1786b763cddc4eb10fe | 38.941685 | 175 | 0.58195 | 5.750311 | false | false | false | false |
brentdax/swift | test/Inputs/resilient_class.swift | 7 | 4746 |
import resilient_struct
// Fixed-layout, fixed-size base class
@_fixed_layout
open class OutsideParent {
open var property: String = "OutsideParent.property"
open class var classProperty: String {
return "OutsideParent.classProperty"
}
public init() {
print("OutsideParent.init()")
}
open func method() {
print("OutsideParent.method()")
}
open class func classMethod() {
print("OutsideParent.classMethod()")
}
}
// Fixed-layout, resiliently-sized base class
@_fixed_layout
open class OutsideParentWithResilientProperty {
public let p: Point
public let s: Size
public let color: Int32
public final lazy var laziestNumber = 0
public init(p: Point, s: Size, color: Int32) {
self.p = p
self.s = s
self.color = color
}
}
// Resilient base class
open class ResilientOutsideParent {
open var property: String = "ResilientOutsideParent.property"
public final var finalProperty: String = "ResilientOutsideParent.finalProperty"
open class var classProperty: String {
return "ResilientOutsideParent.classProperty"
}
public init() {
print("ResilientOutsideParent.init()")
}
open func method() {
print("ResilientOutsideParent.method()")
}
open class func classMethod() {
print("ResilientOutsideParent.classMethod()")
}
open func getValue() -> Int {
return 0
}
}
// Fixed-layout, fixed-size subclass
@_fixed_layout
open class OutsideChild : OutsideParent {
open override func method() {
print("OutsideChild.method()")
super.method()
}
open override class func classMethod() {
print("OutsideChild.classMethod()")
super.classMethod()
}
}
// Resilient subclass
open class ResilientOutsideChild : ResilientOutsideParent {
open override func method() {
print("ResilientOutsideChild.method()")
super.method()
}
open override class func classMethod() {
print("ResilientOutsideChild.classMethod()")
super.classMethod()
}
}
// Fixed-layout, dependently-sized, generic base class
@_fixed_layout
open class GenericOutsideParent<A> {
open var property: A
public init(property: A) {
self.property = property
print("GenericOutsideParent.init()")
}
open func method() {
print("GenericOutsideParent.method()")
}
open class func classMethod() {
print("GenericOutsideParent.classMethod()")
}
}
// Resilient generic base class
open class ResilientGenericOutsideParent<A> {
open var property: A
public init(property: A) {
self.property = property
print("ResilientGenericOutsideParent.init()")
}
open func method() {
print("ResilientGenericOutsideParent.method()")
}
open class func classMethod() {
print("ResilientGenericOutsideParent.classMethod()")
}
}
// Fixed-layout, dependently-sized, generic subclass
@_fixed_layout
open class GenericOutsideChild<A> : GenericOutsideParent<A> {
public override init(property: A) {
print("GenericOutsideGenericChild.init(a: A)")
super.init(property: property)
}
open override func method() {
print("GenericOutsideChild.method()")
super.method()
}
open override class func classMethod() {
print("GenericOutsideChild.classMethod()")
super.classMethod()
}
}
// Resilient generic subclass
open class ResilientGenericOutsideChild<A> : ResilientGenericOutsideParent<A> {
public override init(property: A) {
print("ResilientGenericOutsideGenericChild.init(a: A)")
super.init(property: property)
}
open override func method() {
print("ResilientGenericOutsideChild.method()")
super.method()
}
open override class func classMethod() {
print("ResilientGenericOutsideChild.classMethod()")
super.classMethod()
}
}
// Fixed-layout, fixed-size subclass of generic class
@_fixed_layout
open class ConcreteOutsideChild : GenericOutsideParent<String> {
public override init(property: String) {
print("ConcreteOutsideChild.init(property: String)")
super.init(property: property)
}
open override func method() {
print("ConcreteOutsideChild.method()")
super.method()
}
open override class func classMethod() {
print("ConcreteOutsideChild.classMethod()")
super.classMethod()
}
}
// Resilient subclass of generic class
open class ResilientConcreteOutsideChild : ResilientGenericOutsideParent<String> {
public override init(property: String) {
print("ResilientConcreteOutsideChild.init(property: String)")
super.init(property: property)
}
open override func method() {
print("ResilientConcreteOutsideChild.method()")
super.method()
}
open override class func classMethod() {
print("ResilientConcreteOutsideChild.classMethod()")
super.classMethod()
}
}
| apache-2.0 | 878f9e9239e02fcec32be11d145cd527 | 20.1875 | 82 | 0.707543 | 4.494318 | false | false | false | false |
AndyWoJ/DouYuLive | DouYuLive/DouYuLive/Classes/Home/Controller/HomeViewController.swift | 1 | 4248 | //
// HomeViewController.swift
// DouYuLive
//
// Created by wujian on 2017/1/4.
// Copyright © 2017年 wujian. All rights reserved.
//
import UIKit
private let kTitleViewH = 40.0
class HomeViewController: UIViewController {
//MARK: 懒加载pageTitleView
lazy var pageTitleView : PageTitleView = {[weak self] in
let titleViewFrame = CGRect(x: 0.0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: kTitleViewH)
let titles = ["推荐","游戏","娱乐","趣玩"]
let titleView = PageTitleView(frame: titleViewFrame, titles: titles)
titleView.delegate = self
return titleView
}()
lazy var pageContentView :PageContentView = {[weak self] in
let contentY = kStatusBarH + kNavigationBarH + kTitleViewH
let contentH = kScreenH - contentY - kTabBarH
let contentFrame = CGRect(x: 0, y: contentY, width: kScreenW, height: contentH)
// all child viewControllers
var childViewControlls = [UIViewController]()
childViewControlls.append(RecommendViewController())
for _ in 0..<3{
let vc = UIViewController()
vc.view.backgroundColor = UIColor(R: CGFloat(arc4random_uniform(255)), G: CGFloat(arc4random_uniform(255)), B: CGFloat(arc4random_uniform(255)))
childViewControlls.append(vc)
}
let contentView = PageContentView(frame: contentFrame, childVCs: childViewControlls, parentVC: self)
contentView.delegate = self
return contentView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK - 设置UI界面
extension HomeViewController{
func setupUI(){
//0,不需要调整UIScrollView的内边距
automaticallyAdjustsScrollViewInsets = false
//1,设置导航栏
setupNavigationBar()
//2,添加titleView
view.addSubview(pageTitleView)
//3,添加pageContentView
view.addSubview(pageContentView)
}
fileprivate func setupNavigationBar(){
let leftButton = UIButton()
leftButton.setImage(UIImage(named:"logo"), for: .normal)
leftButton.sizeToFit()
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo")//UIBarButtonItem(customView: leftButton)
let size = CGSize(width: 44, height: 44)
let QRCodeItem = UIBarButtonItem(imageName: "Image_scan", highlighted: "Image_scan_clicked", size: size)//UIBarButtonItem(customView:CreatedCustomView(name: "Image_scan"))
let searchItem = UIBarButtonItem(imageName: "btn_search", highlighted: "btn_search_clicked", size: size)//UIBarButtonItem(customView:CreatedCustomView(name: "btn_search"))
let historyItem = UIBarButtonItem(imageName: "Image_my_history", highlighted: "Image_my_history_clicked", size: size)//UIBarButtonItem(customView:CreatedCustomView(name: "Image_my_history"))
navigationItem.rightBarButtonItems = [historyItem,searchItem,QRCodeItem]
}
/*
private func CreatedCustomView(name:String) -> UIView{
let button = UIButton()
let clickedName = name + "_clicked"
let size = CGSize(width: 44, height: 44)
button.setImage(UIImage(named:name), for: .normal)
button.setImage(UIImage(named:clickedName), for: .highlighted)
button.frame = CGRect(origin:CGPoint(), size: size)
return button
}
*/
}
//MARK : 遵守PageTitleViewDelegate
extension HomeViewController : PageTitleViewDelegate{
func pageTitleView(_ titleView: PageTitleView, selectedIndex index: Int) {
pageContentView.setCurrentIndex(currentIndex: index)
}
}
//MARK : 遵守PageContentViewDelegate
extension HomeViewController : PageContentViewDelegate{
func pageContentView(_ contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTitleView.setTitleViewWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
| mit | 93e44266e982d13516492b9b0114be95 | 37.266055 | 198 | 0.671781 | 4.953682 | false | false | false | false |
kaltura/playkit-ios | Classes/Events/EventsPayloads/PKAdCuePoints.swift | 1 | 1209 | // ===================================================================================================
// Copyright (C) 2017 Kaltura Inc.
//
// Licensed under the AGPLv3 license, unless a different license for a
// particular library is specified in the applicable library path.
//
// You may obtain a copy of the License at
// https://www.gnu.org/licenses/agpl-3.0.html
// ===================================================================================================
import Foundation
@objc public class PKAdCuePoints: NSObject {
@objc public private(set) var cuePoints: [TimeInterval]
@objc public init(cuePoints: [TimeInterval]) {
self.cuePoints = cuePoints.sorted() // makes sure array is sorted
}
@objc public var count: Int {
return self.cuePoints.count
}
@objc public var hasPreRoll: Bool {
return self.cuePoints.filter { $0 == 0 }.count > 0 // pre-roll ads values = 0
}
@objc public var hasMidRoll: Bool {
return self.cuePoints.filter { $0 > 0 }.count > 0
}
@objc public var hasPostRoll: Bool {
return self.cuePoints.filter { $0 < 0 }.count > 0 // post-roll ads values = -1
}
}
| agpl-3.0 | 997e1848883ccf0f88079d83f307d984 | 32.583333 | 102 | 0.528536 | 4.317857 | false | false | false | false |
cdmx/MiniMancera | miniMancera/View/HomeSplash/VHomeSplashBackground.swift | 1 | 1846 | import UIKit
class VHomeSplashBackground:UIView
{
let kHeight:CGFloat = 200
weak var layoutHeight:NSLayoutConstraint!
private weak var controller:CHomeSplash!
private weak var imageView:UIImageView!
private let kBorderHeight:CGFloat = 1
init(controller:CHomeSplash)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
translatesAutoresizingMaskIntoConstraints = false
isUserInteractionEnabled = false
self.controller = controller
let imageView:UIImageView = UIImageView()
imageView.isUserInteractionEnabled = false
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = UIViewContentMode.center
imageView.clipsToBounds = true
imageView.image = controller.model.modelOption.splashImage
self.imageView = imageView
let border:VBorder = VBorder(color:UIColor.white)
addSubview(imageView)
addSubview(border)
NSLayoutConstraint.equals(
view:imageView,
toView:self)
NSLayoutConstraint.bottomToBottom(
view:border,
toView:self)
NSLayoutConstraint.height(
view:border,
constant:kBorderHeight)
NSLayoutConstraint.equalsHorizontal(
view:border,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
let height:CGFloat = imageView.bounds.maxY
if height > kHeight
{
imageView.contentMode = UIViewContentMode.scaleAspectFill
}
else
{
imageView.contentMode = UIViewContentMode.center
}
super.layoutSubviews()
}
}
| mit | dfa3f4e0ea44bc7f94841d9e30f7cd5c | 26.552239 | 69 | 0.619718 | 5.97411 | false | false | false | false |
artimuas/hacking-swift | ActivityViewController/ActivityViewController/AppDelegate.swift | 1 | 3356 | //
// AppDelegate.swift
// ActivityViewController
//
// Created by Saumitra Vaidya on 9/9/15.
// Copyright (c) 2015 agratas. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and 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:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
}
return false
}
}
| mit | 4c6131383766688dc5c7465d2501328a | 52.269841 | 285 | 0.752086 | 6.203327 | false | false | false | false |
weijentu/ResearchKit | samples/ORKSample/ORKSample/IntroductionViewController.swift | 9 | 3636 | /*
Copyright (c) 2015, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
class IntroductionViewController: UIPageViewController, UIPageViewControllerDataSource {
// MARK: Properties
let pageViewControllers: [UIViewController] = {
let introOne = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("introOneViewController")
let introTwo = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("introTwoViewController")
let introThree = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("introThreeViewController")
return [introOne, introTwo, introThree]
}()
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
dataSource = self
setViewControllers([pageViewControllers[0]], direction: .Forward, animated: false, completion: nil)
}
// MARK: UIPageViewControllerDataSource
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
let index = pageViewControllers.indexOf(viewController)!
if index - 1 >= 0 {
return pageViewControllers[index - 1]
}
return nil
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
let index = pageViewControllers.indexOf(viewController)!
if index + 1 < pageViewControllers.count {
return pageViewControllers[index + 1]
}
return nil
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return pageViewControllers.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
}
| bsd-3-clause | 6809f069e849fc0cd5c4a65ce6fc5dc5 | 42.285714 | 161 | 0.7456 | 5.672387 | false | false | false | false |
skarppi/cavok | CAVOK/Weather/Observation/ObservationMarker.swift | 1 | 1375 | //
// ObservationMarker.swift
// CAVOK
//
// Created by Juho Kolehmainen on 21.10.12.
// Copyright © 2016 Juho Kolehmainen. All rights reserved.
//
import Foundation
class ObservationMarker: MaplyScreenMarker {
init(obs: Observation) {
super.init()
self.userObject = obs
self.loc = obs.station!.coordinate()
self.size = CGSize(width: 10, height: 10)
self.image = drawRect(condition: obs.conditionEnum)
}
private func drawRect(condition: WeatherConditions) -> UIImage {
let size = self.size.width * 2
UIGraphicsBeginImageContext(CGSize(width: size, height: size))
if let context = UIGraphicsGetCurrentContext() {
context.setLineWidth(1)
if condition == .NA {
context.setLineDash(phase: 0, lengths: [5])
context.setFillColor(UIColor.black.withAlphaComponent(0).cgColor)
} else {
context.setFillColor(ColorRamp.color(for: condition, alpha: 0.8).cgColor)
}
context.setStrokeColor(UIColor.black.cgColor)
context.addEllipse(in: CGRect(x: 1, y: 1, width: size - 2, height: size - 2))
context.drawPath(using: .fillStroke)
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
| mit | 27588daba916bee66f550fe3a0f1dc56 | 30.227273 | 89 | 0.622271 | 4.334385 | false | false | false | false |
3ph/CollectionPickerView | CollectionPickerView/Classes/CollectionPickerViewFlowLayout.swift | 1 | 10246 | //
// CollectionPickerFlowLayout.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Akkyie Y, 2017 Tomas Friml
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE
import UIKit
public class CollectionPickerViewFlowLayout: UICollectionViewFlowLayout {
open var maxAngle : CGFloat = CGFloat.pi / 2
open var isFlat : Bool = true
fileprivate var _isHorizontal : Bool {
get {
return scrollDirection == .horizontal
}
}
fileprivate var _halfDim : CGFloat {
get {
return (_isHorizontal ? _visibleRect.width : _visibleRect.height) / 2
}
}
fileprivate var _mid : CGFloat {
get {
return _isHorizontal ? _visibleRect.midX : _visibleRect.midY
}
}
fileprivate var _visibleRect : CGRect {
get {
if let cv = collectionView {
return CGRect(origin: cv.contentOffset, size: cv.bounds.size)
}
return CGRect.zero
}
}
func initialize() {
sectionInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)
minimumLineSpacing = 0.0
}
override init() {
super.init()
self.initialize()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
public override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
public override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if let attributes = super.layoutAttributesForItem(at: indexPath)?.copy() as? UICollectionViewLayoutAttributes {
if isFlat == false {
let distance = _isHorizontal ? (attributes.frame.midX - _mid) : (_mid - attributes.frame.midY)
let currentAngle = maxAngle * distance / _halfDim / (CGFloat.pi / 2)
var transform = CATransform3DIdentity
if _isHorizontal {
transform = CATransform3DTranslate(transform, -distance, 0, -_halfDim)
transform = CATransform3DRotate(transform, currentAngle, 0, 1, 0)
} else {
transform = CATransform3DTranslate(transform, 0, distance, -_halfDim)
transform = CATransform3DRotate(transform, currentAngle, 1, 0, 0)
}
transform = CATransform3DTranslate(transform, 0, 0, _halfDim)
attributes.transform3D = transform
attributes.alpha = abs(currentAngle) < maxAngle ? 1.0 : 0.0
return attributes;
}
return attributes
}
return nil
}
public override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
if isFlat == false {
var attributes = [UICollectionViewLayoutAttributes]()
if self.collectionView!.numberOfSections > 0 {
for i in 0 ..< self.collectionView!.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: i, section: 0)
attributes.append(self.layoutAttributesForItem(at: indexPath)!)
}
}
return attributes
}
return super.layoutAttributesForElements(in: rect)
}
// public override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
// guard let cv = collectionView else { return CGPoint.zero }
//
// let dim = _isHorizontal ? cv.bounds.width : cv.bounds.height
// let halfDim = dim / 2
// var offsetAdjustment: CGFloat = CGFloat.greatestFiniteMagnitude
// var selectedCenter: CGFloat = dim
//
// let center: CGFloat = _isHorizontal ? proposedContentOffset.x + halfDim : proposedContentOffset.y + halfDim
// let targetRect = CGRect(x: _isHorizontal ? proposedContentOffset.x : 0, y: _isHorizontal ? 0 : proposedContentOffset.y, width: cv.bounds.size.width, height: cv.bounds.size.height)
// let array:[UICollectionViewLayoutAttributes] = layoutAttributesForElements(in: targetRect)!
// for layoutAttributes: UICollectionViewLayoutAttributes in array {
// let itemCenter: CGFloat = _isHorizontal ? layoutAttributes.center.x : layoutAttributes.center.y
// if abs(itemCenter - center) < abs(offsetAdjustment) {
// offsetAdjustment = itemCenter - center
// selectedCenter = itemCenter
// NSLog("PropX: \(proposedContentOffset.x), offset: \(offsetAdjustment), itemCenter: \(itemCenter), center: \(center)")
// }
// }
// return CGPoint(x: proposedContentOffset.x - (_isHorizontal ? offsetAdjustment : 0), y: proposedContentOffset.y + (_isHorizontal ? 0 : offsetAdjustment))
// }
var snapToCenter : Bool = true
var mostRecentOffset : CGPoint = CGPoint()
public override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
// _ = scrollDirection == .horizontal
//
// if snapToCenter == false {
// return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
// }
// guard let collectionView = collectionView else { return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity) }
//
// var offsetAdjustment = CGFloat.greatestFiniteMagnitude
// let offset = isHorizontal ? proposedContentOffset.x + collectionView.contentInset.left : proposedContentOffset.y + collectionView.contentInset.top
//
// let targetRect : CGRect
// if isHorizontal {
// targetRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)
// } else {
// targetRect = CGRect(x: 0, y: proposedContentOffset.y, width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)
// }
//
// let layoutAttributesArray = super.layoutAttributesForElements(in: targetRect)
//
// layoutAttributesArray?.forEach({ (layoutAttributes) in
// let itemOffset = isHorizontal ? layoutAttributes.frame.origin.x : layoutAttributes.frame.origin.y
// if fabsf(Float(itemOffset - offset)) < fabsf(Float(offsetAdjustment)) {
// offsetAdjustment = itemOffset - offset
// }
// })
//
// if (isHorizontal && velocity.x == 0) || (isHorizontal == false && velocity.y == 0) {
// return mostRecentOffset
// }
//
// if let cv = self.collectionView {
//
// let cvBounds = cv.bounds
// let half = (isHorizontal ? cvBounds.size.width : cvBounds.size.height) * 0.5;
//
// if let attributesForVisibleCells = self.layoutAttributesForElements(in: cvBounds) {
//
// var candidateAttributes : UICollectionViewLayoutAttributes?
// for attributes in attributesForVisibleCells {
//
// // == Skip comparison with non-cell items (headers and footers) == //
// if attributes.representedElementCategory != UICollectionElementCategory.cell {
// continue
// }
//
// if isHorizontal {
// if attributes.center.x == 0 || (attributes.center.x > (cv.contentOffset.x + half) && velocity.x < 0) {
// continue
// }
// } else {
// if attributes.center.y == 0 || (attributes.center.y > (cv.contentOffset.y + half) && velocity.y < 0) {
// continue
// }
// }
//
// candidateAttributes = attributes
// }
//
// // Beautification step , I don't know why it works!
// if (isHorizontal && proposedContentOffset.x == -cv.contentInset.left)
// || (isHorizontal == false && proposedContentOffset.y == -cv.contentInset.top) {
// return proposedContentOffset
// }
//
// guard let _ = candidateAttributes else {
// return mostRecentOffset
// }
//
// if isHorizontal {
// mostRecentOffset = CGPoint(x: floor(candidateAttributes!.center.x - half), y: proposedContentOffset.y)
// } else {
// mostRecentOffset = CGPoint(x: proposedContentOffset.y, y: floor(candidateAttributes!.center.y - half))
// }
//
// return mostRecentOffset
// }
// }
// fallback
mostRecentOffset = super.targetContentOffset(forProposedContentOffset: proposedContentOffset)
return mostRecentOffset
}
}
| mit | 9adcce15f82395723030d6a85dce3c3e | 44.946188 | 193 | 0.608433 | 5.069767 | false | false | false | false |
vermont42/Conjugar | Conjugar/VerbUIV.swift | 1 | 3469 | //
// VerbUIV.swift
// Conjugar
//
// Created by Joshua Adams on 7/18/17.
// Copyright © 2017 Josh Adams. All rights reserved.
//
import UIKit
class VerbUIV: UIView {
@UsesAutoLayout var translation = UILabel()
@UsesAutoLayout var parentOrType = UILabel()
@UsesAutoLayout var participio = UILabel()
@UsesAutoLayout var gerundio = UILabel()
@UsesAutoLayout var raízFutura = UILabel()
@UsesAutoLayout var defectuoso = UILabel()
@UsesAutoLayout private var raízFuturaLabel = UILabel()
@UsesAutoLayout
var table: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = Colors.black
return tableView
}()
required init(coder aDecoder: NSCoder) {
NSCoder.fatalErrorNotImplemented()
}
override init(frame: CGRect) {
super.init(frame: frame)
[translation, parentOrType, participio, gerundio, raízFuturaLabel, raízFutura, defectuoso].forEach {
$0.font = Fonts.label
$0.textColor = Colors.yellow
}
raízFuturaLabel.text = "RF:"
[translation, participio, gerundio, raízFutura, defectuoso].forEach {
$0.isUserInteractionEnabled = true
}
[table, translation, parentOrType, participio, gerundio, raízFuturaLabel, raízFutura, defectuoso].forEach {
addSubview($0)
}
NSLayoutConstraint.activate([
translation.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: Layout.defaultSpacing),
translation.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor),
parentOrType.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: Layout.defaultSpacing),
parentOrType.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor),
participio.topAnchor.constraint(equalTo: translation.bottomAnchor, constant: Layout.defaultSpacing),
participio.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor),
gerundio.topAnchor.constraint(equalTo: parentOrType.bottomAnchor, constant: Layout.defaultSpacing),
gerundio.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor),
raízFuturaLabel.topAnchor.constraint(equalTo: participio.bottomAnchor, constant: Layout.defaultSpacing),
raízFuturaLabel.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor),
raízFutura.topAnchor.constraint(equalTo: participio.bottomAnchor, constant: Layout.defaultSpacing),
raízFutura.leadingAnchor.constraint(equalTo: raízFuturaLabel.trailingAnchor, constant: Layout.defaultSpacing),
defectuoso.topAnchor.constraint(equalTo: gerundio.bottomAnchor, constant: Layout.defaultSpacing),
defectuoso.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor),
table.topAnchor.constraint(equalTo: raízFuturaLabel.bottomAnchor, constant: Layout.defaultSpacing),
table.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor),
table.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor),
table.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -1.0 * Layout.defaultSpacing)
])
}
func setupTable(dataSource: UITableViewDataSource, delegate: UITableViewDelegate) {
table.dataSource = dataSource
table.delegate = delegate
table.register(TenseCell.self, forCellReuseIdentifier: TenseCell.identifier)
table.register(ConjugationCell.self, forCellReuseIdentifier: ConjugationCell.identifier)
}
}
| agpl-3.0 | 88f31634266dc3f793d968e168a60192 | 41.121951 | 118 | 0.77099 | 4.491547 | false | false | false | false |
z-abouzamzam/DaisyChain | DaisyChain/connectionDelegate.swift | 1 | 5018 | //
// ColorServiceManager.swift
// ConnectedColors
//
// Created by Ralf Ebert on 28/04/15.
// Copyright (c) 2015 Ralf Ebert. All rights reserved.
//
import Foundation
import MultipeerConnectivity
protocol ColorServiceManagerDelegate {
func connectedDevicesChanged(manager : newSongManager, connectedDevices: [String])
func songChanged(manager : newSongManager, videoID: String)
}
class newSongManager : NSObject {
private let ColorServiceType = "example-color"
private let myPeerId = MCPeerID(displayName: UIDevice.currentDevice().name)
private let serviceAdvertiser : MCNearbyServiceAdvertiser
private let serviceBrowser : MCNearbyServiceBrowser
var delegate : ColorServiceManagerDelegate?
override init() {
self.serviceAdvertiser = MCNearbyServiceAdvertiser(peer: myPeerId, discoveryInfo: nil, serviceType: ColorServiceType)
self.serviceBrowser = MCNearbyServiceBrowser(peer: myPeerId, serviceType: ColorServiceType)
super.init()
self.serviceAdvertiser.delegate = self
self.serviceAdvertiser.startAdvertisingPeer()
self.serviceBrowser.delegate = self
self.serviceBrowser.startBrowsingForPeers()
}
deinit {
self.serviceAdvertiser.stopAdvertisingPeer()
self.serviceBrowser.stopBrowsingForPeers()
}
lazy var session: MCSession = {
let session = MCSession(peer: self.myPeerId, securityIdentity: nil, encryptionPreference: MCEncryptionPreference.Required)
session.delegate = self
return session
}()
func sendSong(songName : String) {
NSLog("%@", "sendSong: \(songName)")
if session.connectedPeers.count > 0 {
var error : NSError?
do {
try self.session.sendData(songName.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, toPeers: session.connectedPeers, withMode: MCSessionSendDataMode.Reliable)
} catch var error1 as NSError {
error = error1
NSLog("%@", "\(error)")
}
}
}
}
extension newSongManager : MCNearbyServiceAdvertiserDelegate {
func advertiser(advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: NSError) {
NSLog("%@", "didNotStartAdvertisingPeer: \(error)")
}
func advertiser(advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: NSData?, invitationHandler: ((Bool, MCSession) -> Void)) {
NSLog("%@", "didReceiveInvitationFromPeer \(peerID)")
invitationHandler(true, self.session)
}
}
extension newSongManager : MCNearbyServiceBrowserDelegate {
func browser(browser: MCNearbyServiceBrowser, didNotStartBrowsingForPeers error: NSError) {
NSLog("%@", "didNotStartBrowsingForPeers: \(error)")
}
func browser(browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) {
NSLog("%@", "foundPeer: \(peerID)")
NSLog("%@", "invitePeer: \(peerID)")
browser.invitePeer(peerID, toSession: self.session, withContext: nil, timeout: 10)
}
func browser(browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
NSLog("%@", "lostPeer: \(peerID)")
}
}
extension MCSessionState {
func stringValue() -> String {
switch(self) {
case .NotConnected: return "NotConnected"
case .Connecting: return "Connecting"
case .Connected: return "Connected"
default: return "Unknown"
}
}
}
extension newSongManager : MCSessionDelegate {
func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) {
NSLog("%@", "peer \(peerID) didChangeState: \(state.stringValue())")
self.delegate?.connectedDevicesChanged(self, connectedDevices: session.connectedPeers.map({$0.displayName}))
}
func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) {
NSLog("%@", "didReceiveData: \(data.length) bytes")
let str = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
self.delegate?.songChanged(self, videoID: str)
}
func session(session: MCSession, didReceiveStream stream: NSInputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
NSLog("%@", "didReceiveStream")
}
func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) {
NSLog("%@", "didFinishReceivingResourceWithName")
}
func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress) {
NSLog("%@", "didStartReceivingResourceWithName")
}
}
| apache-2.0 | a8900e944d47a43cddcdf4d4c61158d2 | 35.100719 | 196 | 0.676764 | 5.34968 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/Blogging Reminders/BloggingRemindersFlowCompletionViewController.swift | 1 | 9360 | import UIKit
class BloggingRemindersFlowCompletionViewController: UIViewController {
// MARK: - Subviews
private let stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.spacing = Metrics.stackSpacing
stackView.axis = .vertical
stackView.alignment = .center
stackView.distribution = .equalSpacing
return stackView
}()
private let imageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: Images.bellImageName))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.tintColor = .systemYellow
return imageView
}()
private let titleLabel: UILabel = {
let label = UILabel()
label.adjustsFontForContentSizeCategory = true
label.adjustsFontSizeToFitWidth = true
label.font = WPStyleGuide.serifFontForTextStyle(.title1, fontWeight: .semibold)
label.numberOfLines = 2
label.textAlignment = .center
label.text = TextContent.completionTitle
return label
}()
private let promptLabel: UILabel = {
let label = UILabel()
label.adjustsFontForContentSizeCategory = true
label.adjustsFontSizeToFitWidth = true
label.font = .preferredFont(forTextStyle: .body)
label.numberOfLines = 6
label.textAlignment = .center
label.textColor = .text
return label
}()
private let hintLabel: UILabel = {
let label = UILabel()
label.adjustsFontForContentSizeCategory = true
label.adjustsFontSizeToFitWidth = true
label.font = .preferredFont(forTextStyle: .footnote)
label.text = TextContent.completionUpdateHint
label.numberOfLines = 3
label.textAlignment = .center
label.textColor = .secondaryLabel
return label
}()
private lazy var doneButton: UIButton = {
let button = FancyButton()
button.isPrimary = true
button.setTitle(TextContent.doneButtonTitle, for: .normal)
button.addTarget(self, action: #selector(doneButtonTapped), for: .touchUpInside)
return button
}()
// MARK: - Initializers
let blog: Blog
let calendar: Calendar
let tracker: BloggingRemindersTracker
init(blog: Blog, tracker: BloggingRemindersTracker, calendar: Calendar? = nil) {
self.blog = blog
self.tracker = tracker
self.calendar = calendar ?? {
var calendar = Calendar.current
calendar.locale = Locale.autoupdatingCurrent
return calendar
}()
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
// This VC is designed to be instantiated programmatically. If we ever need to initialize this VC
// from a coder, we can implement support for it - but I don't think it's necessary right now.
// - diegoreymendez
fatalError("Use init(tracker:) instead")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .basicBackground
configureStackView()
configureConstraints()
configurePromptLabel()
configureTitleLabel()
navigationController?.setNavigationBarHidden(true, animated: false)
}
override func viewDidAppear(_ animated: Bool) {
tracker.screenShown(.allSet)
super.viewDidAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// If a parent VC is being dismissed, and this is the last view shown in its navigation controller, we'll assume
// the flow was completed.
if isBeingDismissedDirectlyOrByAncestor() && navigationController?.viewControllers.last == self {
tracker.flowCompleted()
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
calculatePreferredContentSize()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
hintLabel.isHidden = traitCollection.preferredContentSizeCategory.isAccessibilityCategory
}
func calculatePreferredContentSize() {
let size = CGSize(width: view.bounds.width, height: UIView.layoutFittingCompressedSize.height)
preferredContentSize = view.systemLayoutSizeFitting(size)
}
// MARK: - View Configuration
private func configureStackView() {
view.addSubview(stackView)
stackView.addArrangedSubviews([
imageView,
titleLabel,
promptLabel,
hintLabel,
doneButton
])
stackView.setCustomSpacing(Metrics.afterHintSpacing, after: hintLabel)
}
private func configureConstraints() {
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: Metrics.edgeMargins.left),
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -Metrics.edgeMargins.right),
stackView.topAnchor.constraint(equalTo: view.topAnchor, constant: Metrics.edgeMargins.top),
stackView.bottomAnchor.constraint(lessThanOrEqualTo: view.safeBottomAnchor, constant: -Metrics.edgeMargins.bottom),
doneButton.heightAnchor.constraint(greaterThanOrEqualToConstant: Metrics.doneButtonHeight),
doneButton.widthAnchor.constraint(equalTo: stackView.widthAnchor),
])
}
// Populates the prompt label with formatted text detailing the reminders set by the user.
//
private func configurePromptLabel() {
guard let scheduler = try? ReminderScheduleCoordinator() else {
return
}
let schedule = scheduler.schedule(for: blog)
let formatter = BloggingRemindersScheduleFormatter()
let style = NSMutableParagraphStyle()
style.lineSpacing = Metrics.promptTextLineSpacing
style.alignment = .center
// The line break mode seems to be necessary to make it possible for the label to adjust it's
// size to stay under the allowed number of lines.
// To understand why this is necessary: turn on the largest available font size under iOS
// accessibility settings, and see that the label adjusts the font size to stay within the
// available space and allowed max number of lines.
style.lineBreakMode = .byTruncatingTail
let defaultAttributes: [NSAttributedString.Key: AnyObject] = [
.paragraphStyle: style,
.foregroundColor: UIColor.text,
]
let promptText = NSMutableAttributedString(attributedString: formatter.longScheduleDescription(for: schedule, time: scheduler.scheduledTime(for: blog).toLocalTime()))
promptText.addAttributes(defaultAttributes, range: NSRange(location: 0, length: promptText.length))
promptLabel.attributedText = promptText
}
private func configureTitleLabel() {
guard let scheduler = try? ReminderScheduleCoordinator() else {
return
}
if scheduler.schedule(for: blog) == .none {
titleLabel.text = TextContent.remindersRemovedTitle
} else {
titleLabel.text = TextContent.completionTitle
}
}
}
// MARK: - Actions
extension BloggingRemindersFlowCompletionViewController: BloggingRemindersActions {
// MARK: - BloggingRemindersActions
@objc func doneButtonTapped() {
dismiss(from: .continue, screen: .allSet, tracker: tracker)
}
@objc private func dismissTapped() {
dismiss(from: .dismiss, screen: .allSet, tracker: tracker)
}
}
// MARK: - DrawerPresentable
extension BloggingRemindersFlowCompletionViewController: DrawerPresentable {
var collapsedHeight: DrawerHeight {
return .intrinsicHeight
}
}
extension BloggingRemindersFlowCompletionViewController: ChildDrawerPositionable {
var preferredDrawerPosition: DrawerPosition {
return .collapsed
}
}
// MARK: - Constants
private enum TextContent {
static let completionTitle = NSLocalizedString("All set!", comment: "Title of the completion screen of the Blogging Reminders Settings screen.")
static let remindersRemovedTitle = NSLocalizedString("Reminders removed", comment: "Title of the completion screen of the Blogging Reminders Settings screen when the reminders are removed.")
static let completionUpdateHint = NSLocalizedString("You can update this any time via My Site > Site Settings",
comment: "Prompt shown on the completion screen of the Blogging Reminders Settings screen.")
static let doneButtonTitle = NSLocalizedString("Done", comment: "Title for a Done button.")
}
private enum Images {
static let bellImageName = "reminders-bell"
}
private enum Metrics {
static let edgeMargins = UIEdgeInsets(top: 46, left: 20, bottom: 20, right: 20)
static let stackSpacing: CGFloat = 20.0
static let doneButtonHeight: CGFloat = 44.0
static let afterHintSpacing: CGFloat = 24.0
static let promptTextLineSpacing: CGFloat = 1.5
}
| gpl-2.0 | 9a73d7e733f479358f670bfb306f75c8 | 34.725191 | 194 | 0.682906 | 5.43554 | false | false | false | false |
touchopia/HackingWithSwift | project23/Project23/GameViewController.swift | 1 | 1393 | //
// GameViewController.swift
// Project23
//
// Created by TwoStraws on 19/08/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| unlicense | 0da2dd9823d0d27fd543d6e97d98231e | 24.309091 | 77 | 0.58046 | 5.52381 | false | false | false | false |
elationfoundation/Reporta-iOS | IWMF/ViewControllers/HomeLoginViewController/Step1_CreateAccountVC.swift | 1 | 68585 | //
// Step1_CreateAccountVC.swift
// IWMF
//
// This class is used for display Step-1 of Create Account and display User Profile.
//
//
import UIKit
enum UserProfile : Int{
case CreateAccount = 1
case UpdateUser = 2
}
class Step1_CreateAccountVC: UIViewController,UITableViewDataSource,UITableViewDelegate,NextButtonProtocol,SelctedLanguageProtocol,FreelancerBtProtocol,PersonalDetailTextProtocol,TextViewTextChanged,ARPersonalDetailsTableView, ARFreelancerBtProtocol,CustomAlertViewDelegate,UserModalProtocol {
var password1 : NSMutableString!
var password2 : NSMutableString!
var createAccntArr : NSMutableArray!
var selectType : Int = 0
var signOutpass : NSString!
var signOutTextField : UITextField!
@IBOutlet var btnInfo : UIButton!
@IBOutlet var btnHome : UIButton!
@IBOutlet weak var btnBarDone: UIBarButtonItem!
@IBOutlet weak var btnBarCancel: UIBarButtonItem!
@IBOutlet weak var tableView: UITableView!
var activeTextField : UITextField!
var isKeyboardEnable : Bool = false
let tableFooteHeight : CGFloat = 110
var freelancer = Bool()
// MARK:- Constraint Property
@IBOutlet weak var verticleSpaceView: NSLayoutConstraint!
@IBOutlet weak var textViewHeigth: NSLayoutConstraint!
// MARK:- View Property
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var checkInView: UIView!
@IBOutlet var toolbar : UIToolbar!
@IBOutlet weak var lblTitle: UILabel!
var isIbuttonOpen : Bool!
var devide : CGFloat!
var arrPassword1 : NSMutableArray!
var arrPassword2 : NSMutableArray!
var isFromProfile : Bool!
var emailRe : NSString!
override func viewDidLoad() {
Structures.Constant.appDelegate.userSignUpDetail = User()
super.viewDidLoad()
arrPassword1 = NSMutableArray()
arrPassword2 = NSMutableArray()
password1 = ""
password2 = ""
emailRe = ""
devide = 1
textView.selectable = false
isIbuttonOpen = false
isFromProfile = false
self.lblTitle.font = Utility.setNavigationFont()
freelancer = false
createAccntArr = NSMutableArray()
self.verticleSpaceView.constant = (UIScreen.mainScreen().bounds.size.height) % self.devide
self.checkInView.frame.origin.y -= (UIScreen.mainScreen().bounds.size.height)
switch selectType
{
case UserProfile.CreateAccount.rawValue :
var cell: NextFooterTableViewCell? = tableView.dequeueReusableCellWithIdentifier(Structures.TableViewCellIdentifiers.nextFooterCellIdentifier) as? NextFooterTableViewCell
let arr : NSArray = NSBundle.mainBundle().loadNibNamed("NextFooterTableViewCell", owner: self, options: nil)
cell = arr[0] as? NextFooterTableViewCell
cell?.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 80)
cell?.nextBtn.addTarget(self, action: "nextButtonClicked", forControlEvents: .TouchUpInside)
cell?.nextBtn.setTitle(NSLocalizedString(Utility.getKey("Next"),comment:""), forState: .Normal)
tableView.tableFooterView = cell
self.tableView.reloadData()
//Load County List
Structures.Constant.appDelegate.countryListUpdate()
//New User Dict allocation
Structures.Constant.appDelegate.dictSignUpCircle[Structures.Constant.ListName] = NSLocalizedString(Utility.getKey("private_circle_name"),comment:"")
Structures.Constant.appDelegate.dictSignUpCircle[Structures.User.CircleType] = "1"
Structures.Constant.appDelegate.dictSignUpCircle[Structures.Constant.DefaultStatus] = "1"
Structures.Constant.appDelegate.dictSignUpCircle["Contacts"] = NSMutableArray()
Structures.Constant.appDelegate.dictSelectToUpdate = Structures.Constant.appDelegate.dictSignUpCircle
isFromProfile = false
self.lblTitle.text = NSLocalizedString(Utility.getKey("create_account_header"),comment:"")
if let path = NSBundle.mainBundle().pathForResource("Step1_CreateAccount", ofType: "plist")
{
createAccntArr = NSMutableArray(contentsOfFile: path)
let arrTemp : NSMutableArray = NSMutableArray(array: createAccntArr)
for (index, element) in arrTemp.enumerate() {
if var innerDict = element as? Dictionary<String, AnyObject> {
let strTitle = innerDict["Title"] as! String!
if strTitle.characters.count != 0
{
let strPlaceholder = innerDict["Placeholder"] as! NSString!
if strPlaceholder != nil
{
if strPlaceholder != "Please describe"
{
innerDict["Placeholder"] = NSLocalizedString(Utility.getKey(strTitle as String),comment:"")
}
}
let strOptionTitle = innerDict["OptionTitle"] as! NSString!
if strOptionTitle != nil
{
if strOptionTitle == "Add"
{
innerDict["OptionTitle"] = NSLocalizedString(Utility.getKey("add"),comment:"")
}
else if strOptionTitle == "(Minimum 8 characters)"
{
innerDict["OptionTitle"] = NSLocalizedString(Utility.getKey("PassHint"),comment:"")
}
}
innerDict["Title"] = NSLocalizedString(Utility.getKey(strTitle as String),comment:"")
self.createAccntArr.replaceObjectAtIndex(index, withObject: innerDict)
}
else
{
let strPlaceholder = innerDict["Placeholder"] as! String!
if strPlaceholder != nil
{
if strPlaceholder == "Please describe"
{
innerDict["Placeholder"] = NSLocalizedString(Utility.getKey(strPlaceholder),comment:"")
self.createAccntArr.replaceObjectAtIndex(index, withObject: innerDict)
}
}
}
}
}
}
break
case UserProfile.UpdateUser.rawValue :
isFromProfile = true
Structures.Constant.appDelegate.userSignUpDetail = Structures.Constant.appDelegate.userSignUpDetail.getLoggedInUser()!
self.lblTitle.text = NSLocalizedString(Utility.getKey("profile"),comment:"")
if let path = NSBundle.mainBundle().pathForResource("UpdateUser", ofType: "plist")
{
createAccntArr = NSMutableArray(contentsOfFile: path)
let arrTemp : NSMutableArray = NSMutableArray(array: createAccntArr)
for (index, element) in arrTemp.enumerate() {
if var innerDict = element as? Dictionary<String, AnyObject> {
let strTitle = innerDict["Title"] as! String!
if strTitle.characters.count != 0
{
let strOptionTitle = innerDict["OptionTitle"] as! NSString!
if strOptionTitle != nil
{
if strOptionTitle == "Add"
{
innerDict["OptionTitle"] = NSLocalizedString(Utility.getKey("add"),comment:"")
}
else if strOptionTitle == "Update"
{
innerDict["OptionTitle"] = NSLocalizedString(Utility.getKey("Update"),comment:"")
}
else if strOptionTitle == "Edit"
{
innerDict["OptionTitle"] = NSLocalizedString(Utility.getKey("Edit"),comment:"")
}
else if strOptionTitle == "Choose"
{
innerDict["OptionTitle"] = NSLocalizedString(Utility.getKey("Choose"),comment:"")
}
if strOptionTitle == "Version"
{
innerDict["OptionTitle"] = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as! String!
}
}
innerDict["Title"] = NSLocalizedString(Utility.getKey(strTitle as String),comment:"")
self.createAccntArr.replaceObjectAtIndex(index, withObject: innerDict)
}
}
}
}
self.getUserData()
break
default :
isFromProfile = false
}
self.tableView.registerNib(UINib(nibName: "FreelancerTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.FreelancerCellIndentifier)
self.tableView.registerNib(UINib(nibName: "ARPersonalDetailsTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.ARPersonalDetailsTableViewCellIndetifier)
self.tableView.registerNib(UINib(nibName: "TitleTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.TitleTableViewCellIdentifier)
self.tableView.registerNib(UINib(nibName: "TitleTableViewCell2", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.TitleTableViewCellIdentifier2)
self.tableView.registerNib(UINib(nibName: "DetailTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.DetailTableViewCellIdentifier)
self.tableView.registerNib(UINib(nibName: "PersonalDetailsTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.PersonalDetailCellIdentifier)
self.tableView.registerNib(UINib(nibName: "LocationListingCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.LocationListingCellIdentifier)
self.tableView.registerNib(UINib(nibName: "ARDetailTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.ARDetailTableViewCellIdentifier)
self.tableView.registerNib(UINib(nibName: "ARTitleTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.ARTitleTableViewCellIdentifier)
self.tableView.registerNib(UINib(nibName: "ARFreelancerTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.ARFreelancerTableViewCellIdentifier)
self.tableView.registerNib(UINib(nibName: "ARLocationListingCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.ARLocationListingCellIdentifier)
self.tableView.registerNib(UINib(nibName: "HelpTextViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.HelpTextViewCellIdentifier)
tableView.rowHeight = UITableViewAutomaticDimension
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool)
{
if isFromProfile == true
{
Structures.Constant.appDelegate.userSignUpDetail = Structures.Constant.appDelegate.userSignUpDetail.getLoggedInUser()!
self.getUserData()
}
switch selectType
{
case UserProfile.CreateAccount.rawValue :
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
break
case UserProfile.UpdateUser.rawValue :
self.tableView.reloadData()
break
default :
print("")
}
self.setUpUpperInfoView()
self.checkInView.hidden = true
if Structures.Constant.appDelegate.isArabic == true
{
btnHome.setImage(UIImage(named: "info.png"), forState: UIControlState.Normal)
btnInfo.setImage(UIImage(named: "home.png"), forState: UIControlState.Normal)
textView.textAlignment = NSTextAlignment.Right
btnBarCancel.title = NSLocalizedString(Utility.getKey("done"),comment:"")
btnBarDone.title = NSLocalizedString(Utility.getKey("Cancel"),comment:"")
}
else
{
btnHome.setImage(UIImage(named: "home.png"), forState: UIControlState.Normal)
btnInfo.setImage(UIImage(named: "info.png"), forState: UIControlState.Normal)
textView.textAlignment = NSTextAlignment.Left
btnBarCancel.title = NSLocalizedString(Utility.getKey("Cancel"),comment:"")
btnBarDone.title = NSLocalizedString(Utility.getKey("done"),comment:"")
}
}
override func viewWillDisappear(animated: Bool)
{
if activeTextField != nil
{
activeTextField.resignFirstResponder()
}
self.view.endEditing(true)
self.tableView.contentInset = UIEdgeInsetsZero
self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero
switch selectType
{
case UserProfile.CreateAccount.rawValue :
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
break
default :
print("")
}
}
func keyboardWillShow(notification : NSNotification)
{
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()
{
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.tableView.contentInset = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.size.height + 20 , 0.0)
self.tableView.scrollIndicatorInsets = self.tableView.contentInset
var rect : CGRect = self.tableView.frame
rect.size.height -= keyboardSize.size.height
if (!CGRectContainsPoint(rect, self.activeTextField.frame.origin) ) {
self.tableView.scrollRectToVisible(self.activeTextField.frame, animated: true)
}
})
}
}
func keyboardWillHide(notification : NSNotification)
{
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.tableView.contentInset = UIEdgeInsetsZero
self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK :- animation methods
@IBAction func btnHomePressed(sender: AnyObject) {
if Structures.Constant.appDelegate.isArabic == true
{
setIBtnView()
}
else
{
backToPreviousScreen()
}
}
func backToPreviousScreen(){
self.navigationController?.popViewControllerAnimated(true)
}
@IBAction func btnInfoPressed(sender: AnyObject) {
if Structures.Constant.appDelegate.isArabic == true
{
backToPreviousScreen()
}
else
{
setIBtnView()
}
}
@IBAction func arrowButton(sender: AnyObject)
{
self.setIBtnView()
}
func setIBtnView(){
if isIbuttonOpen == false
{
self.view.bringSubviewToFront(self.checkInView)
self.checkInView.hidden = false
isIbuttonOpen = true
UIView.animateWithDuration(0.80, delay: 0.1, options: .CurveEaseOut , animations:
{
self.verticleSpaceView.constant = (UIScreen.mainScreen().bounds.size.height) % self.devide
self.checkInView.frame.origin.y += (UIScreen.mainScreen().bounds.size.height)
}, completion: nil)
}
else
{
isIbuttonOpen = false
UIView.animateWithDuration(0.80, delay: 0.1, options: .CurveEaseInOut , animations:
{
self.verticleSpaceView.constant = (UIScreen.mainScreen().bounds.size.height) % self.devide
self.checkInView.frame.origin.y -= (UIScreen.mainScreen().bounds.size.height)
}, completion: {
finished in
self.setUpUpperInfoView()
self.checkInView.hidden = true
self.view.bringSubviewToFront(self.tableView)
})
}
}
func setUpUpperInfoView()
{
self.textView.text = NSLocalizedString(Utility.getKey("Profile - i button"),comment:"")
}
@IBAction func btnToolbarDoneClicked(sender:AnyObject)
{
self.view.endEditing(true);
self.activeTextField.resignFirstResponder()
}
@IBAction func btnToolbarCancelClicked(sender:AnyObject)
{
self.view.endEditing(true);
self.activeTextField.resignFirstResponder()
}
func getUserData()
{
let arrTemp : NSArray = NSArray(array: self.createAccntArr)
for (index, element) in arrTemp.enumerate() {
if var innerDict = element as? Dictionary<String, AnyObject>
{
let iden = innerDict["Identity"] as! NSString!
if iden == "UpdatedUsername"{
innerDict["Title"] = (Structures.Constant.appDelegate.userSignUpDetail.firstName as NSString as String) + " " + (Structures.Constant.appDelegate.userSignUpDetail.lastName as NSString as String)
self.createAccntArr.replaceObjectAtIndex(index, withObject: innerDict)
}
if iden == "SelectedJobTitle"{
innerDict["Title"] = Structures.Constant.appDelegate.userSignUpDetail.jobTitle
self.createAccntArr.replaceObjectAtIndex(index, withObject: innerDict)
}
if iden == "Affiliation"{
if Structures.Constant.appDelegate.userSignUpDetail.affiliation.length != 0
{
innerDict["Title"] = Structures.Constant.appDelegate.userSignUpDetail.affiliation
self.createAccntArr.replaceObjectAtIndex(index, withObject: innerDict)
}
else
{
innerDict["Title"] = NSLocalizedString(Utility.getKey("Affiliation"),comment:"")
self.createAccntArr.replaceObjectAtIndex(index, withObject: innerDict)
}
}
if iden == "Freelancer"{
self.freelancer = Structures.Constant.appDelegate.userSignUpDetail.isFreeLancer as Bool
}
if iden == "CountryOfOrigin"{
innerDict["Title"] = Utility.findCountryFromCode(Structures.Constant.appDelegate.userSignUpDetail.origin)
self.createAccntArr.replaceObjectAtIndex(index, withObject: innerDict)
}
if iden == "CountryWhereWorking"{
innerDict["Title"] = Utility.findCountryFromCode(Structures.Constant.appDelegate.userSignUpDetail.working)
self.createAccntArr.replaceObjectAtIndex(index, withObject: innerDict)
}
}
}
self.tableView.reloadData()
}
//MARK : - NextButtonProtocol
//Updating user
func nextButtonClicked() {
self.view.endEditing(true)
if selectType == 1{
registerUser()
}
if selectType == 2{
SVProgressHUD.showWithStatus(NSLocalizedString(Utility.getKey("updating_user"),comment:""), maskType: 4)
User.registerUser(NSMutableDictionary(dictionary:User.dictToUpdate(Structures.Constant.appDelegate.prefrence.DeviceToken, user: Structures.Constant.appDelegate.userSignUpDetail)),isNewUser : false)
User.sharedInstance.delegate = self
}
}
func commonUserResponse(wsType : WSRequestType ,dict : NSDictionary, isSuccess : Bool)
{
if wsType == WSRequestType.SignOut{
if isSuccess
{
SVProgressHUD.dismiss()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
CheckIn.removeActiveCheckInObject()
if Structures.Constant.appDelegate.prefrence.LanguageSelected != nil
{
if Structures.Constant.appDelegate.prefrence.LanguageSelected == true
{
let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let navigationController:UINavigationController = storyboard.instantiateInitialViewController() as! UINavigationController
let rootViewController:UIViewController = storyboard.instantiateViewControllerWithIdentifier("LoginViewController")
navigationController.viewControllers = [rootViewController]
Structures.Constant.appDelegate.window?.rootViewController = navigationController
}
}
})
}
else
{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
SVProgressHUD.dismiss()
if (Structures.Constant.appDelegate.dictCommonResult.valueForKey(Structures.Constant.Status) as! NSString).isEqualToString("3"){
if Structures.Constant.appDelegate.dictCommonResult.valueForKey(Structures.Constant.Message) != nil
{
Utility.showLogOutAlert((Structures.Constant.appDelegate.dictCommonResult.valueForKey(Structures.Constant.Message) as? String!)!, view: self)
}
}else{
if Structures.Constant.appDelegate.dictCommonResult.valueForKey(Structures.Constant.Message) != nil
{
Utility.showAlertWithTitle(Structures.Constant.appDelegate.dictCommonResult.valueForKey(Structures.Constant.Message) as! String, strMessage: "", strButtonTitle: NSLocalizedString(Utility.getKey("Ok"),comment:""), view: self)
}
}
})
}
}else if wsType == WSRequestType.UpdateUser{
if isSuccess
{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let homeViewScreen : HomeViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("HomeViewController") as! HomeViewController
self.showViewController(homeViewScreen, sender: nil)
SVProgressHUD.dismiss()
})
}
else
{
SVProgressHUD.dismiss()
}
}
else if wsType == WSRequestType.CheckUserNameEmail{
if isSuccess{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
SVProgressHUD.dismiss()
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
Structures.Constant.appDelegate.contactScreensFrom = ContactsFrom.CreateAccount
self.performSegueWithIdentifier("CreateContactListPush", sender: nil);
SVProgressHUD.dismiss()
})
})
}else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
SVProgressHUD.dismiss()
})
}
}
}
//MARK : - FreelancerButtonProtocol
func freelancerButtonClicked(isSelected: NSNumber) {
Structures.Constant.appDelegate.userSignUpDetail.isFreeLancer = isSelected
if freelancer == true
{
freelancer = false
}
else
{
freelancer = true
}
}
func textChanged(changedText: NSString) {
Structures.Constant.appDelegate.userSignUpDetail.affiliation = changedText
changeValueInMainCheckInArray(changedText, identity: "Affiliation")
}
func jobTitleSelcted(selectedText : String){
Structures.Constant.appDelegate.userSignUpDetail.jobTitle = selectedText
changeValueInMainCheckInArray(selectedText, identity: "SelectedJobTitle")
}
func countryOfOrigin(selectedText: String, selectedCode: String) {
Structures.Constant.appDelegate.userSignUpDetail.origin = selectedCode
changeValueInMainCheckInArray(selectedText, identity: "CountryOfOrigin")
}
func countryWhereWorking(selectedText: String, selectedCode: String) {
Structures.Constant.appDelegate.userSignUpDetail.working = selectedCode
changeValueInMainCheckInArray(selectedText, identity: "CountryWhereWorking")
}
// MARK : - DetailTextFieldProtocol
func textFieldShouldChangeCharactersInRange(textField: UITextField, tableViewCell: PersonalDetailsTableViewCell, identity: NSString, level: NSString, range: NSRange, replacementString string: String) {
if identity == "Password" || identity == "NewPassword"
{
if textField.text!.characters.count == range.location
{
arrPassword1.addObject(string)
}
else
{
arrPassword1.removeLastObject()
}
textField.text = hideTextInTextFieldExceptOne(textField.text) as String
}
else if identity == "Re-enterPassword" || identity == "ConfirmPassword"
{
if textField.text!.characters.count == range.location
{
arrPassword2.addObject(string)
}
else
{
arrPassword2.removeLastObject()
}
textField.text = hideTextInTextFieldExceptOne(textField.text) as String
}
}
func textFieldStartEditing(textField : UITextField, tableViewCell : PersonalDetailsTableViewCell, identity : NSString, level : NSString){
textStartEditing(textField, identity: identity)
}
func textFieldEndEditing(textField : UITextField, tableViewCell : PersonalDetailsTableViewCell, identity : NSString, level : NSString){
isValidateField(textField, identity: identity, isEndEditing: true)
}
func textFieldShouldReturn(textField : UITextField, tableViewCell : PersonalDetailsTableViewCell, identity : NSString, level : NSString)
{
if textField.returnKeyType == UIReturnKeyType.Next
{
if isValidateField(textField, identity: identity, isEndEditing: false)
{
if let cell: PersonalDetailsTableViewCell = self.tableView?.cellForRowAtIndexPath(NSIndexPath(forRow: Int(tableViewCell.indexPath.row+1), inSection: 0)) as? PersonalDetailsTableViewCell
{
cell.detailstextField.becomeFirstResponder()
}
else
{
self.view.endEditing(true);
self.tableView.contentInset = UIEdgeInsetsZero
self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero
}
}
}
else
{
self.view.endEditing(true);
self.tableView.contentInset = UIEdgeInsetsZero
self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero
}
}
func textStartEditing(textField : UITextField, identity : NSString)
{
if identity == "Password" || identity == "NewPassword"
{
arrPassword1 = NSMutableArray()
textField.text = ""
password1 = ""
}
else if identity == "Re-enterPassword" || identity == "ConfirmPassword"
{
arrPassword2 = NSMutableArray()
textField.text = ""
password2 = ""
}
textField.inputAccessoryView = toolbar
self.activeTextField = textField
}
func hideTextInTextFieldExceptOne(text: NSString!) -> NSString
{
var len : Int = 0
len = text.length
var test : NSString = ""
for (var i : Int = 0; i < len ; i++ )
{
let range : NSRange = NSMakeRange(i, 1)
test = text.stringByReplacingCharactersInRange(range, withString: "●")
}
return test
}
//MARK:- Arabic
func textFieldShouldChangeCharactersInRange1(textField: UITextField, tableViewCell: ARPersonalDetailsTableViewCell, identity: NSString, level: NSString, range: NSRange, replacementString string: String) {
if identity == "Password" || identity == "NewPassword"
{
if textField.text!.characters.count == range.location
{
arrPassword1.addObject(string)
}
else
{
arrPassword1.removeLastObject()
}
textField.text = hideTextInTextFieldExceptOne(textField.text) as String
}
else if identity == "Re-enterPassword" || identity == "ConfirmPassword"
{
if textField.text!.characters.count == range.location
{
arrPassword2.addObject(string)
}
else
{
arrPassword2.removeLastObject()
}
textField.text = hideTextInTextFieldExceptOne(textField.text) as String
}
}
func textFieldStartEditing1(textField : UITextField, tableViewCell : ARPersonalDetailsTableViewCell, identity : NSString, level : NSString)
{
textStartEditing(textField, identity: identity)
}
func textFieldEndEditing1(textField : UITextField, tableViewCell : ARPersonalDetailsTableViewCell, identity : NSString, level : NSString){
isValidateField(textField, identity: identity, isEndEditing: true)
}
func textFieldShouldReturn1(textField : UITextField, tableViewCell : ARPersonalDetailsTableViewCell, identity : NSString, level : NSString)
{
if textField.returnKeyType == UIReturnKeyType.Next
{
if isValidateField(textField, identity: identity, isEndEditing: false)
{
if let cell: ARPersonalDetailsTableViewCell = self.tableView?.cellForRowAtIndexPath(NSIndexPath(forRow: Int(tableViewCell.indexPath.row+1), inSection: 0)) as? ARPersonalDetailsTableViewCell
{
cell.detailstextField.becomeFirstResponder()
}
else
{
self.view.endEditing(true);
self.tableView.contentInset = UIEdgeInsetsZero
self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero
}
}
}
else
{
self.view.endEditing(true);
self.tableView.contentInset = UIEdgeInsetsZero
self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero
}
}
func isValidateField(textField : UITextField, identity : NSString, isEndEditing: Bool) -> Bool
{
var isValidInfo : Bool = true
var strTitle : String = ""
var strButtonText : String = NSLocalizedString(Utility.getKey("Ok"),comment:"")
if identity == "Username"
{
if !Utility.isValidUsername(textField.text!)
{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("Invalid_username"),comment:"")
}
if textField.text!.characters.count > 26
{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("Could_not_More_Than_25_Character"),comment:"")
}
Structures.Constant.appDelegate.userSignUpDetail.userName = textField.text!
}
else if identity == "Email"
{
if !Utility.isValidEmail(textField.text!)
{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("please_enter_valid_email"),comment:"")
}
if textField.text!.characters.count > 100
{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("Could_not_More_Than_100_Character"),comment:"")
}
Structures.Constant.appDelegate.userSignUpDetail.email = textField.text
}
else if identity == "ReEnterEmail"
{
if Structures.Constant.appDelegate.userSignUpDetail.email != textField.text
{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("Email_notmatch"),comment:"")
emailRe = ""
}
emailRe = textField.text
}else if identity == "Firstname"{
if textField.text!.characters.count > 26{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("Could_not_More_Than_25_Character"),comment:"")
}
Structures.Constant.appDelegate.userSignUpDetail.firstName = textField.text
}
else if identity == "Lastname"
{
if textField.text!.characters.count > 26{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("Could_not_More_Than_25_Character"),comment:"")
}
Structures.Constant.appDelegate.userSignUpDetail.lastName = textField.text
}
else if identity == "Phone"
{
if !Utility.isValidPhone(textField.text!)
{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("please_enter_valid_phone"),comment:"")
}
Structures.Constant.appDelegate.userSignUpDetail.phone = textField.text
}
else if identity == "Please describe"
{
if Structures.Constant.appDelegate.userSignUpDetail.gender_type == "3"
{
Structures.Constant.appDelegate.userSignUpDetail.gender = textField.text
}
}
else if identity == "Password"
{
if textField.text!.characters.count > 0
{
password1 = ""
if arrPassword1.count > 0
{
for(var i : Int = 0; i < arrPassword1.count; i++)
{
password1.appendString(arrPassword1.objectAtIndex(i) as! String)
}
}
if !Utility.isValidPassword(password1 as String, strUserName: Structures.Constant.appDelegate.userSignUpDetail.userName as String)//(password1 as String)
{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.showPasswordAlert()
textField.text = nil
textField.resignFirstResponder()
self.view.endEditing(true)
})
return false
}
Structures.Constant.appDelegate.userSignUpDetail.password = password1
}
}
else if identity == "Re-enterPassword"
{
password2 = ""
if arrPassword2.count > 0
{
for(var i : Int = 0; i < arrPassword2.count; i++)
{
password2.appendString((arrPassword2.objectAtIndex(i) as! String) as String)
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if isEndEditing{
self.view.endEditing(true);
let newContentOffset : CGPoint = CGPointMake(0, self.tableView.contentSize.height-self.tableView.frame.height)
self.tableView.setContentOffset(newContentOffset, animated: true)
}
})
if password2.length > 1
{
if (password2 != Structures.Constant.appDelegate.userSignUpDetail.password)
{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("please_enter_valid_phone"),comment:"")
strButtonText = NSLocalizedString(Utility.getKey("try_again"),comment:"")
self.password2 = ""
self.arrPassword2 = NSMutableArray()
}
}
}
else if identity == "Affiliation"
{
Structures.Constant.appDelegate.userSignUpDetail.affiliation = textField.text
}
if isValidInfo == false {
Utility.showAlertWithTitle(strTitle, strMessage: "", strButtonTitle: strButtonText, view: self)
textField.text = nil
textField.resignFirstResponder()
self.view.endEditing(true)
return isValidInfo
}
return true
}
func validateUser() -> Bool{
var isValidInfo : Bool = true
var strTitle : String = ""
if Structures.Constant.appDelegate.userSignUpDetail.userName.length == 0{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("please_enter_username"),comment:"")
}else if Structures.Constant.appDelegate.userSignUpDetail.email.length == 0{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("please_enter_email"),comment:"")
}
else if Structures.Constant.appDelegate.userSignUpDetail.email != emailRe {
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("Email_notmatch"),comment:"")
}else if Structures.Constant.appDelegate.userSignUpDetail.firstName.length == 0{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("please_enter_firstname"),comment:"")
}else if Structures.Constant.appDelegate.userSignUpDetail.lastName.length == 0{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("please_enter_lastname"),comment:"")
}else if Structures.Constant.appDelegate.userSignUpDetail.phone.length == 0{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("please_enter_phone_no"),comment:"")
}
else if Structures.Constant.appDelegate.userSignUpDetail.gender == ""{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("select_Gender"),comment:"")
}
else if Structures.Constant.appDelegate.userSignUpDetail.jobTitle.length == 0{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("please_select_job_title"),comment:"")
}else if Structures.Constant.appDelegate.userSignUpDetail.origin.length == 0{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("please_select_country_of_origin"),comment:"")
}else if Structures.Constant.appDelegate.userSignUpDetail.working.length == 0{
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("please_select_country_of_working"),comment:"")
}else if password2 != Structures.Constant.appDelegate.userSignUpDetail.password {
password2 = ""
arrPassword2 = NSMutableArray()
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("Password_notmatch"),comment:"")
}
else if Structures.Constant.appDelegate.userSignUpDetail.password.length == 0 {
isValidInfo = false
strTitle = NSLocalizedString(Utility.getKey("please_enter_password"),comment:"")
}
if isValidInfo == false {
Utility.showAlertWithTitle(strTitle, strMessage: "", strButtonTitle: NSLocalizedString(Utility.getKey("Ok"),comment:""), view: self)
return isValidInfo
}
return true
}
func registerUser(){
var validUser : Bool = false
validUser = validateUser()
if validUser == false
{
return
}
SVProgressHUD.showWithStatus(NSLocalizedString(Utility.getKey("please_wait"),comment:""), maskType: 4)
User.checkUsernameEmail(NSMutableDictionary(dictionary:User.dictToCheckUsernameEmail(Structures.Constant.appDelegate.userSignUpDetail.userName, email: Structures.Constant.appDelegate.userSignUpDetail.email)))
User.sharedInstance.delegate = self
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "CreateContactListPush"
{
let vc : Step2_CreateAccountVC = segue.destinationViewController as! Step2_CreateAccountVC
vc.isEditContactList = false
Structures.Constant.appDelegate.contactScreensFrom = ContactsFrom.CreateAccount
vc.circle = Circle(name:"Private", type:.Private,contactList:[]);
}
}
func changeValueInMainCheckInArray(newValue : NSString, identity : NSString){
for (index, element) in self.createAccntArr.enumerate() {
if var innerDict = element as? Dictionary<String, AnyObject> {
let iden = innerDict["Identity"] as! NSString!
if iden == identity{
innerDict["Value"] = newValue
if iden == "SelectedLanguage" || iden == "SelectedJobTitle" || iden == "CountryOfOrigin" || iden == "CountryWhereWorking"{
innerDict["Title"] = newValue
}
if iden == "Affiliation"{
innerDict["Title"] = newValue
innerDict["value"] = newValue
innerDict["OptionTitle"] = NSLocalizedString(Utility.getKey("Update"),comment:"")
}
self.createAccntArr.replaceObjectAtIndex(index, withObject: innerDict)
self.tableView.reloadData()
break
}
}
}
}
//MARK:- Start TableView Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.createAccntArr.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if self.createAccntArr[indexPath.row]["CellIdentifier"] as? NSString == Structures.TableViewCellIdentifiers.HelpTextViewCellIdentifier
{
let cell: HelpTextViewCell = tableView.dequeueReusableCellWithIdentifier(Structures.TableViewCellIdentifiers.HelpTextViewCellIdentifier) as! HelpTextViewCell!
cell.txtHelpTextView.frame = CGRectMake(cell.txtHelpTextView.frame.origin.x, cell.txtHelpTextView.frame.origin.y, tableView.frame.size.width - 60, cell.txtHelpTextView.frame.size.height)
cell.txtHelpTextView.attributedText = CommonUnit.boldSubstring(NSLocalizedString(Utility.getKey("about_reporta_p0assword1"),comment:"") , string: NSLocalizedString(Utility.getKey("about_reporta_password1"),comment:"") + "\n\n" + NSLocalizedString(Utility.getKey("about_reporta_password2"),comment:""), fontName: cell.txtHelpTextView.font)
cell.txtHelpTextView.sizeToFit()
return cell.txtHelpTextView.frame.size.height + 70
}
let kRowHeight = self.createAccntArr[indexPath.row]["RowHeight"] as! CGFloat
return kRowHeight;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let kCellIdentifier = self.createAccntArr[indexPath.row]["CellIdentifier"] as! String
if Structures.Constant.appDelegate.isArabic == true && kCellIdentifier == "TitleTableViewCellIdentifier"
{
if let cell: ARTitleTableViewCell = tableView.dequeueReusableCellWithIdentifier("ARTitleTableViewCellIdentifier") as? ARTitleTableViewCell
{
cell.lblDetail.text = self.createAccntArr[indexPath.row]["OptionTitle"] as! String!
cell.levelString = self.createAccntArr[indexPath.row]["Level"] as! String!
cell.lblTitle.text = self.createAccntArr[indexPath.row]["Title"] as! String!
if self.createAccntArr[indexPath.row]["Identity"] as! NSString == "Version"
{
cell.lblDetail.textColor = UIColor.blackColor()
}
cell.intialize()
return cell
}
}
else
{
if let cell: TitleTableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? TitleTableViewCell
{
cell.lblDetail.text = self.createAccntArr[indexPath.row]["OptionTitle"] as! String!
cell.levelString = self.createAccntArr[indexPath.row]["Level"] as! String!
cell.lblTitle.text = self.createAccntArr[indexPath.row]["Title"] as! String!
if self.createAccntArr[indexPath.row]["Identity"] as! NSString == "Version"
{
cell.lblDetail.textColor = UIColor.blackColor()
}
cell.intialize()
return cell
}
}
if let cell: TitleTableViewCell2 = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? TitleTableViewCell2
{
cell.levelString = self.createAccntArr[indexPath.row]["Level"] as! String!
cell.lblTitle.text = self.createAccntArr[indexPath.row]["Title"] as! String!
if Structures.Constant.appDelegate.isArabic == true
{
cell.lblTitle.textAlignment = NSTextAlignment.Right
}
else
{
cell.lblTitle.textAlignment = NSTextAlignment.Left
}
cell.intialize()
return cell
}
if Structures.Constant.appDelegate.isArabic == true && kCellIdentifier == "DetailTableViewCellIdentifier"
{
if let cell: ARDetailTableViewCell = tableView.dequeueReusableCellWithIdentifier("ARDetailTableViewCellIdentifier") as? ARDetailTableViewCell
{
cell.lblSubDetail.text = self.createAccntArr[indexPath.row]["OptionTitle"] as! String!
cell.levelString = self.createAccntArr[indexPath.row]["Level"] as! String!
cell.lblDetail.text = self.createAccntArr[indexPath.row]["Title"] as! String!
cell.isSelectedValue = self.createAccntArr[indexPath.row]["IsSelected"] as! Bool!
cell.type = self.createAccntArr[indexPath.row]["Type"] as! Int!
cell.identity = self.createAccntArr[indexPath.row]["Identity"] as! String!
cell.intialize()
if cell.isSelectedValue == true
{
cell.ivRight.image = UIImage(named:"ok.png")!
}
return cell
}
}
else
{
if let cell: DetailTableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? DetailTableViewCell
{
cell.lblSubDetail.text = self.createAccntArr[indexPath.row]["OptionTitle"] as! String!
cell.levelString = self.createAccntArr[indexPath.row]["Level"] as! NSString!
cell.lblDetail.text = self.createAccntArr[indexPath.row]["Title"] as! String!
cell.isSelectedValue = self.createAccntArr[indexPath.row]["IsSelected"] as! Bool!
cell.type = self.createAccntArr[indexPath.row]["Type"] as! Int!
cell.identity = self.createAccntArr[indexPath.row]["Identity"] as! String!
cell.intialize()
if cell.isSelectedValue == true
{
cell.ivRight.image = UIImage(named:"ok.png")!
}
return cell
}
}
if Structures.Constant.appDelegate.isArabic == true && kCellIdentifier == "LocationListingCellIdentifier"
{
if let cell: ARLocationListingCell = tableView.dequeueReusableCellWithIdentifier(Structures.TableViewCellIdentifiers.ARLocationListingCellIdentifier) as? ARLocationListingCell
{
cell.value = self.createAccntArr[indexPath.row]["Value"] as! NSString!
cell.detail = self.createAccntArr[indexPath.row]["OptionTitle"] as! String!
cell.title = self.createAccntArr[indexPath.row]["Title"] as! String!
cell.intialize()
return cell
}
}
else
{
if let cell: LocationListingCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? LocationListingCell {
cell.value = self.createAccntArr[indexPath.row]["Value"] as! NSString!
cell.detail = self.createAccntArr[indexPath.row]["OptionTitle"] as! String!
cell.title = self.createAccntArr[indexPath.row]["Title"] as! String!
cell.intialize()
return cell
}
}
if Structures.Constant.appDelegate.isArabic == true && kCellIdentifier == "FreelancerCellIndentifier"
{
if let cell: ARFreelancerTableViewCell = tableView.dequeueReusableCellWithIdentifier(Structures.TableViewCellIdentifiers.ARFreelancerTableViewCellIdentifier) as? ARFreelancerTableViewCell {
cell.isSelectedValue = self.freelancer
cell.initialize()
if isFromProfile == true
{
cell.userInteractionEnabled = false
}
else
{
cell.delegate = self
}
return cell
}
}
else
{
if let cell: FreelancerTableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? FreelancerTableViewCell
{
cell.isSelectedValue = self.freelancer
cell.initialize()
if isFromProfile == true
{
cell.userInteractionEnabled = false
}
else
{
cell.delegate = self
}
return cell
}
}
if Structures.Constant.appDelegate.isArabic == true && kCellIdentifier == "PersonalDetailCellIdentifier"
{
if let cell: ARPersonalDetailsTableViewCell = tableView.dequeueReusableCellWithIdentifier("ARPersonalDetailsTableViewCellIndetifier") as? ARPersonalDetailsTableViewCell {
cell.detailstextField.placeholder = self.createAccntArr[indexPath.row]["Placeholder"] as! String!
cell.detailstextField.accessibilityIdentifier = self.createAccntArr[indexPath.row]["Identity"] as! String!
cell.identity = self.createAccntArr[indexPath.row]["Identity"] as! NSString!
cell.lblDetail.text = self.createAccntArr[indexPath.row]["OptionTitle"] as! String!
cell.levelString = self.createAccntArr[indexPath.row]["Level"] as! NSString!
cell.delegate = self
if isFromProfile == true
{
cell.userInteractionEnabled = false
}
if self.selectType == 1
{
cell.indexPath = indexPath
if cell.identity == "Username" {
cell.value = Structures.Constant.appDelegate.userSignUpDetail.userName as String
}else if cell.identity == "Email" {
cell.value = Structures.Constant.appDelegate.userSignUpDetail.email as String
}else if cell.identity == "ReEnterEmail"{
cell.value = self.emailRe as String
}else if cell.identity == "Firstname"{
cell.value = Structures.Constant.appDelegate.userSignUpDetail.firstName as String
}else if cell.identity == "Lastname"{
cell.value = Structures.Constant.appDelegate.userSignUpDetail.lastName as String
}else if cell.identity == "Phone"{
cell.value = Structures.Constant.appDelegate.userSignUpDetail.phone as String
}else if cell.identity == "Password"{
cell.value = Structures.Constant.appDelegate.userSignUpDetail.password as String
}else if cell.identity == "Re-enterPassword"{
cell.value = password2 as String
}else if cell.identity == "Please describe"{
if Structures.Constant.appDelegate.userSignUpDetail.gender_type == "3"
{
cell.userInteractionEnabled = true
cell.value = Structures.Constant.appDelegate.userSignUpDetail.gender as String
}
else
{
cell.userInteractionEnabled = false
}
}
else if cell.identity == "Affiliation"{
if isFromProfile == true
{
cell.detailstextField.textColor = UIColor.grayColor()
}
cell.value = Structures.Constant.appDelegate.userSignUpDetail.affiliation as String
}
}
cell.initialize()
return cell
}
}
else
{
if let cell: PersonalDetailsTableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? PersonalDetailsTableViewCell {
cell.detailstextField.placeholder = self.createAccntArr[indexPath.row]["Placeholder"] as! String!
cell.detailstextField.accessibilityIdentifier = self.createAccntArr[indexPath.row]["Identity"] as! String!
cell.identity = self.createAccntArr[indexPath.row]["Identity"] as! NSString!
cell.lblDetail.text = self.createAccntArr[indexPath.row]["OptionTitle"] as! String!
cell.levelString = self.createAccntArr[indexPath.row]["Level"] as! NSString!
cell.delegate = self
if isFromProfile == true
{
cell.userInteractionEnabled = false
}
if self.selectType == 1
{
cell.indexPath = indexPath
if cell.identity == "Username" {
cell.value = Structures.Constant.appDelegate.userSignUpDetail.userName as String
}else if cell.identity == "Email" {
cell.value = Structures.Constant.appDelegate.userSignUpDetail.email as String
}else if cell.identity == "ReEnterEmail"{
cell.value = emailRe as String
}else if cell.identity == "Firstname"{
cell.value = Structures.Constant.appDelegate.userSignUpDetail.firstName as String
}else if cell.identity == "Lastname"{
cell.value = Structures.Constant.appDelegate.userSignUpDetail.lastName as String
}else if cell.identity == "Phone"{
cell.value = Structures.Constant.appDelegate.userSignUpDetail.phone as String
}else if cell.identity == "Password"{
cell.value = Structures.Constant.appDelegate.userSignUpDetail.password as String
}else if cell.identity == "Re-enterPassword"{
cell.value = password2 as String
}else if cell.identity == "Please describe"{
if Structures.Constant.appDelegate.userSignUpDetail.gender_type == "3"
{
cell.userInteractionEnabled = true
cell.value = Structures.Constant.appDelegate.userSignUpDetail.gender as String
}
else
{
cell.userInteractionEnabled = false
}
}
else if cell.identity == "Affiliation"{
cell.value = Structures.Constant.appDelegate.userSignUpDetail.affiliation as String
}
}
cell.initialize()
return cell
}
}
if let cell: HelpTextViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? HelpTextViewCell
{
cell.txtHelpTextView.attributedText = CommonUnit.boldSubstring(NSLocalizedString(Utility.getKey("about_reporta_password1"),comment:"") , string: NSLocalizedString(Utility.getKey("about_reporta_password1"),comment:"") + "\n\n" + NSLocalizedString(Utility.getKey("about_reporta_password2"),comment:""), fontName: cell.txtHelpTextView.font)
if Structures.Constant.appDelegate.isArabic == true
{
cell.txtHelpTextView.textAlignment = NSTextAlignment.Right
}
else
{
cell.txtHelpTextView.textAlignment = NSTextAlignment.Left
}
return cell
}
let blankCell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier)!
return blankCell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if self.createAccntArr[indexPath.row]["Method"] as! NSString! == "selectJobTitle"{
selectJobTitle(self.createAccntArr[indexPath.row]["Title"] as! String)
}
if self.createAccntArr[indexPath.row]["Method"] as! NSString! == "selectCountryOfOrigin"{
selectCountryOfOrigin(self.createAccntArr[indexPath.row]["Title"] as! String, code: Structures.Constant.appDelegate.userSignUpDetail.origin as String)
}
if self.createAccntArr[indexPath.row]["Method"] as! NSString! == "selectCountryOfWorking"{
selectCountryOfWorking(self.createAccntArr[indexPath.row]["Title"] as! String, code: Structures.Constant.appDelegate.userSignUpDetail.working as String)
}
if self.createAccntArr[indexPath.row]["Method"] as! NSString! == "addAffiliation"{
}
if self.createAccntArr[indexPath.row]["Method"] as! NSString! == "editContactDetail"{
editContactDetail()
}
if self.createAccntArr[indexPath.row]["Method"] as! NSString! == "signOutUser"
{
self.signOut()
}
if self.createAccntArr[indexPath.row]["Method"] as! NSString! == "selectGender"{
updateGender(indexPath)
}
if self.createAccntArr[indexPath.row]["Method"] as! NSString! == "showLegal"{
showLegalClicked()
}
}
//MARK:- End
func selectJobTitle(text : String!){
let selectLanguageScreen : SelectLanguageViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SelectLanguageViewController") as! SelectLanguageViewController
selectLanguageScreen.delegate = self
selectLanguageScreen.selectedText = text
selectLanguageScreen.selectType = 1
selectLanguageScreen.isFromProfile = 0
showViewController(selectLanguageScreen, sender: self.view)
}
func selectCountryOfOrigin(text : String!, code : String!){
let selectLanguageScreen : SelectLanguageViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SelectLanguageViewController") as! SelectLanguageViewController
selectLanguageScreen.delegate = self
selectLanguageScreen.selectedText = text
selectLanguageScreen.selectedCode = code
selectLanguageScreen.selectType = 2
selectLanguageScreen.isFromProfile = 0
showViewController(selectLanguageScreen, sender: self.view)
}
func selectCountryOfWorking(text : String!, code : String!){
let selectLanguageScreen : SelectLanguageViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SelectLanguageViewController") as! SelectLanguageViewController
selectLanguageScreen.delegate = self
selectLanguageScreen.selectedText = text
selectLanguageScreen.selectedCode = code
selectLanguageScreen.selectType = 3
selectLanguageScreen.isFromProfile = 0
showViewController(selectLanguageScreen, sender: self.view)
}
func editContactDetail(){
let editProfile : EditProfileViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("EditProfileViewController") as! EditProfileViewController
showViewController(editProfile, sender: self.view)
}
func showLegalClicked() {
let agreetermsScreen : AgreeTermsViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("AgreeTermsViewController") as! AgreeTermsViewController
agreetermsScreen.type = 1;
showViewController(agreetermsScreen, sender: self.view)
}
func updateGender(index: AnyObject)
{
let myindexPath : NSIndexPath = index as! NSIndexPath
let dict1 : NSMutableDictionary = createAccntArr.objectAtIndex(myindexPath.row).mutableCopy() as! NSMutableDictionary
if myindexPath.row == 10
{
dict1.setObject(1, forKey: "IsSelected")
Structures.Constant.appDelegate.userSignUpDetail.gender = createAccntArr.objectAtIndex(myindexPath.row).valueForKey("Title") as! NSString
Structures.Constant.appDelegate.userSignUpDetail.gender_type = "1"
let dict2 : NSMutableDictionary = createAccntArr.objectAtIndex(11).mutableCopy() as! NSMutableDictionary
let dict3 : NSMutableDictionary = createAccntArr.objectAtIndex(12).mutableCopy() as! NSMutableDictionary
dict2.setObject(0, forKey: "IsSelected")
dict3.setObject(0, forKey: "IsSelected")
createAccntArr.replaceObjectAtIndex(10, withObject: dict1)
createAccntArr.replaceObjectAtIndex(11, withObject: dict2)
createAccntArr.replaceObjectAtIndex(12, withObject: dict3)
}
else if myindexPath.row == 11
{
dict1.setObject(1, forKey: "IsSelected")
Structures.Constant.appDelegate.userSignUpDetail.gender = createAccntArr.objectAtIndex(myindexPath.row).valueForKey("Title") as! NSString
Structures.Constant.appDelegate.userSignUpDetail.gender_type = "2"
let dict2 : NSMutableDictionary = createAccntArr.objectAtIndex(10).mutableCopy() as! NSMutableDictionary
let dict3 : NSMutableDictionary = createAccntArr.objectAtIndex(12).mutableCopy() as! NSMutableDictionary
dict2.setObject(0, forKey: "IsSelected")
dict3.setObject(0, forKey: "IsSelected")
createAccntArr.replaceObjectAtIndex(10, withObject: dict2)
createAccntArr.replaceObjectAtIndex(11, withObject: dict1)
createAccntArr.replaceObjectAtIndex(12, withObject: dict3)
}
else if myindexPath.row == 12
{
dict1.setObject(1, forKey: "IsSelected")
Structures.Constant.appDelegate.userSignUpDetail.gender = createAccntArr.objectAtIndex(myindexPath.row + 1).valueForKey("Title") as! NSString
Structures.Constant.appDelegate.userSignUpDetail.gender_type = "3"
let dict2 : NSMutableDictionary = createAccntArr.objectAtIndex(10).mutableCopy() as! NSMutableDictionary
let dict3 : NSMutableDictionary = createAccntArr.objectAtIndex(11).mutableCopy() as! NSMutableDictionary
dict2.setObject(0, forKey: "IsSelected")
dict3.setObject(0, forKey: "IsSelected")
createAccntArr.replaceObjectAtIndex(10, withObject: dict2)
createAccntArr.replaceObjectAtIndex(11, withObject: dict3)
createAccntArr.replaceObjectAtIndex(12, withObject: dict1)
}
self.tableView.reloadData()
}
func signOut(){
SVProgressHUD.showWithStatus(NSLocalizedString(Utility.getKey("logging_out"),comment:""), maskType: 4)
User.signOutUser(NSMutableDictionary(dictionary:User.dictForSignOut()))
User.sharedInstance.delegate = self
}
//MARK:- Custom Alert Delegate Methods
func showPasswordAlert()
{
let alertView = CustomAlertView()
alertView.containerView = Utility.createContainerView(NSLocalizedString(Utility.getKey("password_alert_message"),comment:"") as String, titelText: NSLocalizedString(Utility.getKey("password_alert_title"),comment:"") as String, isArabic: Structures.Constant.appDelegate.isArabic)
alertView.delegate = self
alertView.buttonTitles = [
NSLocalizedString(Utility.getKey("Ok"),comment:"")
]
alertView.onButtonTouchUpInside = { (alertView: CustomAlertView, buttonIndex: Int) -> Void in
}
alertView.show()
}
func customAlertViewButtonTouchUpInside(alertView: CustomAlertView, buttonIndex: Int) {
alertView.close()
}
}
| gpl-3.0 | 246982e00209d6e7924668177059d9cb | 47.848291 | 351 | 0.592829 | 5.556879 | false | false | false | false |
ioscreator/ioscreator | IOSAirdropTutorial/IOSAirdropTutorial/ViewController.swift | 1 | 893 | //
// ViewController.swift
// IOSAirdropTutorial
//
// Created by Arthur Knopper on 31/10/2018.
// Copyright © 2018 Arthur Knopper. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBAction func shareImage(_ sender: Any) {
let image = imageView.image!
let controller = UIActivityViewController(activityItems: [image], applicationActivities: nil)
controller.excludedActivityTypes = [.postToFacebook, .postToTwitter, .print, .copyToPasteboard,
.assignToContact, .saveToCameraRoll, .mail]
self.present(controller, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
let image = UIImage(named:"imac.jpg")
imageView.image = image
}
}
| mit | 9a606b344c58c54e6ab5e83e8f7ef283 | 26.875 | 103 | 0.639013 | 4.955556 | false | false | false | false |
nsagora/validation-toolkit | Sources/Predicates/Standard/EmailPredicate.swift | 1 | 2129 | import Foundation
/**
The `EmailPredicate` struct is used to evaluate whether a given input is a syntactically valid email address, based on the RFC 5322 official standard.
```swift
let predicate = EmailPredicate()
let isEmail = predicate.evaluate(with: "[email protected]")
```
*/
public struct EmailPredicate: Predicate {
public typealias InputType = String
private let rule: RegexPredicate
private let regex = "^(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}" +
"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" +
"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-" +
"z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5" +
"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-" +
"9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" +
"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$"
/**
Returns a new `EmailPredicate` instance.
```swift
let predicate = EmailPredicate()
let isEmail = predicate.evaluate(with: "[email protected]")
```
*/
public init() {
rule = RegexPredicate(expression: regex)
}
/**
Returns a `Boolean` value that indicates whether a given email is a syntactically valid, according to the RFC 5322 official standard.
- parameter input: The input against which to evaluate the receiver.
- returns: `true` if input is a syntactically valid email, according to the RFC 5322 standard, otherwise `false`.
*/
public func evaluate(with input: InputType) -> Bool {
return rule.evaluate(with: input)
}
}
// MARK: - Dynamic Lookup Extension
extension Predicate where Self == EmailPredicate {
/**
Returns a new `EmailPredicate` instance.
```swift
let predicate: EmailPredicate = .email
let isEmail = predicate.evaluate(with: "[email protected]")
```
*/
public static var email: Self {
EmailPredicate()
}
}
| mit | 739f27d2b6dbc77d7cf98863a99a9b0e | 32.793651 | 151 | 0.556599 | 3.225758 | false | false | false | false |
xwu/swift | test/Generics/conditional_requirement_inference.swift | 4 | 1917 | // RUN: %target-typecheck-verify-swift -requirement-machine=on
// RUN: not %target-swift-frontend -typecheck -debug-generic-signatures -requirement-machine=on %s 2>&1 | %FileCheck %s
// Valid example
struct EquatableBox<T : Equatable> {
// CHECK: Generic signature: <T, U where T == Array<U>, U : Equatable>
func withArray<U>(_: U) where T == Array<U> {}
}
// A very elaborate invalid example (see comment in mergeP1AndP2())
struct G<T> {}
protocol P {}
extension G : P where T : P {}
protocol P1 {
associatedtype T
associatedtype U where U == G<T>
associatedtype R : P1
}
protocol P2 {
associatedtype U : P
associatedtype R : P2
}
func takesP<T : P>(_: T.Type) {}
// expected-note@-1 {{where 'T' = 'T.T'}}
// expected-note@-2 {{where 'T' = 'T.R.T'}}
// expected-note@-3 {{where 'T' = 'T.R.R.T'}}
// expected-note@-4 {{where 'T' = 'T.R.R.R.T'}}
// CHECK: Generic signature: <T where T : P1, T : P2>
func mergeP1AndP2<T : P1 & P2>(_: T) {
// P1 implies that T.(R)*.U == G<T.(R)*.T>, and P2 implies that T.(R)*.U : P.
//
// These together would seem to imply that G<T.(R)*.T> : P, therefore
// the conditional conformance G : P should imply that T.(R)*.T : P.
//
// However, this would require us to infer an infinite number of
// conformance requirements in the signature of mergeP1AndP2() of the
// form T.(R)*.T : P.
//
// Since we're unable to represent that, make sure that a) we don't crash,
// b) we reject the conformance T.(R)*.T : P.
takesP(T.T.self) // expected-error {{global function 'takesP' requires that 'T.T' conform to 'P'}}
takesP(T.R.T.self) // expected-error {{global function 'takesP' requires that 'T.R.T' conform to 'P'}}
takesP(T.R.R.T.self) // expected-error {{global function 'takesP' requires that 'T.R.R.T' conform to 'P'}}
takesP(T.R.R.R.T.self) // expected-error {{global function 'takesP' requires that 'T.R.R.R.T' conform to 'P'}}
} | apache-2.0 | ba3522dd46d93fb83f19ab0845cf78fc | 35.188679 | 119 | 0.637976 | 2.9447 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/FRP/ReactiveSwift/Property.swift | 2 | 33260 | #if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
import Darwin.POSIX.pthread
#else
import Glibc
#endif
// FIXME: The `Error == Never` constraint is retained for Swift 4.0.x
// compatibility, since `BindingSource` did not impose such constraint
// due to the absence of conditional conformance.
/// Represents a property that allows observation of its changes.
///
/// Only classes can conform to this protocol, because having a signal
/// for changes over time implies the origin must have a unique identity.
public protocol PropertyProtocol: class, BindingSource {
/// The current value of the property.
var value: Value { get }
/// The values producer of the property.
///
/// It produces a signal that sends the property's current value,
/// followed by all changes over time. It completes when the property
/// has deinitialized, or has no further change.
///
/// - note: If `self` is a composed property, the producer would be
/// bound to the lifetime of its sources.
var producer: SignalProducer<Value, Never> { get }
/// A signal that will send the property's changes over time. It
/// completes when the property has deinitialized, or has no further
/// change.
///
/// - note: If `self` is a composed property, the signal would be
/// bound to the lifetime of its sources.
var signal: Signal<Value, Never> { get }
}
/// Represents an observable property that can be mutated directly.
public protocol MutablePropertyProtocol: PropertyProtocol, BindingTargetProvider {
/// The current value of the property.
var value: Value { get set }
/// The lifetime of the property.
var lifetime: Lifetime { get }
}
/// Default implementation of `BindingTargetProvider` for mutable properties.
extension MutablePropertyProtocol {
public var bindingTarget: BindingTarget<Value> {
return BindingTarget(lifetime: lifetime) { [weak self] in self?.value = $0 }
}
}
/// Represents a mutable property that can be safety composed by exposing its
/// synchronization mechanic through the defined closure-based interface.
public protocol ComposableMutablePropertyProtocol: MutablePropertyProtocol {
/// Atomically performs an arbitrary action using the current value of the
/// variable.
///
/// - parameters:
/// - action: A closure that accepts current property value.
///
/// - returns: the result of the action.
func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result
/// Atomically modifies the variable.
///
/// - parameters:
/// - action: A closure that accepts old property value and returns a new
/// property value.
///
/// - returns: The result of the action.
func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result
}
// Property operators.
//
// A composed property is a transformed view of its sources, and does not
// own its lifetime. Its producer and signal are bound to the lifetime of
// its sources.
extension PropertyProtocol {
/// Lifts a unary SignalProducer operator to operate upon PropertyProtocol instead.
fileprivate func lift<U>(_ transform: @escaping (SignalProducer<Value, Never>) -> SignalProducer<U, Never>) -> Property<U> {
return Property(unsafeProducer: transform(producer))
}
/// Lifts a binary SignalProducer operator to operate upon PropertyProtocol instead.
fileprivate func lift<P: PropertyProtocol, U>(_ transform: @escaping (SignalProducer<Value, Never>) -> (SignalProducer<P.Value, Never>) -> SignalProducer<U, Never>) -> (P) -> Property<U> {
return { other in
return Property(unsafeProducer: transform(self.producer)(other.producer))
}
}
}
extension PropertyProtocol {
/// Maps the current value and all subsequent values to a new property.
///
/// - parameters:
/// - transform: A closure that will map the current `value` of this
/// `Property` to a new value.
///
/// - returns: A property that holds a mapped value from `self`.
public func map<U>(_ transform: @escaping (Value) -> U) -> Property<U> {
return lift { $0.map(transform) }
}
/// Map the current value and all susequent values to a new constant property.
///
/// - parameters:
/// - value: A new value.
///
/// - returns: A property that holds a mapped value from `self`.
public func map<U>(value: U) -> Property<U> {
return lift { $0.map(value: value) }
}
/// Maps the current value and all subsequent values to a new property
/// by applying a key path.
///
/// - parameters:
/// - keyPath: A key path relative to the property's `Value` type.
///
/// - returns: A property that holds a mapped value from `self`.
public func map<U>(_ keyPath: KeyPath<Value, U>) -> Property<U> {
return lift { $0.map(keyPath) }
}
/// Passes only the values of the property that pass the given predicate
/// to a new property.
///
/// - parameters:
/// - initial: A `Property` always needs a `value`. The initial `value` is necessary in case the
/// predicate excludes the first (or all) `value`s of this `Property`
/// - predicate: A closure that accepts value and returns `Bool` denoting
/// whether current `value` of this `Property` has passed the test.
///
/// - returns: A property that holds only values from `self` passing the given predicate.
public func filter(initial: Value, _ predicate: @escaping (Value) -> Bool) -> Property<Value> {
return Property(initial: initial, then: self.producer.filter(predicate))
}
/// Combines the current value and the subsequent values of two `Property`s in
/// the manner described by `Signal.combineLatest(with:)`.
///
/// - parameters:
/// - other: A property to combine `self`'s value with.
///
/// - returns: A property that holds a tuple containing values of `self` and
/// the given property.
public func combineLatest<P: PropertyProtocol>(with other: P) -> Property<(Value, P.Value)> {
return Property.combineLatest(self, other)
}
/// Zips the current value and the subsequent values of two `Property`s in
/// the manner described by `Signal.zipWith`.
///
/// - parameters:
/// - other: A property to zip `self`'s value with.
///
/// - returns: A property that holds a tuple containing values of `self` and
/// the given property.
public func zip<P: PropertyProtocol>(with other: P) -> Property<(Value, P.Value)> {
return Property.zip(self, other)
}
/// Forward events from `self` with history: values of the returned property
/// are a tuple whose first member is the previous value and whose second
/// member is the current value. `initial` is supplied as the first member
/// when `self` sends its first value.
///
/// - parameters:
/// - initial: A value that will be combined with the first value sent by
/// `self`.
///
/// - returns: A property that holds tuples that contain previous and
/// current values of `self`.
public func combinePrevious(_ initial: Value) -> Property<(Value, Value)> {
return lift { $0.combinePrevious(initial) }
}
/// Forward only values from `self` that are not considered equivalent to its
/// consecutive predecessor.
///
/// - note: The first value is always forwarded.
///
/// - parameters:
/// - isEquivalent: A closure to determine whether two values are equivalent.
///
/// - returns: A property which conditionally forwards values from `self`.
public func skipRepeats(_ isEquivalent: @escaping (Value, Value) -> Bool) -> Property<Value> {
return lift { $0.skipRepeats(isEquivalent) }
}
}
extension PropertyProtocol where Value: Equatable {
/// Forward only values from `self` that are not equal to its consecutive predecessor.
///
/// - note: The first value is always forwarded.
///
/// - returns: A property which conditionally forwards values from `self`.
public func skipRepeats() -> Property<Value> {
return lift { $0.skipRepeats() }
}
}
extension PropertyProtocol where Value: PropertyProtocol {
/// Flattens the inner property held by `self` (into a single property of
/// values), according to the semantics of the given strategy.
///
/// - parameters:
/// - strategy: The preferred flatten strategy.
///
/// - returns: A property that sends the values of its inner properties.
public func flatten(_ strategy: FlattenStrategy) -> Property<Value.Value> {
return lift { $0.flatMap(strategy) { $0.producer } }
}
}
extension PropertyProtocol {
/// Maps each property from `self` to a new property, then flattens the
/// resulting properties (into a single property), according to the
/// semantics of the given strategy.
///
/// - parameters:
/// - strategy: The preferred flatten strategy.
/// - transform: The transform to be applied on `self` before flattening.
///
/// - returns: A property that sends the values of its inner properties.
public func flatMap<P: PropertyProtocol>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> P) -> Property<P.Value> {
return lift { $0.flatMap(strategy) { transform($0).producer } }
}
/// Forward only those values from `self` that have unique identities across
/// the set of all values that have been held.
///
/// - note: This causes the identities to be retained to check for
/// uniqueness.
///
/// - parameters:
/// - transform: A closure that accepts a value and returns identity
/// value.
///
/// - returns: A property that sends unique values during its lifetime.
public func uniqueValues<Identity: Hashable>(_ transform: @escaping (Value) -> Identity) -> Property<Value> {
return lift { $0.uniqueValues(transform) }
}
}
extension PropertyProtocol where Value: Hashable {
/// Forwards only those values from `self` that are unique across the set of
/// all values that have been seen.
///
/// - note: This causes the identities to be retained to check for uniqueness.
/// Providing a function that returns a unique value for each sent
/// value can help you reduce the memory footprint.
///
/// - returns: A property that sends unique values during its lifetime.
public func uniqueValues() -> Property<Value> {
return lift { $0.uniqueValues() }
}
}
extension PropertyProtocol {
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol>(_ a: A, _ b: B) -> Property<(A.Value, B.Value)> where A.Value == Value {
return a.lift { SignalProducer.combineLatest($0, b) }
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol>(_ a: A, _ b: B, _ c: C) -> Property<(Value, B.Value, C.Value)> where A.Value == Value {
return a.lift { SignalProducer.combineLatest($0, b, c) }
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D) -> Property<(Value, B.Value, C.Value, D.Value)> where A.Value == Value {
return a.lift { SignalProducer.combineLatest($0, b, c, d) }
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E) -> Property<(Value, B.Value, C.Value, D.Value, E.Value)> where A.Value == Value {
return a.lift { SignalProducer.combineLatest($0, b, c, d, e) }
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F) -> Property<(Value, B.Value, C.Value, D.Value, E.Value, F.Value)> where A.Value == Value {
return a.lift { SignalProducer.combineLatest($0, b, c, d, e, f) }
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) -> Property<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value)> where A.Value == Value {
return a.lift { SignalProducer.combineLatest($0, b, c, d, e, f, g) }
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol, H: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H) -> Property<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value)> where A.Value == Value {
return a.lift { SignalProducer.combineLatest($0, b, c, d, e, f, g, h) }
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol, H: PropertyProtocol, I: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I) -> Property<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value)> where A.Value == Value {
return a.lift { SignalProducer.combineLatest($0, b, c, d, e, f, g, h, i) }
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol, H: PropertyProtocol, I: PropertyProtocol, J: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J) -> Property<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value, J.Value)> where A.Value == Value {
return a.lift { SignalProducer.combineLatest($0, b, c, d, e, f, g, h, i, j) }
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`. Returns nil if the sequence is empty.
public static func combineLatest<S: Sequence>(_ properties: S) -> Property<[S.Iterator.Element.Value]>? where S.Iterator.Element: PropertyProtocol {
let producers = properties.map { $0.producer }
guard !producers.isEmpty else {
return nil
}
return Property(unsafeProducer: SignalProducer.combineLatest(producers))
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol>(_ a: A, _ b: B) -> Property<(Value, B.Value)> where A.Value == Value {
return a.lift { SignalProducer.zip($0, b) }
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol>(_ a: A, _ b: B, _ c: C) -> Property<(Value, B.Value, C.Value)> where A.Value == Value {
return a.lift { SignalProducer.zip($0, b, c) }
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D) -> Property<(Value, B.Value, C.Value, D.Value)> where A.Value == Value {
return a.lift { SignalProducer.zip($0, b, c, d) }
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E) -> Property<(Value, B.Value, C.Value, D.Value, E.Value)> where A.Value == Value {
return a.lift { SignalProducer.zip($0, b, c, d, e) }
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F) -> Property<(Value, B.Value, C.Value, D.Value, E.Value, F.Value)> where A.Value == Value {
return a.lift { SignalProducer.zip($0, b, c, d, e, f) }
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) -> Property<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value)> where A.Value == Value {
return a.lift { SignalProducer.zip($0, b, c, d, e, f, g) }
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol, H: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H) -> Property<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value)> where A.Value == Value {
return a.lift { SignalProducer.zip($0, b, c, d, e, f, g, h) }
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol, H: PropertyProtocol, I: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I) -> Property<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value)> where A.Value == Value {
return a.lift { SignalProducer.zip($0, b, c, d, e, f, g, h, i) }
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol, H: PropertyProtocol, I: PropertyProtocol, J: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J) -> Property<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value, J.Value)> where A.Value == Value {
return a.lift { SignalProducer.zip($0, b, c, d, e, f, g, h, i, j) }
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`. Returns nil if the sequence is empty.
public static func zip<S: Sequence>(_ properties: S) -> Property<[S.Iterator.Element.Value]>? where S.Iterator.Element: PropertyProtocol {
let producers = properties.map { $0.producer }
guard !producers.isEmpty else {
return nil
}
return Property(unsafeProducer: SignalProducer.zip(producers))
}
}
extension PropertyProtocol where Value == Bool {
/// Create a property that computes a logical NOT in the latest values of `self`.
///
/// - returns: A property that contains the logial NOT results.
public func negate() -> Property<Value> {
return self.lift { $0.negate() }
}
/// Create a property that computes a logical AND between the latest values of `self`
/// and `property`.
///
/// - parameters:
/// - property: Property to be combined with `self`.
///
/// - returns: A property that contains the logial AND results.
public func and<P: PropertyProtocol>(_ property: P) -> Property<Value> where P.Value == Value {
return self.lift(SignalProducer.and)(property)
}
/// Create a property that computes a logical OR between the latest values of `self`
/// and `property`.
///
/// - parameters:
/// - property: Property to be combined with `self`.
///
/// - returns: A property that contains the logial OR results.
public func or<P: PropertyProtocol>(_ property: P) -> Property<Value> where P.Value == Value {
return self.lift(SignalProducer.or)(property)
}
}
/// A read-only property that can be observed for its changes over time. There
/// are three categories of read-only properties:
///
/// # Constant property
/// Created by `Property(value:)`, the producer and signal of a constant
/// property would complete immediately when it is initialized.
///
/// # Existential property
/// Created by `Property(capturing:)`, it wraps any arbitrary `PropertyProtocol`
/// types, and passes through the behavior. Note that it would retain the
/// wrapped property.
///
/// Existential property would be deprecated when generalized existential
/// eventually lands in Swift.
///
/// # Composed property
/// A composed property presents a composed view of its sources, which can be
/// one or more properties, a producer, or a signal. It can be created using
/// property composition operators, `Property(_:)` or `Property(initial:then:)`.
///
/// It does not own its lifetime, and its producer and signal are bound to the
/// lifetime of its sources. It also does not have an influence on its sources,
/// so retaining a composed property would not prevent its sources from
/// deinitializing.
///
/// Note that composed properties do not retain any of its sources.
public final class Property<Value>: PropertyProtocol {
private let _value: () -> Value
/// The current value of the property.
public var value: Value {
return _value()
}
/// A producer for Signals that will send the property's current
/// value, followed by all changes over time, then complete when the
/// property has deinitialized or has no further changes.
///
/// - note: If `self` is a composed property, the producer would be
/// bound to the lifetime of its sources.
public let producer: SignalProducer<Value, Never>
/// A signal that will send the property's changes over time, then
/// complete when the property has deinitialized or has no further changes.
///
/// - note: If `self` is a composed property, the signal would be
/// bound to the lifetime of its sources.
public let signal: Signal<Value, Never>
/// Initializes a constant property.
///
/// - parameters:
/// - property: A value of the constant property.
public init(value: Value) {
_value = { value }
producer = SignalProducer(value: value)
signal = Signal<Value, Never>.empty
}
/// Initializes an existential property which wraps the given property.
///
/// - note: The resulting property retains the given property.
///
/// - parameters:
/// - property: A property to be wrapped.
public init<P: PropertyProtocol>(capturing property: P) where P.Value == Value {
_value = { property.value }
producer = property.producer
signal = property.signal
}
/// Initializes a composed property which reflects the given property.
///
/// - note: The resulting property does not retain the given property.
///
/// - parameters:
/// - property: A property to be wrapped.
public convenience init<P: PropertyProtocol>(_ property: P) where P.Value == Value {
self.init(unsafeProducer: property.producer)
}
/// Initializes a composed property that first takes on `initial`, then each
/// value sent on a signal created by `producer`.
///
/// - parameters:
/// - initial: Starting value for the property.
/// - values: A producer that will start immediately and send values to
/// the property.
public convenience init(initial: Value, then values: SignalProducer<Value, Never>) {
self.init(unsafeProducer: SignalProducer { observer, lifetime in
observer.send(value: initial)
lifetime += values.start(Signal.Observer(mappingInterruptedToCompleted: observer))
})
}
/// Initializes a composed property that first takes on `initial`, then each
/// value sent on a signal created by `producer`.
///
/// - parameters:
/// - initial: Starting value for the property.
/// - values: A producer that will start immediately and send values to
/// the property.
public convenience init<Values: SignalProducerConvertible>(initial: Value, then values: Values) where Values.Value == Value, Values.Error == Never {
self.init(initial: initial, then: values.producer)
}
/// Initialize a composed property from a producer that promises to send
/// at least one value synchronously in its start handler before sending any
/// subsequent event.
///
/// - important: The producer and the signal of the created property would
/// complete only when the `unsafeProducer` completes.
///
/// - warning: If the producer fails its promise, a fatal error would be
/// raised.
///
/// - warning: `unsafeProducer` should not emit any `interrupted` event unless it is
/// a result of being interrupted by the downstream.
///
/// - parameters:
/// - unsafeProducer: The composed producer for creating the property.
fileprivate init(unsafeProducer: SignalProducer<Value, Never>) {
// The ownership graph:
//
// ------------ weak ----------- strong ------------------
// | Upstream | ~~~~~~~~> | Box | <======== | SignalProducer | <=== strong
// ------------ ----------- // ------------------ \\
// \\ // \\
// \\ ------------ weak ----------- <== ------------
// ==> | Observer | ~~~~> | Relay | <=========================== | Property |
// strong ------------ ----------- strong ------------
let box = PropertyBox<Value?>(nil)
// A composed property tracks its active consumers through its relay signal, and
// interrupts `unsafeProducer` if the relay signal terminates.
let disposable = SerialDisposable()
let (relay, observer) = Signal<Value, Never>.pipe(disposable: disposable)
disposable.inner = unsafeProducer.start { [weak box] event in
// `observer` receives `interrupted` only as a result of the termination of
// `signal`, and would not be delivered anyway. So transforming
// `interrupted` to `completed` is unnecessary here.
guard let box = box else {
// Just forward the event, since no one owns the box or IOW no demand
// for a cached latest value.
return observer.send(event)
}
box.begin { storage in
storage.modify { value in
if let newValue = event.value {
value = newValue
}
}
observer.send(event)
}
}
// Verify that an initial is sent. This is friendlier than deadlocking
// in the event that one isn't.
guard box.value != nil else {
fatalError("The producer promised to send at least one value. Received none.")
}
_value = { box.value! }
signal = relay
producer = SignalProducer { [box, relay] observer, lifetime in
box.withValue { value in
observer.send(value: value!)
lifetime += relay.observe(Signal.Observer(mappingInterruptedToCompleted: observer))
}
}
}
}
extension Property where Value: OptionalProtocol {
/// Initializes a composed property that first takes on `initial`, then each
/// value sent on a signal created by `producer`.
///
/// - parameters:
/// - initial: Starting value for the property.
/// - values: A producer that will start immediately and send values to
/// the property.
public convenience init(initial: Value, then values: SignalProducer<Value.Wrapped, Never>) {
self.init(initial: initial, then: values.map(Value.init(reconstructing:)))
}
/// Initializes a composed property that first takes on `initial`, then each
/// value sent on a signal created by `producer`.
///
/// - parameters:
/// - initial: Starting value for the property.
/// - values: A producer that will start immediately and send values to
/// the property.
public convenience init<Values: SignalProducerConvertible>(initial: Value, then values: Values) where Values.Value == Value.Wrapped, Values.Error == Never {
self.init(initial: initial, then: values.producer)
}
}
/// A mutable property of type `Value` that allows observation of its changes.
///
/// Instances of this class are thread-safe.
public final class MutableProperty<Value>: ComposableMutablePropertyProtocol {
private let token: Lifetime.Token
private let observer: Signal<Value, Never>.Observer
private let box: PropertyBox<Value>
/// The current value of the property.
///
/// Setting this to a new value will notify all observers of `signal`, or
/// signals created using `producer`.
public var value: Value {
get { return box.value }
set { modify { $0 = newValue } }
}
/// The lifetime of the property.
public let lifetime: Lifetime
/// A signal that will send the property's changes over time,
/// then complete when the property has deinitialized.
public let signal: Signal<Value, Never>
/// A producer for Signals that will send the property's current value,
/// followed by all changes over time, then complete when the property has
/// deinitialized.
public var producer: SignalProducer<Value, Never> {
return SignalProducer { [box, signal] observer, lifetime in
box.withValue { value in
observer.send(value: value)
lifetime += signal.observe(Signal.Observer(mappingInterruptedToCompleted: observer))
}
}
}
/// Initializes a mutable property that first takes on `initialValue`
///
/// - parameters:
/// - initialValue: Starting value for the mutable property.
public init(_ initialValue: Value) {
(signal, observer) = Signal.pipe()
(lifetime, token) = Lifetime.make()
/// Need a recursive lock around `value` to allow recursive access to
/// `value`. Note that recursive sets will still deadlock because the
/// underlying producer prevents sending recursive events.
box = PropertyBox(initialValue)
}
/// Atomically replaces the contents of the variable.
///
/// - parameters:
/// - newValue: New property value.
///
/// - returns: The previous property value.
@discardableResult
public func swap(_ newValue: Value) -> Value {
return modify { value in
defer { value = newValue }
return value
}
}
/// Atomically modifies the variable.
///
/// - parameters:
/// - action: A closure that accepts an inout reference to the value.
///
/// - returns: The result of the action.
@discardableResult
public func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result {
return try box.begin { storage in
defer { observer.send(value: storage.value) }
return try storage.modify(action)
}
}
/// Atomically modifies the variable.
///
/// - warning: The reference should not be escaped.
///
/// - parameters:
/// - action: A closure that accepts a reference to the property storage.
///
/// - returns: The result of the action.
@discardableResult
internal func begin<Result>(_ action: (PropertyStorage<Value>) throws -> Result) rethrows -> Result {
return try box.begin(action)
}
/// Atomically performs an arbitrary action using the current value of the
/// variable.
///
/// - parameters:
/// - action: A closure that accepts current property value.
///
/// - returns: the result of the action.
@discardableResult
public func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result {
return try box.withValue { try action($0) }
}
deinit {
observer.sendCompleted()
}
}
internal struct PropertyStorage<Value> {
private unowned let box: PropertyBox<Value>
var value: Value {
return box._value
}
func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result {
guard !box.isModifying else { fatalError("Nested modifications violate exclusivity of access.") }
box.isModifying = true
defer { box.isModifying = false }
return try action(&box._value)
}
fileprivate init(_ box: PropertyBox<Value>) {
self.box = box
}
}
/// A reference counted box which holds a recursive lock and a value storage.
///
/// The requirement of a `Value?` storage from composed properties prevents further
/// implementation sharing with `MutableProperty`.
private final class PropertyBox<Value> {
private let lock: Lock.PthreadLock
fileprivate var _value: Value
fileprivate var isModifying = false
internal var value: Value {
lock.lock()
defer { lock.unlock() }
return _value
}
init(_ value: Value) {
_value = value
lock = Lock.PthreadLock(recursive: true)
}
func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result {
lock.lock()
defer { lock.unlock() }
return try action(_value)
}
func begin<Result>(_ action: (PropertyStorage<Value>) throws -> Result) rethrows -> Result {
lock.lock()
defer { lock.unlock() }
return try action(PropertyStorage(self))
}
}
| mit | 6d7704224ff97bcb066f2b8f847edf41 | 41.208122 | 450 | 0.678653 | 3.744231 | false | false | false | false |
Bunn/firefox-ios | Client/Frontend/Widgets/GradientProgressBar.swift | 9 | 6481 | /* 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/. */
// ADAPTED FROM:
//
// GradientProgressBar.swift
// GradientProgressBar
//
// Created by Felix Mau on 01.03.17.
// Copyright © 2017 Felix Mau. All rights reserved.
//
import UIKit
open class GradientProgressBar: UIProgressView {
private struct DefaultValues {
static let backgroundColor = UIColor.clear
static let animationDuration = 0.2 // CALayer default animation duration
}
var gradientColors: [CGColor] = []
// Alpha mask for visible part of gradient.
private var alphaMaskLayer = CALayer()
// Gradient layer.
open var gradientLayer = CAGradientLayer()
// Duration for "setProgress(animated: true)"
open var animationDuration = DefaultValues.animationDuration
// Workaround to handle orientation change, as "layoutSubviews()" gets triggered each time
// the progress value is changed.
override open var bounds: CGRect {
didSet {
updateAlphaMaskLayerWidth()
}
}
// Update layer mask on direct changes to progress value.
override open var progress: Float {
didSet {
updateAlphaMaskLayerWidth()
}
}
func setGradientColors(startColor: UIColor, endColor: UIColor) {
gradientColors = [startColor, endColor, startColor, endColor, startColor, endColor, startColor].map { $0.cgColor }
gradientLayer.colors = gradientColors
}
func commonInit() {
setupProgressViewColors()
setupAlphaMaskLayer()
setupGradientLayer()
layer.insertSublayer(gradientLayer, at: 0)
updateAlphaMaskLayerWidth()
}
override public init(frame: CGRect) {
gradientColors = []
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
// MARK: - Setup UIProgressView
private func setupProgressViewColors() {
backgroundColor = DefaultValues.backgroundColor
trackTintColor = .clear
progressTintColor = .clear
}
// MARK: - Setup layers
private func setupAlphaMaskLayer() {
alphaMaskLayer.frame = bounds
alphaMaskLayer.cornerRadius = 3
alphaMaskLayer.anchorPoint = .zero
alphaMaskLayer.position = .zero
alphaMaskLayer.backgroundColor = UIColor.Photon.White100.cgColor
}
private func setupGradientLayer() {
// Apply "alphaMaskLayer" as a mask to the gradient layer in order to show only parts of the current "progress"
gradientLayer.mask = alphaMaskLayer
gradientLayer.frame = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.size.width * 2, height: bounds.size.height)
gradientLayer.colors = gradientColors
gradientLayer.locations = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.0]
gradientLayer.startPoint = .zero
gradientLayer.endPoint = CGPoint(x: 1, y: 0)
gradientLayer.drawsAsynchronously = true
}
func hideProgressBar() {
guard progress == 1 else {
return
}
CATransaction.begin()
let moveAnimation = CABasicAnimation(keyPath: "position")
moveAnimation.duration = DefaultValues.animationDuration
moveAnimation.fromValue = gradientLayer.position
moveAnimation.toValue = CGPoint(x: gradientLayer.frame.width, y: gradientLayer.position.y)
moveAnimation.fillMode = CAMediaTimingFillMode.forwards
moveAnimation.isRemovedOnCompletion = false
CATransaction.setCompletionBlock {
self.resetProgressBar()
}
gradientLayer.add(moveAnimation, forKey: "position")
CATransaction.commit()
}
func resetProgressBar() {
// Call on super instead so no animation layers are created
super.setProgress(0, animated: false)
isHidden = true // The URLBar will unhide the view before starting the next animation.
}
override open func layoutSubviews() {
super.layoutSubviews()
self.gradientLayer.frame = CGRect(x: bounds.origin.x - 4, y: bounds.origin.y, width: bounds.size.width * 2, height: bounds.size.height)
}
func animateGradient() {
let gradientChangeAnimation = CABasicAnimation(keyPath: "locations")
gradientChangeAnimation.duration = DefaultValues.animationDuration * 4
gradientChangeAnimation.toValue = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.0]
gradientChangeAnimation.fromValue = [0.0, 0.0, 0.0, 0.2, 0.4, 0.6, 0.8]
gradientChangeAnimation.fillMode = CAMediaTimingFillMode.forwards
gradientChangeAnimation.isRemovedOnCompletion = false
gradientChangeAnimation.repeatCount = .infinity
gradientLayer.add(gradientChangeAnimation, forKey: "colorChange")
}
// MARK: - Update gradient
open func updateAlphaMaskLayerWidth(animated: Bool = false) {
CATransaction.begin()
// Workaround for non animated progress change
// Source: https://stackoverflow.com/a/16381287/3532505
CATransaction.setAnimationDuration(animated ? DefaultValues.animationDuration : 0.0)
alphaMaskLayer.frame = bounds.updateWidth(byPercentage: CGFloat(progress))
if progress == 1 {
// Delay calling hide until the last animation has completed
CATransaction.setCompletionBlock({
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DefaultValues.animationDuration, execute: {
self.hideProgressBar()
})
})
}
CATransaction.commit()
}
override open func setProgress(_ progress: Float, animated: Bool) {
if progress < self.progress && self.progress != 1 {
return
}
// Setup animations
gradientLayer.removeAnimation(forKey: "position")
if gradientLayer.animation(forKey: "colorChange") == nil {
animateGradient()
}
super.setProgress(progress, animated: animated)
updateAlphaMaskLayerWidth(animated: animated)
}
}
extension CGRect {
func updateWidth(byPercentage percentage: CGFloat) -> CGRect {
return CGRect(x: origin.x, y: origin.y, width: size.width * percentage, height: size.height)
}
}
| mpl-2.0 | e82a65206704cec377aff80a01a854c8 | 33.83871 | 143 | 0.662809 | 4.839432 | false | false | false | false |
Laptopmini/SwiftyArtik | Source/MachineLearningAPI.swift | 1 | 10259 | //
// MachineLearningAPI.swift
// SwiftyArtik
//
// Created by Paul-Valentin Mini on 1/11/18.
// Copyright © 2018 Paul-Valentin Mini. All rights reserved.
//
import Foundation
import Alamofire
import PromiseKit
open class MachineLearningAPI {
// MARK: - Main Methods
/// Creates a prediction model that learns a device's data usage.
///
/// - Parameters:
/// - sources: Data source used in model.
/// - sourceToPredict: The device and field to be predicted by the model.
/// - predictIn: Time in seconds from last received data to predict output. Must be greater than 0.
/// - uid: (Optional) User ID. Required if using an application token.
/// - Returns: A `Promise<MachineLearningModel>`
open class func createPredictionModel(sources: [MachineLearningModel.Source], sourceToPredict: MachineLearningModel.Source, predictIn: UInt64, uid: String? = nil) -> Promise<MachineLearningModel> {
if predictIn == 0 {
let promise = Promise<MachineLearningModel>.pending()
promise.reject(ArtikError.machineLearning(reason: .invalidPredictIn))
return promise.promise
}
return create(sources: sources, sourceToPredict: sourceToPredict, predictIn: predictIn, uid: uid)
}
/// Creates an anomaly detection model that learns a device's data usage.
///
/// - Parameters:
/// - sources: Data source used in model.
/// - sourceToPredict: The device and field to be predicted by the model.
/// - sensitivity: (Optional) Sensitivity of anomaly detection. Can be 0 (very few anomalies) to 100 (receive many anomalies). Defaults to 50.
/// - uid: (Optional) User ID. Required if using an application token.
/// - Returns: A `Promise<MachineLearningModel>`
open class func createAnomalyDetectionModel(sources: [MachineLearningModel.Source], sourceToPredict: MachineLearningModel.Source, anomalyDetectionSensitivity sensitivity: UInt64? = nil, uid: String? = nil) -> Promise<MachineLearningModel> {
if let sensitivity = sensitivity, sensitivity > 100 {
let promise = Promise<MachineLearningModel>.pending()
promise.reject(ArtikError.machineLearning(reason: .invalidSensitivity))
return promise.promise
}
return create(sources: sources, sourceToPredict: sourceToPredict, anomalyDetectionSensitivity: sensitivity, uid: uid)
}
/// Returns the predicted output for the specified input.
///
/// - Parameters:
/// - id: The Model's id.
/// - inputs: Data input(s) to use in prediction, returned when creating a model.
/// - Returns: A `Promise<[MachineLearningModel.InputOutput]>`.
open class func predict(id: String, inputs: [MachineLearningModel.InputOutput]) -> Promise<[MachineLearningModel.InputOutput]> {
let promise = Promise<[MachineLearningModel.InputOutput]>.pending()
let path = SwiftyArtikSettings.basePath + "/ml/models/\(id)/predict"
let parameters = [
"inputs": inputs.toJSON()
]
APIHelpers.makeRequest(url: path, method: .post, parameters: parameters, encoding: JSONEncoding.default).then { response -> Void in
if let data = response["data"] as? [String:Any], let outputsRaw = data["outputs"] as? [[String:Any]] {
var outputs = [MachineLearningModel.InputOutput]()
for outputRaw in outputsRaw {
if let output = MachineLearningModel.InputOutput(JSON: outputRaw) {
outputs.append(output)
} else {
promise.reject(ArtikError.json(reason: .unexpectedFormat))
}
}
promise.fulfill(outputs)
}
}.catch { error -> Void in
promise.reject(error)
}
return promise.promise
}
/// Get a Model.
///
/// - Parameter id: The Model's id.
/// - Returns: A `Promise<MachineLearningModel>`.
open class func get(id: String) -> Promise<MachineLearningModel> {
let promise = Promise<MachineLearningModel>.pending()
let path = SwiftyArtikSettings.basePath + "/ml/models/\(id)"
APIHelpers.makeRequest(url: path, method: .get, parameters: nil, encoding: URLEncoding.default).then { response -> Void in
if let data = response["data"] as? [String:Any], let model = MachineLearningModel(JSON: data) {
promise.fulfill(model)
} else {
promise.reject(ArtikError.json(reason: .unexpectedFormat))
}
}.catch { error -> Void in
promise.reject(error)
}
return promise.promise
}
/// Get all models of an application using pagination.
///
/// - Parameters:
/// - count: Number of items returned per query, max `100`.
/// - offset: The offset used for pagination, default `0`.
/// - uid: (Optional) User ID. Required if using an application token.
/// - Returns: A `Promise<Page<MachineLearningModel>>`.
open class func get(count: Int, offset: Int = 0, uid: String? = nil) -> Promise<Page<MachineLearningModel>> {
let promise = Promise<Page<MachineLearningModel>>.pending()
let path = SwiftyArtikSettings.basePath + "/ml/models"
var parameters: [String:Any] = [
"count": count,
"offset": offset,
]
if let uid = uid {
parameters["uid"] = uid
}
APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in
if let total = response["total"] as? Int64, let offset = response["offset"] as? Int64, let count = response["count"] as? Int64, let modelsRaw = response["data"] as? [[String:Any]] {
let page = Page<MachineLearningModel>(offset: offset, total: total)
guard modelsRaw.count == Int(count) else {
promise.reject(ArtikError.json(reason: .countAndContentDoNotMatch))
return
}
for item in modelsRaw {
if let model = MachineLearningModel(JSON: item) {
page.data.append(model)
} else {
promise.reject(ArtikError.json(reason: .invalidItem))
return
}
}
promise.fulfill(page)
} else {
promise.reject(ArtikError.json(reason: .unexpectedFormat))
}
}.catch { error -> Void in
promise.reject(error)
}
return promise.promise
}
/// Get all models of an application using recursive requests.
/// WARNING: May strongly impact your rate limit and quota.
///
/// - Parameter uid: (Optional) User ID. Required if using an application token.
/// - Returns: A `Promise<Page<MachineLearningModel>>`.
open class func get(uid: String? = nil) -> Promise<Page<MachineLearningModel>> {
return getRecursive(Page<MachineLearningModel>(), offset: 0, uid: uid)
}
/// Remove an existing model from ARTIK Cloud.
///
/// - Parameter id: The Model's id.
/// - Returns: A `Promise<Void>`.
open class func delete(id: String) -> Promise<Void> {
let promise = Promise<Void>.pending()
let path = SwiftyArtikSettings.basePath + "/ml/models/\(id)"
APIHelpers.makeRequest(url: path, method: .delete, parameters: nil, encoding: URLEncoding.default).then { _ -> Void in
promise.fulfill(())
}.catch { error -> Void in
promise.reject(error)
}
return promise.promise
}
// MARK: - Helper Methods
fileprivate class func create(sources: [MachineLearningModel.Source], sourceToPredict: MachineLearningModel.Source, predictIn: UInt64? = nil, anomalyDetectionSensitivity sensitivity: UInt64? = nil, uid: String? = nil) -> Promise<MachineLearningModel> {
let promise = Promise<MachineLearningModel>.pending()
let path = SwiftyArtikSettings.basePath + "/ml/models"
let parameters: [String:Any] = [
"data": [
"sources": sources.toJSON()
],
"type": predictIn != nil ? MachineLearningModel.ModelType.prediction.rawValue : MachineLearningModel.ModelType.anomalyDetection.rawValue,
"parameters": APIHelpers.removeNilParameters([
"sourceToPredict": sourceToPredict.toJSON(),
"predictIn": predictIn,
"anomalyDetectionSensitivity": sensitivity
])
]
APIHelpers.makeRequest(url: path, method: .post, parameters: parameters, encoding: JSONEncoding.default).then { response -> Void in
if let data = response["data"] as? [String:Any], let model = MachineLearningModel(JSON: data) {
promise.fulfill(model)
} else {
promise.reject(ArtikError.json(reason: .unexpectedFormat))
}
}.catch { error -> Void in
promise.reject(error)
}
return promise.promise
}
fileprivate class func getRecursive(_ container: Page<MachineLearningModel>, offset: Int = 0, uid: String? = nil) -> Promise<Page<MachineLearningModel>> {
let promise = Promise<Page<MachineLearningModel>>.pending()
get(count: 100, offset: offset, uid: uid).then { result -> Void in
container.data.append(contentsOf: result.data)
container.total = result.total
if container.total > Int64(container.data.count) {
self.getRecursive(container, offset: Int(result.offset) + result.data.count, uid: uid).then { result -> Void in
promise.fulfill(result)
}.catch { error -> Void in
promise.reject(error)
}
} else {
promise.fulfill(container)
}
}.catch { error -> Void in
promise.reject(error)
}
return promise.promise
}
}
| mit | aa4bfe047225ecca0d78a75e756b7477 | 45.627273 | 256 | 0.604504 | 4.561138 | false | false | false | false |
chenqihui/QHAwemeDemo | QHAwemeDemo/Modules/QHNavigationControllerMan/OtherTransition/QHPresentPopTransition.swift | 1 | 1429 | //
// QHPresentPopTransition.swift
// QHAwemeDemo
//
// Created by Anakin chen on 2017/10/29.
// Copyright © 2017年 AnakinChen Network Technology. All rights reserved.
//
import UIKit
class QHPresentPopTransition: QHBaseTransition {
let offSetHeight: CGFloat = 0
override func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return transitionDuration
}
override func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromVC = transitionContext.viewController(forKey: .from)
let toVC = transitionContext.viewController(forKey: .to)
let containerView = transitionContext.containerView
toVC?.view.frame = (fromVC?.view.frame)!
containerView.addSubview((toVC?.view)!)
containerView.addSubview(fromVC!.view)
let toViewFrame = CGRect(x: 0, y: fromVC!.view.frame.size.height - offSetHeight, width: fromVC!.view.frame.size.width, height: fromVC!.view.frame.size.height + offSetHeight)
UIView.animate(withDuration: transitionDuration, delay: 0, options: .curveEaseOut, animations: {
fromVC?.view.frame = toViewFrame
}) { (bFinish) in
fromVC?.view.frame = toViewFrame
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
| mit | aa25f0189e667e511f8d54ed6041058a | 36.526316 | 181 | 0.695652 | 4.917241 | false | false | false | false |
renatoguarato/cidadaoalerta | apps/ios/cidadaoalerta/cidadaoalerta/ExecucaoFinanceiraViewController.swift | 1 | 2294 | //
// ExecucaoFinanceiraViewController.swift
// cidadaoalerta
//
// Created by Renato Guarato on 25/03/16.
// Copyright © 2016 Renato Guarato. All rights reserved.
//
import UIKit
class ExecucaoFinanceiraViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var items = [DetalheTabela]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "tableCell")
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 160.0
self.automaticallyAdjustsScrollViewInsets = false
self.items = [DetalheTabela("Data: 08/12/2008", "Valor: R$ 347.926,32"), DetalheTabela("Data: 22/12/2008", "Valor: 402.314,00"), DetalheTabela("Data: 09/12/2008", "Valor: R$ 1.509.987,99"), DetalheTabela("Data: 10/11/2008", "Valor: R$ 11.124,80")]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func btnVoltar(sender: UIBarButtonItem) {
self.navigationController?.popViewControllerAnimated(true)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
@IBAction func btnAjuda(sender: UIBarButtonItem) {
self.presentViewController(Alert.message("Ajuda", message: "Execução financeira é a utilização dos recursos financeiros visando atender à realização dos subprojetos e/ou subatividades, atribuídos às unidades orçamentárias."), animated: true, completion: nil)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! DetailViewCell
let empenho = self.items[indexPath.row]
cell.lblColunaExecucaoFinanceira.text = empenho.coluna
cell.lblValorExecucaoFinanceira.text = empenho.valor
return cell
}
}
| gpl-3.0 | a0d57478ffa9fbe650a3b98cf6ba4f91 | 34.092308 | 266 | 0.683472 | 4.455078 | false | false | false | false |
lfaoro/Cast | Carthage/Checkouts/RxSwift/RxCocoa/iOS/NSManagedObjectContext+Rx.swift | 1 | 6445 | //
// NSManagedObjectContext+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
//import CoreData
#if !RX_NO_MODULE
import RxSwift
#endif
/*
class FetchResultControllerSectionObserver: NSObject, NSFetchedResultsControllerDelegate, Disposable {
typealias Observer = ObserverOf<[NSFetchedResultsSectionInfo]>
let observer: Observer
let frc: NSFetchedResultsController
init(observer: Observer, frc: NSFetchedResultsController) {
self.observer = observer
self.frc = frc
super.init()
self.frc.delegate = self
var error: NSError? = nil
if !self.frc.performFetch(&error) {
sendError(observer, error ?? UnknownError)
return
}
sendNextElement()
}
func sendNextElement() {
let sections = self.frc.sections as! [NSFetchedResultsSectionInfo]
sendNext(observer, sections)
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
sendNextElement()
}
func dispose() {
self.frc.delegate = nil
}
}
class FetchResultControllerEntityObserver: NSObject, NSFetchedResultsControllerDelegate, Disposable {
typealias Observer = ObserverOf<[NSManagedObject]>
let observer: Observer
let frc: NSFetchedResultsController
init(observer: Observer, frc: NSFetchedResultsController) {
self.observer = observer
self.frc = frc
super.init()
self.frc.delegate = self
var error: NSError? = nil
if !self.frc.performFetch(&error) {
sendError(observer, error ?? UnknownError)
return
}
sendNextElement()
}
func sendNextElement() {
let entities = self.frc.fetchedObjects as! [NSManagedObject]
sendNext(observer, entities)
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
sendNextElement()
}
func dispose() {
self.frc.delegate = nil
}
}
class FetchResultControllerIncrementalObserver: NSObject, NSFetchedResultsControllerDelegate, Disposable {
typealias Observer = ObserverOf<CoreDataEntityEvent>
let observer: Observer
let frc: NSFetchedResultsController
init(observer: Observer, frc: NSFetchedResultsController) {
self.observer = observer
self.frc = frc
super.init()
self.frc.delegate = self
var error: NSError? = nil
if !self.frc.performFetch(&error) {
sendError(observer, error ?? UnknownError)
return
}
let sections = self.frc.sections as! [NSFetchedResultsSectionInfo]
sendNext(observer, .Snapshot(sections: sections))
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
let event: CoreDataEntityEvent
switch type {
case .Insert:
event = .ItemInserted(item: anObject as! NSManagedObject, newIndexPath: newIndexPath!)
case .Delete:
event = .ItemDeleted(withIndexPath: indexPath!)
case .Move:
event = .ItemMoved(item: anObject as! NSManagedObject, sourceIndexPath: indexPath!, destinationIndexPath: newIndexPath!)
case .Update:
event = .ItemUpdated(item: anObject as! NSManagedObject, atIndexPath: indexPath!)
}
sendNext(observer, event)
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
let event: CoreDataEntityEvent
switch type {
case .Insert:
event = .SectionInserted(section: sectionInfo, newIndex: sectionIndex)
case .Delete:
event = .SectionDeleted(withIndex: sectionIndex)
case .Move:
rxFatalError("Unknown event")
event = .SectionInserted(section: sectionInfo, newIndex: -1)
case .Update:
event = .SectionUpdated(section: sectionInfo, atIndex: sectionIndex)
}
sendNext(observer, event)
}
func controllerWillChangeContent(controller: NSFetchedResultsController) {
sendNext(observer, .TransactionStarted)
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
sendNext(observer, .TransactionEnded)
}
func dispose() {
self.frc.delegate = nil
}
}
extension NSManagedObjectContext {
func rx_entitiesAndChanges(query: NSFetchRequest) -> Observable<CoreDataEntityEvent> {
return rx_sectionsAndChanges(query, sectionNameKeyPath: nil)
}
func rx_sectionsAndChanges(query: NSFetchRequest, sectionNameKeyPath: String? = nil) -> Observable<CoreDataEntityEvent> {
return AnonymousObservable { observer in
let frc = NSFetchedResultsController(fetchRequest: query, managedObjectContext: self, sectionNameKeyPath: sectionNameKeyPath, cacheName: nil)
let observerAdapter = FetchResultControllerIncrementalObserver(observer: observer, frc: frc)
return AnonymousDisposable {
observerAdapter.dispose()
}
}
}
func rx_entities(query: NSFetchRequest) -> Observable<[NSManagedObject]> {
return AnonymousObservable { observer in
let frc = NSFetchedResultsController(fetchRequest: query, managedObjectContext: self, sectionNameKeyPath: nil, cacheName: nil)
let observerAdapter = FetchResultControllerEntityObserver(observer: observer, frc: frc)
return AnonymousDisposable {
observerAdapter.dispose()
}
}
}
func rx_sections(query: NSFetchRequest, sectionNameKeyPath: String) -> Observable<[NSFetchedResultsSectionInfo]> {
return AnonymousObservable { observer in
let frc = NSFetchedResultsController(fetchRequest: query, managedObjectContext: self, sectionNameKeyPath: sectionNameKeyPath, cacheName: nil)
let observerAdapter = FetchResultControllerSectionObserver(observer: observer, frc: frc)
return AnonymousDisposable {
observerAdapter.dispose()
}
}
}
}*/
| mit | 21a6a6dee5e9725deab5e26ce0d78de6 | 30.135266 | 211 | 0.675252 | 5.527444 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/MagazineLayout-master/Example/MagazineLayoutExample/Data/DataSource.swift | 1 | 3902 | // Created by bryankeller on 11/28/18.
// Copyright © 2018 Airbnb, 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 MagazineLayout
import UIKit
// MARK: - DataSource
final class DataSource: NSObject {
private(set) var sectionInfos = [SectionInfo]()
func insert(_ sectionInfo: SectionInfo, atSectionIndex sectionIndex: Int) {
sectionInfos.insert(sectionInfo, at: sectionIndex)
}
func insert(
_ itemInfo: ItemInfo,
atItemIndex itemIndex: Int,
inSectionAtIndex sectionIndex: Int)
{
sectionInfos[sectionIndex].itemInfos.insert(itemInfo, at: itemIndex)
}
func removeSection(atSectionIndex sectionIndex: Int) {
sectionInfos.remove(at: sectionIndex)
}
func removeItem(atItemIndex itemIndex: Int, inSectionAtIndex sectionIndex: Int) {
sectionInfos[sectionIndex].itemInfos.remove(at: itemIndex)
}
func setHeaderInfo(_ headerInfo: HeaderInfo, forSectionAtIndex sectionIndex: Int) {
sectionInfos[sectionIndex].headerInfo = headerInfo
}
func setFooterInfo(_ footerInfo: FooterInfo, forSectionAtIndex sectionIndex: Int) {
sectionInfos[sectionIndex].footerInfo = footerInfo
}
}
// MARK: UICollectionViewDataSource
extension DataSource: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return sectionInfos.count
}
func collectionView(
_ collectionView: UICollectionView,
numberOfItemsInSection section: Int)
-> Int
{
return sectionInfos[section].itemInfos.count
}
func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath)
-> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: Cell.description(),
for: indexPath) as! Cell
let itemInfo = sectionInfos[indexPath.section].itemInfos[indexPath.item]
cell.set(itemInfo)
return cell
}
func collectionView(
_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath)
-> UICollectionReusableView
{
switch kind {
case MagazineLayout.SupplementaryViewKind.sectionHeader:
let header = collectionView.dequeueReusableSupplementaryView(
ofKind: MagazineLayout.SupplementaryViewKind.sectionHeader,
withReuseIdentifier: Header.description(),
for: indexPath) as! Header
header.set(sectionInfos[indexPath.section].headerInfo)
return header
case MagazineLayout.SupplementaryViewKind.sectionFooter:
let header = collectionView.dequeueReusableSupplementaryView(
ofKind: MagazineLayout.SupplementaryViewKind.sectionFooter,
withReuseIdentifier: Footer.description(),
for: indexPath) as! Footer
header.set(sectionInfos[indexPath.section].footerInfo)
return header
case MagazineLayout.SupplementaryViewKind.sectionBackground:
return collectionView.dequeueReusableSupplementaryView(
ofKind: kind,
withReuseIdentifier: Background.description(),
for: indexPath)
default:
fatalError("Not supported")
}
}
}
// MARK: DataSourceCountsProvider
extension DataSource: DataSourceCountsProvider {
var numberOfSections: Int {
return sectionInfos.count
}
func numberOfItemsInSection(withIndex sectionIndex: Int) -> Int {
return sectionInfos[sectionIndex].itemInfos.count
}
}
| mit | 8c5fb0ae08de973091abac8bcaa0a601 | 29.24031 | 85 | 0.743399 | 4.86409 | false | false | false | false |
chrisdhaan/CDUntappdKit | Source/CDUntappdEnums.swift | 1 | 1620 | //
// CDUntappdEnums.swift
// CDUntappdKit
//
// Created by Christopher de Haan on 8/4/17.
//
// Copyright © 2016-2022 Christopher de Haan <[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.
//
///
/// A list of the user wish list sort types the Untappd API supports.
///
public enum CDUntappdUserWishListSortType: String {
case checkin = "checkin"
case date = "date"
case highestABV = "highest_abv"
case highestRated = "highest_rated"
case lowestABV = "lowest_abv"
case lowestRated = "lowest_rated"
}
| mit | 1668fdafd30aaf4e1f3f673aa5044d55 | 41.605263 | 81 | 0.726374 | 3.94878 | false | false | false | false |
justMaku/Miazga | Tests/Mock Packets/PacketWithCollection.swift | 1 | 872 | //
// PacketWithCollection.swift
// Miazga
//
// Created by Michał Kałużny on 21/02/16.
//
//
import Foundation
import Miazga
struct PacketWithCollection: Packet, Equatable {
let numberOfElements: UInt32
let elements: [UInt32]
init(elements: [UInt32]) {
self.elements = elements
self.numberOfElements = UInt32(elements.count)
}
static func decode(fromStream stream: Stream) -> PacketWithCollection {
let numberOfElements: UInt32 = stream.read()
let elements: [UInt32] = stream.read(count: Int(numberOfElements))
return PacketWithCollection(elements: elements)
}
func map() -> [StreamWriteableType] {
return [numberOfElements, elements]
}
}
func ==(lhs: PacketWithCollection, rhs: PacketWithCollection) -> Bool {
return lhs.elements == rhs.elements
} | mit | 379de52543d97460e1fca2af5cf22ac3 | 22.513514 | 75 | 0.659379 | 4.023148 | false | false | false | false |
btanner/Eureka | Source/Rows/DoublePickerRow.swift | 7 | 4551 | //
// MultiplePickerRow.swift
// Eureka
//
// Created by Mathias Claassen on 5/8/18.
// Copyright © 2018 Xmartlabs. All rights reserved.
//
import Foundation
import UIKit
public struct Tuple<A: Equatable, B: Equatable> {
public let a: A
public let b: B
public init(a: A, b: B) {
self.a = a
self.b = b
}
}
extension Tuple: Equatable {}
public func == <A: Equatable, B: Equatable>(lhs: Tuple<A, B>, rhs: Tuple<A, B>) -> Bool {
return lhs.a == rhs.a && lhs.b == rhs.b
}
// MARK: MultiplePickerCell
open class DoublePickerCell<A, B> : _PickerCell<Tuple<A, B>> where A: Equatable, B: Equatable {
private var pickerRow: _DoublePickerRow<A, B>? { return row as? _DoublePickerRow<A, B> }
public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func update() {
super.update()
if let selectedValue = pickerRow?.value, let indexA = pickerRow?.firstOptions().firstIndex(of: selectedValue.a),
let indexB = pickerRow?.secondOptions(selectedValue.a).firstIndex(of: selectedValue.b) {
picker.selectRow(indexA, inComponent: 0, animated: true)
picker.selectRow(indexB, inComponent: 1, animated: true)
}
}
open override func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
open override func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
guard let pickerRow = pickerRow else { return 0 }
return component == 0 ? pickerRow.firstOptions().count : pickerRow.secondOptions(pickerRow.selectedFirst()).count
}
open override func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
guard let pickerRow = pickerRow else { return "" }
if component == 0 {
return pickerRow.displayValueForFirstRow(pickerRow.firstOptions()[row])
} else {
return pickerRow.displayValueForSecondRow(pickerRow.secondOptions(pickerRow.selectedFirst())[row])
}
}
open override func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
guard let pickerRow = pickerRow else { return }
if component == 0 {
let a = pickerRow.firstOptions()[row]
if let value = pickerRow.value {
guard value.a != a else {
return
}
if pickerRow.secondOptions(a).contains(value.b) {
pickerRow.value = Tuple(a: a, b: value.b)
pickerView.reloadComponent(1)
return
} else {
pickerRow.value = Tuple(a: a, b: pickerRow.secondOptions(a)[0])
}
} else {
pickerRow.value = Tuple(a: a, b: pickerRow.secondOptions(a)[0])
}
pickerView.reloadComponent(1)
pickerView.selectRow(0, inComponent: 1, animated: true)
} else {
let a = pickerRow.selectedFirst()
pickerRow.value = Tuple(a: a, b: pickerRow.secondOptions(a)[row])
}
}
}
// MARK: PickerRow
open class _DoublePickerRow<A, B> : Row<DoublePickerCell<A, B>> where A: Equatable, B: Equatable {
/// Options for first component. Will be called often so should be O(1)
public var firstOptions: (() -> [A]) = {[]}
/// Options for second component given the selected value from the first component. Will be called often so should be O(1)
public var secondOptions: ((A) -> [B]) = {_ in []}
/// Modify the displayed values for the first picker row.
public var displayValueForFirstRow: ((A) -> (String)) = { a in return String(describing: a) }
/// Modify the displayed values for the second picker row.
public var displayValueForSecondRow: ((B) -> (String)) = { b in return String(describing: b) }
required public init(tag: String?) {
super.init(tag: tag)
}
func selectedFirst() -> A {
return value?.a ?? firstOptions()[0]
}
}
/// A generic row where the user can pick an option from a picker view
public final class DoublePickerRow<A, B>: _DoublePickerRow<A, B>, RowType where A: Equatable, B: Equatable {
required public init(tag: String?) {
super.init(tag: tag)
}
}
| mit | 6b1ad26a69391e69ea31be81b374cf47 | 34.271318 | 126 | 0.62 | 4.284369 | false | false | false | false |
cabarique/TheProposalGame | MyProposalGame/Entities/PrincessEntity.swift | 1 | 2596 | //
// PrincessEntity.swift
// MyProposalGame
//
// Created by Luis Cabarique on 10/25/16.
// Copyright © 2016 Luis Cabarique. All rights reserved.
//
import SpriteKit
import GameplayKit
class PrincessEntity: SGEntity {
var spriteComponent: SpriteComponent!
var animationComponent: AnimationComponent!
var physicsComponent: PhysicsComponent!
var gameScene:GamePlayMode!
override init() {
super.init()
}
init(position: CGPoint, size: CGSize, atlas: SKTextureAtlas, scene:GamePlayMode, name: String) {
super.init()
gameScene = scene
//Initialize components
spriteComponent = SpriteComponent(entity: self, texture: SKTexture(), size: size, position:position)
spriteComponent.node.xScale = -1
addComponent(spriteComponent)
animationComponent = AnimationComponent(node: spriteComponent.node, animations: loadAnimations(atlas))
animationComponent.requestedAnimationState = .Idle
addComponent(animationComponent)
physicsComponent = PhysicsComponent(entity: self, bodySize: CGSize(width: spriteComponent.node.size.width * 0.8, height: spriteComponent.node.size.height * 0.8), bodyShape: .squareOffset, rotation: false)
physicsComponent.setCategoryBitmask(ColliderType.Princess.rawValue, dynamic: true)
physicsComponent.setPhysicsCollisions(ColliderType.Wall.rawValue)
addComponent(physicsComponent)
//Final setup of components
spriteComponent.node.physicsBody = physicsComponent.physicsBody
spriteComponent.node.name = "\(name)Node"
self.name = "\(name)Entity"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func loadAnimations(textureAtlas:SKTextureAtlas) -> [AnimationState: Animation] {
var animations = [AnimationState: Animation]()
animations[.Idle] = AnimationComponent.animationFromAtlas(textureAtlas,
withImageIdentifier: AnimationState.Idle.rawValue,
forAnimationState: .Idle, repeatTexturesForever: true, textureSize: CGSize(width: 34.94, height: 55.0))
return animations
}
override func updateWithDeltaTime(seconds: NSTimeInterval) {
super.updateWithDeltaTime(seconds)
}
override func contactWith(entity:SGEntity) {
}
}
| mit | 3d56c0d53d0cf8e7448ee6a0d3cdf45c | 34.067568 | 212 | 0.647784 | 4.942857 | false | false | false | false |
visenze/visearch-widget-swift | ViSearchWidgets/ViSearchWidgets/ViFilterCategoryViewController.swift | 2 | 6302 | //
// ViFilterCategoryViewController.swift
// ViSearchWidgets
//
// Created by Hung on 30/11/16.
// Copyright © 2016 Visenze. All rights reserved.
//
import UIKit
private let reuseIdentifier = "ViFilterCategoryViewControllerCell"
/// delegate
public protocol ViFilterCategoryViewControllerDelegate : class {
func categoryFilterDone(filterItem: ViFilterItemCategory?)
func categoryFilterReset(filterItem: ViFilterItemCategory?)
}
/// Filter category view controller which allows multiple selection
open class ViFilterCategoryViewController: UIViewController , UITableViewDelegate, UITableViewDataSource {
/// table view which shows list of category options
public var tableView : UITableView {
let resultsView = self.view as! ViFilterTableView
return resultsView.tableView!
}
/// show/hide Power by Visenze image
public var showPowerByViSenze : Bool = true
/// Filter item configuration and selected items
open var filterItem : ViFilterItemCategory? = nil {
didSet {
// copy the selected options over
// we only want to keep the selected options once it is confirmed i.e. click on Done button
if let item = self.filterItem {
var arr : [ViFilterItemCategoryOption] = []
for option in item.selectedOptions {
arr.append(option)
}
self.selectedOptions = arr
}
}
}
/// store selected options
open var selectedOptions : [ViFilterItemCategoryOption] = []
/// delegate
open var delegate : ViFilterCategoryViewControllerDelegate? = nil
open override func loadView() {
self.view = ViFilterTableView(frame: .zero)
}
override open func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
let filterTableView = self.view as! ViFilterTableView
filterTableView.powerImgView.isHidden = !self.showPowerByViSenze
// filterTableView.okBtn.addTarget(self, action: #selector(self.okBtnTap(sender:forEvent:) ), for: .touchUpInside)
let resetBarItem = UIBarButtonItem(title: "Clear All", style: .plain, target: self, action: #selector(resetBtnTap(sender:)))
self.navigationItem.leftBarButtonItem = resetBarItem
let doneBtnItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneBtnTap(sender:)) )
self.navigationItem.rightBarButtonItem = doneBtnItem
}
// MARK: Buttons events
public func okBtnTap(sender: UIButton, forEvent event: UIEvent) {
self.doneTap()
}
open func resetBtnTap(sender: UIBarButtonItem) {
// clear all selection
self.selectedOptions.removeAll()
self.tableView.reloadData()
delegate?.categoryFilterReset(filterItem: self.filterItem)
}
private func doneTap(){
self.filterItem?.selectedOptions.removeAll()
// set selected
var arr : [ViFilterItemCategoryOption] = []
for option in self.selectedOptions {
arr.append(option)
}
self.filterItem?.selectedOptions = arr
delegate?.categoryFilterDone(filterItem: self.filterItem)
}
open func doneBtnTap(sender: UIBarButtonItem) {
self.doneTap()
}
// MARK: - Table view data source
open func numberOfSections(in tableView: UITableView) -> Int {
if let _ = self.filterItem {
return 1
}
return 0
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let item = self.filterItem {
return item.options.count
}
return 0
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let filterItem = self.filterItem {
let item = filterItem.options[indexPath.row]
var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier)
if (cell == nil) {
cell = UITableViewCell(style: .default, reuseIdentifier: reuseIdentifier)
}
if let cell = cell {
cell.textLabel?.text = item.option
// check whether selected
let (selected , _ ) = self.isSelected(item, filterItem)
cell.accessoryType = selected ? .checkmark : .none
}
return cell!
}
// this should never happen
return UITableViewCell(style: .value1, reuseIdentifier: reuseIdentifier)
}
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
if let filterItem = self.filterItem {
let item = filterItem.options[indexPath.row]
let (selected , selectedIndex ) = self.isSelected(item, filterItem)
if selected {
// remove from option
if (selectedIndex >= 0 && selectedIndex < self.selectedOptions.count) {
self.selectedOptions.remove(at: selectedIndex)
}
}
else {
self.selectedOptions.append(item)
}
self.tableView.reloadData()
}
}
// MARK: Helper methods
// check whether this option is currently selected
private func isSelected(_ curOption : ViFilterItemCategoryOption , _ filterItem: ViFilterItemCategory) -> (Bool , Int) {
var selected : Bool = false
var selectedIndex : Int = -1
for (index, selectedOption) in self.selectedOptions.enumerated() {
if selectedOption.value == curOption.value {
selected = true
selectedIndex = index
break
}
}
return (selected , selectedIndex )
}
}
| mit | 6804efd515ac88bb12e3384a975e1e8b | 30.663317 | 132 | 0.588319 | 5.362553 | false | false | false | false |
southfox/JFAlgo | Example/JFAlgo/BinaryGapViewController.swift | 1 | 2233 | //
// BinaryGapViewController.swift
// JFAlgo
//
// Created by Javier Fuchs on 9/6/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import JFAlgo
/// BinaryGap
/// Find longest sequence of zeros in binary representation of an integer.
/// A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
///
/// For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.
///
/// Write a function:
///
/// public func solution(N : Int) -> Int
/// that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
///
/// For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.
///
/// Assume that:
///
/// N is an integer within the range [1..2,147,483,647].
/// Complexity:
///
/// expected worst-case time complexity is O(log(N));
/// expected worst-case space complexity is O(1).
class BinaryGapViewController : BaseViewController {
@IBOutlet weak var numberField: UITextField!
@IBOutlet weak var runButton: UIButton!
let binaryGap = BinaryGap()
lazy var closure : (()->())? = { [weak self] in
if let strong = self {
strong.runButton.enabled = true
}
}
@IBAction func runAction() {
guard let text = numberField.text,
number = Int(text) else {
return
}
if binaryGap.checkDomainGenerator(number) == false {
self.showAlert(self.binaryGap.domainErrorMessage(), completion: closure)
return
}
runButton.enabled = false
let solution = binaryGap.solution(number)
self.showAlert("\(number): Solution = \(solution)", completion: closure)
}
} | mit | c8356ce2b537382a549d68d10bb35471 | 36.216667 | 370 | 0.676523 | 4.30888 | false | false | false | false |
sajeel/AutoScout | AutoScout/Models & View Models/CarsViewModel.swift | 1 | 4019 | //
// CarsViewModel.swift
// AutoScout
//
// Created by Sajjeel Khilji on 5/21/17.
// Copyright © 2017 Saj. All rights reserved.
//
import Foundation
import RealmSwift
class CarsViewModel: ViewsModelData, CustomViewModelInput
{
let backEndApi: AutoScoutAPIProtocol
var lastCancelableToken: AutoScoutAPICancelable?
internal var _delegate: ViewModelOutput?
var timer: DispatchSourceTimer?
private (set) var loading: Bool = false
private (set) var cars: [CellViewModel] = []
private (set) var carType: CarsRequestType = .All
init(backEndAPI: AutoScoutAPIProtocol)
{
self.backEndApi = backEndAPI
startTimer()
}
func loadInitialData()
{
self.loadData()
}
func clearData()
{
self.cars = []
}
public var delegate: ViewModelOutput?
{
get{
return _delegate
}
set (outputDelegate){
_delegate = outputDelegate!
}
}
private func startTimer() {
let queue = DispatchQueue.main
timer?.cancel() // cancel previous timer if any
timer = DispatchSource.makeTimerSource(queue: queue)
timer?.scheduleRepeating(deadline: .now() + .milliseconds(5), interval: DispatchTimeInterval.seconds(60), leeway: DispatchTimeInterval.seconds(5))
timer?.setEventHandler { [weak self] in
self?.loadInitialData()
}
timer?.resume()
}
private func stopTimer() {
timer?.cancel()
timer = nil
}
func loadData(responseValidationHandler: ((CarsResponse) -> Bool)? = nil)
{
// It's preferable to call this method on the main thread
assert(OperationQueue.current == OperationQueue.main)
self.lastCancelableToken?.cancel()
self.loading = true
self.lastCancelableToken = self.backEndApi.loadCars( carType, completionHandler: {
[weak self]
( response:CarsResponse ) in
if !(responseValidationHandler?(response) ?? true) {
return
}
switch response {
case .success(let cars):
let loadedCars = cars.map { CarInfo(
id: Int($0.carID!),
make: $0.make!,
milage: Int($0.milage!),
price: Int($0.price!),
fuelType: $0.fuelType!,
imageUrl: $0.imageUrl!,
firsRegistration: $0.firstRegistration!,
accidentFree: Bool($0.accidentFree!),
isFav:false)}
let cellViewModels = loadedCars.map{
CellViewModel(car: $0, delegate:self)
}
OperationQueue.main.addOperation({
self?.clearData()
self?.cars = (self?.cars ?? []) + cellViewModels
self?.loading = false
self?.delegate?.viewModelDidUpdate()
self?.carType = (self?.carType.circularNextCase())!
})
case .error(let error):
OperationQueue.main.addOperation({
self?.loading = false
self?.delegate?.viewModelLoadingDidFail(error: error)
})
}
})
}
func getReamlObject() -> Realm{
let realm = try! Realm()
return realm
}
}
extension CarsViewModel : CellViewModelOutput{
func saveFav(car: CarInfo){
let realm = getReamlObject()
try! realm.write() { // 2
car.isFav = true
realm.add(car,update: true)
}
}
func deleteFav(car: CarInfo){
//no implementation needed as this is
//find a better solution for this
}
}
| gpl-3.0 | 014d5a114f1420efddd19308db0b471a | 25.434211 | 154 | 0.520159 | 4.936118 | false | false | false | false |
slavapestov/swift | test/SILGen/generic_witness.swift | 4 | 969 | // RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
protocol Runcible {
func runce<A>(x: A)
}
// CHECK-LABEL: sil hidden @_TF15generic_witness3foo{{.*}} : $@convention(thin) <B where B : Runcible> (@in B) -> () {
func foo<B : Runcible>(x: B) {
// CHECK: [[METHOD:%.*]] = witness_method $B, #Runcible.runce!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : Runcible><τ_1_0> (@in τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[METHOD]]<B, Int>
x.runce(5)
}
// CHECK-LABEL: sil hidden @_TF15generic_witness3bar{{.*}} : $@convention(thin) (@in Runcible) -> ()
func bar(x: Runcible) {
var x = x
// CHECK: [[BOX:%.*]] = alloc_box $Runcible
// CHECK: [[TEMP:%.*]] = alloc_stack $Runcible
// CHECK: [[EXIST:%.*]] = open_existential_addr [[TEMP]] : $*Runcible to $*[[OPENED:@opened(.*) Runcible]]
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #Runcible.runce!1
// CHECK: apply [[METHOD]]<[[OPENED]], Int>
x.runce(5)
}
| apache-2.0 | 395c0212ee6d3539294826a6d4d34c87 | 39.166667 | 174 | 0.590249 | 3.041009 | false | false | false | false |
borglab/SwiftFusion | Scripts/Fan10.swift | 1 | 3270 | import ArgumentParser
import SwiftFusion
import BeeDataset
import BeeTracking
import TensorFlow
import PythonKit
import Foundation
/// Fan10: RP Tracker, using the new tracking model
struct Fan10: ParsableCommand {
typealias LikelihoodModel = TrackingLikelihoodModel<PretrainedDenseRAE, MultivariateGaussian, MultivariateGaussian>
@Option(help: "Run on track number x")
var trackId: Int = 3
@Option(help: "Run for number of frames")
var trackLength: Int = 80
@Option(help: "Size of feature space")
var featureSize: Int = 20
@Flag(help: "Training mode")
var training: Bool = false
func getTrainingDataEM(
from dataset: OISTBeeVideo,
numberForeground: Int = 300,
numberBackground: Int = 300
) -> [LikelihoodModel.Datum] {
let bgBoxes = dataset.makeBackgroundBoundingBoxes(patchSize: (40, 70), batchSize: numberBackground).map {
(frame: $0.frame, type: LikelihoodModel.PatchType.bg, obb: $0.obb)
}
let fgBoxes = dataset.makeForegroundBoundingBoxes(patchSize: (40, 70), batchSize: numberForeground).map {
(frame: $0.frame, type: LikelihoodModel.PatchType.fg, obb: $0.obb)
}
return fgBoxes + bgBoxes
}
// Just runs an RP tracker and saves image to file
// Make sure you have a folder `Results/fan10` before running
func run() {
let kHiddenDimension = 100
let dataDir = URL(fileURLWithPath: "./OIST_Data")
let generator = ARC4RandomNumberGenerator(seed: 42)
var em = MonteCarloEM<LikelihoodModel>(sourceOfEntropy: generator)
let trainingDataset = OISTBeeVideo(directory: dataDir, length: 30)!
let trainingData = getTrainingDataEM(from: trainingDataset)
let trackingModel = em.run(
with: trainingData,
iterationCount: 3,
hook: { i, _, _ in
print("EM run iteration \(i)")
},
given: LikelihoodModel.HyperParameters(
encoder: PretrainedDenseRAE.HyperParameters(hiddenDimension: kHiddenDimension, latentDimension: featureSize, weightFile: "./oist_rae_weight_\(featureSize).npy")
)
)
let exprName = "fan10_ae_mg_mg_track\(trackId)_\(featureSize)"
let imagesPath = "Results/fan10/\(exprName)"
if !FileManager.default.fileExists(atPath: imagesPath) {
do {
try FileManager.default.createDirectory(atPath: imagesPath, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error.localizedDescription);
}
}
let (fig, track, gt) = runProbabilisticTracker(
directory: dataDir,
likelihoodModel: trackingModel,
onTrack: trackId, forFrames: trackLength, withSampling: true,
withFeatureSize: featureSize,
savePatchesIn: "Results/fan10/\(exprName)"
)
/// Actual track v.s. ground truth track
fig.savefig("Results/fan10/\(exprName).pdf", bbox_inches: "tight")
fig.savefig("Results/fan10/\(exprName).png", bbox_inches: "tight")
let json = JSONEncoder()
json.outputFormatting = .prettyPrinted
let track_data = try! json.encode(track)
try! track_data.write(to: URL(fileURLWithPath: "Results/fan10/\(exprName)_track.json"))
let gt_data = try! json.encode(gt)
try! gt_data.write(to: URL(fileURLWithPath: "Results/fan10/\(exprName)_gt.json"))
}
}
| apache-2.0 | fd2140038ed4ac5d38cdb5ac9dccbccf | 33.0625 | 168 | 0.691437 | 3.784722 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Domains/Domain registration/RegisterDomainDetails/ViewModel/RegisterDomainDetailsServiceProxy.swift | 1 | 6077 | import Foundation
/// Protocol for cart response, empty because there are no external details.
protocol CartResponseProtocol {}
extension CartResponse: CartResponseProtocol {}
/// A proxy for being able to use dependency injection for RegisterDomainDetailsViewModel
/// especially for unittest mocking purposes
protocol RegisterDomainDetailsServiceProxyProtocol {
func validateDomainContactInformation(contactInformation: [String: String],
domainNames: [String],
success: @escaping (ValidateDomainContactInformationResponse) -> Void,
failure: @escaping (Error) -> Void)
func getDomainContactInformation(success: @escaping (DomainContactInformation) -> Void,
failure: @escaping (Error) -> Void)
func getSupportedCountries(success: @escaping ([WPCountry]) -> Void,
failure: @escaping (Error) -> Void)
func getStates(for countryCode: String,
success: @escaping ([WPState]) -> Void,
failure: @escaping (Error) -> Void)
func createShoppingCart(siteID: Int,
domainSuggestion: DomainSuggestion,
privacyProtectionEnabled: Bool,
success: @escaping (CartResponseProtocol) -> Void,
failure: @escaping (Error) -> Void)
func redeemCartUsingCredits(cart: CartResponseProtocol,
domainContactInformation: [String: String],
success: @escaping () -> Void,
failure: @escaping (Error) -> Void)
func changePrimaryDomain(siteID: Int,
newDomain: String,
success: @escaping () -> Void,
failure: @escaping (Error) -> Void)
}
class RegisterDomainDetailsServiceProxy: RegisterDomainDetailsServiceProxyProtocol {
private lazy var restApi: WordPressComRestApi = {
let accountService = AccountService(managedObjectContext: ContextManager.sharedInstance().mainContext)
return accountService.defaultWordPressComAccount()?.wordPressComRestApi ?? WordPressComRestApi.defaultApi(oAuthToken: "")
}()
private lazy var domainsServiceRemote = {
return DomainsServiceRemote(wordPressComRestApi: restApi)
}()
private lazy var transactionsServiceRemote = {
return TransactionsServiceRemote(wordPressComRestApi: restApi)
}()
func validateDomainContactInformation(contactInformation: [String: String],
domainNames: [String],
success: @escaping (ValidateDomainContactInformationResponse) -> Void,
failure: @escaping (Error) -> Void) {
domainsServiceRemote.validateDomainContactInformation(
contactInformation: contactInformation,
domainNames: domainNames,
success: success,
failure: failure
)
}
func getDomainContactInformation(success: @escaping (DomainContactInformation) -> Void,
failure: @escaping (Error) -> Void) {
domainsServiceRemote.getDomainContactInformation(success: success,
failure: failure)
}
func getSupportedCountries(success: @escaping ([WPCountry]) -> Void,
failure: @escaping (Error) -> Void) {
transactionsServiceRemote.getSupportedCountries(success: success,
failure: failure)
}
func getStates(for countryCode: String,
success: @escaping ([WPState]) -> Void,
failure: @escaping (Error) -> Void) {
domainsServiceRemote.getStates(for: countryCode,
success: success,
failure: failure)
}
func createShoppingCart(siteID: Int,
domainSuggestion: DomainSuggestion,
privacyProtectionEnabled: Bool,
success: @escaping (CartResponseProtocol) -> Void,
failure: @escaping (Error) -> Void) {
transactionsServiceRemote.createShoppingCart(siteID: siteID,
domainSuggestion: domainSuggestion,
privacyProtectionEnabled: privacyProtectionEnabled,
success: success,
failure: failure)
}
func redeemCartUsingCredits(cart: CartResponseProtocol,
domainContactInformation: [String: String],
success: @escaping () -> Void,
failure: @escaping (Error) -> Void) {
guard let cartResponse = cart as? CartResponse else {
fatalError()
}
transactionsServiceRemote.redeemCartUsingCredits(cart: cartResponse,
domainContactInformation: domainContactInformation,
success: success,
failure: failure)
}
func changePrimaryDomain(siteID: Int,
newDomain: String,
success: @escaping () -> Void,
failure: @escaping (Error) -> Void) {
domainsServiceRemote.setPrimaryDomainForSite(siteID: siteID,
domain: newDomain,
success: success,
failure: failure)
}
}
| gpl-2.0 | 543583d9fda6a65b2b8a63749511896c | 46.108527 | 129 | 0.527234 | 6.774805 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/WordPressTest/MediaTests.swift | 1 | 3858 | import XCTest
@testable import WordPress
class MediaTests: XCTestCase {
fileprivate var contextManager: TestContextManager!
fileprivate var context: NSManagedObjectContext!
fileprivate func newTestMedia() -> Media {
return NSEntityDescription.insertNewObject(forEntityName: Media.classNameWithoutNamespaces(), into: context) as! Media
}
override func setUp() {
super.setUp()
contextManager = TestContextManager()
context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.parent = contextManager.mainContext
}
override func tearDown() {
context.rollback()
ContextManager.overrideSharedInstance(nil)
super.tearDown()
}
func testThatAbsoluteURLsWork() {
do {
let media = newTestMedia()
let filePath = "sample.jpeg"
var expectedAbsoluteURL = try MediaFileManager.uploadsDirectoryURL()
expectedAbsoluteURL.appendPathComponent(filePath)
media.absoluteLocalURL = expectedAbsoluteURL
guard
let localPath = media.localURL,
let localURL = URL(string: localPath),
let absoluteURL = media.absoluteLocalURL
else {
XCTFail("Error building expected absolute URL: \(expectedAbsoluteURL)")
return
}
XCTAssert(localURL.lastPathComponent == expectedAbsoluteURL.lastPathComponent, "Error: unexpected local Media URL")
XCTAssert(absoluteURL == expectedAbsoluteURL, "Error: unexpected absolute Media URL")
} catch {
XCTFail("Error testing absolute URLs: \(error)")
}
}
func testThatAbsoluteThumbnailURLsWork() {
do {
let media = newTestMedia()
let filePath = "sample-thumbnail.jpeg"
var expectedAbsoluteURL = try MediaFileManager.cache.directoryURL()
expectedAbsoluteURL.appendPathComponent(filePath)
media.absoluteThumbnailLocalURL = expectedAbsoluteURL
guard
let localPath = media.localThumbnailURL,
let localURL = URL(string: localPath),
let absoluteURL = media.absoluteThumbnailLocalURL
else {
XCTFail("Error building expected absolute thumbnail URL: \(expectedAbsoluteURL)")
return
}
XCTAssert(localURL.lastPathComponent == expectedAbsoluteURL.lastPathComponent, "Error: unexpected local thumbnail Media URL")
XCTAssert(absoluteURL == expectedAbsoluteURL, "Error: unexpected absolute thumbnail Media URL")
} catch {
XCTFail("Error testing absolute thumbnail URLs: \(error)")
}
}
func testMediaHasAssociatedPost() {
let post = PostBuilder(context).build()
let media = newTestMedia()
media.addPostsObject(post)
XCTAssertTrue(media.hasAssociatedPost())
}
func testMediaHasntAssociatedPost() {
let media = newTestMedia()
XCTAssertFalse(media.hasAssociatedPost())
}
// MARK: - AutoUpload Failure Count
func testThatIncrementAutoUploadFailureCountWorks() {
let media = newTestMedia()
XCTAssertEqual(media.autoUploadFailureCount, 0)
media.incrementAutoUploadFailureCount()
XCTAssertEqual(media.autoUploadFailureCount, 1)
media.incrementAutoUploadFailureCount()
XCTAssertEqual(media.autoUploadFailureCount, 2)
}
func testThatResetAutoUploadFailureCountWorks() {
let media = newTestMedia()
media.incrementAutoUploadFailureCount()
media.incrementAutoUploadFailureCount()
media.resetAutoUploadFailureCount()
XCTAssertEqual(media.autoUploadFailureCount, 0)
}
}
| gpl-2.0 | f4d769069eed74392a78ab4f69cab689 | 35.056075 | 137 | 0.65267 | 6 | false | true | false | false |
nextriot/Abacus | Abacus/GameOptionsTableViewController.swift | 1 | 5288 | //
// GameOptionsTableViewController.swift
// Abacus
//
// Created by Kyle Gillen on 03/09/2015.
// Copyright © 2015 Next Riot. All rights reserved.
//
import UIKit
class GameOptionsTableViewController: UITableViewController {
@IBOutlet private var segmentedControls: [UISegmentedControl]! {
didSet {
segmentedControls.forEach { $0.tintColor = Constants.Colors.Fuchsia }
}
}
@IBOutlet private var sliders: [TooltipSlider]! {
didSet {
sliders.forEach { $0.tintColor = Constants.Colors.Fuchsia }
}
}
@IBOutlet private var labels: [UILabel]! {
didSet {
labels.forEach { $0.textColor = Constants.Colors.Fuchsia }
}
}
@IBOutlet private weak var participantsLabel: UILabel!
@IBOutlet private weak var goalLabel: UILabel!
@IBOutlet private weak var timerLabel: UILabel!
private var participantsType: UISegmentedControl?
private var participantsSlider: TooltipSlider?
private var goalMultiplier: UISegmentedControl?
private var goalSlider: TooltipSlider?
private var timerValue: UISegmentedControl?
private let tooltip = TooltipView(labelText: "0")
var gameOptions: CardGames.Canasta?
override func viewDidLoad() {
super.viewDidLoad()
if DeviceType.IS_IPHONE_4_OR_LESS {
tableView.scrollEnabled = true
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
participantsType = segmentedControls[0]
participantsSlider = sliders[1]
goalMultiplier = segmentedControls[1]
goalSlider = sliders[0]
timerValue = segmentedControls[2]
updateParticipantsLabel(participantsType?.selectedSegmentIndex, participants: participantsSlider?.value)
updateGoalLabel(goalMultiplier?.selectedSegmentIndex, goal: goalSlider?.value, slider: nil)
updateTimerLabel(timerValue?.selectedSegmentIndex)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: IBActions
@IBAction func participantsSliderChanged(sender: TooltipSlider) {
updateParticipantsLabel(participantsType?.selectedSegmentIndex, participants: sender.value)
}
@IBAction func participantsSegmentedControlChanged(sender: UISegmentedControl) {
updateParticipantsLabel(sender.selectedSegmentIndex, participants: participantsSlider?.value)
}
@IBAction func goalSliderChanged(sender: TooltipSlider) {
updateGoalLabel(goalMultiplier?.selectedSegmentIndex, goal: sender.value, slider: sender)
}
@IBAction func goalSegmentedControlChanged(sender: UISegmentedControl) {
updateGoalLabel(sender.selectedSegmentIndex, goal: goalSlider?.value, slider: nil)
}
@IBAction func timerSegmentedControlChanged(sender: UISegmentedControl) {
updateTimerLabel(sender.selectedSegmentIndex)
}
// MARK: Utility Methods
func updateParticipantsLabel(type: Int?, participants: Float?) {
if let _type = type, let _participants = participants {
var typeOfParticipants: String
switch (_type, _participants) {
case let (t, p) where t == 0 && p < 2: typeOfParticipants = "Player"
case let (t, p) where t == 1 && p < 2: typeOfParticipants = "Team"
case let (t, p) where t == 0 && p > 1: typeOfParticipants = "Players"
case let (t, p) where t == 1 && p > 1: typeOfParticipants = "Teams"
default: typeOfParticipants = "Participants"
}
let numberOfParticipants = String(Int(_participants))
participantsLabel.text = numberOfParticipants + " " + typeOfParticipants
}
}
func updateGoalLabel(multiplier: Int?, goal: Float?, slider: TooltipSlider?) {
if let _multiplier = multiplier, let _goal = goal {
let powerOfMultiplier: Int
var winningGoal = Int(_goal)
switch _multiplier {
case 0:
powerOfMultiplier = 10
goalSlider?.maximumValue = 50
case 1:
powerOfMultiplier = 100
goalSlider?.maximumValue = 50
case 2:
powerOfMultiplier = 1000
goalSlider?.maximumValue = 10
// sets slider to 5000 in case where previous selection
// exceeded 10 as, the multiplier would set the goal
// in excess of 10_000
if _goal > 10.0 {
goalSlider?.value = 5.0
winningGoal = Int(goalSlider!.value)
}
default:
powerOfMultiplier = 10
}
// update multiplier property of slider so that tooltipView will reflect the correct value
slider?.multiplier = powerOfMultiplier
let goalLabelText = winningGoal * powerOfMultiplier
goalLabel.text = String(goalLabelText) + " " + "Points"
}
}
func updateTimerLabel(time: Int?) {
if let _time = time {
var timeValue: Int
switch _time {
case 0: timeValue = 0
case 1: timeValue = 5
case 2: timeValue = 15
case 3: timeValue = 45
case 4: timeValue = 60
default: timeValue = 0
}
let timerLabelText = timeValue > 0 ? String(timeValue) + " " + "Minutes" : "No Timer"
timerLabel.text = timerLabelText
}
}
}
| apache-2.0 | afc5f764c5cfca8346782b25832c5a1c | 30.849398 | 108 | 0.672026 | 4.662257 | false | false | false | false |
steryokhin/AsciiArtPlayer | src/AsciiArtPlayer/Pods/DKImagePickerController/DKImagePickerController/DKImageResource.swift | 5 | 2008 | //
// DKImageResource.swift
// DKImagePickerController
//
// Created by ZhangAo on 15/8/11.
// Copyright (c) 2015年 ZhangAo. All rights reserved.
//
import UIKit
public extension Bundle {
class func imagePickerControllerBundle() -> Bundle {
let assetPath = Bundle(for: DKImageResource.self).resourcePath!
return Bundle(path: (assetPath as NSString).appendingPathComponent("DKImagePickerController.bundle"))!
}
}
public class DKImageResource {
private class func imageForResource(_ name: String) -> UIImage {
let bundle = Bundle.imagePickerControllerBundle()
let imagePath = bundle.path(forResource: name, ofType: "png", inDirectory: "Images")
let image = UIImage(contentsOfFile: imagePath!)
return image!
}
private class func stretchImgFromMiddle(_ image: UIImage) -> UIImage {
let centerX = image.size.width / 2
let centerY = image.size.height / 2
return image.resizableImage(withCapInsets: UIEdgeInsets(top: centerY, left: centerX, bottom: centerY, right: centerX))
}
class func checkedImage() -> UIImage {
return stretchImgFromMiddle(imageForResource("checked_background"))
}
class func blueTickImage() -> UIImage {
return imageForResource("tick_blue")
}
class func cameraImage() -> UIImage {
return imageForResource("camera")
}
class func videoCameraIcon() -> UIImage {
return imageForResource("video_camera")
}
class func emptyAlbumIcon() -> UIImage {
return stretchImgFromMiddle(imageForResource("empty_album"))
}
}
public class DKImageLocalizedString {
public class func localizedStringForKey(_ key: String) -> String {
return NSLocalizedString(key, tableName: "DKImagePickerController", bundle:Bundle.imagePickerControllerBundle(), value: "", comment: "")
}
}
public func DKImageLocalizedStringWithKey(_ key: String) -> String {
return DKImageLocalizedString.localizedStringForKey(key)
}
| mit | be914c2e232c18a2d9fab697026981fe | 28.5 | 144 | 0.694915 | 4.72 | false | false | false | false |
smoope/swift-client-conversation | Framework/Source/items/ConversationCollectionCells.swift | 1 | 3359 | //
// Copyright 2017 smoope GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
internal struct ConversationCellUserInfoKey: RawRepresentable, Equatable, Hashable {
internal typealias RawValue = String
internal var rawValue: String
internal var hashValue: Int { return rawValue.hashValue }
internal init(rawValue: RawValue) {
self.rawValue = rawValue
}
internal init(_ rawValue: RawValue) {
self.init(rawValue: rawValue)
}
/// represented as CGFloat
internal static var maxWidth: ConversationCellUserInfoKey =
.init("MaxWidthBaseConversationKey")
///
internal static var backgroundColor: ConversationCellUserInfoKey =
.init("BackgroundColorConversationKey")
///
internal static var foregroundColor: ConversationCellUserInfoKey =
.init("ForegroundColorConversationKey")
///
internal static var text: ConversationCellUserInfoKey =
.init("TextBaseConversationKey")
///
internal static var attributedText: ConversationCellUserInfoKey =
.init("AttributedTextBaseConversationKey")
///
internal static var detailText: ConversationCellUserInfoKey =
.init("DetailTextBaseConversationKey")
///
internal static var attributedDetailText: ConversationCellUserInfoKey =
.init("AttributedDetailTextBaseConversationKey")
}
internal class BaseConversationCell: UICollectionViewCell {
internal class func size(in conversationView: ConversationView,
with userInfo: [ConversationCellUserInfoKey : Any]?) -> CGSize {
return .zero
}
/// default implementation does nothing
internal func prepare(in conversationView: ConversationView,
with userInfo: [ConversationCellUserInfoKey : Any]?) {
// prepare the cell with data given in userInfo
}
}
internal class MessageBackgroundConversationCell: BaseConversationCell {
internal let backgroundImage: UIImageView
internal override init(frame: CGRect) {
backgroundImage = UIImageView(frame: frame)
backgroundImage.image = UIImage(named: "filled-background-16", in: Bundle(for: ConversationView.self), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate)
super.init(frame: frame)
backgroundView = backgroundImage
}
internal required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal override func prepare(in conversationView: ConversationView, with userInfo: [ConversationCellUserInfoKey: Any]?) {
super.prepare(in: conversationView, with: userInfo)
backgroundView?.tintColor = userInfo?[.backgroundColor] as? UIColor
}
}
| apache-2.0 | 6883c0ef92f55305acf17c2049c677c4 | 33.628866 | 167 | 0.695445 | 5.409018 | false | false | false | false |
tispr/tispr-card-stack | TisprCardStack/TisprCardStack/CardStackViewController.swift | 1 | 3244 | /*
Copyright 2015 BuddyHopp, 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.
*/
//
// CardStackViewController
//
// Created by Andrei Pitsko on 07/12/15.
//
import UIKit
public typealias CardStackView = UICollectionView
public typealias CardStackViewCell = UICollectionViewCell
public protocol CardStackDelegate {
func cardDidChangeState(_ cardIndex: Int)
}
public protocol CardStackDatasource {
func numberOfCards(in cardStack: CardStackView) -> Int
func card(_ cardStack: CardStackView, cardForItemAtIndex index: IndexPath) -> CardStackViewCell
}
open class CardStackViewController: UICollectionViewController, UIGestureRecognizerDelegate {
private struct Constants {
static let cardsPadding: CGFloat = 20
static let cardsHeightFactor: CGFloat = 0.33
}
open var delegate: CardStackDelegate? {
didSet {
layout.delegate = delegate
}
}
open var datasource: CardStackDatasource?
open var layout: CardStackViewLayout { return collectionViewLayout as! CardStackViewLayout }
override open func viewDidLoad() {
super.viewDidLoad()
layout.gesturesEnabled = true
collectionView!.isScrollEnabled = false
setCardSize(CGSize(width: collectionView!.bounds.width - 2 * Constants.cardsPadding, height: Constants.cardsHeightFactor * collectionView!.bounds.height))
}
override open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let datasource = datasource else {
assertionFailure("please set datasource before")
return 0
}
return datasource.numberOfCards(in: collectionView)
}
override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return datasource!.card(collectionView, cardForItemAtIndex: indexPath)
}
//This method should be called when new card added
open func newCardAdded() {
layout.newCardDidAdd(datasource!.numberOfCards(in: collectionView!) - 1)
}
//method to change animation speed
open func setAnimationSpeed(_ speed: Float) {
collectionView!.layer.speed = speed
}
//method to set size of cards
open func setCardSize(_ size: CGSize) {
layout.cardSize = size
}
open func moveCardUp() {
if layout.index > 0 {
layout.index -= 1
}
}
open func moveCardDown() {
if layout.index <= datasource!.numberOfCards(in: collectionView!) - 1 {
layout.index += 1
}
}
open func deleteCard() {
layout.cardDidRemoved(layout.index)
}
}
| apache-2.0 | 2a50eaf214fd9ee6f300e7b95ef803d2 | 29.037037 | 162 | 0.692972 | 4.915152 | false | false | false | false |
RobotRebels/SwiftLessons | students_trashspace/pnaumov/GeometryFigure.playground/Contents.swift | 1 | 2034 | //: Playground - noun: a place where people can play
import UIKit
protocol GeometryProtocol {
func calcPerimeter() -> Float // метод рассчитывающий периметр фигуры
func calcArea() -> Float // метод рассчитывающий площадь фигуры
}
protocol AxisProtocol {
var centerX: Int { get set } // координата центра фигуры на оси X
var centerY: Int { get set } // координата центра фигуры на оси Y
var rotationAngle: Float { get set } // угол поворота фигуры относительно оси X
var length: Int { get set }
var width: Int { get set }
func placeIntoAxisCenter() // разместить фигуру в центре координатной оси
func isCrossingFigure(otherFigure: AxisProtocol) -> Bool
}
class SquareFigure: GeometryProtocol, AxisProtocol {
var centerX: Int
var centerY: Int
var length: Int
var width: Int
var rotationAngle: Float
static let sidesCount: Int = 4
init(centerX: Int, centerY: Int, side: Int, rotationAngle: Float) {
self.width = side
self.length = side
self.centerX = centerX
self.centerY = centerY
self.rotationAngle = rotationAngle
}
// периметр фигуры
func calcPerimeter() -> Float {
return Float(SquareFigure.sidesCount * width)
}
// площадь фигуры
func calcArea() -> Float {
return pow(Float(width), 2.0)
}
func placeIntoAxisCenter() {
centerX = 0
centerY = 0
}
func isCrossingFigure(otherFigure: AxisProtocol) -> Bool {
return false
}
}
var newFigureFirst: SquareFigure = SquareFigure(centerX: 10, centerY: 10, side: 4, rotationAngle: 45)
var newFigureSecond: SquareFigure = SquareFigure(centerX: 20, centerY: 30, side: 5, rotationAngle: 5)
newFigureFirst.placeIntoAxisCenter()
| mit | 58af3b9afd08a54ac6ad6c4db773d4ae | 23.226667 | 102 | 0.653825 | 3.809224 | false | false | false | false |
jlainog/Messages | Messages/Messages/Message.swift | 1 | 2310 | //
// Message.swift
// Messages
//
// Created by Luis Ramirez on 3/9/17.
// Copyright © 2017 JLainoG. All rights reserved.
//
import Foundation
import JSQMessagesViewController
enum MessageType {
case text
}
extension MessageType {
var type: String {
switch self {
case .text: return "text"
}
}
}
protocol MessageInfo : Parseable, JSQMessageData {
var userId: String { get }
var userName: String { get }
var message: String { get }
var messageType : MessageType { get }
var timestamp: Double { get }
}
class Message : NSObject, MessageInfo {
var userId: String
var userName: String
var message: String
var messageType: MessageType
var timestamp: Double
required init(json: NSDictionary) {
self.userId = json["userId"] as? String ?? ""
self.userName = json["userName"] as? String ?? ""
self.message = json["message"] as? String ?? ""
self.messageType = json["messageType"] as? MessageType ?? MessageType.text
self.timestamp = json["timestamp"] as? Double ?? 0
}
convenience init(userId: String, userName: String, message: String, messageType: MessageType = .text, timestamp: TimeInterval = Date().timeIntervalSince1970) {
let json = ["userId": userId, "userName": userName, "message": message, "messageType": messageType, "timestamp": timestamp] as NSDictionary
self.init(json: json)
}
func buildJSON() -> NSDictionary {
var json = Dictionary<String, Any>()
json["userId"] = userId
json["userName"] = userName
json["message"] = message
json["messageType"] = messageType.type
json["timestamp"] = timestamp
return json as NSDictionary
}
}
//MARK: JSQMessageData
extension Message {
func senderId() -> String! {
return self.userId
}
func senderDisplayName() -> String! {
return self.userName
}
func text() -> String! {
return self.message
}
func isMediaMessage() -> Bool {
return self.messageType != .text
}
func date() -> Date! {
return Date(timeIntervalSince1970: self.timestamp)
}
func messageHash() -> UInt {
return UInt(self.hashValue)
}
}
| mit | d32179d8cfa19baa95db9e74a206448d | 24.655556 | 163 | 0.610654 | 4.44894 | false | false | false | false |
swift-lang/swift-k | tests/stdlib-v2/strings/008-string-functions.swift | 2 | 2391 | import "stdlib.v2";
assertEqual(string[] a, string[] b) {
assertEqual(length(a), length(b), msg = "Array sizes don't match");
foreach i in [0 : length(a) - 1] {
assertEqual(a[i], b[i]);
}
}
assertEqual(strcat("left", 1, "right"), "left1right");
assertEqual(strcat("oneArg"), "oneArg");
assertEqual(strcat("two", "Args"), "twoArgs");
assertEqual(length("0123456789"), 10);
assertEqual(length(""), 0);
string[] expected1 = ["one", "two", "three"];
string[] actual1 = split("one two three", " ");
assertEqual(actual1, expected1);
string[] expected11 = ["one", "two", "three", "four"];
string[] actual11 = split("one two three four", " ");
assertEqual(actual11, expected11);
string[] expected2 = ["one", "two three"];
string[] actual2 = split("one two three", " ", 2);
assertEqual(actual2, expected2);
string[] expected3 = ["one", "two", "three"];
string[] actual3 = splitRe("one two three", "\\s+");
assertEqual(actual3, expected3);
string[] expected4 = ["one", "two three"];
string[] actual4 = splitRe("one two three", "\\s+", 2);
assertEqual(actual4, expected4);
assertEqual(trim(" bla\n"), "bla");
assertEqual(substring("blabla", 3), "bla");
assertEqual(substring("blabla", 3, 5), "bl");
assertEqual(toUpper("blaBla"), "BLABLA");
assertEqual(toLower("BLAbLA"), "blabla");
assertEqual(join(["one", "two", "three"], " "), "one two three");
string[] empty = [];
assertEqual(join(empty, ""), "");
assertEqual(replaceAll("one two three two", "two", "four"), "one four three four");
assertEqual(replaceAll("one two three two", "two", "four", 1, 8), "one four three two");
assertEqual(replaceAllRe("one two three two", "([nr]e)", "x$1x"), "oxnex two thxrexe two");
assertEqual(replaceAllRe("one two three two", "t[wh]", "x", 1, 12), "one xo xree two");
assertEqual(indexOf("one two three two", "two", 0), 4);
assertEqual(indexOf("one two three two", "four", 0), -1);
assertEqual(indexOf("one two three two", "two", 6, 16), 14);
assertEqual(indexOf("one two three two", "two", 6, 10), -1);
assertEqual(lastIndexOf("one two three two", "two", -1), 14);
assertEqual(lastIndexOf("one two three two", "four", -1), -1);
assertEqual(lastIndexOf("one two three two", "two", 13, 0), 4);
assert(matches("aaabbccdd", "[ab]+[cd]+"));
string[] expected5 = ["one", "two", "three"];
string[] actual5 = findAllRe("one two three", "(\\w+)");
assertEqual(actual5, expected5);
| apache-2.0 | 9d275d6edee943eb206cd6ecc35312d4 | 32.676056 | 91 | 0.640736 | 3.12549 | false | false | false | false |
oacastefanita/PollsFramework | PollsFramework/Classes/APIClient.swift | 1 | 22145 | import Alamofire
#if os(iOS)
import SwiftSpinner
#elseif os(OSX)
import ProgressKit
import Cocoa
#elseif os(watchOS)
import WatchKit
#endif
open class APIClient: NSObject{
/// Singleton
public static let sharedInstance = APIClient()
/// Log level for console output
///
/// - noLog: nothing in the console
/// - info: just the url of the requests
/// - debug: full info
public enum LogLevel {
case noLog
case info
case debug
}
//TODO:Change for production
open var logLevel:LogLevel = .debug
override init() {
super.init()
}
/// JSON string to be printed in the console
var jsonString = ""
/// URL path to be printed in the console
var logPath = ""
/// The last request performed by the singleton used when a relogin is necessary
var lastRequest: URLRequest?
/// PUT request
///
/// - Parameters:
/// - path: URL path to the request (not the full path, this is added to the baseURL)
/// - object: Body parameters of the request
/// - stringObject: String to be printed in the console
/// - headers: Header parameters of the request
/// - completionHandler: Handler that will be called when the response is received
open func putObject(_ path:String, object:[String: Any], stringObject:String = "", headers:[String:String]? = nil, completionHandler:((Bool, Any?) -> Void)?) {
self.logRequest(path, object: object, stringObject: stringObject, headers: headers)
self.showSpinner()
Alamofire.request( "\(POLLS_FRAMEWORK.baseURL!)\(path)", method: .put, parameters: object, encoding: JSONEncoding.default, headers:addVersionToHeaders(headers)).responseJSON { (response) in
DispatchQueue.main.async {
self.log(path, response:response)
self.lastRequest = response.request
self.hideSpinner()
if response.result.isSuccess {
if let dict = response.result.value as? NSDictionary {
self.checkResponseDict(dict: dict, withCompletionHandler: completionHandler)
}
}
else {
if POLLS_FRAMEWORK.handleErrors {
self.showErrorWithMessage(message: response.description)
} else if let handler = completionHandler {
handler(false,response.description)
}
}
}
}
}
/// POST request
///
/// - Parameters:
/// - path: URL path to the request (not the full path, this is added to the baseURL)
/// - object: Body parameters of the request
/// - stringObject: String to be printed in the console
/// - headers: Header parameters of the request
/// - completionHandler: Handler that will be called when the response is received
open func postObject(_ path:String, object:[String: Any], stringObject:String = "", headers:[String:String]? = nil, completionHandler:((Bool, Any?) -> Void)?) {
self.logRequest(path, object: object, stringObject: stringObject, headers: headers)
self.showSpinner()
Alamofire.request( "\(POLLS_FRAMEWORK.baseURL!)\(path)", method: .post, parameters: object, encoding: JSONEncoding.default, headers:addVersionToHeaders(headers)).responseJSON { (response) in
DispatchQueue.main.async {
self.log(path, response:response)
if path.range(of: "Login") == nil{
self.lastRequest = response.request
}
self.hideSpinner()
if response.result.isSuccess {
if let dict = response.result.value as? NSDictionary {
self.checkResponseDict(dict: dict, withCompletionHandler: completionHandler)
} else if let handler = completionHandler {
handler(true,response.result.value)
}
}
else {
if POLLS_FRAMEWORK.handleErrors {
self.showErrorWithMessage(message: response.description)
} else if let handler = completionHandler {
handler(false,response.description)
}
}
}
}
}
/// Image file upload
///
/// - Parameters:
/// - path: URL path to the request (not the full path, this is added to the baseURL)
/// - image: The local URL of the image
/// - headers: Header parameters of the request
/// - completionHandler: Handler that will be called when the response is received
open func multipartImageUpload(_ path:String, image:URL, headers:[String:String]? = nil, completionHandler:((Bool, Any?) -> Void)?) {
self.showSpinner()
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(image, withName: "fileUpload")
},
to: "\(POLLS_FRAMEWORK.baseURL!)\(path)",
headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
DispatchQueue.main.async {
self.log(path, response:response)
self.hideSpinner()
if let dict = response.result.value as? NSDictionary {
self.checkResponseDict(dict: dict, withCompletionHandler: completionHandler)
} else if let handler = completionHandler {
handler(true,response.result.value)
}
}
}
case .failure(let encodingError):
DispatchQueue.main.async {
self.hideSpinner()
if POLLS_FRAMEWORK.handleErrors {
self.showErrorWithMessage(message: encodingError.localizedDescription)
} else if let handler = completionHandler {
handler(false,encodingError.localizedDescription)
}
}
}
})
}
/// GET request
///
/// - Parameters:
/// - path: URL path to the request (not the full path, this is added to the baseURL)
/// - object: Body parameters of the request
/// - stringObject: String to be printed in the console
/// - headers: Header parameters of the request
/// - completionHandler: Handler that will be called when the response is received
open func getObject(_ path:String, object:[String: Any], stringObject:String = "", headers:[String:String]? = nil, completionHandler:((Bool, Any?) -> Void)?) {
self.logRequest(path, object: object, stringObject: stringObject, headers: headers)
self.showSpinner()
Alamofire.request( "\(POLLS_FRAMEWORK.baseURL!)\(path)", method: .get, parameters: object, headers:addVersionToHeaders(headers)).responseJSON { (response) in
DispatchQueue.main.async {
self.log(path, response:response)
self.lastRequest = response.request
self.hideSpinner()
if response.result.isSuccess {
if let dict = response.result.value as? NSDictionary {
self.checkResponseDict(dict: dict, withCompletionHandler: completionHandler)
} else if let handler = completionHandler {
handler(true,response.result.value)
}
}
else {
if POLLS_FRAMEWORK.handleErrors {
self.showErrorWithMessage(message: response.description)
} else if let handler = completionHandler {
handler(false,response.description)
}
}
}
}
}
/// Add authentication headers
///
/// - Parameter headers: headers where the new authentication headers needs to be added
/// - Returns: new headers with the authetication headers included
func addVersionToHeaders(_ headers:[String:String]?) -> [String:String]!{
var newHeaders = headers
if newHeaders == nil{
newHeaders = [String:String]()
}
newHeaders?["version"] = "1.0"
return newHeaders
}
#if os(iOS) || os(watchOS) || os(tvOS)
/// Download image from server
///
/// - Parameters:
/// - path: URL path to the request (not the full path, this is added to the baseURL)
/// - headers: Header parameters of the request
/// - completionHandler: Handler that will be called when the response is received
open func downloadImage(_ path:String, headers:[String:String]? = nil, completionHandler:((Bool, UIImage?) -> Void)?) {
self.showSpinner()
Alamofire.request(path).responseData { response in
self.hideSpinner()
DispatchQueue.main.async {
if let data = response.result.value {
let image = UIImage(data: data)
if let handler = completionHandler {
handler(false, image)
}
} else{
if let handler = completionHandler {
handler(false, nil)
}
}
}
}
}
#elseif os(OSX)
/// Download image from server
///
/// - Parameters:
/// - path: URL path to the request (not the full path, this is added to the baseURL)
/// - headers: Header parameters of the request
/// - completionHandler: Handler that will be called when the response is received
open func downloadImage(_ path:String, headers:[String:String]? = nil, completionHandler:((Bool, NSImage?) -> Void)?) {
self.showSpinner()
Alamofire.request(path).responseData { response in
DispatchQueue.main.async {
self.hideSpinner()
if let data = response.result.value {
let image = NSImage(data: data)
if let handler = completionHandler {
handler(false, image)
}
} else{
if let handler = completionHandler {
handler(false, nil)
}
}
}
}
}
#endif
/// Show loading spinner
func showSpinner(){
if POLLS_FRAMEWORK.showLoadingIndicator{
#if os(iOS)
SwiftSpinner.show("Loading. Please wait")
#elseif os(tvOS)
let view = UIView(frame:CGRect(x:0, y:0, width:(POLLS_FRAMEWORK.window.frame.size.width), height:(POLLS_FRAMEWORK.window.frame.size.height)))
view.backgroundColor = UIColor.gray
view.tag = 99
let activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView.init(activityIndicatorStyle: .whiteLarge)
activityIndicator.alpha = 1.0
view.addSubview(activityIndicator)
activityIndicator.center = CGPoint(x:view.frame.size.width / 2,y: view.frame.size.height / 2)
activityIndicator.startAnimating()
POLLS_FRAMEWORK.window.addSubview(view)
#elseif os(OSX)
let view = NSView(frame:CGRect(x:0, y:0, width:(POLLS_FRAMEWORK.application.windows.last?.frame.size.width)!, height:(POLLS_FRAMEWORK.application.windows.last?.frame.size.height)!))
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.gray.cgColor
view.identifier = NSUserInterfaceItemIdentifier(rawValue: "999")
let indicator = NSProgressIndicator(frame:CGRect(x:0, y:0, width:(POLLS_FRAMEWORK.application.windows.last?.frame.size.width)!, height:(POLLS_FRAMEWORK.application.windows.last?.frame.size.height)!))
indicator.isIndeterminate = false
indicator.minValue = 0
indicator.maxValue = 15
indicator.increment(by: 0.3)
let timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { (timer) in
indicator.increment(by: 0.3)
}
view.addSubview(indicator)
POLLS_FRAMEWORK.application.windows.last?.contentView?.addSubview(view, positioned:.above, relativeTo:nil)
#endif
}
}
/// Hide loading spinner
func hideSpinner(){
#if os(iOS)
SwiftSpinner.hide()
#elseif os(tvOS)
for view in (POLLS_FRAMEWORK.window.subviews){
if view.tag == 99{
view.removeFromSuperview()
break
}
}
#elseif os(OSX)
for window in POLLS_FRAMEWORK.application.windows{
for view in (window.contentView?.subviews)!{
if view.identifier!.rawValue == "999"{
view.removeFromSuperview()
break
}
}
}
#endif
}
/// Log the request in the console for debug purposes
///
/// - Parameters:
/// - url: URL path of the request
/// - parameters: Body parameters of the request
/// - headers: Header parameters of the request
func logRequest(_ url:String, parameters:[String: Any], headers:[String:String]? = nil){
if logLevel == .info {
print("\n\nREQUEST " + POLLS_FRAMEWORK.baseURL + "/" + url)
}
else if logLevel == .debug {
if parameters != nil && headers != nil {
print("REQUEST:\(POLLS_FRAMEWORK.baseURL + url) HEAD:{\(headers!)} BODY:{\(jsonString)}")
}
else if headers != nil {
print("REQUEST:\(POLLS_FRAMEWORK.baseURL + url) HEAD:{\(headers!)}")
}
else if parameters != nil {
print("REQUEST:\(POLLS_FRAMEWORK.baseURL + url) BODY:{\(jsonString)}")
}
else {
print("REQUEST:\(POLLS_FRAMEWORK.baseURL + url)")
}
}
}
/// Log the response in the console for debug purposes
///
/// - Parameters:
/// - path: URL path of the request
/// - response: response received from the server
func log(_ path:String, response:DataResponse<Any>) {
if logLevel == .info {
print("\n\nRESPONSE for " + POLLS_FRAMEWORK.baseURL + "/" + path)
}
else if logLevel == .debug {
if let respData = response.data {
if response.data!.count > 0 {
if let strdata = String(data: respData, encoding: String.Encoding.utf8) {
print("\n\nRESPONSE for " + POLLS_FRAMEWORK.baseURL + path + ": " + strdata)
}
}
else {
print("\n\nRESPONSE for " + POLLS_FRAMEWORK.baseURL + path + ": " + response.description)
}
}
else {
print("\n\nRESPONSE for " + POLLS_FRAMEWORK.baseURL + path + ": " + response.description)
}
}
}
/// Log request in the console for debug purposes
///
/// - Parameters:
/// - path: URL path of the request
/// - object: Body parameters of the request
/// - stringObject: Custom body sent to be printed in the console
/// - headers: Header parameters of the request
func logRequest(_ path:String, object:[String: Any], stringObject:String = "", headers:[String:String]? = nil){
logPath = path
if stringObject.isEmpty {
do {
let postData : Data = try JSONSerialization.data(withJSONObject: object, options: JSONSerialization.WritingOptions.prettyPrinted)
jsonString = NSString(data: postData, encoding: String.Encoding.utf8.rawValue)! as String
}
catch {
jsonString = ""
print(error)
}
}
else {
jsonString = stringObject
}
self.logRequest(path, parameters: object, headers: headers)
}
/// Process the server response
///
/// - Parameters:
/// - dict: server response body
/// - completionHandler: handle to be called when processing is complete
open func checkResponseDict(dict: NSDictionary, withCompletionHandler completionHandler:((Bool, Any?) -> Void)?){
if let errorCode = dict["ErrorCode"] as? Int, let additionalInformation = dict["AdditionalInformation"] as? String{
if errorCode == 16842757 {
if lastRequest == nil{
//take the user out
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kTakeUserOutNotification), object: nil)
#if os(iOS)
POLLS_FRAMEWORK.window.replaceRootViewControllerWith(POLLS_FRAMEWORK.window.rootViewController!, animated: true, completion:({
self.showErrorWithMessage(message: "Authentication Failed")
}))
#endif
return
}
POLLS_FRAMEWORK.login(login: LoginStruct(POLLS_FRAMEWORK.lastLogin)){ (success, response) in
if success {
Alamofire.request(self.lastRequest!).responseJSON { (response) in
self.lastRequest = nil
if response.result.isSuccess {
if let dict = response.result.value as? NSDictionary {
self.checkResponseDict(dict: dict, withCompletionHandler: completionHandler)
}
}
else {
if POLLS_FRAMEWORK.handleErrors {
self.showErrorWithMessage(message: response.description)
} else if let handler = completionHandler {
handler(false,response.description)
}
}
}
}
else {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kTakeUserOutNotification), object: nil)
#if os(iOS)
POLLS_FRAMEWORK.window.replaceRootViewControllerWith(POLLS_FRAMEWORK.window.rootViewController!, animated: true, completion:({
self.showErrorWithMessage(message: "Authentication Failed")
}))
#endif
}
}
return
}
if POLLS_FRAMEWORK.handleErrors {
if let handler = completionHandler {
handler(false, additionalInformation)
}
showErrorWithMessage(message: additionalInformation)
} else if let handler = completionHandler {
handler(false, additionalInformation)
}
} else if let message = dict["message"] as? String, message.range(of: "invalid") != nil{
if POLLS_FRAMEWORK.handleErrors {
if let handler = completionHandler {
handler(false, message)
}
showErrorWithMessage(message: "\(dict)")
} else if let handler = completionHandler {
handler(false, "\(dict)")
}
}else {
if let handler = completionHandler {
handler(true, dict)
}
}
}
/// Show error alert
///
/// - Parameter message: Alert message
func showErrorWithMessage(message: String){
#if os(iOS)
let alert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.destructive, handler: nil))
POLLS_FRAMEWORK.window.visibleViewController?.present(alert, animated: true, completion: nil)
#elseif os(tvOS)
let alert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.destructive, handler: nil))
POLLS_FRAMEWORK.window.visibleViewController?.present(alert, animated: true, completion: nil)
#elseif os(OSX)
self.showCloseAlert(title:"Error", message: message) { answer in
if answer == true{
}
}
#endif
}
#if os(OSX)
/// Show a close alert
///
/// - Parameters:
/// - title: Title of the alert
/// - message: Message of the alert
/// - completion: Handler to be called after showing the alert
func showCloseAlert(title: String, message: String,completion : (Bool)->Void) {
let alert = NSAlert()
alert.messageText = title
alert.informativeText = message
alert.alertStyle = NSAlert.Style.warning
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
completion(alert.runModal() == NSApplication.ModalResponse.alertFirstButtonReturn)
}
#endif
}
| mit | 00306008f9569d1037d6afa0d37bc54b | 42.336595 | 215 | 0.54396 | 5.248874 | false | false | false | false |
iAugux/Zoom-Contacts | Phonetic/Phonetic.swift | 1 | 3792 | //
// Phonetic.swift
// Phonetic
//
// Created by Augus on 2/6/16.
// Copyright © 2016 iAugus. All rights reserved.
//
import Contacts
let kQuickSearchKeyRawValue = "kQuickSearchKeyRawValueRawValue"
let kAdditionalSettingsStatus = "kAdditionalSettingsStatus"
let kEnableNickname = "kEnableNickname"
let kEnableCustomName = "kEnableCustomName"
let kOverwriteAlreadyExists = "kOverwriteAlreadyExists"
let kEnableAllCleanPhonetic = "kEnableAllCleanPhonetic"
let kCleanPhoneticNickname = "kCleanPhoneticNickname"
let kCleanPhoneticMiddleName = "kCleanPhoneticMiddleName"
let kCleanPhoneticDepartment = "kCleanPhoneticDepartment"
let kCleanPhoneticCompany = "kCleanPhoneticCompany"
let kCleanPhoneticJobTitle = "kCleanPhoneticJobTitle"
let kCleanPhoneticPrefix = "kCleanPhoneticPrefix"
let kCleanPhoneticSuffix = "kCleanPhoneticSuffix"
let kCleanSocialProfilesKeys = "kCleanSocialProfilesKeys"
let kCleanInstantMessageAddressesKeys = "kCleanInstantMessageAddressesKeys"
let kEnableNicknameDefaultBool = true
let kEnableCustomNameDefaultBool = false
let kOverwriteAlreadyExistsDefaultBool = false
let kEnableAllCleanPhoneticDefaultBool = false
let kCleanPhoneticNicknameDefaultBool = false
let kCleanPhoneticMiddleNameDefaultBool = false
let kCleanPhoneticDepartmentDefaultBool = false
let kCleanPhoneticCompanyDefaultBool = false
let kCleanPhoneticJobTitleDefaultBool = false
let kCleanPhoneticPrefixDefaultBool = false
let kCleanPhoneticSuffixDefaultBool = false
let kCleanSocialProfilesKeysDefaultBool = false
let kCleanInstantMessageKeysDefaultBool = false
struct Phonetic {
var brief: String
var value: String?
}
enum QuickSearch: Int {
case MiddleName
case Department
case Company
case JobTitle
case Prefix
case Suffix
case Cancel
var key: String {
switch self {
case .MiddleName:
return NSLocalizedString("Middle Name", comment: "")
case .Department:
return NSLocalizedString("Department", comment: "")
case .Company:
return NSLocalizedString("Company", comment: "")
case .JobTitle:
return NSLocalizedString("Job Title", comment: "")
case .Prefix:
return NSLocalizedString("Prefix", comment: "")
case .Suffix:
return NSLocalizedString("Suffix", comment: "")
case .Cancel:
return NSLocalizedString("Cancel", comment: "")
}
}
}
enum PhoneticKeys: String {
case Nickname
case MiddleName
case Department
case Company
case JobTitle
case Prefix
case Suffix
case SocialProfiles
case InstantMessageAddresses
var key: String {
switch self {
case .Nickname:
return NSLocalizedString("Nickname", comment: "")
case .MiddleName:
return NSLocalizedString("Middle Name", comment: "")
case .Department:
return NSLocalizedString("Department", comment: "")
case .Company:
return NSLocalizedString("Company", comment: "")
case .JobTitle:
return NSLocalizedString("Job Title", comment: "")
case .Prefix:
return NSLocalizedString("Prefix", comment: "")
case .Suffix:
return NSLocalizedString("Suffix", comment: "")
case .SocialProfiles:
return NSLocalizedString("Social Profiles", comment: "")
case .InstantMessageAddresses:
return NSLocalizedString("Instant Message Addresses", comment: "")
}
}
} | mit | e074ba76945b30a29bcdf0bd033b5484 | 32.857143 | 78 | 0.662094 | 4.578502 | false | false | false | false |
Guichaguri/react-native-track-player | ios/RNTrackPlayer/Vendor/SwiftAudio/Classes/NowPlayingInfoController/NowPlayingInfoController.swift | 1 | 2149 | //
// MediaInfoController.swift
// SwiftAudio
//
// Created by Jørgen Henrichsen on 15/03/2018.
//
import Foundation
import MediaPlayer
public class NowPlayingInfoController: NowPlayingInfoControllerProtocol {
private let concurrentInfoQueue: DispatchQueueType
private var _infoCenter: NowPlayingInfoCenter
private var _info: [String: Any] = [:]
var infoCenter: NowPlayingInfoCenter {
return _infoCenter
}
var info: [String: Any] {
return _info
}
public required init() {
self.concurrentInfoQueue = DispatchQueue(label: "com.doublesymmetry.nowPlayingInfoQueue", attributes: .concurrent)
self._infoCenter = MPNowPlayingInfoCenter.default()
}
/// Used for testing purposes.
public required init(dispatchQueue: DispatchQueueType, infoCenter: NowPlayingInfoCenter) {
self.concurrentInfoQueue = dispatchQueue
self._infoCenter = infoCenter
}
public required init(infoCenter: NowPlayingInfoCenter) {
self.concurrentInfoQueue = DispatchQueue(label: "com.doublesymmetry.nowPlayingInfoQueue", attributes: .concurrent)
self._infoCenter = infoCenter
}
public func set(keyValues: [NowPlayingInfoKeyValue]) {
concurrentInfoQueue.async(flags: .barrier) { [weak self] in
guard let self = self else { return }
keyValues.forEach { (keyValue) in
self._info[keyValue.getKey()] = keyValue.getValue()
}
self._infoCenter.nowPlayingInfo = self._info
}
}
public func set(keyValue: NowPlayingInfoKeyValue) {
concurrentInfoQueue.async(flags: .barrier) { [weak self] in
guard let self = self else { return }
self._info[keyValue.getKey()] = keyValue.getValue()
self._infoCenter.nowPlayingInfo = self._info
}
}
public func clear() {
concurrentInfoQueue.async(flags: .barrier) { [weak self] in
guard let self = self else { return }
self._info = [:]
self._infoCenter.nowPlayingInfo = self._info
}
}
}
| gpl-3.0 | 812e1a316ea8376e219b10f4c05188ae | 29.253521 | 122 | 0.640596 | 4.639309 | false | false | false | false |
psmortal/Berry | Pod/Classes/global.swift | 1 | 1537 | //
// global.swift
// Zuzhong
//
// Created by mortal on 2016/12/13.
// Copyright © 2016年 矩点医疗科技有 限公司. All rights reserved.
//
import Foundation
import UIKit
public let SWIDTH = UIScreen.main.bounds.width
public let SHEIGHT = UIScreen.main.bounds.height
//MARK:- 是否模拟器
public struct Platform {
static let isSimulator: Bool = {
var isSim = false
#if arch(i386) || arch(x86_64)
isSim = true
#endif
return isSim
}()
}
public enum ScreenType {
case S4_0, S4_7,S5_5,S5_8,unknown
static func current() -> ScreenType {
switch SWIDTH,SHEIGHT{
case 320.0,_:
return ScreenType.S4_0
case 375.0,667.0:
return ScreenType.S4_7
case 375.0,812.0:
return ScreenType.S5_8
case 414.0,_:
return ScreenType.S5_5
default:
return ScreenType.unknown
}
}
}
public func splice(strs:[String?],with:String)->String{
let newStrs = strs.filter{$0 != nil}
if newStrs.count == 0 {
return ""
}
if newStrs.count == 1{
return strs[0]!
}
var str = ""
for i in 0...newStrs.count - 1 {
if newStrs[i] != nil && str.characters.count > 0{
str += with + newStrs[i]!
}
if newStrs[i] != nil && str.characters.count == 0 {
str += newStrs[i]!
}
if newStrs[i] == nil {
continue
}
}
return str
}
| mit | 0b73efb64b51a25def4adc9de5eb4255 | 19.888889 | 59 | 0.527261 | 3.530516 | false | false | false | false |
ps2/rileylink_ios | MinimedKit/Radio/MinimedPacket.swift | 1 | 1043 | //
// MinimedPacket.swift
// RileyLinkBLEKit
//
// Created by Pete Schwamb on 10/7/17.
// Copyright © 2017 Pete Schwamb. All rights reserved.
//
import Foundation
public struct MinimedPacket {
public let data: Data
public init(outgoingData: Data) {
self.data = outgoingData
}
public init?(encodedData: Data) {
if let decoded = encodedData.decode4b6b() {
if decoded.count == 0 {
return nil
}
let msg = decoded.prefix(upTo: (decoded.count - 1))
if decoded.last != msg.crc8() {
// CRC invalid
return nil
}
self.data = Data(msg)
} else {
// Could not decode message
return nil
}
}
public func encodedData() -> Data {
var dataWithCRC = self.data
dataWithCRC.append(data.crc8())
var encodedData = dataWithCRC.encode4b6b()
encodedData.append(0)
return Data(encodedData)
}
}
| mit | d041dbaffc11c11449c3e2a09d2daca4 | 22.681818 | 63 | 0.534549 | 4.305785 | false | false | false | false |
sunlijian/sinaBlog_repository | sinaBlog_sunlijian/sinaBlog_sunlijian/Classes/Model/IWUserAccount.swift | 1 | 3214 | //
// IWUserAccount.swift
// sinaBlog_sunlijian
//
// Created by sunlijian on 15/10/13.
// Copyright © 2015年 myCompany. All rights reserved.
//
import UIKit
class IWUserAccount: NSObject,NSCoding {
//访问令牌
var access_token: String?
//过期时间
var expires_in: NSTimeInterval = 0{// 如果是 Int?系统不会分配空间 会默认抛出一个错误 undefinedKey Int = 0会分配空间
didSet{
let nowDate = NSDate()
expires_date = nowDate.dateByAddingTimeInterval(expires_in)
}
}
var remind_in :String?
//用户的 uid
var uid: String?
//过期的时间
var expires_date :NSDate?
//用户的高清头像
var avatar_large: String?
//用户名
var name : String?
init(dictionary:[String: AnyObject]) {
super.init()
//字典转模型
setValuesForKeysWithDictionary(dictionary) //基于运行时的 运行的时候自动分配内存空间
}
//内部默认实现 如果只想要转一部分key 必须重写这个方法 从而忽略不需要转的值
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
//重写 description 打印出的是 字典类型的样式
override var description: String {
let keys = ["access_token","expires_in","remind_in","uid"]
return dictionaryWithValuesForKeys(keys).description
}
//拿到路径
static let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archiver")
//保存帐号信息 进行归档
func saveAccount(){
print(IWUserAccount.path)
//归档
NSKeyedArchiver.archiveRootObject(self, toFile: IWUserAccount.path)
}
class func loadAccount() -> IWUserAccount?{
let account = NSKeyedUnarchiver.unarchiveObjectWithFile(self.path) as? IWUserAccount
if let acc = account {
if acc.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
return account
}
}
return nil
}
//怎么归档
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(access_token, forKey: "access_token")
aCoder.encodeObject(expires_date, forKey: "expires_date")
aCoder.encodeObject(remind_in, forKey: "remind_in")
aCoder.encodeObject(uid, forKey: "uid")
aCoder.encodeObject(avatar_large, forKey: "avatar_large")
aCoder.encodeObject(name, forKey: "name")
}
//怎么解档
required init?(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObjectForKey("access_token") as? String
expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
remind_in = aDecoder.decodeObjectForKey("remind_in") as? String
uid = aDecoder.decodeObjectForKey("uid") as? String
avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
name = aDecoder.decodeObjectForKey("name") as? String
}
}
| apache-2.0 | 9f88d280f278e9f5470c550b5668afe5 | 30.387097 | 214 | 0.641316 | 4.422727 | false | false | false | false |
russbishop/swift | stdlib/public/SDK/Foundation/Notification.swift | 1 | 4859 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
@_silgen_name("__NSNotificationCreate")
internal func __NSNotificationCreate(_ name: NSString, _ object: AnyObject?, _ userInfo: AnyObject?) -> NSNotification
@_silgen_name("__NSNotificationUserInfo")
internal func __NSNotificationUserInfo(_ notif: NSNotification) -> AnyObject?
/**
`Notification` encapsulates information broadcast to observers via a `NotificationCenter`.
*/
public struct Notification : ReferenceConvertible, Equatable, Hashable {
public typealias ReferenceType = NSNotification
/// A tag identifying the notification.
public var name: Name
/// An object that the poster wishes to send to observers.
///
/// Typically this is the object that posted the notification.
public var object: AnyObject?
/// Storage for values or objects related to this notification.
public var userInfo: [String : Any]?
/// Initialize a new `Notification`.
///
/// The default value for `userInfo` is nil.
public init(name: Name, object: AnyObject? = nil, userInfo: [String : Any]? = nil) {
self.name = name
self.object = object
self.userInfo = userInfo
}
public var hashValue: Int {
return name.rawValue.hash
}
public var description: String {
return "name = \(name.rawValue), object = \(object), userInfo = \(userInfo)"
}
public var debugDescription: String {
return description
}
// FIXME: Handle directly via API Notes
public typealias Name = NSNotification.Name
}
/// Compare two notifications for equality.
///
/// - note: Notifications that contain non NSObject values in userInfo will never compare as equal. This is because the type information is not preserved in the `userInfo` dictionary.
public func ==(lhs: Notification, rhs: Notification) -> Bool {
if lhs.name.rawValue != rhs.name.rawValue {
return false
}
if let lhsObj = lhs.object {
if let rhsObj = rhs.object {
if lhsObj !== rhsObj {
return false
}
} else {
return false
}
} else if rhs.object != nil {
return false
}
if let lhsUserInfo = lhs.userInfo {
if let rhsUserInfo = rhs.userInfo {
if lhsUserInfo.count != rhsUserInfo.count {
return false
}
return _NSUserInfoDictionary.compare(lhsUserInfo, rhsUserInfo)
} else {
return false
}
} else if rhs.userInfo != nil {
return false
}
return true
}
extension Notification : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public static func _getObjectiveCType() -> Any.Type {
return NSNotification.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSNotification {
if let info = userInfo {
return __NSNotificationCreate(name.rawValue as NSString, object, _NSUserInfoDictionary.bridgeValue(from: info))
}
return NSNotification(name: name, object: object, userInfo: nil)
}
public static func _forceBridgeFromObjectiveC(_ x: NSNotification, result: inout Notification?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge type")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSNotification, result: inout Notification?) -> Bool {
if let userInfo = __NSNotificationUserInfo(x) {
if let info : [String : Any]? = _NSUserInfoDictionary.bridgeReference(from: userInfo) {
result = Notification(name: x.name, object: x.object, userInfo: info)
return true
} else {
result = nil
return false // something terrible went wrong...
}
} else {
result = Notification(name: x.name, object: x.object, userInfo: nil)
}
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNotification?) -> Notification {
var result: Notification? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
| apache-2.0 | 25b3c6810af1768c4664fc109589a4a1 | 33.21831 | 183 | 0.614736 | 5.120126 | false | false | false | false |
alexburtnik/ABSwiftExtensions | ABSwiftExtensions/Classes/UIKit/UIView+Storyboard.swift | 1 | 2396 | //
// UIView+IBInspectables.swift
// Cropper
//
// Created by Alex Burtnik on 6/3/17.
// Copyright © 2017 alexburtnik. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
public extension UIView {
@IBInspectable public var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable public var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable public var borderColor: UIColor? {
get {
return UIColor(cgColor: layer.borderColor!)
}
set {
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable public var shadowColor: UIColor? {
set {
layer.shadowColor = newValue!.cgColor
}
get {
if let color = layer.shadowColor {
return UIColor(cgColor:color)
}
else {
return nil
}
}
}
@IBInspectable public var shadowOpacity: Float {
set {
layer.shadowOpacity = newValue
}
get {
return layer.shadowOpacity
}
}
@IBInspectable public var shadowOffset: CGPoint {
set {
layer.shadowOffset = CGSize(width: newValue.x, height: newValue.y)
}
get {
return CGPoint(x: layer.shadowOffset.width, y:layer.shadowOffset.height)
}
}
@IBInspectable public var shadowRadius: CGFloat {
set {
layer.shadowRadius = newValue
}
get {
return layer.shadowRadius
}
}
}
public extension UIView {
public func setupConstraints(inContainer container: UIView) {
translatesAutoresizingMaskIntoConstraints = false
container.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: NSLayoutFormatOptions.alignAllCenterY , metrics: nil, views: ["view": self]))
container.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: NSLayoutFormatOptions.alignAllCenterX , metrics: nil, views: ["view": self]))
}
}
| mit | af6ebc4bfe2993fe21ff2c93f0f07c32 | 25.032609 | 182 | 0.573695 | 5.263736 | false | false | false | false |
P0ed/FireTek | Source/IO/GamepadKit/EventsController.swift | 1 | 3561 | import Foundation
import OpenEmuSystem
class EventsController {
lazy var deviceConfiguration = DeviceConfiguration(buttonsMapTable: [:], dPadMapTable: [:], keyboardMapTable: [:])
var leftJoystick = DSVector.zeroVector
var rightJoystick = DSVector.zeroVector
var leftTrigger = 0.0
var rightTrigger = 0.0
var hatDirection = DSHatDirection.null
func handleEvent(_ event: OEHIDEvent) {
switch event.type.rawValue {
case OEHIDEventTypeAxis.rawValue:
switch event.axis.rawValue {
case OEHIDEventAxisX.rawValue:
leftJoystick.dx = event.value.native
case OEHIDEventAxisY.rawValue:
leftJoystick.dy = -event.value.native
case OEHIDEventAxisZ.rawValue:
rightJoystick.dx = event.value.native
case OEHIDEventAxisRz.rawValue:
rightJoystick.dy = -event.value.native
default: break
}
case OEHIDEventTypeTrigger.rawValue:
switch event.axis.rawValue {
case OEHIDEventAxisRx.rawValue:
leftTrigger = event.value.native
case OEHIDEventAxisRy.rawValue:
rightTrigger = event.value.native
default: break
}
case OEHIDEventTypeButton.rawValue:
if let button = DSButton(rawValue: Int(event.buttonNumber)), let action = deviceConfiguration.buttonsMapTable[button] {
action.performAction(event.state == OEHIDEventStateOn)
}
case OEHIDEventTypeHatSwitch.rawValue:
if let hatDirection = DSHatDirection(rawValue: Int(event.hatDirection.rawValue)) {
let buttons = changedStateDPadButtons(self.hatDirection, current: hatDirection)
self.hatDirection = hatDirection
func performActions(_ buttons: [DSHatDirection], pressed: Bool) {
buttons.forEach { button in
if let action = deviceConfiguration.dPadMapTable[button] {
action.performAction(pressed)
}
}
}
performActions(buttons.up, pressed: false)
performActions(buttons.down, pressed: true)
}
case OEHIDEventTypeKeyboard.rawValue:
if let action = deviceConfiguration.keyboardMapTable[Int(event.keycode)] {
action.performAction(event.state == OEHIDEventStateOn)
}
default: break
}
}
func controlForEvent(_ event: OEHIDEvent) -> DSControl? {
var control: DSControl?
switch event.type.rawValue {
case OEHIDEventTypeAxis.rawValue:
if event.axis.rawValue == OEHIDEventAxisX.rawValue || event.axis.rawValue == OEHIDEventAxisY.rawValue {
control = .stick(.left)
} else if event.axis.rawValue == OEHIDEventAxisZ.rawValue || event.axis.rawValue == OEHIDEventAxisRz.rawValue {
control = .stick(.right)
}
case OEHIDEventTypeTrigger.rawValue:
if event.axis.rawValue == OEHIDEventAxisRx.rawValue {
control = .trigger(.left)
} else if event.axis.rawValue == OEHIDEventAxisRy.rawValue {
control = .trigger(.right)
}
case OEHIDEventTypeButton.rawValue:
if let button = DSButton(rawValue: Int(event.buttonNumber)) {
control = .button(button)
}
case OEHIDEventTypeHatSwitch.rawValue:
if let hatDirection = DSHatDirection(rawValue: Int(event.hatDirection.rawValue)) {
control = .dPad(hatDirection)
}
default: break
}
return control
}
}
func changedStateDPadButtons(_ previous: DSHatDirection, current: DSHatDirection) -> (up: [DSHatDirection], down: [DSHatDirection]) {
var up: [DSHatDirection] = []
var down: [DSHatDirection] = []
for i in 0...3 {
let bit = 1 << i
let was = previous.rawValue & bit
let now = current.rawValue & bit
if was != now {
if was != 0 {
up.append(DSHatDirection(rawValue: bit)!)
} else {
down.append(DSHatDirection(rawValue: bit)!)
}
}
}
return (up, down)
}
| mit | 1fb04e83b0a52f1d1b1557b3723e738a | 30.513274 | 133 | 0.724235 | 3.306407 | false | false | false | false |
peferron/algo | EPI/Primitive Types/Compute the parity of a word/swift/main.swift | 1 | 1559 | // O(n) where n is the size of the value type.
public func parityBruteforceReduce(value: UInt64) -> UInt {
return (0..<64).reduce(0) { (parity, i) in parity ^ UInt(value >> i & 1) }
}
// Still O(n), but much faster than the reduce.
public func parityBruteforceLoop(value: UInt64) -> UInt {
var parity: UInt = 0
var v = value
while v != 0 {
parity ^= UInt(v & 1)
v >>= 1
}
return parity
}
// O(k) where k is the number of bits set to 1 in the value.
public func parityBruteforceDropLowestBit(value: UInt64) -> UInt {
var parity: UInt = 0
var v = value
while v != 0 {
parity ^= 1
v &= (v - 1)
}
return parity
}
// O(log n) where n is the size of the value type.
public func parityXor(value: UInt64) -> UInt {
var v = value
v ^= v >> 32
v ^= v >> 16
v ^= v >> 8
v ^= v >> 4
v ^= v >> 2
v ^= v >> 1
return UInt(v & 1)
}
// O(n/m) where n is the size of the value type and m the size of the lookup table value type.
private func buildLookupTable() -> [UInt] {
let length = 1 << 16;
var table = [UInt](repeating: 0, count: length)
var parity: UInt = 0
for i in 0..<length {
let grayCode = i ^ (i >> 1)
table[grayCode] = parity
parity ^= 1
}
return table
}
private let lookupTable = buildLookupTable()
private let lookupMask: UInt64 = 1 << 16 - 1
public func parityLookupTable(value: UInt64) -> UInt {
var v = value;
v ^= v >> 32
v ^= v >> 16
return lookupTable[Int(v & lookupMask)]
}
| mit | 406b69a9949ac8d6b0645fda35f14542 | 23.359375 | 94 | 0.570237 | 3.295983 | false | false | false | false |
Raizlabs/SketchyCode | SketchyCode/SketchClasses/SketchClasses+Helpers.swift | 1 | 9316 | //
// SketchClasses+Helpers.swift
// SketchyCode
//
// Created by Brian King on 5/24/17.
// Copyright © 2017 Brian King. All rights reserved.
//
import Foundation
import Marshal
public typealias SketchUnknown = Any
extension CGFloat: ValueType {}
extension CGPoint: Unmarshaling {
public init(object: MarshaledObject) throws {
self.x = try object.value(for: "x")
self.y = try object.value(for: "y")
}
}
extension CGSize: Unmarshaling {
public init(object: MarshaledObject) throws {
self.width = try object.value(for: "width")
self.height = try object.value(for: "height")
}
}
// FIXME: This should really be an `MSFont` object. I'm not sure how this will behave if fonts used don't exist on the mac, but I'm pretty sure everything will be nil.
extension NSFont: ValueType {
public static func value(from object: Any) throws -> Value {
guard let obj = object as? [String: Any] else {
throw MarshalError.typeMismatch(expected: [String:Any].self, actual: type(of: object))
}
let attrs: [String: Any] = try obj.value(for: "attributes")
guard let font = NSFont(
name: try attrs.value(for: "NSFontNameAttribute"),
size: try attrs.value(for: "NSFontSizeAttribute")
) else {
throw MarshalError.typeMismatch(expected: [String:Any].self, actual: type(of: object))
}
return font
}
}
extension NSColor: ValueType {
// "rgba(0,0,0,0.15)"
// "#FFFFFF"
public static func value(from object: Any) throws -> Value {
guard let obj = object as? [String: Any] else {
throw MarshalError.typeMismatch(expected: [String:Any].self, actual: type(of: object))
}
let value: String = try obj.value(for: "value") ?? obj.value(for: "color")
if value.characters.first == "#" {
return try parse(hex: value)
}
else {
return try parse(command: value)
}
}
static func parse(command: String) throws -> NSColor {
let parts = command.components(separatedBy: CharacterSet(charactersIn: "()"))
let cmd = parts[0]
let levels = parts[1].components(separatedBy: ",")
.map(Double.init).flatMap() { $0 }
.map() { CGFloat($0) }.flatMap() { $0 }
switch (cmd, levels) {
case ("rgba", let levels) where levels.count == 4:
return NSColor(red: levels[0], green: levels[1], blue: levels[2], alpha: levels[3])
default:
throw MarshalError.typeMismatch(expected: "NSColor", actual: command)
}
}
static func parse(hex: String) throws -> NSColor {
// map over hex-string pairs
let rgb = (0..<3).map() { (index: Int) -> String in
let (start, end) = (
hex.index(hex.startIndex, offsetBy: (2 * index)),
hex.index(hex.startIndex, offsetBy: (2 * index) + 2)
)
return hex[start..<end]
// Scan into integers
}.map() { (chunk: String) -> UInt32 in
var scanInt: UInt32 = 0
Scanner(string: chunk).scanHexInt32(&scanInt)
return scanInt
// Convert to floats
}.map() { (scan: UInt32) -> CGFloat in
return CGFloat(scan) / 255.0
}
return NSColor(red: rgb[0], green: rgb[1], blue: rgb[2], alpha: 1)
}
}
extension NSParagraphStyle: ValueType {
public static func value(from inputObject: Any) throws -> Value {
guard let object = inputObject as? [String: Any] else {
throw MarshalError.typeMismatch(expected: [String:Any].self, actual: type(of: inputObject))
}
let style: [String: Any] = try object.value(for: "style")
let paragraph = NSMutableParagraphStyle()
paragraph.headerLevel = try style.value(for: "headerLevel")
paragraph.paragraphSpacing = try style.value(for: "paragraphSpacing")
let tabStops: [CGFloat] = try style.value(for: "tabStops")
paragraph.tabStops = tabStops.map { NSTextTab(textAlignment: .natural, location: $0, options: [:]) }
paragraph.headIndent = try style.value(for: "headIndent")
paragraph.lineBreakMode = NSLineBreakMode(rawValue: try style.value(for: "lineBreakMode")) ?? .byWordWrapping
paragraph.hyphenationFactor = try style.value(for: "hyphenationFactor")
paragraph.alignment = NSTextAlignment(rawValue: try style.value(for: "alignment")) ?? .natural
paragraph.paragraphSpacingBefore = try style.value(for: "paragraphSpacingBefore")
paragraph.tailIndent = try style.value(for: "tailIndent")
paragraph.firstLineHeadIndent = try style.value(for: "firstLineHeadIndent")
paragraph.minimumLineHeight = try style.value(for: "minimumLineHeight")
paragraph.lineSpacing = try style.value(for: "lineSpacing")
paragraph.maximumLineHeight = try style.value(for: "maximumLineHeight")
paragraph.lineHeightMultiple = try style.value(for: "lineHeightMultiple")
paragraph.baseWritingDirection = NSWritingDirection(rawValue: try style.value(for: "baseWritingDirection")) ?? .natural
paragraph.defaultTabInterval = try style.value(for: "defaultTabInterval")
return paragraph
}
}
/**
* The expected format for NSAttributedString.
<class>: NSConcreteAttributedString
value: [
<class>: NSConcreteAttributedString
text: XXX
attributes:
[
[
location: X
length: Y
text: XXX // Subset of text above
... // NSAttributedString key / values
],
]
]
*/
extension NSAttributedString: ValueType {
public static func value(from inputObject: Any) throws -> Value {
guard let object = inputObject as? [String: Any] else {
throw MarshalError.typeMismatch(expected: [String:Any].self, actual: type(of: inputObject))
}
if let innerValue: [String: Any] = try object.value(for: "value") {
return try NSAttributedString.value(from: innerValue)
} else if let text: String = try object.value(for: "text"),
let attributes: [[String: Any]] = try object.value(for: "attributes") {
let string = NSMutableAttributedString(string: text)
for subStringParts in attributes {
var subStringParts = subStringParts
guard let length = subStringParts.removeValue(forKey: "length") as? Int,
let location: Int = subStringParts.removeValue(forKey: "location") as? Int,
let text: String = subStringParts.removeValue(forKey: "text") as? String else {
throw MarshalError.typeMismatch(expected: "length/location/text information", actual: subStringParts)
}
let range = NSRange(location: location, length: length)
// This text can be discarded, but we'll double check it matches the length/location.
guard text == string.attributedSubstring(from: range).string else {
throw MarshalError.typeMismatch(expected: "containing string does not match location / length", actual: text)
}
var attributes: [String: Any] = [:]
if let font: NSFont = try subStringParts.value(for: "NSFont") {
attributes["NSFont"] = font
subStringParts.removeValue(forKey: "NSFont")
}
if let color: NSColor = try subStringParts.value(for: "NSColor") {
attributes["NSColor"] = color
subStringParts.removeValue(forKey: "NSColor")
}
for intKey in ["NSStrikethrough", "NSLigature", "NSUnderline", "NSSuperScript"] {
if let numericRepresentation: Int = try subStringParts.value(for: intKey) {
attributes[intKey] = numericRepresentation
subStringParts.removeValue(forKey: intKey)
}
}
for floatKey in ["NSKern", "NSBaselineOffset"] {
if let kern: CGFloat = try subStringParts.value(for: floatKey) {
attributes[floatKey] = kern
subStringParts.removeValue(forKey: floatKey)
}
}
if let paragraphStyle: NSParagraphStyle = try subStringParts.value(for: "NSParagraphStyle") {
attributes["NSParagraphStyle"] = paragraphStyle
subStringParts.removeValue(forKey: "NSParagraphStyle")
}
// Not sure how to represent this in NSAttributedString
subStringParts.removeValue(forKey: "MSAttributedStringTextTransformAttribute")
// Double check that there are no keys we don't know about.
guard subStringParts.count == 0 else {
throw MarshalError.typeMismatch(expected: "Not all attributes extracted", actual: subStringParts)
}
string.setAttributes(attributes, range: range)
}
return string
} else {
throw MarshalError.keyNotFound(key: "text/attributes or value")
}
}
}
| mit | 7c69fd9fae49014d4bb6f44cb2c059ca | 43.357143 | 167 | 0.603972 | 4.606825 | false | false | false | false |
gregomni/swift | SwiftCompilerSources/Sources/SIL/Value.swift | 2 | 3019 | //===--- Value.swift - the Value protocol ---------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import Basic
import SILBridging
public protocol Value : AnyObject, CustomStringConvertible {
var uses: UseList { get }
var type: Type { get }
var definingInstruction: Instruction? { get }
}
extension Value {
public var description: String {
SILNode_debugDescription(bridgedNode).takeString()
}
public var uses: UseList {
UseList(SILValue_firstUse(bridged))
}
public var function: Function {
SILNode_getFunction(bridgedNode).function
}
public var type: Type { SILValue_getType(bridged).type }
public var definingInstruction: Instruction? {
switch self {
case let inst as SingleValueInstruction:
return inst
case let mvi as MultipleValueInstructionResult:
return mvi.instruction
default:
return nil
}
}
public var definingBlock: BasicBlock? {
if let inst = definingInstruction {
return inst.block
}
if let arg = self as? Argument {
return arg.block
}
return nil
}
public var hashable: HashableValue { ObjectIdentifier(self) }
public var bridged: BridgedValue {
BridgedValue(obj: SwiftObject(self as AnyObject))
}
var bridgedNode: BridgedNode {
BridgedNode(obj: SwiftObject(self as AnyObject))
}
}
public typealias HashableValue = ObjectIdentifier
// We can't make `Value` inherit from `Equatable`, since `Equatable` is a PAT,
// and we do use `Value` existentials around the codebase. Thus functions from
// `Equatable` are declared separately.
public func ==(_ lhs: Value, _ rhs: Value) -> Bool {
return lhs === rhs
}
public func !=(_ lhs: Value, _ rhs: Value) -> Bool {
return !(lhs === rhs)
}
extension BridgedValue {
public func getAs<T: AnyObject>(_ valueType: T.Type) -> T { obj.getAs(T.self) }
public var value: Value {
// This is much faster than a conformance lookup with `as! Value`.
let v = getAs(AnyObject.self)
switch v {
case let inst as SingleValueInstruction:
return inst
case let arg as Argument:
return arg
case let mvr as MultipleValueInstructionResult:
return mvr
case let undef as Undef:
return undef
default:
fatalError("unknown Value type")
}
}
}
final class Undef : Value {
public var definingInstruction: Instruction? { nil }
}
final class PlaceholderValue : Value {
public var definingInstruction: Instruction? { nil }
}
extension OptionalBridgedValue {
var value: Value? { obj.getAs(AnyObject.self) as? Value }
}
| apache-2.0 | a8550cf9de6a6d51ba9abdbf32e0196a | 25.955357 | 81 | 0.65949 | 4.343885 | false | false | false | false |
aol-public/OneMobileSDK-videorenderer-ios | VideoRenderer/VideoRenderer/PictureInPictureControllerObserver.swift | 1 | 2169 | // Copyright 2018, Oath Inc.
// Licensed under the terms of the MIT License. See LICENSE.md file in project root for terms.
import Foundation
import AVKit
public final class PictureInPictureControllerObserver: NSObject {
public enum Event {
case didChangedPossibility(to: Bool)
}
private let keyPathPiPPossible: String? = {
#if os(iOS)
return #keyPath(AVPictureInPictureController.pictureInPicturePossible)
#else
return nil
#endif
}()
private let emit: Action<Event>
private let pictureInPictureController: AnyObject
public init(pictureInPictureController: AnyObject, emit: @escaping Action<Event>) {
self.emit = emit
self.pictureInPictureController = pictureInPictureController
super.init()
guard let keyPathPiPPossible = keyPathPiPPossible else { return }
pictureInPictureController.addObserver(self,
forKeyPath: keyPathPiPPossible,
options: [.initial, .new],
context: nil)
}
override public func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath else { fatalError("Unexpected nil keypath!") }
guard let change = change else { fatalError("Change should not be nil!") }
guard keyPath == keyPathPiPPossible else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
guard let newKey = change[.newKey] as? NSNumber else { return }
emit(.didChangedPossibility(to: newKey.boolValue))
}
deinit {
guard let keyPathPiPPossible = keyPathPiPPossible else { return }
pictureInPictureController.removeObserver(self, forKeyPath: keyPathPiPPossible)
}
}
| mit | 3cd8c8386c2494b339d0659a938510f5 | 36.396552 | 97 | 0.586906 | 5.784 | false | false | false | false |
react-native-kit/react-native-track-player | ios/RNTrackPlayer/Vendor/SwiftAudio/Classes/AudioItem.swift | 1 | 5385 | //
// AudioItem.swift
// SwiftAudio
//
// Created by Jørgen Henrichsen on 18/03/2018.
//
import Foundation
import AVFoundation
public enum SourceType {
case stream
case file
}
public protocol AudioItem {
func getSourceUrl() -> String
func getArtist() -> String?
func getTitle() -> String?
func getAlbumTitle() -> String?
func getSourceType() -> SourceType
func getArtwork(_ handler: @escaping (UIImage?) -> Void)
}
/// Make your `AudioItem`-subclass conform to this protocol to control which AVAudioTimePitchAlgorithm is used for each item.
public protocol TimePitching {
func getPitchAlgorithmType() -> AVAudioTimePitchAlgorithm
}
/// Make your `AudioItem`-subclass conform to this protocol to control enable the ability to start an item at a specific time of playback.
public protocol InitialTiming {
func getInitialTime() -> TimeInterval
}
/// Make your `AudioItem`-subclass conform to this protocol to set initialization options for the asset. Available keys available at [Apple Developer Documentation](https://developer.apple.com/documentation/avfoundation/avurlasset/initialization_options).
public protocol AssetOptionsProviding {
func getAssetOptions() -> [String: Any]
}
public class DefaultAudioItem: AudioItem {
public var audioUrl: String
public var artist: String?
public var title: String?
public var albumTitle: String?
public var sourceType: SourceType
public var artwork: UIImage?
public init(audioUrl: String, artist: String? = nil, title: String? = nil, albumTitle: String? = nil, sourceType: SourceType, artwork: UIImage? = nil) {
self.audioUrl = audioUrl
self.artist = artist
self.title = title
self.albumTitle = albumTitle
self.sourceType = sourceType
self.artwork = artwork
}
public func getSourceUrl() -> String {
return audioUrl
}
public func getArtist() -> String? {
return artist
}
public func getTitle() -> String? {
return title
}
public func getAlbumTitle() -> String? {
return albumTitle
}
public func getSourceType() -> SourceType {
return sourceType
}
public func getArtwork(_ handler: @escaping (UIImage?) -> Void) {
handler(artwork)
}
}
/// An AudioItem that also conforms to the `TimePitching`-protocol
public class DefaultAudioItemTimePitching: DefaultAudioItem, TimePitching {
public var pitchAlgorithmType: AVAudioTimePitchAlgorithm
public override init(audioUrl: String, artist: String?, title: String?, albumTitle: String?, sourceType: SourceType, artwork: UIImage?) {
self.pitchAlgorithmType = AVAudioTimePitchAlgorithm.lowQualityZeroLatency
super.init(audioUrl: audioUrl, artist: artist, title: title, albumTitle: albumTitle, sourceType: sourceType, artwork: artwork)
}
public init(audioUrl: String, artist: String?, title: String?, albumTitle: String?, sourceType: SourceType, artwork: UIImage?, audioTimePitchAlgorithm: AVAudioTimePitchAlgorithm) {
self.pitchAlgorithmType = audioTimePitchAlgorithm
super.init(audioUrl: audioUrl, artist: artist, title: title, albumTitle: albumTitle, sourceType: sourceType, artwork: artwork)
}
public func getPitchAlgorithmType() -> AVAudioTimePitchAlgorithm {
return pitchAlgorithmType
}
}
/// An AudioItem that also conforms to the `InitialTiming`-protocol
public class DefaultAudioItemInitialTime: DefaultAudioItem, InitialTiming {
public var initialTime: TimeInterval
public override init(audioUrl: String, artist: String?, title: String?, albumTitle: String?, sourceType: SourceType, artwork: UIImage?) {
self.initialTime = 0.0
super.init(audioUrl: audioUrl, artist: artist, title: title, albumTitle: albumTitle, sourceType: sourceType, artwork: artwork)
}
public init(audioUrl: String, artist: String?, title: String?, albumTitle: String?, sourceType: SourceType, artwork: UIImage?, initialTime: TimeInterval) {
self.initialTime = initialTime
super.init(audioUrl: audioUrl, artist: artist, title: title, albumTitle: albumTitle, sourceType: sourceType, artwork: artwork)
}
public func getInitialTime() -> TimeInterval {
return initialTime
}
}
/// An AudioItem that also conforms to the `AssetOptionsProviding`-protocol
public class DefaultAudioItemAssetOptionsProviding: DefaultAudioItem, AssetOptionsProviding {
public var options: [String: Any]
public override init(audioUrl: String, artist: String?, title: String?, albumTitle: String?, sourceType: SourceType, artwork: UIImage?) {
self.options = [:]
super.init(audioUrl: audioUrl, artist: artist, title: title, albumTitle: albumTitle, sourceType: sourceType, artwork: artwork)
}
public init(audioUrl: String, artist: String?, title: String?, albumTitle: String?, sourceType: SourceType, artwork: UIImage?, options: [String: Any]) {
self.options = options
super.init(audioUrl: audioUrl, artist: artist, title: title, albumTitle: albumTitle, sourceType: sourceType, artwork: artwork)
}
public func getAssetOptions() -> [String: Any] {
return options
}
}
| apache-2.0 | d2e62d51a31476591295e7f976a4cb1c | 34.189542 | 255 | 0.696508 | 4.586031 | false | false | false | false |
mbogh/Schnell | Schnell/ViewControllers/SectionsViewController.swift | 1 | 2030 | //
// SectionsViewController.swift
// Schnell
//
// Created by Morten Bøgh on 05/06/14.
// Copyright (c) 2014 Morten Bøgh. All rights reserved.
//
import UIKit
import SchnellKit
class SectionsViewController: UITableViewController {
var viewModel = SectionsViewModel()
var favoriteSections = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = SectionCell.estimatedHeight
viewModel.activate()
self.tableView.reloadData()
}
// #pragma mark - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.viewModel.sections.count
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("SectionCell") as SectionCell
let roadSection = self.viewModel.sections[indexPath.row]
cell.addressLabel.text = roadSection.name
cell.zipcodeCityLabel.text = roadSection.zipcodeCity
cell.accessoryType = contains(favoriteSections, roadSection.id) ? .Checkmark : .None
return cell
}
// #pragma mark - UITableViewDelegate
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
let roadSection = self.viewModel.sections[indexPath.row]
if let index = find(favoriteSections, roadSection.id) {
favoriteSections.removeAtIndex(index)
}
else {
favoriteSections.append(roadSection.id)
}
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
| mit | 548fb6ffd9b3204282218f8f05504103 | 31.709677 | 121 | 0.685404 | 5.336842 | false | false | false | false |
jhwayne/Brew | DNApp/Spring/DesignableTextView.swift | 1 | 1428 | //
// DesignableTextView.swift
// 3DTransform
//
// Created by Meng To on 2014-11-27.
// Copyright (c) 2014 Meng To. All rights reserved.
//
import UIKit
@IBDesignable public class DesignableTextView: SpringTextView {
@IBInspectable public var borderColor: UIColor = UIColor.clearColor() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable public var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable public var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable public var lineHeight: CGFloat = 1.5 {
didSet {
var font = UIFont(name: self.font.fontName, size: self.font.pointSize)
var text = self.text
var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineHeight
var attributedString = NSMutableAttributedString(string: text!)
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))
attributedString.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
}
| mit | e74087f138d1f523cbbb16563955a366 | 29.382979 | 143 | 0.629552 | 5.429658 | false | false | false | false |
donnycrash/DCRadialGraph | Pod/Classes/DCRadialGraph.swift | 1 | 4682 | //
// DCRadialGraph.swift
// Pods
//
// Created by Donovan Crewe on 2015/09/16.
//
//
@IBDesignable public class DCRadialGraph: UIView {
@IBInspectable public var totalSegments: Int = 8
@IBInspectable public var counter: Int = 2 {
didSet {
if counter <= totalSegments {
animate()
} else {
counter = totalSegments
animate()
}
}
}
private var label = UILabel()
@IBInspectable public var arcOffset: CGFloat = 0.0
@IBInspectable public var arcColor: UIColor = UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0)
@IBInspectable public var arcBgColor: UIColor = UIColor(red:0.94, green:0.94, blue:0.94, alpha:1.0)
@IBInspectable var arcWidth: CGFloat = 3
private var segment:CAShapeLayer?
@IBInspectable public var duration: CGFloat = 3.0
@IBInspectable public var clockwise: Bool = false
@IBInspectable public var percentFont: UIFont = UIFont(name: "HelveticaNeue-UltraLight", size: 33)!
@IBInspectable public var autoLabel: Bool = true
override public func prepareForInterfaceBuilder() {
setup()
}
override public init(frame: CGRect) {
super.init(frame: frame)
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
#if !TARGET_INTERFACE_BUILDER
override public func layoutSubviews() {
setup()
}
#endif
var hasBgLayer = false
func setup() {
if autoLabel {
addAutoLabel()
}
segment = CAShapeLayer()
var backgroundLayer = CAShapeLayer()
self.backgroundColor = UIColor.clearColor()
let center = CGPoint(x:bounds.width/2, y: bounds.height/2)
let radius: CGFloat = max(bounds.width, bounds.height)
var endAngle: CGFloat = CGFloat(2 * M_PI)
var startAngle: CGFloat = 0
backgroundLayer.path = UIBezierPath(arcCenter: center,
radius: radius/2 - arcWidth/2,
startAngle: startAngle,
endAngle: endAngle,
clockwise: clockwise).CGPath
backgroundLayer.fillColor = UIColor.clearColor().CGColor
backgroundLayer.lineWidth = arcWidth
backgroundLayer.strokeColor = arcBgColor.CGColor
if !hasBgLayer {
self.layer.addSublayer(backgroundLayer)
segment?.fillColor = UIColor.clearColor().CGColor
segment?.lineWidth = arcWidth
segment?.strokeColor = arcColor.CGColor
self.layer.addSublayer(segment)
hasBgLayer = true
}
animate()
}
func animate(){
updateText()
let center = CGPoint(x:bounds.width/2, y: bounds.height/2)
let arcLengthPerSegment = 2 * CGFloat(M_PI) / CGFloat(totalSegments)
let segmentEndAngle = clockwise ? arcLengthPerSegment * CGFloat(counter) * -1 : arcLengthPerSegment * CGFloat(counter)
var startAngle = clockwise ? arcOffset : segmentEndAngle + arcOffset
var endAngle = clockwise ? segmentEndAngle + arcOffset : arcOffset
segment?.path = UIBezierPath(arcCenter: center,
radius: bounds.width/2 - arcWidth/2,
startAngle: startAngle,
endAngle: endAngle,
clockwise: false).CGPath
#if !TARGET_INTERFACE_BUILDER
var drawAnimation: CABasicAnimation?
if clockwise {
segment?.strokeEnd = 1.0
drawAnimation = CABasicAnimation(keyPath: "strokeEnd")
drawAnimation?.toValue = 1
drawAnimation?.fromValue = 0
} else {
drawAnimation = CABasicAnimation(keyPath: "strokeStart")
drawAnimation?.toValue = 0
drawAnimation?.fromValue = 1
}
var d = duration
drawAnimation?.duration = CFTimeInterval(d)
drawAnimation?.removedOnCompletion = true
drawAnimation?.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
drawAnimation?.delegate = self
segment?.addAnimation(drawAnimation, forKey: "drawCircleAnimation")
#endif
}
func addAutoLabel(){
label.textColor = tintColor
label.font = UIFont(name: percentFont.fontName, size: frame.height/2)
label.frame = CGRectMake(0, bounds.height/6, bounds.width, label.font.lineHeight)
label.textAlignment = NSTextAlignment.Center
var sublabel = UILabel(frame: CGRectMake(label.bounds.origin.x, label.bounds.height - label.font.lineHeight/6, label.frame.width, label.font.lineHeight/6))
sublabel.font = UIFont(name: percentFont.fontName, size: label.font.lineHeight/5)
sublabel.text = "PERCENT"
sublabel.textAlignment = label.textAlignment
sublabel.textColor = label.textColor
label.addSubview(sublabel)
addSubview(label)
bringSubviewToFront(label)
}
private func updateText(){
var percent = Int(Float(counter)/Float(totalSegments) * 100)
label.text = "\(percent)"
}
}
| mit | 88e66d24717f9400ef460a1e29e7f206 | 31.971831 | 159 | 0.687527 | 4.315207 | false | false | false | false |
chenl326/stwitter | stwitter/stwitter/Classes/Tools/Network/CLNetworkManager+Extension.swift | 1 | 3500 | //
// CLNetworkManager+Extension.swift
// stwitter
//
// Created by sun on 2017/5/24.
// Copyright © 2017年 sun. All rights reserved.
//
import Foundation
extension CLNetworkManager{
func statusList(since_id:Int64 = 0,max_id:Int64 = 0,completion:@escaping (_ list:[[String: Any]]?,_ isSuccess:Bool)->()) {
// let urlString = "http://cdn.a8.tvesou.com/right/recommend_video_list?leagueId=6"
let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
// let params = ["since_id": since_id, "max_id": max_id > 0 ?max_id - 1 : 0]
let params = ["since_id": since_id, "max_id": max_id > 0 ?max_id - 1 : 0] as [String : Any]
tokenRequest(URLString: urlString, parameters: params as [String : Any]!) { (jsonDict,isSuccess) in
let dic = jsonDict as? Dictionary<String,Any>
guard let result = dic?["statuses"] as?[[String:Any]] else{
return
}
// let dic = jsonDict as! [String:Any]
// print("json---\(dic["statuses"])")
/// Type 'Any' has no subscript members
// let result = dic["statuses"] as?[[String:Any]]
completion(result, isSuccess)
}
}
func unreadCount(completion:@escaping (_ unreadCount:Int) ->()) {
guard let uid = userAccount.uid else {
return
}
let urlStr = "https://rm.api.weibo.com/2/remind/unread_count.json"
let params = ["uid":uid]
tokenRequest(URLString: urlStr, parameters: params) { (json, isSuccess) in
print("unread---\(String(describing: json))")
let dic = json as?[String:Any]
let unreadCount = dic?["status"] as? Int
completion(unreadCount ?? 0)
}
}
}
//MARK -用户信息
extension CLNetworkManager{
func loadUserInfo(completion:@escaping (_ dict: [String:Any])->()) {
guard let uid = userAccount.uid else {
return
}
let urlStr = "https://api.weibo.com/2/users/show.json"
let params = ["uid":uid]
tokenRequest(URLString: urlStr, parameters: params) { (json, isSuccess) in
print(json ?? [:])
completion(json as? [String : Any] ?? [:])
}
}
}
//MARK -OAuth
extension CLNetworkManager{
func loadAccessToken(code:String,completion:@escaping (_ isSuccess: Bool)->()){
let urlStr = "https://api.weibo.com/oauth2/access_token"
let params = ["client_id":CLAppKey,
"client_secret":CLAppSecret,
"grant_type":"authorization_code",
"code":code,
"redirect_uri":CLRedirectURL
]
request(method: .POST, URLString: urlStr, parameters: params) { (json, isSuccess) in
// print("json---\(String(describing: json))")
//字典-》模型
self.userAccount.yy_modelSet(with: json as? [String : Any] ?? [:])
self.loadUserInfo(completion: { (json) in
print("userAccount---\(self.userAccount)")
self.userAccount.yy_modelSet(with: json)
self.userAccount.saveAccount()
completion(isSuccess)
})
}
}
}
| apache-2.0 | 4f1f90670c5e4ec000394ee766eabe35 | 31.820755 | 126 | 0.51739 | 4.305693 | false | false | false | false |
inacioferrarini/York | Classes/Extensions/UINavigationControllerExtension.swift | 1 | 1882 | // The MIT License (MIT)
//
// Copyright (c) 2016 Inácio Ferrarini
//
// 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
public enum PresentationMode: String {
case Push = "push"
case Show = "show"
case Modal = "modal"
// case Popover = "popover"
}
public extension UINavigationController {
public func presentViewController(_ viewController: UIViewController, animated: Bool, presentationMode: PresentationMode) {
if presentationMode == .Push {
self.pushViewController(viewController, animated: animated)
} else if presentationMode == .Show {
self.show(viewController, sender: self)
} else if presentationMode == .Modal {
self.present(viewController, animated: animated, completion: nil)
}
}
}
| mit | aa68edb4aaf841387ccd82a691d99754 | 39.021277 | 127 | 0.704413 | 4.655941 | false | false | false | false |
gribozavr/swift | test/type/subclass_composition.swift | 1 | 19978 | // RUN: %target-typecheck-verify-swift
protocol P1 {
typealias DependentInConcreteConformance = Self
}
class Base<T> : P1 { // expected-note {{arguments to generic parameter 'T' ('String' and 'Int') are expected to be equal}}
typealias DependentClass = T
required init(classInit: ()) {}
func classSelfReturn() -> Self {}
}
protocol P2 {
typealias FullyConcrete = Int
typealias DependentProtocol = Self
init(protocolInit: ())
func protocolSelfReturn() -> Self
}
typealias BaseAndP2<T> = Base<T> & P2
typealias BaseIntAndP2 = BaseAndP2<Int>
class Derived : Base<Int>, P2 {
required init(protocolInit: ()) {
super.init(classInit: ())
}
required init(classInit: ()) {
super.init(classInit: ())
}
func protocolSelfReturn() -> Self {}
}
class Other : Base<Int> {}
typealias OtherAndP2 = Other & P2
protocol P3 : class {}
struct Unrelated {}
//
// If a class conforms to a protocol concretely, the resulting protocol
// composition type should be equivalent to the class type.
//
// FIXME: Not implemented yet.
//
func alreadyConforms<T>(_: Base<T>) {} // expected-note {{'alreadyConforms' previously declared here}}
func alreadyConforms<T>(_: Base<T> & P1) {} // expected-note {{'alreadyConforms' previously declared here}}
func alreadyConforms<T>(_: Base<T> & AnyObject) {} // expected-error {{invalid redeclaration of 'alreadyConforms'}}
func alreadyConforms<T>(_: Base<T> & P1 & AnyObject) {} // expected-error {{invalid redeclaration of 'alreadyConforms'}}
func alreadyConforms(_: P3) {}
func alreadyConforms(_: P3 & AnyObject) {}
// SE-0156 stipulates that a composition can contain multiple classes, as long
// as they are all the same.
func basicDiagnostics(
_: Base<Int> & Base<Int>,
_: Base<Int> & Derived, // expected-error{{protocol-constrained type cannot contain class 'Derived' because it already contains class 'Base<Int>'}}
// Invalid typealias case
_: Derived & OtherAndP2, // expected-error{{protocol-constrained type cannot contain class 'Other' because it already contains class 'Derived'}}
// Valid typealias case
_: OtherAndP2 & P3) {}
// A composition containing only a single class is actually identical to
// the class type itself.
struct Box<T : Base<Int>> {}
func takesBox(_: Box<Base<Int>>) {}
func passesBox(_ b: Box<Base<Int> & Base<Int>>) {
takesBox(b)
}
// Test that subtyping behaves as you would expect.
func basicSubtyping(
base: Base<Int>,
baseAndP1: Base<Int> & P1,
baseAndP2: Base<Int> & P2,
baseAndP2AndAnyObject: Base<Int> & P2 & AnyObject,
baseAndAnyObject: Base<Int> & AnyObject,
derived: Derived,
derivedAndP2: Derived & P2,
derivedAndP3: Derived & P3,
derivedAndAnyObject: Derived & AnyObject,
p1AndAnyObject: P1 & AnyObject,
p2AndAnyObject: P2 & AnyObject,
anyObject: AnyObject) {
// Errors
let _: Base & P2 = base // expected-error {{value of type 'Base<Int>' does not conform to specified type 'P2'}}
let _: Base<Int> & P2 = base // expected-error {{value of type 'Base<Int>' does not conform to specified type 'P2'}}
let _: P3 = baseAndP1 // expected-error {{value of type 'Base<Int> & P1' does not conform to specified type 'P3'}}
let _: P3 = baseAndP2 // expected-error {{value of type 'Base<Int> & P2' does not conform to specified type 'P3'}}
let _: Derived = baseAndP1 // expected-error {{cannot convert value of type 'Base<Int> & P1' to specified type 'Derived'}}
let _: Derived = baseAndP2 // expected-error {{cannot convert value of type 'Base<Int> & P2' to specified type 'Derived'}}
let _: Derived & P2 = baseAndP2 // expected-error {{value of type 'Base<Int> & P2' does not conform to specified type 'Derived & P2'}}
let _ = Unrelated() as Derived & P2 // expected-error {{value of type 'Unrelated' does not conform to 'Derived & P2' in coercion}}
let _ = Unrelated() as? Derived & P2 // expected-warning {{always fails}}
let _ = baseAndP2 as Unrelated // expected-error {{cannot convert value of type 'Base<Int> & P2' to type 'Unrelated' in coercion}}
let _ = baseAndP2 as? Unrelated // expected-warning {{always fails}}
// Different behavior on Linux vs Darwin because of id-as-Any.
// let _ = Unrelated() as AnyObject
// let _ = Unrelated() as? AnyObject
let _ = anyObject as Unrelated // expected-error {{'AnyObject' is not convertible to 'Unrelated'; did you mean to use 'as!' to force downcast?}}
let _ = anyObject as? Unrelated
// No-ops
let _: Base & P1 = base
let _: Base<Int> & P1 = base
let _: Base & AnyObject = base
let _: Base<Int> & AnyObject = base
let _: Derived & AnyObject = derived
let _ = base as Base<Int> & P1
let _ = base as Base<Int> & AnyObject
let _ = derived as Derived & AnyObject
let _ = base as? Base<Int> & P1 // expected-warning {{always succeeds}}
let _ = base as? Base<Int> & AnyObject // expected-warning {{always succeeds}}
let _ = derived as? Derived & AnyObject // expected-warning {{always succeeds}}
// Erasing superclass constraint
let _: P1 = baseAndP1
let _: P1 & AnyObject = baseAndP1
let _: P1 = derived
let _: P1 & AnyObject = derived
let _: AnyObject = baseAndP1
let _: AnyObject = baseAndP2
let _: AnyObject = derived
let _: AnyObject = derivedAndP2
let _: AnyObject = derivedAndP3
let _: AnyObject = derivedAndAnyObject
let _ = baseAndP1 as P1
let _ = baseAndP1 as P1 & AnyObject
let _ = derived as P1
let _ = derived as P1 & AnyObject
let _ = baseAndP1 as AnyObject
let _ = derivedAndAnyObject as AnyObject
let _ = baseAndP1 as? P1 // expected-warning {{always succeeds}}
let _ = baseAndP1 as? P1 & AnyObject // expected-warning {{always succeeds}}
let _ = derived as? P1 // expected-warning {{always succeeds}}
let _ = derived as? P1 & AnyObject // expected-warning {{always succeeds}}
let _ = baseAndP1 as? AnyObject // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? AnyObject // expected-warning {{always succeeds}}
// Erasing conformance constraint
let _: Base = baseAndP1
let _: Base<Int> = baseAndP1
let _: Base = derivedAndP3
let _: Base<Int> = derivedAndP3
let _: Derived = derivedAndP2
let _: Derived = derivedAndAnyObject
let _ = baseAndP1 as Base<Int>
let _ = derivedAndP3 as Base<Int>
let _ = derivedAndP2 as Derived
let _ = derivedAndAnyObject as Derived
let _ = baseAndP1 as? Base<Int> // expected-warning {{always succeeds}}
let _ = derivedAndP3 as? Base<Int> // expected-warning {{always succeeds}}
let _ = derivedAndP2 as? Derived // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? Derived // expected-warning {{always succeeds}}
// Upcasts
let _: Base & P2 = derived
let _: Base<Int> & P2 = derived
let _: Base & P2 & AnyObject = derived
let _: Base<Int> & P2 & AnyObject = derived
let _: Base & P3 = derivedAndP3
let _: Base<Int> & P3 = derivedAndP3
let _ = derived as Base<Int> & P2
let _ = derived as Base<Int> & P2 & AnyObject
let _ = derivedAndP3 as Base<Int> & P3
let _ = derived as? Base<Int> & P2 // expected-warning {{always succeeds}}
let _ = derived as? Base<Int> & P2 & AnyObject // expected-warning {{always succeeds}}
let _ = derivedAndP3 as? Base<Int> & P3 // expected-warning {{always succeeds}}
// Calling methods with Self return
let _: Base & P2 = baseAndP2.classSelfReturn()
let _: Base<Int> & P2 = baseAndP2.classSelfReturn()
let _: Base & P2 = baseAndP2.protocolSelfReturn()
let _: Base<Int> & P2 = baseAndP2.protocolSelfReturn()
// Downcasts
let _ = baseAndP2 as Derived // expected-error {{did you mean to use 'as!' to force downcast?}}
let _ = baseAndP2 as? Derived
let _ = baseAndP2 as Derived & P3 // expected-error {{did you mean to use 'as!' to force downcast?}}
let _ = baseAndP2 as? Derived & P3
let _ = base as Derived & P2 // expected-error {{did you mean to use 'as!' to force downcast?}}
let _ = base as? Derived & P2
// Invalid cases
let _ = derived as Other & P2 // expected-error {{value of type 'Derived' does not conform to 'Other & P2' in coercion}}
let _ = derived as? Other & P2 // expected-warning {{always fails}}
let _ = derivedAndP3 as Other // expected-error {{cannot convert value of type 'Derived & P3' to type 'Other' in coercion}}
let _ = derivedAndP3 as? Other // expected-warning {{always fails}}
let _ = derivedAndP3 as Other & P3 // expected-error {{value of type 'Derived & P3' does not conform to 'Other & P3' in coercion}}
let _ = derivedAndP3 as? Other & P3 // expected-warning {{always fails}}
let _ = derived as Other // expected-error {{cannot convert value of type 'Derived' to type 'Other' in coercion}}
let _ = derived as? Other // expected-warning {{always fails}}
}
// Test conversions in return statements
func eraseProtocolInReturn(baseAndP2: Base<Int> & P2) -> Base<Int> {
return baseAndP2
}
func eraseProtocolInReturn(baseAndP2: (Base<Int> & P2)!) -> Base<Int> {
return baseAndP2
}
func eraseProtocolInReturn(baseAndP2: Base<Int> & P2) -> Base<Int>? {
return baseAndP2
}
func eraseClassInReturn(baseAndP2: Base<Int> & P2) -> P2 {
return baseAndP2
}
func eraseClassInReturn(baseAndP2: (Base<Int> & P2)!) -> P2 {
return baseAndP2
}
func eraseClassInReturn(baseAndP2: Base<Int> & P2) -> P2? {
return baseAndP2
}
func upcastToExistentialInReturn(derived: Derived) -> Base<Int> & P2 {
return derived
}
func upcastToExistentialInReturn(derived: Derived!) -> Base<Int> & P2 {
return derived
}
func upcastToExistentialInReturn(derived: Derived) -> (Base<Int> & P2)? {
return derived
}
func takesBase<T>(_: Base<T>) {}
func takesP2(_: P2) {}
func takesBaseMetatype<T>(_: Base<T>.Type) {}
func takesP2Metatype(_: P2.Type) {}
func takesBaseIntAndP2(_ x: Base<Int> & P2) {
takesBase(x)
takesP2(x)
}
func takesBaseIntAndP2Metatype(_ x: (Base<Int> & P2).Type) {
takesBaseMetatype(x)
takesP2Metatype(x)
}
func takesDerived(x: Derived) {
takesBaseIntAndP2(x)
}
func takesDerivedMetatype(x: Derived.Type) {
takesBaseIntAndP2Metatype(x)
}
//
// Looking up member types of subclass existentials.
//
func dependentMemberTypes<T : BaseIntAndP2>(
_: T.DependentInConcreteConformance,
_: T.DependentProtocol,
_: T.DependentClass,
_: T.FullyConcrete,
_: BaseIntAndP2.DependentInConcreteConformance, // FIXME expected-error {{}}
_: BaseIntAndP2.DependentProtocol, // expected-error {{type alias 'DependentProtocol' can only be used with a concrete type or generic parameter base}}
_: BaseIntAndP2.DependentClass,
_: BaseIntAndP2.FullyConcrete) {}
func conformsToAnyObject<T : AnyObject>(_: T) {}
// expected-note@-1 {{where 'T' = 'P1'}}
func conformsToP1<T : P1>(_: T) {}
// expected-note@-1 {{required by global function 'conformsToP1' where 'T' = 'P1'}}
func conformsToP2<T : P2>(_: T) {}
func conformsToBaseIntAndP2<T : Base<Int> & P2>(_: T) {}
// expected-note@-1 {{where 'T' = 'FakeDerived'}}
// expected-note@-2 {{where 'T' = 'T1'}}
// expected-note@-3 2 {{where 'T' = 'Base<Int>'}}
func conformsToBaseIntAndP2WithWhereClause<T>(_: T) where T : Base<Int> & P2 {}
// expected-note@-1 {{where 'T' = 'FakeDerived'}}
// expected-note@-2 {{where 'T' = 'T1'}}
class FakeDerived : Base<String>, P2 {
required init(classInit: ()) {
super.init(classInit: ())
}
required init(protocolInit: ()) {
super.init(classInit: ())
}
func protocolSelfReturn() -> Self { return self }
}
//
// Metatype subtyping.
//
func metatypeSubtyping(
base: Base<Int>.Type,
derived: Derived.Type,
derivedAndAnyObject: (Derived & AnyObject).Type,
baseIntAndP2: (Base<Int> & P2).Type,
baseIntAndP2AndAnyObject: (Base<Int> & P2 & AnyObject).Type) {
// Erasing conformance constraint
let _: Base<Int>.Type = baseIntAndP2
let _: Base<Int>.Type = baseIntAndP2AndAnyObject
let _: Derived.Type = derivedAndAnyObject
let _: BaseAndP2<Int>.Type = baseIntAndP2AndAnyObject
let _ = baseIntAndP2 as Base<Int>.Type
let _ = baseIntAndP2AndAnyObject as Base<Int>.Type
let _ = derivedAndAnyObject as Derived.Type
let _ = baseIntAndP2AndAnyObject as BaseAndP2<Int>.Type
let _ = baseIntAndP2 as? Base<Int>.Type // expected-warning {{always succeeds}}
let _ = baseIntAndP2AndAnyObject as? Base<Int>.Type // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? Derived.Type // expected-warning {{always succeeds}}
let _ = baseIntAndP2AndAnyObject as? BaseAndP2<Int>.Type // expected-warning {{always succeeds}}
// Upcast
let _: BaseAndP2<Int>.Type = derived
let _: BaseAndP2<Int>.Type = derivedAndAnyObject
let _ = derived as BaseAndP2<Int>.Type
let _ = derivedAndAnyObject as BaseAndP2<Int>.Type
let _ = derived as? BaseAndP2<Int>.Type // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? BaseAndP2<Int>.Type // expected-warning {{always succeeds}}
// Erasing superclass constraint
let _: P2.Type = baseIntAndP2
let _: P2.Type = derived
let _: P2.Type = derivedAndAnyObject
let _: (P2 & AnyObject).Type = derived
let _: (P2 & AnyObject).Type = derivedAndAnyObject
let _ = baseIntAndP2 as P2.Type
let _ = derived as P2.Type
let _ = derivedAndAnyObject as P2.Type
let _ = derived as (P2 & AnyObject).Type
let _ = derivedAndAnyObject as (P2 & AnyObject).Type
let _ = baseIntAndP2 as? P2.Type // expected-warning {{always succeeds}}
let _ = derived as? P2.Type // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? P2.Type // expected-warning {{always succeeds}}
let _ = derived as? (P2 & AnyObject).Type // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? (P2 & AnyObject).Type // expected-warning {{always succeeds}}
// Initializers
let _: Base<Int> & P2 = baseIntAndP2.init(classInit: ())
let _: Base<Int> & P2 = baseIntAndP2.init(protocolInit: ())
let _: Base<Int> & P2 & AnyObject = baseIntAndP2AndAnyObject.init(classInit: ())
let _: Base<Int> & P2 & AnyObject = baseIntAndP2AndAnyObject.init(protocolInit: ())
let _: Derived = derived.init(classInit: ())
let _: Derived = derived.init(protocolInit: ())
let _: Derived & AnyObject = derivedAndAnyObject.init(classInit: ())
let _: Derived & AnyObject = derivedAndAnyObject.init(protocolInit: ())
}
//
// Conformance relation.
//
func conformsTo<T1 : P2, T2 : Base<Int> & P2>(
anyObject: AnyObject,
p1: P1,
p2: P2,
p3: P3,
base: Base<Int>,
badBase: Base<String>,
derived: Derived,
fakeDerived: FakeDerived,
p2Archetype: T1,
baseAndP2Archetype: T2) {
// FIXME: Uninformative diagnostics
// Errors
conformsToAnyObject(p1)
// expected-error@-1 {{global function 'conformsToAnyObject' requires that 'P1' be a class type}}
conformsToP1(p1)
// expected-error@-1 {{value of protocol type 'P1' cannot conform to 'P1'; only struct/enum/class types can conform to protocols}}
// FIXME: Following diagnostics are not great because when
// `conformsTo*` methods are re-typechecked, they loose information
// about `& P2` in generic parameter.
conformsToBaseIntAndP2(base)
// expected-error@-1 {{global function 'conformsToBaseIntAndP2' requires that 'Base<Int>' conform to 'P2'}}
conformsToBaseIntAndP2(badBase)
// expected-error@-1 {{global function 'conformsToBaseIntAndP2' requires that 'Base<Int>' conform to 'P2'}}
// expected-error@-2 {{cannot convert value of type 'Base<String>' to expected argument type 'Base<Int>'}}
conformsToBaseIntAndP2(fakeDerived)
// expected-error@-1 {{global function 'conformsToBaseIntAndP2' requires that 'FakeDerived' inherit from 'Base<Int>'}}
conformsToBaseIntAndP2WithWhereClause(fakeDerived)
// expected-error@-1 {{global function 'conformsToBaseIntAndP2WithWhereClause' requires that 'FakeDerived' inherit from 'Base<Int>'}}
conformsToBaseIntAndP2(p2Archetype)
// expected-error@-1 {{global function 'conformsToBaseIntAndP2' requires that 'T1' inherit from 'Base<Int>'}}
conformsToBaseIntAndP2WithWhereClause(p2Archetype)
// expected-error@-1 {{global function 'conformsToBaseIntAndP2WithWhereClause' requires that 'T1' inherit from 'Base<Int>'}}
// Good
conformsToAnyObject(anyObject)
conformsToAnyObject(baseAndP2Archetype)
conformsToP1(derived)
conformsToP1(baseAndP2Archetype)
conformsToP2(derived)
conformsToP2(baseAndP2Archetype)
conformsToBaseIntAndP2(derived)
conformsToBaseIntAndP2(baseAndP2Archetype)
conformsToBaseIntAndP2WithWhereClause(derived)
conformsToBaseIntAndP2WithWhereClause(baseAndP2Archetype)
}
// Subclass existentials inside inheritance clauses
class CompositionInClassInheritanceClauseAlias : BaseIntAndP2 {
required init(classInit: ()) {
super.init(classInit: ())
}
required init(protocolInit: ()) {
super.init(classInit: ())
}
func protocolSelfReturn() -> Self { return self }
func asBase() -> Base<Int> { return self }
}
class CompositionInClassInheritanceClauseDirect : Base<Int> & P2 {
required init(classInit: ()) {
super.init(classInit: ())
}
required init(protocolInit: ()) {
super.init(classInit: ())
}
func protocolSelfReturn() -> Self { return self }
func asBase() -> Base<Int> { return self }
}
protocol CompositionInAssociatedTypeInheritanceClause {
associatedtype A : BaseIntAndP2
}
// Members of metatypes and existential metatypes
protocol ProtocolWithStaticMember {
static func staticProtocolMember()
func instanceProtocolMember()
}
class ClassWithStaticMember {
static func staticClassMember() {}
func instanceClassMember() {}
}
func staticMembers(
m1: (ProtocolWithStaticMember & ClassWithStaticMember).Protocol,
m2: (ProtocolWithStaticMember & ClassWithStaticMember).Type) {
_ = m1.staticProtocolMember() // expected-error {{static member 'staticProtocolMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}}
_ = m1.staticProtocolMember // expected-error {{static member 'staticProtocolMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}}
_ = m1.staticClassMember() // expected-error {{static member 'staticClassMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}}
_ = m1.staticClassMember // expected-error {{static member 'staticClassMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}}
_ = m1.instanceProtocolMember
_ = m1.instanceClassMember
_ = m2.staticProtocolMember()
_ = m2.staticProtocolMember
_ = m2.staticClassMember()
_ = m2.staticClassMember
_ = m2.instanceProtocolMember // expected-error {{instance member 'instanceProtocolMember' cannot be used on type 'ClassWithStaticMember & ProtocolWithStaticMember'}}
_ = m2.instanceClassMember // expected-error {{instance member 'instanceClassMember' cannot be used on type 'ClassWithStaticMember & ProtocolWithStaticMember'}}
}
// Make sure we correctly form subclass existentials in expression context.
func takesBaseIntAndPArray(_: [Base<Int> & P2]) {}
func passesBaseIntAndPArray() {
takesBaseIntAndPArray([Base<Int> & P2]())
}
//
// Superclass constrained generic parameters
//
struct DerivedBox<T : Derived> {}
// expected-note@-1 {{requirement specified as 'T' : 'Derived' [with T = Derived & P3]}}
func takesBoxWithP3(_: DerivedBox<Derived & P3>) {}
// expected-error@-1 {{'DerivedBox' requires that 'Derived & P3' inherit from 'Derived'}}
// A bit of a tricky setup -- the real problem is that matchTypes() did the
// wrong thing when solving a Bind constraint where both sides were protocol
// compositions, but one of them had a superclass constraint containing type
// variables. We were checking type equality in this case, which is not
// correct; we have to do a 'deep equality' check, recursively matching the
// superclass types.
struct Generic<T> {
var _x: (Base<T> & P2)!
var x: (Base<T> & P2)? {
get { return _x }
set { _x = newValue }
_modify {
yield &_x
}
}
}
| apache-2.0 | 08760795c682dcb7b8d913559a840022 | 35.192029 | 188 | 0.70037 | 3.635007 | false | false | false | false |
blackfog/BFGAlertController | Source/AlertSimpleStackView.swift | 1 | 4246 | //
// AlertSimpleStackView.swift
//
// Created by Craig Pearlman on 2015-06-30.
//
import UIKit
// MARK: - Main
class AlertSimpleStackView: UIView {
// MARK: - Definitions
var stackViews = [UIView]()
var viewHeight = CGFloat(44.0)
var viewHeights = [CGFloat]()
var dividerColor = UIColor.gray
var dividerHeight = CGFloat(0.5)
// MARK: - Constructors
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(views: [UIView]) {
assert(views.count > 0, "There are no views to stack")
self.init(frame: CGRect())
self.stackViews = views
}
// MARK: - Lifecycle
override func layoutSubviews() {
var alignToView: UIView = self
var alignToAttribute: NSLayoutAttribute = .top
for i in 0..<self.stackViews.count {
let view = self.stackViews[i]
view.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(view)
let viewHeight = self.viewHeights.count > 0 && i <= self.viewHeights.endIndex ?
self.viewHeights[i] : self.viewHeight
self.addConstraints([
NSLayoutConstraint(
item: view, attribute: .top,
relatedBy: .equal,
toItem: alignToView, attribute: alignToAttribute,
multiplier: 1.0, constant: 0.0
),
NSLayoutConstraint(
item: view, attribute: .leading,
relatedBy: .equal,
toItem: self, attribute: .leading,
multiplier: 1.0, constant: 0.0
),
NSLayoutConstraint(
item: view, attribute: .trailing,
relatedBy: .equal,
toItem: self, attribute: .trailing,
multiplier: 1.0, constant: 0.0
),
NSLayoutConstraint(
item: view, attribute: .height,
relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute,
multiplier: 1.0, constant: viewHeight
)
])
if self.dividerHeight > 0 && i != self.stackViews.endIndex - 1 {
let divider = UIView()
divider.backgroundColor = self.dividerColor
divider.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(divider)
self.addConstraints([
NSLayoutConstraint(
item: divider, attribute: .top,
relatedBy: .equal,
toItem: view, attribute: .bottom,
multiplier: 1.0, constant: 0.0
),
NSLayoutConstraint(
item: divider, attribute: .leading,
relatedBy: .equal,
toItem: self, attribute: .leading,
multiplier: 1.0, constant: 0.0
),
NSLayoutConstraint(
item: divider, attribute: .trailing,
relatedBy: .equal,
toItem: self, attribute: .trailing,
multiplier: 1.0, constant: 0.0
),
NSLayoutConstraint(
item: divider, attribute: .height,
relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute,
multiplier: 1.0, constant: self.dividerHeight
)
])
alignToView = divider
alignToAttribute = .bottom
}
else {
alignToView = view
alignToAttribute = .bottom
}
}
self.setNeedsLayout()
}
}
| mit | 4240e4e5771235fc427ebb28e4f1abdc | 33.803279 | 91 | 0.459727 | 5.722372 | false | false | false | false |
lyft/SwiftLint | Source/SwiftLintFramework/Rules/DiscouragedDirectInitRule.swift | 1 | 1993 | import Foundation
import SourceKittenFramework
public struct DiscouragedDirectInitRule: ASTRule, ConfigurationProviderRule {
public var configuration = DiscouragedDirectInitConfiguration()
public init() {}
public static let description = RuleDescription(
identifier: "discouraged_direct_init",
name: "Discouraged Direct Initialization",
description: "Discouraged direct initialization of types that can be harmful.",
kind: .lint,
nonTriggeringExamples: [
"let foo = UIDevice.current",
"let foo = Bundle.main",
"let foo = Bundle(path: \"bar\")",
"let foo = Bundle(identifier: \"bar\")",
"let foo = Bundle.init(path: \"bar\")",
"let foo = Bundle.init(identifier: \"bar\")"
],
triggeringExamples: [
"↓UIDevice()",
"↓Bundle()",
"let foo = ↓UIDevice()",
"let foo = ↓Bundle()",
"let foo = bar(bundle: ↓Bundle(), device: ↓UIDevice())",
"↓UIDevice.init()",
"↓Bundle.init()",
"let foo = ↓UIDevice.init()",
"let foo = ↓Bundle.init()",
"let foo = bar(bundle: ↓Bundle.init(), device: ↓UIDevice.init())"
]
)
public func validate(file: File,
kind: SwiftExpressionKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard
kind == .call,
let offset = dictionary.nameOffset,
let name = dictionary.name,
dictionary.bodyLength == 0,
configuration.discouragedInits.contains(name)
else {
return []
}
return [StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: offset))]
}
}
| mit | 05e974ef76a4b24c42e9550906606d52 | 36.150943 | 92 | 0.540884 | 5.15445 | false | true | false | false |
attaswift/Attabench | Attabench/ChartView.swift | 2 | 3176 | // Copyright © 2017 Károly Lőrentey.
// This file is part of Attabench: https://github.com/attaswift/Attabench
// For licensing information, see the file LICENSE.md in the Git repository above.
import Cocoa
import BenchmarkModel
import BenchmarkCharts
import GlueKit
@IBDesignable
class ChartView: NSView {
var documentBasename: String = "Benchmark"
private let modelConnector = Connector()
var model: Attaresult? {
didSet {
modelConnector.disconnect()
if let model = model {
modelConnector.connect(model.chartOptionsTick) {
self.render()
}
}
}
}
private var themeConnection: Connection? = nil
var theme: AnyObservableValue<BenchmarkTheme> = .constant(BenchmarkTheme.Predefined.screen) {
didSet {
themeConnection?.disconnect()
themeConnection = theme.values.subscribe { [unowned self] _ in self.render() }
}
}
var chart: BenchmarkChart? = nil {
didSet {
self.render()
}
}
var image: NSImage? = nil {
didSet {
self.needsDisplay = true
}
}
@IBInspectable
var backgroundColor: NSColor = .clear {
didSet {
self.needsDisplay = true
}
}
var downEvent: NSEvent? = nil
func render() {
self.image = render(at: theme.value.imageSize ?? self.bounds.size)
}
func render(at size: CGSize) -> NSImage? {
guard let chart = self.chart else { return nil }
var options = BenchmarkRenderer.Options()
let legendMargin = min(0.05 * size.width, 0.05 * size.height)
options.showTitle = false
options.legendPosition = chart.tasks.count > 10 ? .hidden : .topLeft
options.legendHorizontalMargin = legendMargin
options.legendVerticalMargin = legendMargin
let renderer = BenchmarkRenderer(chart: chart,
theme: self.theme.value,
options: options,
in: CGRect(origin: .zero, size: size))
return renderer.image
}
override func draw(_ dirtyRect: NSRect) {
// Draw background.
self.backgroundColor.setFill()
dirtyRect.fill()
let bounds = self.bounds
if let image = image, image.size.width * image.size.height > 0 {
let aspect = image.size.width / image.size.height
let fitSize = CGSize(width: min(bounds.width, aspect * bounds.height),
height: min(bounds.height, bounds.width / aspect))
image.draw(in: CGRect(origin: CGPoint(x: bounds.minX + (bounds.width - fitSize.width) / 2,
y: bounds.minY + (bounds.height - fitSize.height) / 2),
size: fitSize))
}
}
override var frame: NSRect {
get { return super.frame }
set {
super.frame = newValue
if theme.value.imageSize == nil {
render()
}
}
}
}
| mit | 0e2a918adda2a2db1061ea8a410f77e0 | 30.73 | 105 | 0.55468 | 4.757121 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Pods/MobilePlayer/MobilePlayer/Parsers/YoutubeParser.swift | 1 | 3695 | //
// YoutubeParser.swift
// MobilePlayer
//
// Created by Toygar Dündaralp on 09/06/15.
// Copyright (c) 2015 MovieLaLa. All rights reserved.
//
import Foundation
struct YoutubeVideoInfo {
let title: String?
let previewImageURL: String?
let videoURL: String?
let isStream: Bool?
}
class YoutubeParser: NSObject {
static let infoURL = "https://www.youtube.com/get_video_info?video_id="
static let userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2)"
+ " AppleWebKit/537.4 (KHTML, like Gecko)"
+ " Chrome/22.0.1229.79 Safari/537.4"
private static func decodeURLEncodedString(urlString: String) -> String {
let withSpaces = urlString.replacingOccurrences(of: "+", with: " ")
return withSpaces.removingPercentEncoding ?? withSpaces
}
private static func queryStringToDictionary(queryString: String) -> [String: Any] {
var parameters = [String: Any]()
for keyValuePair in queryString.components(separatedBy: "&") {
let keyValueArray = keyValuePair.components(separatedBy: "=")
if keyValueArray.count < 2 {
continue
}
let key = decodeURLEncodedString(urlString: keyValueArray[0])
let value = decodeURLEncodedString(urlString: keyValueArray[1])
parameters[key] = value
}
return parameters
}
static func youtubeIDFromURL(url: URL) -> String? {
guard let host = url.host else { return nil }
if host.range(of: "youtu.be") != nil {
return url.pathComponents[1]
} else if (host.range(of: "youtube.com") != nil && url.pathComponents[1] == "embed") || (host == "youtube.googleapis.com") {
return url.pathComponents[2]
} else if
host.range(of: "youtube.com") != nil,
let queryString = url.query,
let videoParam = queryStringToDictionary(queryString: queryString)["v"] as? String {
return videoParam
}
return nil
}
static func h264videosWithYoutubeID(_ youtubeID: String,
completion: @escaping (_ videoInfo: YoutubeVideoInfo?, _ error: NSError?) -> Void) {
var request = URLRequest(url: URL(string: "\(infoURL)\(youtubeID)")!)
request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
request.httpMethod = "GET"
NSURLConnection.sendAsynchronousRequest(
request,
queue: .main,
completionHandler: { response, data, error in
if let error = error {
completion(nil, error as NSError?)
return
}
guard let
data = data,
let dataString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as String? else {
completion(
nil,
NSError(domain: "com.movielala.MobilePlayer.error", code: 0, userInfo: nil))
return
}
let parts = self.queryStringToDictionary(queryString: dataString)
let title = parts["title"] as? String
let previewImageURL = parts["iurl"] as? String
if parts["live_playback"] != nil {
completion(
YoutubeVideoInfo(
title: title,
previewImageURL: previewImageURL,
videoURL: parts["hlsvp"] as? String,
isStream: true),
nil)
} else if let fmtStreamMap = parts["url_encoded_fmt_stream_map"] as? String {
let videoComponents = self.queryStringToDictionary(queryString: fmtStreamMap.components(separatedBy: ",")[0])
completion(
YoutubeVideoInfo(
title: title,
previewImageURL: previewImageURL,
videoURL: videoComponents["url"] as? String,
isStream: false),
nil)
}
})
}
}
| mit | 4f7bd427f990b969e89173edbd8f5ce8 | 34.519231 | 128 | 0.624256 | 4.397619 | false | false | false | false |
WildDogTeam/lib-ios-streambase | StreamBaseExample/StreamBaseKit/BaseItem.swift | 1 | 2248 | //
// BaseItem.swift
// StreamBaseKit
//
// Created by IMacLi on 15/10/12.
// Copyright © 2015年 liwuyang. All rights reserved.
//
import Wilddog
/**
Protocol describing behavior of BaseItem. This is useful for creating other
protocols that extend the behavior of BaseItem subclasses.
*/
public protocol BaseItemProtocol : KeyedObject {
var key: String? { get set }
var dict: [String: AnyObject] { get }
init(key: String?)
func update(dict: [String: AnyObject]?)
func clone() -> BaseItemProtocol
}
/**
A base class for objects persisted in Wilddog that make up the
items in streams.
*/
public class BaseItem: Equatable, BaseItemProtocol {
/**
The final part of the wilddog path.
*/
public var key: String?
/**
Used for persisting data to wilddog. Subclasses should override,
appending their fields to this dictionary.
*/
public var dict: [String: AnyObject] {
return [:]
}
/**
Create an empty instance. Typically used for constructing new instances
where the key and ref are filled in later.
*/
public convenience init() {
self.init(key: nil)
}
/**
Create an instance fully initialized with the key, ref and data.
:param: key The last part of the wilddog path
:param: ref The full wilddog reference (including key)
:param: dict The data with which to populate this object
*/
public required init(key: String?) {
self.key = key
}
/**
Subclasses should override to initialize fields. If the dict is nil, then
the object has been deleted.
:param: dict The dictionary containing the values of the fields.
*/
public func update(dict: [String: AnyObject]?) {
}
/**
Produce a shallow copy of this object.
*/
public func clone() -> BaseItemProtocol {
let copy = self.dynamicType.init(key: key)
copy.update(dict)
return copy
}
}
// NOTE: This would make more sense on KeyedObject, but Swift 1.2 doesn't support
// Equatable protocols.
public func ==(lhs: BaseItem, rhs: BaseItem) -> Bool {
return lhs.key == rhs.key
}
| mit | 0ece9052fd6f1d4bf59dd32107027a7d | 25.411765 | 82 | 0.627171 | 4.235849 | false | false | false | false |
lambdaacademy/2015.01_swift | Lectures/1/LA_2015.01_2-Closures_completed.playground/section-1.swift | 1 | 2070 | //
// Lambda Academy 2015.01 Lecture 1
//
import Foundation
func square(a:Float) -> Float {
return a * a
}
func cube(a:Float) -> Float {
return a * a * a
}
func averageSumOfSquares(a:Float,b:Float) -> Float {
return (square(a) + square(b)) / 2.0
}
func averageSumOfCubes(a:Float,b:Float) -> Float {
return (cube(a) + cube(b)) / 2.0
}
averageSumOfCubes(3, 4)
averageSumOfSquares(3, 4)
// Excersise 1
func averageOfFunction(a:Float,b:Float,f:(Float -> Float)) -> Float {
return (f(a) + f(b)) / 2
}
averageOfFunction(3, 4, cube)
averageOfFunction(3, 4, square)
// Excersise 2 - Lambda
// explicit argument type
var res = averageOfFunction(3, 4, {(x: Float) in return x*x} )
print(res)
res = averageOfFunction(3, 4, {(x: Float) in return x*x*x} )
print(res)
//implicit argument type
res = averageOfFunction(3, 4, {x in return x*x} )
print(res)
res = averageOfFunction(3, 4, {x in return x*x*x} )
print(res)
//shortcut form (without argument name)
res = averageOfFunction(3, 4, {$0*$0} )
print(res)
res = averageOfFunction(3, 4, {$0*$0*$0} )
print(res)
// Functional Concepts
// map reduce
func averageOfFunction1(numbers: [Float],f:(Float -> Float)) -> Float {
var sum : Float = 0
for a in numbers {
let transformed = f(a)
sum += transformed
}
let avrg = sum / Float(numbers.count)
return avrg
}
func averageOfFunction2(numbers: [Float],f:(Float -> Float)) -> Float {
let transformed = numbers.map(f)
let sum = transformed.reduce(0, combine:+)
let avrg = sum/Float(numbers.count)
return avrg
}
func averageOfFunction3(numbers: [Float],f:(Float -> Float)) -> Float {
return numbers.map(f).reduce(0, combine: +) / Float(numbers.count)
}
func averageOfFunction4(numbers: [Float],f:(Float -> Float), filter: (Float -> Bool)) -> Float {
let filtered = numbers.filter(filter)
return filtered.map(f).reduce(0, combine: +) / Float(filtered.count)
}
let a = averageOfFunction3([3, 4], {$0*$0})
print(a)
let b = averageOfFunction4([3, 4, -1], {$0*$0}, {$0>0})
print(b) | apache-2.0 | ae127f6a686351c01ec06fd2c14c267c | 20.572917 | 97 | 0.642029 | 2.863071 | false | false | false | false |
surik00/RocketWidget | RocketWidget/Model/SwiftMD5.swift | 1 | 5939 | //
// SwiftMD5.swift
// RocketWidget
//
// Created by Suren Khorenyan on 01.10.17.
// Faithfully borrowed from https://github.com/mpurland/SwiftMD5/blob/master/SwiftMD5/SwiftMD5.swift and slightly modified
//
public typealias Byte = UInt8
typealias Word = UInt32
public struct Digest {
public let digest: [Byte]
init(_ digest: [Byte]) {
self.digest = digest
}
}
private func F(_ b: Word, _ c: Word, _ d: Word) -> Word {
return (b & c) | ((~b) & d)
}
private func G(_ b: Word, _ c: Word, _ d: Word) -> Word {
return (b & d) | (c & (~d))
}
private func H(_ b: Word, _ c: Word, _ d: Word) -> Word {
return b ^ c ^ d
}
private func I(_ b: Word, _ c: Word, _ d: Word) -> Word {
return c ^ (b | (~d))
}
private func rotateLeft(_ x: Word, by: Word) -> Word {
return ((x << by) & 0xFFFFFFFF) | (x >> (32 - by))
}
// MARK: - Calculating a MD5 digest of bytes from bytes
public func md5(_ bytes: [Byte]) -> [Byte] {
// Initialization
let s: [Word] = [
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
]
let K: [Word] = [
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
]
var a0: Word = 0x67452301 // A
var b0: Word = 0xefcdab89 // B
var c0: Word = 0x98badcfe // C
var d0: Word = 0x10325476 // D
// Pad message with a single bit "1"
var message = bytes
let originalLength = bytes.count
let bitLength = UInt64(originalLength * 8)
message.append(0x80)
// Pad message with bit "0" until message length is 64 bits fewer than 512
repeat {
message.append(0x0)
} while (message.count * 8) % 512 != 448
message.append(Byte((bitLength >> 0) & 0xFF))
message.append(Byte((bitLength >> 8) & 0xFF))
message.append(Byte((bitLength >> 16) & 0xFF))
message.append(Byte((bitLength >> 24) & 0xFF))
message.append(Byte((bitLength >> 32) & 0xFF))
message.append(Byte((bitLength >> 40) & 0xFF))
message.append(Byte((bitLength >> 48) & 0xFF))
message.append(Byte((bitLength >> 56) & 0xFF))
let newBitLength = message.count * 8
// Transform
let chunkLength = 512 // 512-bit
let chunkLengthInBytes = chunkLength / 8 // 64-bytes
let totalChunks = newBitLength / chunkLength
for chunk in 0..<totalChunks {
let index = chunk*chunkLengthInBytes
var chunk: [Byte] = Array(message[index..<index+chunkLengthInBytes]) // 512-bit/64-byte chunk
// break chunk into sixteen 32-bit words
var M: [Word] = []
for j in 0..<16 {
let m0 = Word(chunk[4*j+0]) << 0
let m1 = Word(chunk[4*j+1]) << 8
let m2 = Word(chunk[4*j+2]) << 16
let m3 = Word(chunk[4*j+3]) << 24
let m = Word(m0 | m1 | m2 | m3)
M.append(m)
}
var A: Word = a0
var B: Word = b0
var C: Word = c0
var D: Word = d0
for i in 0..<64 {
var f: Word = 0
var g: Int = 0
if i < 16 {
f = F(B, C, D)
g = i
} else if i >= 16 && i <= 31 {
f = G(B, C, D)
g = ((5*i + 1) % 16)
} else if i >= 32 && i <= 47 {
f = H(B, C, D)
g = ((3*i + 5) % 16)
} else if i >= 48 && i <= 63 {
f = I(B, C, D)
g = ((7*i) % 16)
}
let dTemp = D
D = C
C = B
let x = A &+ f &+ K[i] &+ M[g]
let by = s[i]
B = B &+ rotateLeft(x, by: by)
A = dTemp
}
a0 = a0 &+ A
b0 = b0 &+ B
c0 = c0 &+ C
d0 = d0 &+ D
}
let digest0: Byte = Byte((a0 >> 0) & 0xFF)
let digest1: Byte = Byte((a0 >> 8) & 0xFF)
let digest2: Byte = Byte((a0 >> 16) & 0xFF)
let digest3: Byte = Byte((a0 >> 24) & 0xFF)
let digest4: Byte = Byte((b0 >> 0) & 0xFF)
let digest5: Byte = Byte((b0 >> 8) & 0xFF)
let digest6: Byte = Byte((b0 >> 16) & 0xFF)
let digest7: Byte = Byte((b0 >> 24) & 0xFF)
let digest8: Byte = Byte((c0 >> 0) & 0xFF)
let digest9: Byte = Byte((c0 >> 8) & 0xFF)
let digest10: Byte = Byte((c0 >> 16) & 0xFF)
let digest11: Byte = Byte((c0 >> 24) & 0xFF)
let digest12: Byte = Byte((d0 >> 0) & 0xFF)
let digest13: Byte = Byte((d0 >> 8) & 0xFF)
let digest14: Byte = Byte((d0 >> 16) & 0xFF)
let digest15: Byte = Byte((d0 >> 24) & 0xFF)
let digest = [
digest0, digest1, digest2, digest3, digest4, digest5, digest6, digest7,
digest8, digest9, digest10, digest11, digest12, digest13, digest14, digest15,
]
return Digest(digest).digest
}
| bsd-3-clause | 58929e081de836e5ae432663bab48e69 | 30.759358 | 123 | 0.518101 | 2.832141 | false | false | false | false |
flypaper0/ethereum-wallet | ethereum-wallet/Common/CustomViews/Conicoin/BorderView/BorderView.swift | 1 | 2839 | /*
Copyright DApps Platform Inc. All rights reserved.
*/
import UIKit
class BorderView: UIView {
private let initialImageView = UIImageView()
private let scrolledImageView = UIImageView()
private let shadowImage = UIImage(named: "HeaderShadow")
var initialImage: UIImage? {
get { return initialImageView.image }
set {
initialImageView.image = newValue
setNeedsLayout()
}
}
var scrolledImage: UIImage? {
get { return scrolledImageView.image }
set {
scrolledImageView.image = newValue
setNeedsLayout()
}
}
var progress: CGFloat = 0 {
didSet {
if progress != oldValue {
updateProgress()
}
}
}
var topInset: CGFloat = 0
var offsetThreshold: CGFloat = 48
var borderOffset: CGFloat = 0
private weak var scrollView: UIScrollView! = .none
init() {
super.init(frame: .zero)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func attach(to view: UIScrollView) {
scrollView = view
scrollView.addObserver(self, forKeyPath: "bounds", options: .new, context: &KVOContext.bounds)
scrollView.addSubview(self)
updateFrame()
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let scrollView = scrollView, context == &KVOContext.bounds else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
scrollView.bringSubviewToFront(self)
updateFrame()
}
override func removeFromSuperview() {
superview?.removeObserver(self, forKeyPath: "bounds", context: &KVOContext.bounds)
super.removeFromSuperview()
}
override func layoutSubviews() {
super.layoutSubviews()
for imageView in [initialImageView, scrolledImageView] {
imageView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: imageView.image?.size.height ?? 0)
}
}
}
private extension BorderView {
struct KVOContext {
static var bounds = true
}
func setupView() {
addSubview(initialImageView)
addSubview(scrolledImageView)
scrolledImage = shadowImage
isUserInteractionEnabled = false
updateProgress()
}
func updateFrame() {
guard let scrollView = scrollView else {
return
}
let position = CGPoint(x: scrollView.bounds.origin.x, y: scrollView.bounds.origin.y + topInset)
frame = CGRect(origin: position, size: CGSize(width: scrollView.bounds.width, height: 16))
progress = min(1, max(0, (scrollView.bounds.origin.y) - borderOffset) / offsetThreshold)
}
func updateProgress() {
initialImageView.alpha = 1 - progress
scrolledImageView.alpha = progress
}
}
| gpl-3.0 | 3b7703cd8f62fe9a65129de54506c9e1 | 24.348214 | 148 | 0.676294 | 4.535144 | false | false | false | false |
volodg/iAsync.async | Lib/ArrayLoadersMerger/ArrayLoadersMerger.swift | 1 | 9298 | //
// ArrayLoadersMerger.swift
// iAsync_async
//
// Created by Vladimir Gorbenko on 11.06.14.
// Copyright (c) 2014 EmbeddedSources. All rights reserved.
//
import Foundation
import iAsync_utils
import iAsync_reactiveKit
import ReactiveKit
final public class ArrayLoadersMerger<Arg: Hashable, Value> {
public typealias AsyncOpAr = AsyncTypes<[Value], NSError>.Async
public typealias ArrayOfObjectsLoader = (keys: [Arg]) -> AsyncOpAr
private var _pendingLoadersCallbacksByKey = [Arg:LoadersCallbacksData<Value>]()
private let _cachedAsyncOp = MergedAsyncStream<Arg, Value, AnyObject, NSError>()
private let _arrayLoader: ArrayOfObjectsLoader
private var activeArrayLoaders = [ActiveArrayLoader<Arg, Value>]()
private func removeActiveLoader(loader: ActiveArrayLoader<Arg, Value>) {
for (index, element) in activeArrayLoaders.enumerate() {
if element === loader {
self.activeArrayLoaders.removeAtIndex(index)
}
}
}
public init(arrayLoader: ArrayOfObjectsLoader) {
_arrayLoader = arrayLoader
}
public func oneObjectLoader(key: Arg) -> AsyncTypes<Value, NSError>.Async {
let loader = { (progressCallback: AsyncProgressCallback?,
finishCallback : AsyncTypes<Value, NSError>.DidFinishAsyncCallback?) -> AsyncHandler in
if let currentLoader = self.activeLoaderForKey(key) {
let resultIndex = currentLoader.indexOfKey(key)
let loader = bindSequenceOfAsyncs(currentLoader.nativeLoader!, { (result: [Value]) -> AsyncTypes<Value, NSError>.Async in
if result.count <= resultIndex {
//TODO fail
return async(result: .Failure(AsyncInterruptedError()))
}
return async(value: result[resultIndex])
})
return loader(
progressCallback: progressCallback,
finishCallback : finishCallback)
}
let callbacks = LoadersCallbacksData(
progressCallback: progressCallback,
doneCallback : finishCallback)
self._pendingLoadersCallbacksByKey[key] = callbacks
dispatch_async(dispatch_get_main_queue(), { [weak self] () -> () in
self?.runLoadingOfPendingKeys()
})
return { (task: AsyncHandlerTask) -> () in
switch task {
case .UnSubscribe:
let indexOption = self._pendingLoadersCallbacksByKey.indexForKey(key)
if let index = indexOption {
let (_, callbacks) = self._pendingLoadersCallbacksByKey[index]
self._pendingLoadersCallbacksByKey.removeAtIndex(index)
callbacks.doneCallback = nil
callbacks.unsubscribe()
} else {
self.activeLoaderForKey(key)?.unsubscribe(key)
}
case .Cancel:
let indexOption = self._pendingLoadersCallbacksByKey.indexForKey(key)
if let index = indexOption {
let (_, callbacks) = self._pendingLoadersCallbacksByKey[index]
self._pendingLoadersCallbacksByKey.removeAtIndex(index)
if let finishCallback = callbacks.doneCallback {
callbacks.doneCallback = nil
finishCallback(result: .Failure(AsyncInterruptedError()))
}
callbacks.unsubscribe()
} else {
self.activeLoaderForKey(key)?.cancelLoader()
}
}
}
}
return self._cachedAsyncOp.mergedStream( { asyncToStream(loader) }, key: key).toAsync()
}
private func runLoadingOfPendingKeys() {
if _pendingLoadersCallbacksByKey.count == 0 {
return
}
let loader = ActiveArrayLoader(loadersCallbacksByKey:_pendingLoadersCallbacksByKey, owner: self)
activeArrayLoaders.append(loader)
_pendingLoadersCallbacksByKey.removeAll(keepCapacity: true)
loader.runLoader()
}
private func activeLoaderForKey(key: Arg) -> ActiveArrayLoader<Arg, Value>? {
let index = activeArrayLoaders.indexOf( { (activeLoader: ActiveArrayLoader<Arg, Value>) -> Bool in
return activeLoader.loadersCallbacksByKey[key] != nil
})
return index.flatMap { activeArrayLoaders[$0] }
}
}
final private class LoadersCallbacksData<Value> {
var progressCallback: AsyncProgressCallback?
var doneCallback : AsyncTypes<Value, NSError>.DidFinishAsyncCallback?
var suspended = false
init(
progressCallback: AsyncProgressCallback?,
doneCallback : AsyncTypes<Value, NSError>.DidFinishAsyncCallback?) {
self.progressCallback = progressCallback
self.doneCallback = doneCallback
}
func unsubscribe() {
progressCallback = nil
doneCallback = nil
}
func copy() -> LoadersCallbacksData {
return LoadersCallbacksData(
progressCallback: self.progressCallback,
doneCallback : self.doneCallback )
}
}
final private class ActiveArrayLoader<Arg: Hashable, Value> {
var loadersCallbacksByKey: [Arg:LoadersCallbacksData<Value>]
weak var owner: ArrayLoadersMerger<Arg, Value>?
var keys = KeysType()
private func indexOfKey(key: Arg) -> Int {
for (index, currentKey) in keys.enumerate() {
if currentKey == key {
return index
}
}
return -1
}
var nativeLoader : AsyncTypes<[Value], NSError>.Async? //Should be strong
private var _nativeHandler: AsyncHandler?
init(loadersCallbacksByKey: [Arg:LoadersCallbacksData<Value>], owner: ArrayLoadersMerger<Arg, Value>) {
self.loadersCallbacksByKey = loadersCallbacksByKey
self.owner = owner
}
func cancelLoader() {
guard let block = _nativeHandler else { return }
_nativeHandler = nil
block(task: .Cancel)
self.clearState()
}
func clearState() {
for (_, value) in loadersCallbacksByKey {
value.unsubscribe()
}
loadersCallbacksByKey.removeAll(keepCapacity: false)
owner?.removeActiveLoader(self)
_nativeHandler = nil
nativeLoader = nil
}
func unsubscribe(key: Arg) {
guard let index = loadersCallbacksByKey.indexForKey(key) else { return }
let callbacks = loadersCallbacksByKey[index]
callbacks.1.unsubscribe()
loadersCallbacksByKey.removeAtIndex(index)
}
typealias KeysType = HashableArray<Arg>
let _cachedAsyncOp = MergedAsyncStream<KeysType, [Value], AnyObject, NSError>()
func runLoader() {
assert(self.nativeLoader == nil)
keys.removeAll()
for (key, _) in loadersCallbacksByKey {
keys.append(key)
}
let arrayLoader = owner!._arrayLoader(keys: Array(keys))
let loader = { [weak self] (
progressCallback: AsyncProgressCallback?,
finishCallback : AsyncTypes<[Value], NSError>.DidFinishAsyncCallback?) -> AsyncHandler in
let progressCallbackWrapper = { (progressInfo: AnyObject) -> () in
if let self_ = self {
for (_, value) in self_.loadersCallbacksByKey {
value.progressCallback?(progressInfo: progressInfo)
}
}
progressCallback?(progressInfo: progressInfo)
}
let doneCallbackWrapper = { (results: Result<[Value], NSError>) -> () in
if let self_ = self {
var loadersCallbacksByKey = [Arg:LoadersCallbacksData<Value>]()
for (key, value) in self_.loadersCallbacksByKey {
loadersCallbacksByKey[key] = value.copy()
}
self_.clearState()
for (key, value) in loadersCallbacksByKey {
//TODO test not full results array
let result = results.map { $0[self_.indexOfKey(key)] }
value.doneCallback?(result: result)
value.unsubscribe()
}
}
finishCallback?(result: results)
}
return arrayLoader(
progressCallback: progressCallbackWrapper,
finishCallback : doneCallbackWrapper)
}
let nativeLoader: AsyncTypes<[Value], NSError>.Async = _cachedAsyncOp.mergedStream( { asyncToStream(loader) }, key: keys).toAsync()
self.nativeLoader = nativeLoader
var finished = false
let handler = nativeLoader(
progressCallback: nil,
finishCallback : { (result: Result<[Value], NSError>) -> () in finished = true })
if !finished {
_nativeHandler = handler
}
}
}
| mit | 73e59bd02d67fee6b4616066a00e8d5f | 31.397213 | 139 | 0.583459 | 5.100384 | false | false | false | false |
moray95/MCChat | Pod/Classes/Message.swift | 1 | 2078 | //
// Message.swift
// BluetoothChat
//
// Created by Moray on 23/06/15.
// Copyright © 2015 Moray. All rights reserved.
//
import UIKit
import JSQMessagesViewController
@objc class Message : NSObject, JSQMessageData
{
var body : String
var sender : String
let dateCreated = NSDate()
var initials : String
var image : UIImage?
let isSystemMessage : Bool
init(sender : String, body : String)
{
self.sender = sender
self.body = body
let str = sender as NSString
initials = str.substringToIndex(1)
for i in 1..<sender.length
{
if sender[i-1] == Character(" ") && sender[i] != Character(" ")
{
initials = initials + "\(sender[i])"
}
}
isSystemMessage = false
}
init(systemMessage sender : String, body : String)
{
self.sender = sender
self.body = body
let str = sender as NSString
initials = str.substringToIndex(1)
for i in 1..<sender.length
{
if sender[i-1] == Character(" ") && sender[i] != Character(" ")
{
initials = initials + "\(sender[i])"
}
}
isSystemMessage = true
}
var jsqMessage : JSQMessage
{
if image == nil
{
return JSQMessage(senderId: senderId(), senderDisplayName: senderDisplayName(), date: date(), text: text())
}
return JSQMessage(senderId: senderId(), senderDisplayName: senderDisplayName(), date: date(), media: JSQPhotoMediaItem(image: image!))
}
// MARK: JSQMessageData
func senderDisplayName() -> String!
{
return sender
}
func senderId() -> String!
{
return senderDisplayName()
}
func text() -> String!
{
return body
}
func date() -> NSDate!
{
return dateCreated
}
func isMediaMessage() -> Bool
{
return false
}
func messageHash() -> UInt
{
return UInt(abs(body.hash))
}
} | mit | 55cfd1f39b83806799f12ba465841fb3 | 20.204082 | 142 | 0.541647 | 4.595133 | false | false | false | false |
mitochrome/complex-gestures-demo | apps/GestureRecognizer/Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/NSLayoutConstraint+RxTests.swift | 7 | 2745 | //
// NSLayoutConstraint+RxTests.swift
// Tests
//
// Created by Krunoslav Zaher on 12/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import RxSwift
import RxCocoa
import XCTest
#if os(macOS)
import AppKit
typealias View = NSView
let topLayoutAttribute = NSLayoutConstraint.Attribute.top
let equalLayoutRelation = NSLayoutConstraint.Relation.equal
#else
import UIKit
typealias View = UIView
let topLayoutAttribute = NSLayoutAttribute.top
let equalLayoutRelation = NSLayoutRelation.equal
#endif
final class NSLayoutConstraintTest : RxTest {
}
extension NSLayoutConstraintTest {
func testConstant_0() {
let subject = View(frame: CGRect.zero)
let subject2 = View(frame: CGRect.zero)
let constraint = NSLayoutConstraint(item: subject, attribute: topLayoutAttribute, relatedBy: equalLayoutRelation, toItem: subject2, attribute: topLayoutAttribute, multiplier: 0.5, constant: 0.5)
Observable.just(0).subscribe(constraint.rx.constant).dispose()
XCTAssertTrue(constraint.constant == 0.0)
}
func testConstant_1() {
let subject = View(frame: CGRect.zero)
let subject2 = View(frame: CGRect.zero)
let constraint = NSLayoutConstraint(item: subject, attribute: topLayoutAttribute, relatedBy: equalLayoutRelation, toItem: subject2, attribute: topLayoutAttribute, multiplier: 0.5, constant: 0.5)
Observable.just(1.0).subscribe(constraint.rx.constant).dispose()
XCTAssertTrue(constraint.constant == 1.0)
}
}
@available(iOS 8, OSX 10.10, *)
extension NSLayoutConstraintTest {
func testActive_True() {
let parent = View(frame: CGRect.zero)
let subject = View(frame: CGRect.zero)
let subject2 = View(frame: CGRect.zero)
parent.addSubview(subject)
parent.addSubview(subject2)
let constraint = NSLayoutConstraint(item: subject, attribute: topLayoutAttribute, relatedBy: equalLayoutRelation, toItem: subject2, attribute: topLayoutAttribute, multiplier: 0.5, constant: 0.5)
Observable.just(true).subscribe(constraint.rx.active).dispose()
XCTAssertTrue(constraint.isActive == true)
}
func testActive_False() {
let parent = View(frame: CGRect.zero)
let subject = View(frame: CGRect.zero)
let subject2 = View(frame: CGRect.zero)
parent.addSubview(subject)
parent.addSubview(subject2)
let constraint = NSLayoutConstraint(item: subject, attribute: topLayoutAttribute, relatedBy: equalLayoutRelation, toItem: subject2, attribute: topLayoutAttribute, multiplier: 0.5, constant: 0.5)
Observable.just(false).subscribe(constraint.rx.active).dispose()
XCTAssertTrue(constraint.isActive == false)
}
}
| mit | 18ceeb82b70bd90c6d0a66efeb52c6d8 | 36.589041 | 202 | 0.720117 | 4.314465 | false | true | false | false |
joerocca/GitHawk | Pods/Tabman/Sources/Tabman/TabmanBar/TabmanBar+Indicator.swift | 1 | 2480 | //
// TabmanBar+Indicator.swift
// Tabman
//
// Created by Merrick Sapsford on 15/03/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import UIKit
import PureLayout
import Pageboy
// MARK: - TabmanBar Indicator creation and mutation
extension TabmanBar {
/// Remove a scroll indicator from the bar.
internal func clear(indicator: TabmanIndicator?) {
self.indicatorMaskView.frame = .zero // reset mask
indicator?.removeFromSuperview()
indicator?.removeConstraints(indicator?.constraints ?? [])
}
/// Create a new indicator for a style.
///
/// - Parameter style: The style.
/// - Returns: The new indicator.
internal func create(indicatorForStyle style: TabmanIndicator.Style) -> TabmanIndicator? {
if let indicatorType = style.rawType {
return indicatorType.init()
}
return nil
}
/// Update the current indicator for a preferred style.
///
/// - Parameter preferredStyle: The new preferred style.
internal func updateIndicator(forPreferredStyle preferredStyle: TabmanIndicator.Style?) {
guard let preferredIndicatorStyle = self.preferredIndicatorStyle else {
// restore default if no preferred style
self.indicator = self.create(indicatorForStyle: self.defaultIndicatorStyle())
guard let indicator = self.indicator else {
return
}
add(indicator: indicator, to: contentView)
self.updateForCurrentPosition()
return
}
guard self.usePreferredIndicatorStyle() else {
return
}
// return nil if same type as current indicator
if let indicator = self.indicator {
guard type(of: indicator) != preferredStyle?.rawType else {
return
}
}
// Create new preferred style indicator.
self.indicator = self.create(indicatorForStyle: preferredIndicatorStyle)
guard let indicator = self.indicator else {
return
}
// disable progressive indicator if indicator does not support it.
if self.indicator?.isProgressiveCapable == false && self.indicatorIsProgressive {
self.indicatorIsProgressive = false
}
add(indicator: indicator, to: contentView)
self.updateForCurrentPosition()
}
}
| mit | 630760ebf64d6adde3d0b04a0f5547d2 | 31.618421 | 94 | 0.621622 | 5.308351 | false | false | false | false |
bugsnag/bugsnag-cocoa | features/fixtures/shared/scenarios/AttemptDeliveryOnCrashScenario.swift | 1 | 1012 | //
// AttemptDeliveryOnCrashScenario.swift
// iOSTestApp
//
// Created by Nick Dowell on 29/09/2022.
// Copyright © 2022 Bugsnag. All rights reserved.
//
class AttemptDeliveryOnCrashScenario: Scenario {
override func startBugsnag() {
BSGCrashSentryDeliveryTimeout = 15
config.attemptDeliveryOnCrash = true
config.addOnSendError { event in
event.context = "OnSendError"
return true
}
super.startBugsnag()
}
override func run() {
guard let eventMode = eventMode else { return }
switch eventMode {
case "BadAccess":
if let ptr = UnsafePointer<CChar>(bitPattern: 42) {
strlen(ptr)
}
break
case "NSException":
NSArray().object(at: 42)
break
case "SwiftFatalError":
_ = URL(string: "")!
break
default:
break
}
}
}
| mit | 72b1a7e267d1fbb8c550c3725fa38af9 | 23.071429 | 63 | 0.525223 | 4.884058 | false | false | false | false |
Acuant/AcuantiOSMobileSDK | Sample-Connect-Swift-App/AcuantiOSSDKAssureIDSwiftSample/ImageLoad.swift | 1 | 1259 | //
// ImageLoad.swift
// AcuantiOSSDKAssureIDSwiftSample
//
// Created by Tapas Behera on 8/7/17.
// Copyright © 2017 Acuant. All rights reserved.
//
import Foundation
extension UIImageView {
func downloadedFrom(urlStr:String,username:String,password:String) {
let loginData = String(format: "%@:%@", username, password).data(using: String.Encoding.utf8)!
let base64LoginData = loginData.base64EncodedString()
// create the request
let url = URL(string: urlStr)!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Basic \(base64LoginData)", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() { () -> Void in
self.image = image
self.isHidden=false;
}
}.resume()
}
}
| apache-2.0 | bec373fde69f7baa90d7b1db62d7f72f | 36 | 104 | 0.603339 | 4.541516 | false | false | false | false |
kingcos/Swift-X-Algorithms | LeetCode/009-Palindrome-Number/009-Palindrome-Number.playground/Contents.swift | 1 | 1019 | import UIKit
class Solution_1 {
// 80 ms
func isPalindrome(_ x: Int) -> Bool {
var x = x
guard x >= 0 else { return false }
var digits = [Int]()
while x != 0 {
digits.append(x % 10)
x /= 10
}
return digits == digits.reversed()
}
}
class Solution_2 {
// 56 ms
func isPalindrome(_ x: Int) -> Bool {
var y = x
guard x >= 0 else { return false }
var result = 0
while y != 0 {
result *= 10
result += y % 10
y /= 10
}
return result == x
}
}
class Solution_3 {
// 56 ms
func isPalindrome(_ x: Int) -> Bool {
var x = x
guard x >= 0,
x % 10 != 0 || x == 0 else { return false }
var result = 0
while x > result {
result = result * 10 + x % 10
x /= 10
}
return result == x || result / 10 == x
}
}
| mit | 22c9f9b1a475fdbfb84d287622f271e7 | 18.980392 | 55 | 0.393523 | 4.193416 | false | false | false | false |
jpedrosa/sua | examples/glob_list/Sources/main.swift | 1 | 1606 |
import Glibc
import Sua
func printUsage() {
print("GlobList: GlobList <pattern>\n" +
"Where the pattern follows a Glob pattern, including a directory path\n" +
"that may include a recursion command.\n" +
"E.g. GlobList \"~/**/*.txt\"\n\n" +
"**Note** It's best to enclose the pattern within quotes, so that the\n" +
" shell does not try to interpret it itself.\n\n" +
"Table of supported Glob features:\n" +
" * The ? wildcard - It will match a single character of any kind.\n" +
"\n" +
" * The * wildcard - It will match any character until the next\n" +
" pattern is found.\n" +
" * The [a-z] [abc] [A-Za-z0-9_] character set - It will match a\n" +
" character included in its ranges or sets.\n" +
" * The [!a-z] [!def] character set negation. It will match a\n" +
" character that is not included in the set.\n" +
" * The {jpg,png} optional names - It will match one of the names\n" +
" included in its list.\n\n" +
"The special characters could be escaped with the \\ backslash\n" +
"character in order to allow them to work like any other character.")
}
func parseOpt() -> String? {
return Process.arguments.count > 1 ? Process.arguments[1] : nil
}
if let s = parseOpt() {
var z = s
if s.utf16[0] == 126 { // ~
z = try File.expandPath(path: s)
}
try Dir.glob(pattern: z) { name, type, path in
print("\(type): \(path)\(name)")
}
} else {
printUsage()
}
| apache-2.0 | 732ae1b98ba4d57a9a0bb813d623a773 | 36.348837 | 80 | 0.560399 | 3.537445 | false | false | false | false |
iThinkersTeam/Blog | SnapKitLoginScreen/Pods/SnapKit/Source/ConstraintMakerRelatable.swift | 1 | 5131 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class ConstraintMakerRelatable {
internal let description: ConstraintDescription
internal init(_ description: ConstraintDescription) {
self.description = description
}
internal func relatedTo(_ other: ConstraintRelatableTarget, relation: ConstraintRelation, file: String, line: UInt) -> ConstraintMakerEditable {
let related: ConstraintItem
let constant: ConstraintConstantTarget
if let other = other as? ConstraintItem {
guard other.attributes == ConstraintAttributes.none ||
other.attributes.layoutAttributes.count <= 1 ||
other.attributes.layoutAttributes == self.description.attributes.layoutAttributes ||
other.attributes == .edges && self.description.attributes == .margins ||
other.attributes == .margins && self.description.attributes == .edges else {
fatalError("Cannot constraint to multiple non identical attributes. (\(file), \(line))")
}
related = other
constant = 0.0
} else if let other = other as? ConstraintView {
related = ConstraintItem(target: other, attributes: ConstraintAttributes.none)
constant = 0.0
} else if let other = other as? ConstraintConstantTarget {
related = ConstraintItem(target: nil, attributes: ConstraintAttributes.none)
constant = other
} else {
fatalError("Invalid constraint. (\(file), \(line))")
}
let editable = ConstraintMakerEditable(self.description)
editable.description.sourceLocation = (file, line)
editable.description.relation = relation
editable.description.related = related
editable.description.constant = constant
return editable
}
@discardableResult
public func equalTo(_ other: ConstraintRelatableTarget, _ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable {
return self.relatedTo(other, relation: .equal, file: file, line: line)
}
@discardableResult
public func equalToSuperview(_ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable {
guard let other = self.description.view.superview else {
fatalError("Expected superview but found nil when attempting make constraint `equalToSuperview`.")
}
return self.relatedTo(other, relation: .equal, file: file, line: line)
}
@discardableResult
public func lessThanOrEqualTo(_ other: ConstraintRelatableTarget, _ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable {
return self.relatedTo(other, relation: .lessThanOrEqual, file: file, line: line)
}
@discardableResult
public func lessThanOrEqualToSuperview(_ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable {
guard let other = self.description.view.superview else {
fatalError("Expected superview but found nil when attempting make constraint `lessThanOrEqualToSuperview`.")
}
return self.relatedTo(other, relation: .lessThanOrEqual, file: file, line: line)
}
@discardableResult
public func greaterThanOrEqualTo(_ other: ConstraintRelatableTarget, _ file: String = #file, line: UInt = #line) -> ConstraintMakerEditable {
return self.relatedTo(other, relation: .greaterThanOrEqual, file: file, line: line)
}
@discardableResult
public func greaterThanOrEqualToSuperview(_ file: String = #file, line: UInt = #line) -> ConstraintMakerEditable {
guard let other = self.description.view.superview else {
fatalError("Expected superview but found nil when attempting make constraint `greaterThanOrEqualToSuperview`.")
}
return self.relatedTo(other, relation: .greaterThanOrEqual, file: file, line: line)
}
}
| mit | da9cfb2099a498bcb762be1ff34187a6 | 46.073394 | 148 | 0.690704 | 5.030392 | false | false | false | false |
adamcumiskey/BlockDataSource | Example/BlockDataSource/CellTypesTableViewController.swift | 1 | 973 | //
// CellTypesTableViewController.swift
// BlockDataSource_Example
//
// Created by Adam on 6/25/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import BlockDataSource
import UIKit
let cellTypesViewController = BlockTableViewController(
style: .grouped,
dataSource: DataSource(
items: [
Item { (cell: BedazzledTableViewCell) in
cell.titleLabel.text = "Custom cells"
},
Item { (cell: SubtitleTableViewCell) in
cell.textLabel?.text = "Load any cell with ease"
cell.detailTextLabel?.text = "BlockDataSource automatically registers and loads the correct cell by using the class specified in the configure block."
cell.detailTextLabel?.numberOfLines = 0
}
],
middleware: Middleware(
tableViewCellMiddleware: [
TableViewCellMiddleware.noCellSelectionStyle
]
)
)
)
| mit | 100783b0e62cd14a58533b1dbaa3412b | 30.354839 | 166 | 0.622428 | 5.0625 | false | false | false | false |
narner/AudioKit | Examples/macOS/RandomClips/RandomClips/ViewController.swift | 1 | 4745 | //
// ViewController.swift
// RandomClips
//
// Created by David O'Neill on 9/8/17.
// Copyright © 2017 AudioKit. All rights reserved.
//
import Cocoa
import AudioKit
import AudioKitUI
class ViewController: NSViewController {
let drumPlayer = AKClipPlayer()
let guitarPlayer = AKClipPlayer()
let mixer = AKMixer()
var drumLooper: AKAudioPlayer?
let playButton = AKButton()
let guitarDelay = AVAudioUnitDelay()
let reverb = AKReverb()
let highPass = AKHighPassFilter()
override func viewDidLoad() {
super.viewDidLoad()
guard
let drumURL = Bundle.main.url(forResource: "drumloop", withExtension: "wav"),
let guitarURL = Bundle.main.url(forResource: "leadloop", withExtension: "wav"),
let guitarLoopURL = Bundle.main.url(forResource: "guitarloop", withExtension: "wav"),
let drumFile = try? AKAudioFile(forReading: drumURL),
let guitarFile = try? AKAudioFile(forReading: guitarURL),
let guitarLoopFile = try? AKAudioFile(forReading: guitarLoopURL),
let drumLooper = try? AKAudioPlayer(file: drumFile, looping: true),
let guitarLooper = try? AKAudioPlayer(file: guitarLoopFile, looping: true)
else {
print("missing resources!")
return
}
[drumPlayer >>> highPass,
guitarPlayer >>> guitarDelay >>> reverb,
drumLooper,
guitarLooper] >>> mixer
guitarDelay.delayTime = guitarFile.duration / 8
guitarDelay.feedback = 1
guitarDelay.wetDryMix = 0.6
reverb.loadFactoryPreset(.cathedral)
reverb.dryWetMix = 0.8
highPass.cutoffFrequency = 600
drumPlayer.volume = 1
guitarPlayer.volume = 0.6
guitarLooper.volume = 0.3
drumPlayer.volume = 0.6
AudioKit.output = mixer
AudioKit.start()
playButton.title = "Play"
playButton.frame = view.bounds
view.addSubview(playButton)
let drumChops = 32
let guitarChops = 16
let loops = 100
func randomChopClips(audioFile: AKAudioFile, chops: Int, count: Int) -> [AKFileClip] {
let duration = audioFile.duration / Double(chops)
let randomOffset: () -> Double = {
let btwn0andChop = arc4random_uniform(UInt32(chops))
return duration * Double(btwn0andChop)
}
var clips = [AKFileClip(audioFile: audioFile,
time: 0,
offset: randomOffset(),
duration: duration)]
for _ in 0..<count {
guard let lastClip = clips.last else { fatalError() }
clips.append(AKFileClip(audioFile: audioFile,
time: lastClip.endTime,
offset: randomOffset(),
duration: duration))
}
return clips
}
playButton.callback = { [drumPlayer, guitarPlayer] button in
if drumPlayer.isPlaying {
drumPlayer.stop()
guitarPlayer.stop()
guitarLooper.stop()
drumLooper.stop()
button.title = drumPlayer.isPlaying ? "Stop" : "Play"
} else {
drumPlayer.clips = randomChopClips(audioFile: drumFile,
chops: drumChops,
count: loops * drumChops)
guitarPlayer.clips = randomChopClips(audioFile: guitarFile,
chops: guitarChops,
count: loops * guitarChops)
drumPlayer.currentTime = 0
guitarPlayer.currentTime = 0
drumPlayer.prepare(withFrameCount: 44_100)
guitarPlayer.prepare(withFrameCount: 44_100)
drumLooper.schedule(from: 0, to: drumLooper.duration, avTime: nil)
guitarLooper.schedule(from: 0, to: guitarLooper.duration, avTime: nil)
let twoRendersTime = AKSettings.ioBufferDuration * 2
let futureTime = AVAudioTime.now() + twoRendersTime
drumLooper.play(at: futureTime)
guitarLooper.play(at: futureTime)
let loopDur = drumFile.duration
drumPlayer.play(at: futureTime + loopDur)
guitarPlayer.play(at: futureTime + loopDur * 2)
}
button.title = drumPlayer.isPlaying ? "Stop" : "Play"
}
}
}
| mit | fd674c99e172a538a5d0ea8dbb39c8f7 | 36.0625 | 97 | 0.544688 | 4.692384 | false | false | false | false |
LKY769215561/KYHandMade | KYHandMade/KYHandMade/Class/Tools/KYNetWorkTool.swift | 1 | 2031 | //
// KYNetWorkTool.swift
// KYHandMade
//
// Created by Kerain on 2017/6/13.
// Copyright © 2017年 广州市九章信息科技有限公司. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
/// 网络请求回调
typealias NetworkFinished = (_ success: Bool,_ result:JSON?,_ error:NSError?) -> ()
class KYNetWorkTool: NSObject {
static let shared = KYNetWorkTool()
}
// MARK: - 基础请求方法
extension KYNetWorkTool{
/**
GET请求
- parameter urlString: urlString
- parameter parameters: 参数
- parameter finished: 完成回调
*/
func get(_ urlString : String,parameters : [String : Any],finished:@escaping NetworkFinished) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
Alamofire.request(urlString, method: .get, parameters: parameters, headers: nil).responseJSON { (response) in
self.handle(response: response, finished: finished)
}
}
/**
POST请求
- parameter urlString: urlString
- parameter parameters: 参数
- parameter finished: 完成回调
*/
func post(_ urlString: String, parameters: [String : Any]?, finished: @escaping NetworkFinished) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
Alamofire.request(urlString, method: .post, parameters: parameters, headers: nil).responseJSON { (response) in
self.handle(response: response, finished: finished)
}
}
/// 处理响应结果
/// - response: 响应对象
/// - finished: 完成回调
fileprivate func handle(response : DataResponse<Any>,finished:@escaping NetworkFinished)
{
UIApplication.shared.isNetworkActivityIndicatorVisible = false
guard let result = response.result.value else {
KYProgressHUD.showErrorWithStatus("失败了,赶紧跑")
return
}
finished(true, JSON(result), nil)
}
}
| apache-2.0 | 817923179285ded2fd5e92a7814d746d | 27.029412 | 118 | 0.639035 | 4.527316 | false | false | false | false |
freak4pc/netfox | netfox/Core/NFXHTTPModel.swift | 1 | 10775 | //
// NFXHTTPModel.swift
// netfox
//
// Copyright © 2016 netfox. All rights reserved.
//
import Foundation
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
@objc public class NFXHTTPModel: NSObject
{
@objc public var requestURL: String?
@objc public var requestMethod: String?
@objc public var requestCachePolicy: String?
@objc public var requestDate: Date?
@objc public var requestTime: String?
@objc public var requestTimeout: String?
@objc public var requestHeaders: [AnyHashable: Any]?
public var requestBodyLength: Int?
@objc public var requestType: String?
@objc public var requestCurl: String?
public var responseStatus: Int?
@objc public var responseType: String?
@objc public var responseDate: Date?
@objc public var responseTime: String?
@objc public var responseHeaders: [AnyHashable: Any]?
public var responseBodyLength: Int?
public var timeInterval: Float?
@objc public var randomHash: NSString?
@objc public var shortType: NSString = HTTPModelShortType.OTHER.rawValue as NSString
@objc public var noResponse: Bool = true
func saveRequest(_ request: URLRequest)
{
self.requestDate = Date()
self.requestTime = getTimeFromDate(self.requestDate!)
self.requestURL = request.getNFXURL()
self.requestMethod = request.getNFXMethod()
self.requestCachePolicy = request.getNFXCachePolicy()
self.requestTimeout = request.getNFXTimeout()
self.requestHeaders = request.getNFXHeaders()
self.requestType = requestHeaders?["Content-Type"] as! String?
self.requestCurl = request.getCurl()
}
func saveRequestBody(_ request: URLRequest)
{
saveRequestBodyData(request.getNFXBody())
}
func logRequest(_ request: URLRequest)
{
formattedRequestLogEntry().appendToFile(filePath: NFXPath.SessionLog)
}
func saveErrorResponse()
{
self.responseDate = Date()
}
func saveResponse(_ response: URLResponse, data: Data)
{
self.noResponse = false
self.responseDate = Date()
self.responseTime = getTimeFromDate(self.responseDate!)
self.responseStatus = response.getNFXStatus()
self.responseHeaders = response.getNFXHeaders()
let headers = response.getNFXHeaders()
if let contentType = headers["Content-Type"] as? String {
self.responseType = contentType.components(separatedBy: ";")[0]
self.shortType = getShortTypeFrom(self.responseType!).rawValue as NSString
}
self.timeInterval = Float(self.responseDate!.timeIntervalSince(self.requestDate!))
saveResponseBodyData(data)
formattedResponseLogEntry().appendToFile(filePath: NFXPath.SessionLog)
}
func saveRequestBodyData(_ data: Data)
{
let tempBodyString = NSString.init(data: data, encoding: String.Encoding.utf8.rawValue)
self.requestBodyLength = data.count
if (tempBodyString != nil) {
saveData(tempBodyString!, toFile: getRequestBodyFilepath())
}
}
func saveResponseBodyData(_ data: Data)
{
var bodyString: NSString?
if self.shortType as String == HTTPModelShortType.IMAGE.rawValue {
bodyString = data.base64EncodedString(options: .endLineWithLineFeed) as NSString?
} else {
if let tempBodyString = NSString.init(data: data, encoding: String.Encoding.utf8.rawValue) {
bodyString = tempBodyString
}
}
if (bodyString != nil) {
self.responseBodyLength = data.count
saveData(bodyString!, toFile: getResponseBodyFilepath())
}
}
fileprivate func prettyOutput(_ rawData: Data, contentType: String? = nil) -> NSString
{
if let contentType = contentType {
let shortType = getShortTypeFrom(contentType)
if let output = prettyPrint(rawData, type: shortType) {
return output as NSString
}
}
return NSString(data: rawData, encoding: String.Encoding.utf8.rawValue) ?? ""
}
@objc public func getRequestBody() -> NSString
{
guard let data = readRawData(getRequestBodyFilepath()) else {
return ""
}
return prettyOutput(data, contentType: requestType)
}
@objc public func getResponseBody() -> NSString
{
guard let data = readRawData(getResponseBodyFilepath()) else {
return ""
}
return prettyOutput(data, contentType: responseType)
}
@objc public func getRandomHash() -> NSString
{
if !(self.randomHash != nil) {
self.randomHash = UUID().uuidString as NSString?
}
return self.randomHash!
}
@objc public func getRequestBodyFilepath() -> String
{
let dir = getDocumentsPath() as NSString
return dir.appendingPathComponent(getRequestBodyFilename())
}
@objc public func getRequestBodyFilename() -> String
{
return String("nfx_request_body_") + "\(self.requestTime!)_\(getRandomHash() as String)"
}
@objc public func getResponseBodyFilepath() -> String
{
let dir = getDocumentsPath() as NSString
return dir.appendingPathComponent(getResponseBodyFilename())
}
@objc public func getResponseBodyFilename() -> String
{
return String("nfx_response_body_") + "\(self.requestTime!)_\(getRandomHash() as String)"
}
@objc public func getDocumentsPath() -> String
{
return NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first!
}
@objc public func saveData(_ dataString: NSString, toFile: String)
{
do {
try dataString.write(toFile: toFile, atomically: false, encoding: String.Encoding.utf8.rawValue)
} catch {
print("catch !!!")
}
}
@objc public func readRawData(_ fromFile: String) -> Data?
{
return (try? Data(contentsOf: URL(fileURLWithPath: fromFile)))
}
@objc public func getTimeFromDate(_ date: Date) -> String?
{
let calendar = Calendar.current
let components = (calendar as NSCalendar).components([.hour, .minute], from: date)
guard let hour = components.hour, let minutes = components.minute else {
return nil
}
if minutes < 10 {
return "\(hour):0\(minutes)"
} else {
return "\(hour):\(minutes)"
}
}
public func getShortTypeFrom(_ contentType: String) -> HTTPModelShortType
{
if NSPredicate(format: "SELF MATCHES %@",
"^application/(vnd\\.(.*)\\+)?json$").evaluate(with: contentType) {
return .JSON
}
if (contentType == "application/xml") || (contentType == "text/xml") {
return .XML
}
if contentType == "text/html" {
return .HTML
}
if contentType.hasPrefix("image/") {
return .IMAGE
}
return .OTHER
}
public func prettyPrint(_ rawData: Data, type: HTTPModelShortType) -> NSString?
{
switch type {
case .JSON:
do {
let rawJsonData = try JSONSerialization.jsonObject(with: rawData, options: [])
let prettyPrintedString = try JSONSerialization.data(withJSONObject: rawJsonData, options: [.prettyPrinted])
return NSString(data: prettyPrintedString, encoding: String.Encoding.utf8.rawValue)
} catch {
return nil
}
default:
return nil
}
}
@objc public func isSuccessful() -> Bool
{
if (self.responseStatus != nil) && (self.responseStatus < 400) {
return true
} else {
return false
}
}
@objc public func formattedRequestLogEntry() -> String {
var log = String()
if let requestURL = self.requestURL {
log.append("-------START REQUEST - \(requestURL) -------\n")
}
if let requestMethod = self.requestMethod {
log.append("[Request Method] \(requestMethod)\n")
}
if let requestDate = self.requestDate {
log.append("[Request Date] \(requestDate)\n")
}
if let requestTime = self.requestTime {
log.append("[Request Time] \(requestTime)\n")
}
if let requestType = self.requestType {
log.append("[Request Type] \(requestType)\n")
}
if let requestTimeout = self.requestTimeout {
log.append("[Request Timeout] \(requestTimeout)\n")
}
if let requestHeaders = self.requestHeaders {
log.append("[Request Headers]\n\(requestHeaders)\n")
}
log.append("[Request Body]\n \(getRequestBody())\n")
if let requestURL = self.requestURL {
log.append("-------END REQUEST - \(requestURL) -------\n\n")
}
return log;
}
@objc public func formattedResponseLogEntry() -> String {
var log = String()
if let requestURL = self.requestURL {
log.append("-------START RESPONSE - \(requestURL) -------\n")
}
if let responseStatus = self.responseStatus {
log.append("[Response Status] \(responseStatus)\n")
}
if let responseType = self.responseType {
log.append("[Response Type] \(responseType)\n")
}
if let responseDate = self.responseDate {
log.append("[Response Date] \(responseDate)\n")
}
if let responseTime = self.responseTime {
log.append("[Response Time] \(responseTime)\n")
}
if let responseHeaders = self.responseHeaders {
log.append("[Response Headers]\n\(responseHeaders)\n\n")
}
log.append("[Response Body]\n \(getResponseBody())\n")
if let requestURL = self.requestURL {
log.append("-------END RESPONSE - \(requestURL) -------\n\n")
}
return log;
}
}
| mit | d1e82cea1856e5e3ad02f28df60b3333 | 30.138728 | 163 | 0.581028 | 4.897273 | false | false | false | false |
rajeejones/SavingPennies | Pods/IBAnimatable/IBAnimatable/ActivityIndicatorAnimationLineScale.swift | 5 | 1641 | //
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationLineScale: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 1
fileprivate let timingFunction = CAMediaTimingFunction(controlPoints: 0.2, 0.68, 0.18, 1.08)
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let lineSize = size.width / 9
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let beginTime = CACurrentMediaTime()
let beginTimes = [0.1, 0.2, 0.3, 0.4, 0.5]
let animation = self.animation
for i in 0 ..< 5 {
let line = ActivityIndicatorShape.line.makeLayer(size: CGSize(width: lineSize, height: size.height), color: color)
let frame = CGRect(x: x + lineSize * 2 * CGFloat(i), y: y, width: lineSize, height: size.height)
animation.beginTime = beginTime + beginTimes[i]
line.frame = frame
line.add(animation, forKey: "animation")
layer.addSublayer(line)
}
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationLineScale {
var animation: CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: "transform.scale.y")
animation.keyTimes = [0, 0.5, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.4, 1]
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
}
| gpl-3.0 | 82727665d121535c70344a2ffdf38ba2 | 29.962264 | 120 | 0.697745 | 4.031941 | false | false | false | false |
eungkyu/JSONCodable | Demo/Demo/ViewController.swift | 1 | 1699 | //
// ViewController.swift
// Demo
//
// Created by Matthew Cheok on 18/7/15.
// Copyright © 2015 matthewcheok. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let JSON = [
"id": 24,
"full_name": "John Appleseed",
"email": "[email protected]",
"company": [
"name": "Apple",
"address": "1 Infinite Loop, Cupertino, CA"
],
"friends": [
["id": 27, "full_name": "Bob Jefferson"],
["id": 29, "full_name": "Jen Jackson"]
],
"website": ["url": "http://johnappleseed.com"],
"props": ["prop a": "value a", "prop b": "value b"]
]
print("Initial JSON:\n\(JSON)\n\n")
let user = User(JSONDictionary: JSON)!
print("Decoded: \n\(user)\n\n")
do {
let dict = try user.toJSON()
print("Encoded: \n\(dict as! [String: AnyObject])\n\n")
}
catch {
print("Error: \(error)")
}
//do {
// let string = try user.JSONString()
// print(string)
//
// let userAgain = User(JSONString: string)
// print(userAgain)
//} catch {
// print("Error: \(error)")
//}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | c8d3356ad25e0f96cc2fb89af7090ea4 | 24.343284 | 80 | 0.471143 | 4.277078 | false | false | false | false |
Havi4/CFCityPickerVC | CFCityPickerVC/CFCityPickerVC/View/CitySearchBar.swift | 21 | 2225 | //
// CitySearchBar.swift
// CFCityPickerVC
//
// Created by 冯成林 on 15/8/6.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import UIKit
class CitySearchBar: UISearchBar,UISearchBarDelegate {
var searchBarShouldBeginEditing: (()->())?
var searchBarDidEndditing: (()->())?
var searchAction: ((searchText: String)->Void)?
var searchTextDidChangedAction: ((searchText: String)->Void)?
var searchBarCancelAction: (()->())?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
/** 视图准备 */
self.viewPrepare()
}
override init(frame: CGRect) {
super.init(frame: frame)
/** 视图准备 */
self.viewPrepare()
}
/** 视图准备 */
func viewPrepare(){
self.backgroundColor = UIColor.clearColor()
self.backgroundImage = UIImage()
self.layer.borderColor = CFCityPickerVC.cityPVCTintColor.CGColor
self.layer.borderWidth = 0.5
self.layer.cornerRadius = 4
self.layer.masksToBounds = true
self.setTranslatesAutoresizingMaskIntoConstraints(false)
self.placeholder = "输出城市名、拼音或者首字母查询"
self.tintColor = CFCityPickerVC.cityPVCTintColor
self.delegate = self
}
}
extension CitySearchBar{
func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
searchBar.setShowsCancelButton(true, animated: true)
searchBarShouldBeginEditing?()
return true
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchBarDidEndditing?()
searchBar.setShowsCancelButton(false, animated: true)
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.endEditing(true)
searchBarCancelAction?()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchAction?(searchText: searchBar.text)
searchBar.endEditing(true)
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
searchTextDidChangedAction?(searchText: searchText)
}
}
| mit | 122e401833232dd1be90809da7ef4386 | 24.987952 | 78 | 0.639314 | 5.087264 | false | false | false | false |
izotx/iTenWired-Swift | Pods/JMCiBeaconManager/JMCiBeaconManager/Classes/JMCBeaconManager.swift | 5 | 14765 | //
// JMCBeaconManager.swift
// PerfecTour
//
// Created by Janusz Chudzynski on 1/30/16.
// Copyright © 2016 PerfecTour. All rights reserved.
import UIKit
import CoreLocation
/**Used to broadcast NSNotification*/
public enum iBeaconNotifications:String{
case BeaconProximity
case BeaconState
case Location // new location discoverd
case iBeaconEnabled
case iBeaconDisabled
}
/**Interacting with the iBeacons*/
public class JMCBeaconManager: NSObject, CLLocationManagerDelegate {
let locationManager:CLLocationManager = CLLocationManager()
// private var beacons = [iBeacon]() // Currently unused
/**Storing reference to registered regions*/
private var regions = [CLBeaconRegion]()
public var stateCallback:((beacon:iBeacon)->Void)?
public var rangeCallback:((beacon:iBeacon)->Void)?
var bluetoothManager:BluetoothManager?
public var logging = true
var broadcasting = true
//Different cases
var bluetoothDisabled = true
/**Error Callback*/
var errorCallback:((messages:[String])->Void)?
/**Success Callback*/
var successCallback:(()->Void)?
override public init(){
super.init()
// bluetoothManager.callback = bluetoothUpdate
locationManager.delegate = self
registerNotifications()
//locationManager.startUpdatingLocation()
//test if enabled
}
/**Starts Monitoring for beacons*/
public func startMonitoring(successCallback:(()->Void), errorCallback:(messages:[String])->Void){
self.successCallback = successCallback
self.errorCallback = errorCallback
checkStatus()
}
/**Checks the status of the application*/
func checkStatus(){
//starts from Bluetooth
if let _ = self.bluetoothManager{
}
else{
bluetoothManager = BluetoothManager()
bluetoothManager?.callback = bluetoothUpdate
}
}
// var bluetoothManager
/**Check Bluetooth*/
private func bluetoothUpdate(status:Bool)->Void{
if status == true{
bluetoothDisabled = false
//rund additional status check
let tuple = statusCheck()
if tuple.0{
self.successCallback?()
NSNotificationCenter.defaultCenter().postNotificationName(iBeaconNotifications.iBeaconEnabled.rawValue, object: nil)
startMonitoring()
}
else{
self.errorCallback?(messages: tuple.messages)
NSNotificationCenter.defaultCenter().postNotificationName(iBeaconNotifications.iBeaconDisabled.rawValue, object: tuple.messages)
}
}
else{
NSNotificationCenter.defaultCenter().postNotificationName(iBeaconNotifications.iBeaconDisabled.rawValue, object:nil)
self.errorCallback?(messages: ["Bluetooth not enabled."])
bluetoothDisabled = true
}
}
/**Checks if ibeacons are enabled. Should be called first*/
private func statusCheck()->(Bool,messages:[String]){
locationManager.requestAlwaysAuthorization()
var check = true
var messages = [String]()
if bluetoothDisabled == true
{
messages.append("Bluetooth must be turned on.")
check = false
}
if CLLocationManager.authorizationStatus() != .AuthorizedAlways {
if logging {
print("Error - authorization status not enabled!")
}
messages.append("Location Services Must be Authorized.")
check = false
}
if !CLLocationManager.isMonitoringAvailableForClass(CLRegion){
check = false
messages.append("CLLocationManager monitoring is not enabled on this device.")
}
return (check, messages)
}
//
/**Register Notifications*/
func registerNotifications()
{
NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationBackgroundRefreshStatusDidChangeNotification, object: UIApplication.sharedApplication(), queue: nil) { (notification) -> Void in
}
}
/**Register iBeacons*/
public func registerBeacons(beacons:[iBeacon])
{
for beacon in beacons{
var beaconRegion:CLBeaconRegion = CLBeaconRegion(proximityUUID: NSUUID(UUIDString:beacon.UUID)!, identifier: beacon.id)
/**Only major infoermation provided*/
if let major = beacon.major{
beaconRegion = CLBeaconRegion(proximityUUID: NSUUID(UUIDString:beacon.UUID)!, major: major, identifier: beacon.id)
}
/**All the information provided*/
if let major = beacon.major, minor = beacon.minor{
beaconRegion = CLBeaconRegion(proximityUUID: NSUUID(UUIDString:beacon.UUID)!, major: major, minor: minor, identifier: beacon.id)
}
beaconRegion.notifyEntryStateOnDisplay = true
beaconRegion.notifyOnEntry = true
beaconRegion.notifyOnExit = true
regions.append( beaconRegion)
}
}
/**Register iBeacons*/
public func registerBeacon(beaconId:String)
{
let bid = CLBeaconRegion(proximityUUID: NSUUID(UUIDString:beaconId)!, identifier: "Testing Beacon")
regions.append(bid)
}
/**Starts monitoring beacons*/
func startMonitoring(){
locationManager.startUpdatingLocation()
locationManager.distanceFilter = 10
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
for beaconRegion in regions{
locationManager.startMonitoringForRegion(beaconRegion)
locationManager.startRangingBeaconsInRegion(beaconRegion)
//FIXME: check if needed [self.locationManager performSelector:@selector(requestStateForRegion:) withObject:beaconRegion afterDelay:1];
//FIXME: added more validation for the ibeacons permission matrix
}
}
/**Stops monitoring beacons*/
public func stopMonitoring(){
for beaconRegion in regions{
locationManager.stopMonitoringForRegion(beaconRegion)
locationManager.stopRangingBeaconsInRegion(beaconRegion)
}
locationManager.stopUpdatingLocation()
}
// MARK: Core Location Delegate
/*
* locationManager:didDetermineState:forRegion:
*
* Discussion:
* Invoked when there's a state transition for a monitored region or in response to a request for state via a
* a call to requestStateForRegion:.
*/
public func locationManager(manager: CLLocationManager, didDetermineState state: CLRegionState, forRegion region: CLRegion)
{
//we found a beacon. Now
if let region = region as? CLBeaconRegion
{
if logging {
print("State determined\(region) \(state.rawValue)")
}
}
//we found a beacon. Now
if let region = region as? CLBeaconRegion, minor = region.minor, major = region.major{
let beacon = iBeacon(minor: minor.unsignedShortValue, major: major.unsignedShortValue, proximityId: region.proximityUUID.UUIDString)
beacon.state = state
if logging {
print("State determined\(region) \(state.rawValue)")
}
if broadcasting{
//broadcast notification
//get beacon from clregion
NSNotificationCenter.defaultCenter().postNotificationName(iBeaconNotifications.BeaconState.rawValue, object: beacon)
}
if let callback = self.stateCallback{
callback(beacon: beacon)
}
}
//if we are outside stop ranging
if state == .Outside{
manager.stopRangingBeaconsInRegion(region as! CLBeaconRegion)
}
if state == .Inside{
manager.startRangingBeaconsInRegion(region as! CLBeaconRegion)
}
}
/*
* locationManager:didRangeBeacons:inRegion:
*
* Discussion:
* Invoked when a new set of beacons are available in the specified region.
* beacons is an array of CLBeacon objects.
* If beacons is empty, it may be assumed no beacons that match the specified region are nearby.
* Similarly if a specific beacon no longer appears in beacons, it may be assumed the beacon is no longer received
* by the device.
*/
public func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion)
{
//Notify the delegates and etc that we know how far are we from the iBeacon
if logging {
print("Did Range Beacons \(beacons)")
}
if broadcasting{
//broadcast notification
//convert CLBeacon to iBeacon
var myBeacons = [iBeacon]()
//convert it to our iBeacons
for beacon in beacons{
if beacon.proximity != .Unknown{
let myBeacon = iBeacon(beacon: beacon)
myBeacons.append(myBeacon)
}
}
myBeacons.sortInPlace({$0.proximity.sortIndex < $1.proximity.sortIndex})
NSNotificationCenter.defaultCenter().postNotificationName(iBeaconNotifications.BeaconProximity.rawValue, object: myBeacons)
}
for beacon in beacons{
if logging {
print("Did Range Beacon \(beacon)")
}
if let callback = self.rangeCallback{
//convert it to the internal type of the beacon
let ibeacon = iBeacon(minor: beacon.minor.unsignedShortValue, major: beacon.major.unsignedShortValue, proximityId: beacon.proximityUUID.UUIDString)
ibeacon.proximity = beacon.proximity
callback(beacon: ibeacon)
}
}
}
/**Update Location*/
public func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last{
print("Update Location to \(location)")
NSNotificationCenter.defaultCenter().postNotificationName(iBeaconNotifications.Location.rawValue, object: location)
}
}
/*
* locationManager:rangingBeaconsDidFailForRegion:withError:
*
* Discussion:
* Invoked when an error has occurred ranging beacons in a region. Error types are defined in "CLError.h".
*/
public func locationManager(manager: CLLocationManager, rangingBeaconsDidFailForRegion region: CLBeaconRegion, withError error: NSError)
{
if logging {
print("Ranging Fail\(region) \(error.debugDescription)")
}
}
/*
* locationManager:didEnterRegion:
*
* Discussion:
* Invoked when the user enters a monitored region. This callback will be invoked for every allocated
* CLLocationManager instance with a non-nil delegate that implements this method.
*/
public func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion)
{
if region is CLBeaconRegion{
if logging {
print("Region Entered! \(region) ")
manager.startRangingBeaconsInRegion(region as! CLBeaconRegion)
}
}
}
/*
* locationManager:didExitRegion:
*
* Discussion:
* Invoked when the user exits a monitored region. This callback will be invoked for every allocated
* CLLocationManager instance with a non-nil delegate that implements this method.
*/
public func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion)
{
if region is CLBeaconRegion{
if logging {
print("Exit Region! \(region) ")
manager.stopRangingBeaconsInRegion(region as! CLBeaconRegion)
}
}
}
/*
* locationManager:didFailWithError:
*
* Discussion:
* Invoked when an error has occurred. Error types are defined in "CLError.h".
*/
public func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
if logging {
print("Manager Failed with error \(error)")
}
}
/*
* locationManager:monitoringDidFailForRegion:withError:
*
* Discussion:
* Invoked when a region monitoring error has occurred. Error types are defined in "CLError.h".
*/
public func locationManager(manager: CLLocationManager, monitoringDidFailForRegion region: CLRegion?, withError error: NSError)
{
if logging {
print("Monitoring Failed with error \(error)")
}
}
/*
* locationManager:didChangeAuthorizationStatus:
*
* Discussion:
* Invoked when the authorization status changes for this application.
*/
public func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus)
{
if status == CLAuthorizationStatus.AuthorizedAlways{
if statusCheck().0 == true {
startMonitoring()
}
}
}
/*
* locationManager:didStartMonitoringForRegion:
*
* Discussion:
* Invoked when a monitoring for a region started successfully.
*/
public func locationManager(manager: CLLocationManager, didStartMonitoringForRegion region: CLRegion)
{
}
/*
* Discussion:
* Invoked when location updates are automatically paused.
*/
public func locationManagerDidPauseLocationUpdates(manager: CLLocationManager)
{
}
/*
* Discussion:
* Invoked when location updates are automatically resumed.
*
* In the event that your application is terminated while suspended, you will
* not receive this notification.
*/
public func locationManagerDidResumeLocationUpdates(manager: CLLocationManager)
{
}
/*
** Returns true is the beacon is inside the required range, false otherwise
**
*/
public static func isInRange( objectProximity : CLProximity, requiredProximity: CLProximity) -> Bool {
return objectProximity.sortIndex <= requiredProximity.sortIndex
}
}
| bsd-2-clause | 0ccc045630b1ec6398549add61e95ee6 | 31.663717 | 205 | 0.623341 | 5.709203 | false | false | false | false |
brunophilipe/tune | tune/User Interface/UIDialog.swift | 1 | 2170 | //
// UIDialog.swift
// tune
//
// Created by Bruno Philipe on 1/5/17.
// Copyright © 2017 Bruno Philipe. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import Foundation
/// Wrapper around the ncurses `panel` object.
class UIDialog: UIWindow
{
internal var panel: UnsafeMutablePointer<PANEL>? = nil
override init(frame: UIFrame)
{
super.init(frame: frame)
panel = new_panel(windowRef)
}
deinit
{
if let panel = self.panel
{
del_panel(panel)
self.panel = nil
}
}
override var frame: UIFrame
{
didSet
{
if let panel = self.panel
{
move_panel(panel, frame.y, frame.x)
wresize(windowRef, frame.height, frame.width)
replace_panel(panel, windowRef)
}
else
{
mvwin(windowRef, frame.y, frame.x)
wresize(windowRef, frame.height, frame.width)
}
wclear(windowRef)
container.frame = UIFrame(size: frame.size)
}
}
var hidden: Bool
{
get
{
if let panel = self.panel
{
return panel_hidden(panel) != 0
}
else
{
return false
}
}
set
{
if let panel = self.panel
{
if newValue
{
hide_panel(panel)
}
else
{
show_panel(panel)
}
}
}
}
func pullToTop()
{
if let panel = self.panel
{
top_panel(panel)
}
}
func pushToBottom()
{
if let panel = self.panel
{
bottom_panel(panel)
}
}
override func draw()
{
if panel != nil
{
// We should not call wrefresh on windows that are also panels
container.draw()
}
else
{
super.draw()
}
}
}
| gpl-3.0 | 9d9bf976675d8382357c86581c6d9611 | 16.352 | 73 | 0.640387 | 3.01669 | false | false | false | false |
practicalswift/swift | stdlib/public/Darwin/Foundation/CharacterSet.swift | 2 | 32501 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import CoreFoundation
import _SwiftCoreFoundationOverlayShims
import _SwiftFoundationOverlayShims
private func _utfRangeToCFRange(_ inRange : Range<Unicode.Scalar>) -> CFRange {
return CFRange(
location: Int(inRange.lowerBound.value),
length: Int(inRange.upperBound.value - inRange.lowerBound.value))
}
private func _utfRangeToCFRange(_ inRange : ClosedRange<Unicode.Scalar>) -> CFRange {
return CFRange(
location: Int(inRange.lowerBound.value),
length: Int(inRange.upperBound.value - inRange.lowerBound.value + 1))
}
// MARK: -
// NOTE: older overlays called this class _CharacterSetStorage.
// The two must coexist without a conflicting ObjC class name, so it
// was renamed. The old name must not be used in the new runtime.
fileprivate final class __CharacterSetStorage : Hashable {
fileprivate enum Backing {
case immutable(CFCharacterSet)
case mutable(CFMutableCharacterSet)
}
fileprivate var _backing : Backing
@nonobjc
init(immutableReference r : CFCharacterSet) {
_backing = .immutable(r)
}
@nonobjc
init(mutableReference r : CFMutableCharacterSet) {
_backing = .mutable(r)
}
// MARK: -
fileprivate var hashValue : Int {
switch _backing {
case .immutable(let cs):
return Int(CFHash(cs))
case .mutable(let cs):
return Int(CFHash(cs))
}
}
fileprivate static func ==(lhs : __CharacterSetStorage, rhs : __CharacterSetStorage) -> Bool {
switch (lhs._backing, rhs._backing) {
case (.immutable(let cs1), .immutable(let cs2)):
return CFEqual(cs1, cs2)
case (.immutable(let cs1), .mutable(let cs2)):
return CFEqual(cs1, cs2)
case (.mutable(let cs1), .immutable(let cs2)):
return CFEqual(cs1, cs2)
case (.mutable(let cs1), .mutable(let cs2)):
return CFEqual(cs1, cs2)
}
}
// MARK: -
fileprivate func mutableCopy() -> __CharacterSetStorage {
switch _backing {
case .immutable(let cs):
return __CharacterSetStorage(mutableReference: CFCharacterSetCreateMutableCopy(nil, cs))
case .mutable(let cs):
return __CharacterSetStorage(mutableReference: CFCharacterSetCreateMutableCopy(nil, cs))
}
}
// MARK: Immutable Functions
fileprivate var bitmapRepresentation : Data {
switch _backing {
case .immutable(let cs):
return CFCharacterSetCreateBitmapRepresentation(nil, cs) as Data
case .mutable(let cs):
return CFCharacterSetCreateBitmapRepresentation(nil, cs) as Data
}
}
fileprivate func hasMember(inPlane plane: UInt8) -> Bool {
switch _backing {
case .immutable(let cs):
return CFCharacterSetHasMemberInPlane(cs, CFIndex(plane))
case .mutable(let cs):
return CFCharacterSetHasMemberInPlane(cs, CFIndex(plane))
}
}
// MARK: Mutable functions
fileprivate func insert(charactersIn range: Range<Unicode.Scalar>) {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
CFCharacterSetAddCharactersInRange(r, _utfRangeToCFRange(range))
_backing = .mutable(r)
case .mutable(let cs):
CFCharacterSetAddCharactersInRange(cs, _utfRangeToCFRange(range))
}
}
fileprivate func insert(charactersIn range: ClosedRange<Unicode.Scalar>) {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
CFCharacterSetAddCharactersInRange(r, _utfRangeToCFRange(range))
_backing = .mutable(r)
case .mutable(let cs):
CFCharacterSetAddCharactersInRange(cs, _utfRangeToCFRange(range))
}
}
fileprivate func remove(charactersIn range: Range<Unicode.Scalar>) {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
CFCharacterSetRemoveCharactersInRange(r, _utfRangeToCFRange(range))
_backing = .mutable(r)
case .mutable(let cs):
CFCharacterSetRemoveCharactersInRange(cs, _utfRangeToCFRange(range))
}
}
fileprivate func remove(charactersIn range: ClosedRange<Unicode.Scalar>) {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
CFCharacterSetRemoveCharactersInRange(r, _utfRangeToCFRange(range))
_backing = .mutable(r)
case .mutable(let cs):
CFCharacterSetRemoveCharactersInRange(cs, _utfRangeToCFRange(range))
}
}
fileprivate func insert(charactersIn string: String) {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
CFCharacterSetAddCharactersInString(r, string as CFString)
_backing = .mutable(r)
case .mutable(let cs):
CFCharacterSetAddCharactersInString(cs, string as CFString)
}
}
fileprivate func remove(charactersIn string: String) {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
CFCharacterSetRemoveCharactersInString(r, string as CFString)
_backing = .mutable(r)
case .mutable(let cs):
CFCharacterSetRemoveCharactersInString(cs, string as CFString)
}
}
fileprivate func invert() {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
CFCharacterSetInvert(r)
_backing = .mutable(r)
case .mutable(let cs):
CFCharacterSetInvert(cs)
}
}
// -----
// MARK: -
// MARK: SetAlgebraType
@discardableResult
fileprivate func insert(_ character: Unicode.Scalar) -> (inserted: Bool, memberAfterInsert: Unicode.Scalar) {
insert(charactersIn: character...character)
// TODO: This should probably return the truth, but figuring it out requires two calls into NSCharacterSet
return (true, character)
}
@discardableResult
fileprivate func update(with character: Unicode.Scalar) -> Unicode.Scalar? {
insert(character)
// TODO: This should probably return the truth, but figuring it out requires two calls into NSCharacterSet
return character
}
@discardableResult
fileprivate func remove(_ character: Unicode.Scalar) -> Unicode.Scalar? {
// TODO: Add method to CFCharacterSet to do this in one call
let result : Unicode.Scalar? = contains(character) ? character : nil
remove(charactersIn: character...character)
return result
}
fileprivate func contains(_ member: Unicode.Scalar) -> Bool {
switch _backing {
case .immutable(let cs):
return CFCharacterSetIsLongCharacterMember(cs, member.value)
case .mutable(let cs):
return CFCharacterSetIsLongCharacterMember(cs, member.value)
}
}
// MARK: -
// Why do these return CharacterSet instead of CharacterSetStorage?
// We want to keep the knowledge of if the returned value happened to contain a mutable or immutable CFCharacterSet as close to the creation of that instance as possible
// When the underlying collection does not have a method to return new CharacterSets with changes applied, so we will copy and apply here
private static func _apply(_ lhs : __CharacterSetStorage, _ rhs : __CharacterSetStorage, _ f : (CFMutableCharacterSet, CFCharacterSet) -> ()) -> CharacterSet {
let copyOfMe : CFMutableCharacterSet
switch lhs._backing {
case .immutable(let cs):
copyOfMe = CFCharacterSetCreateMutableCopy(nil, cs)!
case .mutable(let cs):
copyOfMe = CFCharacterSetCreateMutableCopy(nil, cs)!
}
switch rhs._backing {
case .immutable(let cs):
f(copyOfMe, cs)
case .mutable(let cs):
f(copyOfMe, cs)
}
return CharacterSet(_uncopiedStorage: __CharacterSetStorage(mutableReference: copyOfMe))
}
private func _applyMutation(_ other : __CharacterSetStorage, _ f : (CFMutableCharacterSet, CFCharacterSet) -> ()) {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
switch other._backing {
case .immutable(let otherCs):
f(r, otherCs)
case .mutable(let otherCs):
f(r, otherCs)
}
_backing = .mutable(r)
case .mutable(let cs):
switch other._backing {
case .immutable(let otherCs):
f(cs, otherCs)
case .mutable(let otherCs):
f(cs, otherCs)
}
}
}
fileprivate var inverted : CharacterSet {
switch _backing {
case .immutable(let cs):
return CharacterSet(_uncopiedStorage: __CharacterSetStorage(immutableReference: CFCharacterSetCreateInvertedSet(nil, cs)))
case .mutable(let cs):
// Even if input is mutable, the result is immutable
return CharacterSet(_uncopiedStorage: __CharacterSetStorage(immutableReference: CFCharacterSetCreateInvertedSet(nil, cs)))
}
}
fileprivate func union(_ other: __CharacterSetStorage) -> CharacterSet {
return __CharacterSetStorage._apply(self, other, CFCharacterSetUnion)
}
fileprivate func formUnion(_ other: __CharacterSetStorage) {
_applyMutation(other, CFCharacterSetUnion)
}
fileprivate func intersection(_ other: __CharacterSetStorage) -> CharacterSet {
return __CharacterSetStorage._apply(self, other, CFCharacterSetIntersect)
}
fileprivate func formIntersection(_ other: __CharacterSetStorage) {
_applyMutation(other, CFCharacterSetIntersect)
}
fileprivate func subtracting(_ other: __CharacterSetStorage) -> CharacterSet {
return intersection(other.inverted._storage)
}
fileprivate func subtract(_ other: __CharacterSetStorage) {
_applyMutation(other.inverted._storage, CFCharacterSetIntersect)
}
fileprivate func symmetricDifference(_ other: __CharacterSetStorage) -> CharacterSet {
return union(other).subtracting(intersection(other))
}
fileprivate func formSymmetricDifference(_ other: __CharacterSetStorage) {
// This feels like cheating
_backing = symmetricDifference(other)._storage._backing
}
fileprivate func isSuperset(of other: __CharacterSetStorage) -> Bool {
switch _backing {
case .immutable(let cs):
switch other._backing {
case .immutable(let otherCs):
return CFCharacterSetIsSupersetOfSet(cs, otherCs)
case .mutable(let otherCs):
return CFCharacterSetIsSupersetOfSet(cs, otherCs)
}
case .mutable(let cs):
switch other._backing {
case .immutable(let otherCs):
return CFCharacterSetIsSupersetOfSet(cs, otherCs)
case .mutable(let otherCs):
return CFCharacterSetIsSupersetOfSet(cs, otherCs)
}
}
}
// MARK: -
fileprivate var description: String {
switch _backing {
case .immutable(let cs):
return CFCopyDescription(cs) as String
case .mutable(let cs):
return CFCopyDescription(cs) as String
}
}
fileprivate var debugDescription: String {
return description
}
// MARK: -
public func bridgedReference() -> NSCharacterSet {
switch _backing {
case .immutable(let cs):
return cs as NSCharacterSet
case .mutable(let cs):
return cs as NSCharacterSet
}
}
}
// MARK: -
/**
A `CharacterSet` represents a set of Unicode-compliant characters. Foundation types use `CharacterSet` to group characters together for searching operations, so that they can find any of a particular set of characters during a search.
This type provides "copy-on-write" behavior, and is also bridged to the Objective-C `NSCharacterSet` class.
*/
public struct CharacterSet : ReferenceConvertible, Equatable, Hashable, SetAlgebra {
public typealias ReferenceType = NSCharacterSet
fileprivate var _storage : __CharacterSetStorage
// MARK: Init methods
/// Initialize an empty instance.
public init() {
// It's unlikely that we are creating an empty character set with no intention to mutate it
_storage = __CharacterSetStorage(mutableReference: CFCharacterSetCreateMutable(nil))
}
/// Initialize with a range of integers.
///
/// It is the caller's responsibility to ensure that the values represent valid `Unicode.Scalar` values, if that is what is desired.
public init(charactersIn range: Range<Unicode.Scalar>) {
_storage = __CharacterSetStorage(immutableReference: CFCharacterSetCreateWithCharactersInRange(nil, _utfRangeToCFRange(range)))
}
/// Initialize with a closed range of integers.
///
/// It is the caller's responsibility to ensure that the values represent valid `Unicode.Scalar` values, if that is what is desired.
public init(charactersIn range: ClosedRange<Unicode.Scalar>) {
_storage = __CharacterSetStorage(immutableReference: CFCharacterSetCreateWithCharactersInRange(nil, _utfRangeToCFRange(range)))
}
/// Initialize with the characters in the given string.
///
/// - parameter string: The string content to inspect for characters.
public init(charactersIn string: __shared String) {
_storage = __CharacterSetStorage(immutableReference: CFCharacterSetCreateWithCharactersInString(nil, string as CFString))
}
/// Initialize with a bitmap representation.
///
/// This method is useful for creating a character set object with data from a file or other external data source.
/// - parameter data: The bitmap representation.
public init(bitmapRepresentation data: __shared Data) {
_storage = __CharacterSetStorage(immutableReference: CFCharacterSetCreateWithBitmapRepresentation(nil, data as CFData))
}
/// Initialize with the contents of a file.
///
/// Returns `nil` if there was an error reading the file.
/// - parameter file: The file to read.
public init?(contentsOfFile file: __shared String) {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: file), options: .mappedIfSafe)
_storage = __CharacterSetStorage(immutableReference: CFCharacterSetCreateWithBitmapRepresentation(nil, data as CFData))
} catch {
return nil
}
}
fileprivate init(_bridged characterSet: __shared NSCharacterSet) {
_storage = __CharacterSetStorage(immutableReference: characterSet.copy() as! CFCharacterSet)
}
fileprivate init(_uncopiedImmutableReference characterSet: CFCharacterSet) {
_storage = __CharacterSetStorage(immutableReference: characterSet)
}
fileprivate init(_uncopiedStorage : __CharacterSetStorage) {
_storage = _uncopiedStorage
}
fileprivate init(_builtIn: __shared CFCharacterSetPredefinedSet) {
_storage = __CharacterSetStorage(immutableReference: CFCharacterSetGetPredefined(_builtIn))
}
// MARK: Static functions
/// Returns a character set containing the characters in Unicode General Category Cc and Cf.
public static var controlCharacters : CharacterSet {
return CharacterSet(_builtIn: .control)
}
/// Returns a character set containing the characters in Unicode General Category Zs and `CHARACTER TABULATION (U+0009)`.
public static var whitespaces : CharacterSet {
return CharacterSet(_builtIn: .whitespace)
}
/// Returns a character set containing characters in Unicode General Category Z*, `U+000A ~ U+000D`, and `U+0085`.
public static var whitespacesAndNewlines : CharacterSet {
return CharacterSet(_builtIn: .whitespaceAndNewline)
}
/// Returns a character set containing the characters in the category of Decimal Numbers.
public static var decimalDigits : CharacterSet {
return CharacterSet(_builtIn: .decimalDigit)
}
/// Returns a character set containing the characters in Unicode General Category L* & M*.
public static var letters : CharacterSet {
return CharacterSet(_builtIn: .letter)
}
/// Returns a character set containing the characters in Unicode General Category Ll.
public static var lowercaseLetters : CharacterSet {
return CharacterSet(_builtIn: .lowercaseLetter)
}
/// Returns a character set containing the characters in Unicode General Category Lu and Lt.
public static var uppercaseLetters : CharacterSet {
return CharacterSet(_builtIn: .uppercaseLetter)
}
/// Returns a character set containing the characters in Unicode General Category M*.
public static var nonBaseCharacters : CharacterSet {
return CharacterSet(_builtIn: .nonBase)
}
/// Returns a character set containing the characters in Unicode General Categories L*, M*, and N*.
public static var alphanumerics : CharacterSet {
return CharacterSet(_builtIn: .alphaNumeric)
}
/// Returns a character set containing individual Unicode characters that can also be represented as composed character sequences (such as for letters with accents), by the definition of "standard decomposition" in version 3.2 of the Unicode character encoding standard.
public static var decomposables : CharacterSet {
return CharacterSet(_builtIn: .decomposable)
}
/// Returns a character set containing values in the category of Non-Characters or that have not yet been defined in version 3.2 of the Unicode standard.
public static var illegalCharacters : CharacterSet {
return CharacterSet(_builtIn: .illegal)
}
@available(*, unavailable, renamed: "punctuationCharacters")
public static var punctuation : CharacterSet {
return CharacterSet(_builtIn: .punctuation)
}
/// Returns a character set containing the characters in Unicode General Category P*.
public static var punctuationCharacters : CharacterSet {
return CharacterSet(_builtIn: .punctuation)
}
/// Returns a character set containing the characters in Unicode General Category Lt.
public static var capitalizedLetters : CharacterSet {
return CharacterSet(_builtIn: .capitalizedLetter)
}
/// Returns a character set containing the characters in Unicode General Category S*.
public static var symbols : CharacterSet {
return CharacterSet(_builtIn: .symbol)
}
/// Returns a character set containing the newline characters (`U+000A ~ U+000D`, `U+0085`, `U+2028`, and `U+2029`).
public static var newlines : CharacterSet {
return CharacterSet(_builtIn: .newline)
}
// MARK: Static functions, from NSURL
/// Returns the character set for characters allowed in a user URL subcomponent.
public static var urlUserAllowed : CharacterSet {
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLUserAllowedCharacterSet() as NSCharacterSet)
} else {
return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLUserAllowedCharacterSet() as! NSCharacterSet)
}
}
/// Returns the character set for characters allowed in a password URL subcomponent.
public static var urlPasswordAllowed : CharacterSet {
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLPasswordAllowedCharacterSet() as NSCharacterSet)
} else {
return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLPasswordAllowedCharacterSet() as! NSCharacterSet)
}
}
/// Returns the character set for characters allowed in a host URL subcomponent.
public static var urlHostAllowed : CharacterSet {
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLHostAllowedCharacterSet() as NSCharacterSet)
} else {
return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLHostAllowedCharacterSet() as! NSCharacterSet)
}
}
/// Returns the character set for characters allowed in a path URL component.
public static var urlPathAllowed : CharacterSet {
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLPathAllowedCharacterSet() as NSCharacterSet)
} else {
return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLPathAllowedCharacterSet() as! NSCharacterSet)
}
}
/// Returns the character set for characters allowed in a query URL component.
public static var urlQueryAllowed : CharacterSet {
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLQueryAllowedCharacterSet() as NSCharacterSet)
} else {
return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLQueryAllowedCharacterSet() as! NSCharacterSet)
}
}
/// Returns the character set for characters allowed in a fragment URL component.
public static var urlFragmentAllowed : CharacterSet {
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLFragmentAllowedCharacterSet() as NSCharacterSet)
} else {
return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLFragmentAllowedCharacterSet() as! NSCharacterSet)
}
}
// MARK: Immutable functions
/// Returns a representation of the `CharacterSet` in binary format.
@nonobjc
public var bitmapRepresentation: Data {
return _storage.bitmapRepresentation
}
/// Returns an inverted copy of the receiver.
@nonobjc
public var inverted : CharacterSet {
return _storage.inverted
}
/// Returns true if the `CharacterSet` has a member in the specified plane.
///
/// This method makes it easier to find the plane containing the members of the current character set. The Basic Multilingual Plane (BMP) is plane 0.
public func hasMember(inPlane plane: UInt8) -> Bool {
return _storage.hasMember(inPlane: plane)
}
// MARK: Mutable functions
/// Insert a range of integer values in the `CharacterSet`.
///
/// It is the caller's responsibility to ensure that the values represent valid `Unicode.Scalar` values, if that is what is desired.
public mutating func insert(charactersIn range: Range<Unicode.Scalar>) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.insert(charactersIn: range)
}
/// Insert a closed range of integer values in the `CharacterSet`.
///
/// It is the caller's responsibility to ensure that the values represent valid `Unicode.Scalar` values, if that is what is desired.
public mutating func insert(charactersIn range: ClosedRange<Unicode.Scalar>) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.insert(charactersIn: range)
}
/// Remove a range of integer values from the `CharacterSet`.
public mutating func remove(charactersIn range: Range<Unicode.Scalar>) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.remove(charactersIn: range)
}
/// Remove a closed range of integer values from the `CharacterSet`.
public mutating func remove(charactersIn range: ClosedRange<Unicode.Scalar>) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.remove(charactersIn: range)
}
/// Insert the values from the specified string into the `CharacterSet`.
public mutating func insert(charactersIn string: String) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.insert(charactersIn: string)
}
/// Remove the values from the specified string from the `CharacterSet`.
public mutating func remove(charactersIn string: String) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.remove(charactersIn: string)
}
/// Invert the contents of the `CharacterSet`.
public mutating func invert() {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.invert()
}
// -----
// MARK: -
// MARK: SetAlgebraType
/// Insert a `Unicode.Scalar` representation of a character into the `CharacterSet`.
///
/// `Unicode.Scalar` values are available on `Swift.String.UnicodeScalarView`.
@discardableResult
public mutating func insert(_ character: Unicode.Scalar) -> (inserted: Bool, memberAfterInsert: Unicode.Scalar) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
return _storage.insert(character)
}
/// Insert a `Unicode.Scalar` representation of a character into the `CharacterSet`.
///
/// `Unicode.Scalar` values are available on `Swift.String.UnicodeScalarView`.
@discardableResult
public mutating func update(with character: Unicode.Scalar) -> Unicode.Scalar? {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
return _storage.update(with: character)
}
/// Remove a `Unicode.Scalar` representation of a character from the `CharacterSet`.
///
/// `Unicode.Scalar` values are available on `Swift.String.UnicodeScalarView`.
@discardableResult
public mutating func remove(_ character: Unicode.Scalar) -> Unicode.Scalar? {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
return _storage.remove(character)
}
/// Test for membership of a particular `Unicode.Scalar` in the `CharacterSet`.
public func contains(_ member: Unicode.Scalar) -> Bool {
return _storage.contains(member)
}
/// Returns a union of the `CharacterSet` with another `CharacterSet`.
public func union(_ other: CharacterSet) -> CharacterSet {
return _storage.union(other._storage)
}
/// Sets the value to a union of the `CharacterSet` with another `CharacterSet`.
public mutating func formUnion(_ other: CharacterSet) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.formUnion(other._storage)
}
/// Returns an intersection of the `CharacterSet` with another `CharacterSet`.
public func intersection(_ other: CharacterSet) -> CharacterSet {
return _storage.intersection(other._storage)
}
/// Sets the value to an intersection of the `CharacterSet` with another `CharacterSet`.
public mutating func formIntersection(_ other: CharacterSet) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.formIntersection(other._storage)
}
/// Returns a `CharacterSet` created by removing elements in `other` from `self`.
public func subtracting(_ other: CharacterSet) -> CharacterSet {
return _storage.subtracting(other._storage)
}
/// Sets the value to a `CharacterSet` created by removing elements in `other` from `self`.
public mutating func subtract(_ other: CharacterSet) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.subtract(other._storage)
}
/// Returns an exclusive or of the `CharacterSet` with another `CharacterSet`.
public func symmetricDifference(_ other: CharacterSet) -> CharacterSet {
return _storage.symmetricDifference(other._storage)
}
/// Sets the value to an exclusive or of the `CharacterSet` with another `CharacterSet`.
public mutating func formSymmetricDifference(_ other: CharacterSet) {
self = symmetricDifference(other)
}
/// Returns true if `self` is a superset of `other`.
public func isSuperset(of other: CharacterSet) -> Bool {
return _storage.isSuperset(of: other._storage)
}
// MARK: -
public var hashValue: Int {
return _storage.hashValue
}
/// Returns true if the two `CharacterSet`s are equal.
public static func ==(lhs : CharacterSet, rhs: CharacterSet) -> Bool {
return lhs._storage == rhs._storage
}
}
// MARK: Objective-C Bridging
extension CharacterSet : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSCharacterSet.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSCharacterSet {
return _storage.bridgedReference()
}
public static func _forceBridgeFromObjectiveC(_ input: NSCharacterSet, result: inout CharacterSet?) {
result = CharacterSet(_bridged: input)
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSCharacterSet, result: inout CharacterSet?) -> Bool {
result = CharacterSet(_bridged: input)
return true
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSCharacterSet?) -> CharacterSet {
guard let src = source else { return CharacterSet() }
return CharacterSet(_bridged: src)
}
}
extension CharacterSet : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return _storage.description
}
public var debugDescription: String {
return _storage.debugDescription
}
}
extension NSCharacterSet : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as CharacterSet)
}
}
extension CharacterSet : Codable {
private enum CodingKeys : Int, CodingKey {
case bitmap
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let bitmap = try container.decode(Data.self, forKey: .bitmap)
self.init(bitmapRepresentation: bitmap)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.bitmapRepresentation, forKey: .bitmap)
}
}
| apache-2.0 | b74c6e1a2aa6449fa430654c91d3b77c | 38.205066 | 274 | 0.658257 | 5.156433 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureInterest/Sources/FeatureInterestUI/InterestAccountList/Reducer/InterestAccountListReducer.swift | 1 | 12931 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import Combine
import ComposableArchitecture
import FeatureInterestDomain
import PlatformKit
import ToolKit
struct TransactionFetchIdentifier: Hashable {}
typealias InterestAccountListReducer = Reducer<
InterestAccountListState,
InterestAccountListAction,
InterestAccountSelectionEnvironment
>
let interestAccountListReducer = Reducer.combine(
interestNoEligibleWalletsReducer
.optional()
.pullback(
state: \.interestNoEligibleWalletsState,
action: /InterestAccountListAction.interestAccountNoEligibleWallets,
environment: { _ in .init() }
),
interestAccountDetailsReducer
.optional()
.pullback(
state: \.interestAccountDetailsState,
action: /InterestAccountListAction.interestAccountDetails,
environment: {
InterestAccountDetailsEnvironment(
fiatCurrencyService: $0.fiatCurrencyService,
blockchainAccountRepository: $0.blockchainAccountRepository,
priceService: $0.priceService,
mainQueue: $0.mainQueue
)
}
),
Reducer<
InterestAccountListState,
InterestAccountListAction,
InterestAccountSelectionEnvironment
> { state, action, environment in
switch action {
case .didReceiveInterestAccountResponse(let response):
switch response {
case .success(let accountOverviews):
let details: [InterestAccountDetails] = accountOverviews.map {
.init(
ineligibilityReason: $0.ineligibilityReason,
currency: $0.currency,
balance: $0.balance,
interestEarned: $0.totalEarned,
rate: $0.interestAccountRate.rate
)
}
.sorted { $0.balance.isPositive && !$1.balance.isPositive }
state.interestAccountOverviews = accountOverviews
state.interestAccountDetails = .init(uniqueElements: details)
state.loadingStatus = .loaded
case .failure(let error):
state.loadingStatus = .loaded
Logger.shared.error(error)
}
return .none
case .setupInterestAccountListScreen:
if state.loadingStatus == .loaded {
return .none
}
state.loadingStatus = .fetchingAccountStatus
return environment
.kycVerificationService
.isKYCVerified
.receive(on: environment.mainQueue)
.eraseToEffect()
.map { result in
.didReceiveKYCVerificationResponse(result)
}
case .didReceiveKYCVerificationResponse(let value):
state.isKYCVerified = value
return Effect(value: .loadInterestAccounts)
case .loadInterestAccounts:
state.loadingStatus = .fetchingRewardsAccounts
return environment
.fiatCurrencyService
.displayCurrencyPublisher
.flatMap { [environment] fiatCurrency in
environment
.accountOverviewRepository
.fetchInterestAccountOverviewListForFiatCurrency(fiatCurrency)
}
.receive(on: environment.mainQueue)
.catchToEffect()
.map { result in
.didReceiveInterestAccountResponse(result)
}
case .interestAccountButtonTapped(let selected, let action):
switch action {
case .viewInterestButtonTapped:
guard let overview = state
.interestAccountOverviews
.first(where: { $0.id == selected.identity })
else {
fatalError("Expected an InterestAccountOverview")
}
state.interestAccountDetailsState = .init(interestAccountOverview: overview)
return .enter(into: .details, context: .none)
case .earnInterestButtonTapped(let value):
let blockchainAccountRepository = environment.blockchainAccountRepository
let currency = value.currency
return blockchainAccountRepository
.accountWithCurrencyType(
currency,
accountType: .custodial(.savings)
)
.compactMap { $0 as? CryptoInterestAccount }
.flatMap { account -> AnyPublisher<(Bool, InterestTransactionState), Never> in
let availableAccounts = blockchainAccountRepository
.accountsAvailableToPerformAction(
.interestTransfer,
target: account
)
.map { $0.filter { $0.currencyType == account.currencyType } }
.map { !$0.isEmpty }
.replaceError(with: false)
.eraseToAnyPublisher()
let interestTransactionState = InterestTransactionState(
account: account,
action: .interestTransfer
)
return Publishers.Zip(
availableAccounts,
Just(interestTransactionState)
)
.eraseToAnyPublisher()
}
.receive(on: environment.mainQueue)
.catchToEffect()
.map { values -> InterestAccountListAction in
guard let (areAccountsAvailable, transactionState) = values.success else {
impossible()
}
if areAccountsAvailable {
return .interestTransactionStateFetched(transactionState)
}
let ineligibleWalletsState = InterestNoEligibleWalletsState(
interestAccountRate: InterestAccountRate(
currencyCode: currency.code,
rate: value.rate
)
)
return .interestAccountIsWithoutEligibleWallets(ineligibleWalletsState)
}
}
case .interestAccountIsWithoutEligibleWallets(let ineligibleWalletsState):
state.interestNoEligibleWalletsState = ineligibleWalletsState
return .enter(into: .noWalletsError)
case .interestAccountNoEligibleWallets(let action):
switch action {
case .startBuyTapped:
return .none
case .dismissNoEligibleWalletsScreen:
return .dismiss()
case .startBuyAfterDismissal(let cryptoCurrency):
state.loadingStatus = .fetchingRewardsAccounts
return Effect(value: .dismissAndLaunchBuy(cryptoCurrency))
case .startBuyOnDismissalIfNeeded:
return .none
}
case .dismissAndLaunchBuy(let cryptoCurrency):
state.buyCryptoCurrency = cryptoCurrency
return .none
case .interestTransactionStateFetched(let transactionState):
state.interestTransactionState = transactionState
let isTransfer = transactionState.action == .interestTransfer
return Effect(
value:
isTransfer ? .startInterestTransfer(transactionState) : .startInterestWithdraw(transactionState)
)
case .startInterestWithdraw(let value):
return environment
.transactionRouterAPI
.presentTransactionFlow(to: .interestWithdraw(value.account))
.catchToEffect()
.map { _ -> InterestAccountListAction in
.loadInterestAccounts
}
case .startInterestTransfer(let value):
return environment
.transactionRouterAPI
.presentTransactionFlow(to: .interestTransfer(value.account))
.catchToEffect()
.map { _ -> InterestAccountListAction in
.loadInterestAccounts
}
case .route(let route):
state.route = route
return .none
case .interestAccountDetails:
return .none
}
},
interestReducerCore
)
.analytics()
let interestReducerCore = Reducer<
InterestAccountListState,
InterestAccountListAction,
InterestAccountSelectionEnvironment
> { _, action, environment in
switch action {
case .interestAccountDetails(.dismissInterestDetailsScreen):
return .dismiss()
case .interestAccountDetails(.loadCryptoInterestAccount(isTransfer: let isTransfer, let currency)):
return environment
.blockchainAccountRepository
.accountWithCurrencyType(
currency,
accountType: .custodial(.savings)
)
.compactMap { $0 as? CryptoInterestAccount }
.map { account in
InterestTransactionState(
account: account,
action: isTransfer ? .interestTransfer : .interestWithdraw
)
}
.catchToEffect()
.map { transactionState in
guard let value = transactionState.success else {
unimplemented()
}
return value
}
.map { transactionState -> InterestAccountListAction in
.interestTransactionStateFetched(transactionState)
}
default:
return .none
}
}
// MARK: - Analytics Extension
extension Reducer where
State == InterestAccountListState,
Action == InterestAccountListAction,
Environment == InterestAccountSelectionEnvironment
{
/// Helper reducer for analytics tracking
fileprivate func analytics() -> Self {
combined(
with: Reducer<
InterestAccountListState,
InterestAccountListAction,
InterestAccountSelectionEnvironment
> { state, action, environment in
switch action {
case .didReceiveInterestAccountResponse(.success):
return .fireAndForget {
environment.analyticsRecorder.record(
event: .interestViewed
)
}
case .interestAccountButtonTapped(_, .viewInterestButtonTapped(let details)):
return .fireAndForget {
environment.analyticsRecorder.record(
event: .walletRewardsDetailClicked(currency: details.currency.code)
)
}
case .interestAccountDetails(.interestAccountActionsFetched):
return .fireAndForget { [state] in
let currencyCode = state.interestAccountDetailsState?.interestAccountOverview.currency.code
environment.analyticsRecorder.record(
event: .walletRewardsDetailViewed(currency: currencyCode ?? "")
)
}
case .interestAccountButtonTapped(_, .earnInterestButtonTapped(let details)):
return .fireAndForget {
environment.analyticsRecorder.record(
event: .interestDepositClicked(currency: details.currency.code)
)
}
case .interestAccountDetails(.interestWithdrawTapped(let currency)):
return .fireAndForget {
environment.analyticsRecorder.record(
event: .interestWithdrawalClicked(currency: currency.code)
)
}
case .interestAccountDetails(.interestTransferTapped(let currency)):
return .fireAndForget {
environment.analyticsRecorder.record(
event: .walletRewardsDetailDepositClicked(currency: currency.code)
)
}
default:
return .none
}
}
)
}
}
| lgpl-3.0 | ac2135232597dfac2bbafa77ff96a31f | 40.442308 | 115 | 0.543387 | 6.550152 | false | false | false | false |
matthewcheok/Kaleidoscope | Kaleidoscope/Regex.swift | 1 | 833 | //
// Regex.swift
// Kaleidoscope
//
// Created by Matthew Cheok on 15/11/15.
// Copyright © 2015 Matthew Cheok. All rights reserved.
//
import Foundation
var expressions = [String: NSRegularExpression]()
public extension String {
public func match(regex: String) -> String? {
let expression: NSRegularExpression
if let exists = expressions[regex] {
expression = exists
} else {
expression = try! NSRegularExpression(pattern: "^\(regex)", options: [])
expressions[regex] = expression
}
let range = expression.rangeOfFirstMatchInString(self, options: [], range: NSMakeRange(0, self.utf16.count))
if range.location != NSNotFound {
return (self as NSString).substringWithRange(range)
}
return nil
}
} | mit | b4063daece91c35ef0b9114fcfadc90b | 28.75 | 116 | 0.623798 | 4.571429 | false | false | false | false |
seanwoodward/IBAnimatable | IBAnimatable/ActivityIndicatorAnimationBallSpinFadeLoader.swift | 1 | 2823 | //
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallSpinFadeLoader: ActivityIndicatorAnimating {
// MARK: Properties
private let duration: CFTimeInterval = 1
// MARK: ActivityIndicatorAnimating
public func configAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSpacing: CGFloat = -2
let circleSize = (size.width - 4 * circleSpacing) / 5
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let beginTime = CACurrentMediaTime()
let beginTimes: [CFTimeInterval] = [0, 0.12, 0.24, 0.36, 0.48, 0.6, 0.72, 0.84]
let animation = self.animation
// Draw circles
for i in 0 ..< 8 {
let circle = circleAt(angle: CGFloat(M_PI_4 * Double(i)),
size: circleSize,
origin: CGPoint(x: x, y: y),
containerSize: size,
color: color)
animation.beginTime = beginTime + beginTimes[i]
circle.addAnimation(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
func circleAt(angle angle: CGFloat, size: CGFloat, origin: CGPoint, containerSize: CGSize, color: UIColor) -> CALayer {
let radius = containerSize.width / 2 - size / 2
let circle = ActivityIndicatorShape.Circle.createLayerWith(size: CGSize(width: size, height: size), color: color)
let frame = CGRect(
x: origin.x + radius * (cos(angle) + 1),
y: origin.y + radius * (sin(angle) + 1),
width: size,
height: size)
circle.frame = frame
return circle
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationBallSpinFadeLoader {
var animation: CAAnimationGroup {
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, opacityAnimation]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = duration
animation.repeatCount = .infinity
animation.removedOnCompletion = false
return animation
}
var scaleAnimation: CAKeyframeAnimation {
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.values = [1, 0.4, 1]
scaleAnimation.duration = duration
return scaleAnimation
}
var opacityAnimation: CAKeyframeAnimation {
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.keyTimes = [0, 0.5, 1]
opacityAnimation.values = [1, 0.3, 1]
opacityAnimation.duration = duration
return opacityAnimation
}
}
| mit | d603c5611e34621a4144de51d5ebff09 | 32.211765 | 123 | 0.643642 | 4.643092 | false | false | false | false |
iCodeForever/ifanr | ifanr/ifanr/Controllers/DetailController/IFSafariController.swift | 1 | 6250 | //
// NewsFlashDetailController.swift
// ifanr
//
// Created by sys on 16/7/17.
// Copyright © 2016年 ifanrOrg. All rights reserved.
//
import UIKit
import WebKit
class IFSafariController: UIViewController {
//MARK:-----Variables-----
var shadowView: UIView?
var shareView: ShareView?
var urlStr: String?
fileprivate var model: CommonModel?
convenience init(model: CommonModel){
self.init()
self.model = model
}
//MARK:-----Life Cycle-----
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.wkWebView)
self.view.addSubview(self.bottomBar)
self.setupLayout()
self.bottomBarSetUpLayout()
self.loadData()
}
//MARK:-----Custom Function------
// get data
func loadData() {
var links: [String] = (model!.content.getSuitableString("http(.*?)html"))
if links.count == 0 {
links = (model!.content.getSuitableString("http(.*?)htm"))
}
if links.count != 0 {
urlStr = links[0]
self.wkWebView.load(URLRequest(url: URL(string: urlStr!)!))
}
}
//MARK:-----Private Function-----
func bottomBarSetUpLayout() {
self.backButton.snp.makeConstraints { (make) in
make.left.equalTo(self.bottomBar).offset(30)
make.top.equalTo(self.bottomBar).offset(20)
make.width.height.equalTo(15)
}
self.shareButton.snp.makeConstraints { (make) in
make.right.equalTo(self.view).offset(-30)
make.top.equalTo(self.bottomBar).offset(15)
make.width.height.equalTo(20)
}
self.safariButton.snp.makeConstraints { (make) in
make.right.equalTo(self.shareButton.snp.left).offset(-35)
make.top.equalTo(self.bottomBar).offset(15)
make.width.height.equalTo(20)
}
self.reloadButton.snp.makeConstraints { (make) in
make.right.equalTo(self.safariButton.snp.left).offset(-35)
make.top.equalTo(self.bottomBar).offset(15)
make.width.height.equalTo(18)
}
}
func setupLayout() {
self.bottomBar.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(self.view)
make.height.equalTo(45)
}
}
func backButtonDidClick() {
self.dismiss(animated: true, completion: nil)
}
func shareButtonDidClick() {
showShareView()
}
func safariButtonDidClick() {
UIApplication.shared.openURL(URL(string: self.urlStr!)!)
}
func reloadButtonDidClick() {
self.wkWebView.loadHTMLString("", baseURL: nil)
self.wkWebView.load(URLRequest(url: URL(string: urlStr!)!))
}
override var prefersStatusBarHidden : Bool {
return true
}
//MARK:-----Getter and Setter-----
fileprivate lazy var wkWebView: WKWebView = {
let wkWebView: WKWebView = WKWebView(frame: self.view.frame)
wkWebView.navigationDelegate = self
return wkWebView
}()
/// 底部的工具栏
fileprivate lazy var bottomBar: UIView = {
let bottomBar: UIView = UIView()
bottomBar.backgroundColor = UIColor.black
bottomBar.addSubview(self.backButton)
bottomBar.addSubview(self.reloadButton)
bottomBar.addSubview(self.shareButton)
bottomBar.addSubview(self.safariButton)
return bottomBar
}()
/// 返回按钮
fileprivate lazy var backButton: UIButton = {
let backButton: UIButton = UIButton()
backButton.setImage(UIImage(named: "ic_close"), for: UIControlState())
backButton.imageView?.contentMode = .scaleAspectFit
backButton.addTarget(self, action: #selector(backButtonDidClick), for: .touchUpInside)
return backButton
}()
/// 重新加载按钮
fileprivate lazy var reloadButton: UIButton = {
let reloadButton: UIButton = UIButton()
reloadButton.setImage(UIImage(named: "ic_refresh"), for: UIControlState())
reloadButton.contentMode = .scaleAspectFit
reloadButton.addTarget(self, action: #selector(reloadButtonDidClick), for: .touchUpInside)
return reloadButton
}()
/// 跳转到Safari
fileprivate lazy var safariButton: UIButton = {
let safariButton: UIButton = UIButton()
safariButton.setImage(UIImage(named: "ic_system_browser"), for: UIControlState())
safariButton.imageView?.contentMode = .scaleAspectFit
safariButton.addTarget(self, action: #selector(safariButtonDidClick), for: .touchUpInside)
return safariButton
}()
/// 分享按钮
fileprivate lazy var shareButton: UIButton = {
let shareButton: UIButton = UIButton()
shareButton.setImage(UIImage(named: "ic_comment_bar_share"), for: UIControlState())
shareButton.imageView?.contentMode = .scaleAspectFit
shareButton.addTarget(self, action: #selector(shareButtonDidClick), for: .touchUpInside)
return shareButton
}()
}
//MARK:-----ShareViewDelegate-----
extension IFSafariController: ShareViewDelegate, shareResuable {
func weixinShareButtonDidClick() {
shareToFriend((model?.excerpt)!,
shareImageUrl: (model?.image)!,
shareUrl: urlStr!,
shareTitle: (model?.title)!)
}
func friendsCircleShareButtonDidClick() {
shareToFriendsCircle((model?.excerpt)!,
shareTitle: (model?.title)!,
shareUrl: urlStr!,
shareImageUrl: (model?.image)!)
}
func shareMoreButtonDidClick() {
hiddenShareView()
}
}
//MARK:-----UIWebView Delegate-----
extension IFSafariController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
self.showProgress()
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.hiddenProgress()
}
}
| mit | d822a0a746171bd3c40f771641579730 | 30.637755 | 98 | 0.606999 | 4.829439 | false | false | false | false |
gzios/SystemLearn | SwiftBase/wb/wb/Classes/Home/HomeViewController.swift | 1 | 3114 | //
// HomeViewController.swift
// wb
//
// Created by 郭振涛 on 2017/12/14.
// Copyright © 2017年 郭振涛. All rights reserved.
//
import UIKit
class HomeViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 6567dda96874b9d2b30e9624f87fb6f2 | 31.621053 | 136 | 0.668603 | 5.26146 | false | false | false | false |
AliSoftware/Dip | SampleApp/DipSampleApp/AppDelegate.swift | 3 | 1681 | //
// AppDelegate.swift
// Dip
//
// Created by Olivier Halligon on 04/10/2015.
// Copyright © 2015 AliSoftware. All rights reserved.
//
import UIKit
import Dip
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private let container = DependencyContainer()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
// Override point for customization after application launch.
//This is a composition root where container is configured and all dependencies are resolved
configure(container: container)
let personProvider = try! container.resolve() as PersonProviderAPI
let starshipProvider = try! container.resolve() as StarshipProviderAPI
if let tabBarVC = self.window?.rootViewController as? UITabBarController,
let vcs = tabBarVC.viewControllers as? [UINavigationController] {
if let personListVC = vcs[0].topViewController as? PersonListViewController {
personListVC.personProvider = personProvider
personListVC.starshipProvider = starshipProvider
personListVC.loadFirstPage()
}
if let starshipListVC = vcs[1].topViewController as? StarshipListViewController {
starshipListVC.starshipProvider = starshipProvider
starshipListVC.personProvider = personProvider
starshipListVC.loadFirstPage()
}
}
return true
}
}
| mit | a66020f7793cf5e9f45ac2f9148a5d62 | 37.181818 | 151 | 0.656548 | 5.694915 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.