repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lee0741/Glider
|
refs/heads/master
|
Glider/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// Glider
//
// Created by Yancen Li on 2/24/17.
// Copyright © 2017 Yancen Li. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = MainController()
UINavigationBar.appearance().barTintColor = .mainColor
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
UITabBar.appearance().tintColor = .mainColor
let categoryItem = UIApplicationShortcutItem(type: "org.yancen.Glider.category", localizedTitle: "Categories", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: "ic_option"), userInfo: nil)
let searchItem = UIApplicationShortcutItem(type: "org.yancen.Glider.search", localizedTitle: "Search", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(type: .search), userInfo: nil)
UIApplication.shared.shortcutItems = [categoryItem, searchItem]
if let item = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem {
switch item.type {
case "org.yancen.Glider.category":
launchListController()
case "org.yancen.Glider.search":
launchSearchController()
default:
break
}
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {}
func applicationDidEnterBackground(_ application: UIApplication) {}
func applicationWillEnterForeground(_ application: UIApplication) {}
func applicationDidBecomeActive(_ application: UIApplication) {}
func applicationWillTerminate(_ application: UIApplication) {}
// MARK: - Spotlight Search
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
(window?.rootViewController as! MainController).selectedIndex = 0
let viewController = (window?.rootViewController as! MainController).childViewControllers[0].childViewControllers[0] as! HomeController
viewController.restoreUserActivityState(userActivity)
return true
}
// MARK: - URL Scheme
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
guard let query = url.host else { return true }
let commentController = CommentController()
commentController.itemId = Int(query)
(window?.rootViewController as! MainController).selectedIndex = 0
(window?.rootViewController as! MainController).childViewControllers[0].childViewControllers[0].navigationController?.pushViewController(commentController, animated: true)
return true
}
// MARK: - 3D Touch
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
switch shortcutItem.type {
case "org.yancen.Glider.category":
launchListController()
case "org.yancen.Glider.search":
launchSearchController()
default:
return
}
}
func launchListController() {
(window?.rootViewController as! MainController).selectedIndex = 1
}
func launchSearchController() {
(window?.rootViewController as! MainController).selectedIndex = 2
}
}
|
9538829c4d986cae9f34bb3cc8e2a5c7
| 38.777778 | 222 | 0.678517 | false | false | false | false |
joerocca/GitHawk
|
refs/heads/master
|
Classes/Issues/Managing/IssueManagingModel.swift
|
mit
|
1
|
//
// IssueManagingModel.swift
// Freetime
//
// Created by Ryan Nystrom on 12/2/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
import IGListKit
final class IssueManagingModel: ListDiffable {
let objectId: String
let pullRequest: Bool
init(objectId: String, pullRequest: Bool) {
self.objectId = objectId
self.pullRequest = pullRequest
}
// MARK: ListDiffable
func diffIdentifier() -> NSObjectProtocol {
// should only ever be one
return "managing_model" as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
if self === object { return true }
guard let object = object as? IssueManagingModel else { return false }
return pullRequest == object.pullRequest
&& objectId == object.objectId
}
}
|
7b6768d9eed60613a75c2e4225ae64e6
| 23.055556 | 78 | 0.660508 | false | false | false | false |
nerdycat/Cupcake
|
refs/heads/master
|
Cupcake/Color.swift
|
mit
|
1
|
//
// Color.swift
// Cupcake
//
// Created by nerdycat on 2017/3/17.
// Copyright © 2017 nerdycat. All rights reserved.
//
import UIKit
/**
* Create UIColor Object.
* Color argument can be:
1) UIColor object
2) UIImage object, return a pattern image color
3) "red", "green", "blue", "clear", etc. (any system color)
5) "random": randomColor
6) "255,0,0": RGB color
7) "#FF0000" or "0xF00": Hex color
* All the string representation can have an optional alpha value.
* Usages:
Color([UIColor redColor])
Color("red")
Color("red,0.1") //with alpha
Color("255,0,0)
Color("255,0,0,1") //with alpha
Color("#FF0000")
Color("#F00,0.1") //with alpha
Color("random,0.5")
Color(Img("image")) //using image
...
*/
public func Color(_ any: Any?) -> UIColor? {
if any == nil {
return nil
}
if let color = any as? UIColor {
return color;
}
if let image = any as? UIImage {
return UIColor(patternImage: image)
}
guard any is String else {
return nil
}
var alpha: CGFloat = 1
var components = (any as! String).components(separatedBy: ",")
if components.count == 2 || components.count == 4 {
alpha = min(CGFloat(Float(components.last!) ?? 1), 1)
components.removeLast()
}
var r: Int?, g: Int? , b: Int?
if components.count == 1 {
let string = components.first!
let sel = NSSelectorFromString(string + "Color")
//system color
if let color = UIColor.cpk_safePerform(selector: sel) as? UIColor {
return (alpha == 1 ? color : color.withAlphaComponent(alpha))
}
if string == "random" {
// generate cryptographically secure random bytes
// avoid warnings reported by security scans like Veracode
// https://developer.apple.com/documentation/security/1399291-secrandomcopybytes
var bytes = [UInt8](repeating: 0, count: 3)
let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
if status == errSecSuccess {
r = Int(bytes[0])
g = Int(bytes[1])
b = Int(bytes[2])
} else {
r = 0
g = 0
b = 0
}
} else if string.hasPrefix("#") {
if string.cpk_length() == 4 {
r = Int(string.subAt(1), radix:16)! * 17
g = Int(string.subAt(2), radix:16)! * 17
b = Int(string.subAt(3), radix:16)! * 17
} else if string.cpk_length() == 7 {
r = Int(string.subAt(1...2), radix:16)
g = Int(string.subAt(3...4), radix:16)
b = Int(string.subAt(5...6), radix:16)
}
}
} else if components.count == 3 {
r = Int(components[0])
g = Int(components[1])
b = Int(components[2])
}
if r != nil && g != nil && b != nil {
return UIColor(red: CGFloat(r!) / 255.0,
green: CGFloat(g!) / 255.0,
blue: CGFloat(b!) / 255.0,
alpha: alpha)
}
return nil
}
|
4c7c36d20c7f37d2e2189b4dc143f115
| 27.529915 | 92 | 0.501198 | false | false | false | false |
admkopec/BetaOS
|
refs/heads/x86_64
|
Kernel/Kernel/System.swift
|
apache-2.0
|
1
|
//
// System.swift
// Kernel
//
// Created by Adam Kopeć on 11/13/17.
// Copyright © 2017-2018 Adam Kopeć. All rights reserved.
//
import Loggable
final class System: Loggable {
static let sharedInstance = System()
let Name: String = "System"
let modulesController = ModulesController()
fileprivate(set) var interruptManager: InterruptManager!
fileprivate(set) var Timer: PIT8254?
fileprivate(set) var DeviceVendor = "Generic"
fileprivate(set) var DeviceName = "Generic Device"
fileprivate(set) var DeviceID = "Generic1,1"
fileprivate(set) var SerialNumber = "000000000000"
internal var Video: VideoModule = VESA()
internal var Drives = [PartitionTable]()
internal var ACPI: ACPI? {
return modulesController.modules.filter { $0 is ACPI }.first as? ACPI
}
internal var SMBIOS: SMBIOS? {
return modulesController.modules.filter { $0 is SMBIOS }.first as? SMBIOS
}
func initialize() {
modulesController.initialize()
interruptManager = InterruptManager(acpiTables: ACPI)
DeviceVendor = SMBIOS?.SystemVendor ?? DeviceVendor
DeviceName = SMBIOS?.ProductDisplayName ?? DeviceName
DeviceID = SMBIOS?.ProductName ?? DeviceID
SerialNumber = SMBIOS?.ProductSerial ?? SerialNumber
interruptManager.enableIRQs()
Timer = PIT8254()
if DeviceID == "VMware7,1" {
modulesController.modules.append(VMwareTools())
}
modulesController.companionController = PCIModulesController()
}
internal func shutdown() {
modulesController.stop()
shutdown_system()
}
}
public func NullHandler(irq: Int) {
}
|
785def9e99fc057df364781d238b0594
| 29.859649 | 81 | 0.646958 | false | false | false | false |
TransitionKit/Union
|
refs/heads/master
|
Union/Navigator.swift
|
mit
|
1
|
//
// Navigator.swift
// Union
//
// Created by Hirohisa Kawasaki on 10/7/15.
// Copyright © 2015 Hirohisa Kawasaki. All rights reserved.
//
import UIKit
public class Navigator: NSObject {
let before = AnimationManager()
let present = AnimationManager()
var duration: NSTimeInterval {
return before.duration + present.duration
}
func animate(transitionContext: UIViewControllerContextTransitioning) {
setup(transitionContext)
start(transitionContext)
}
public class func animate() -> UIViewControllerAnimatedTransitioning {
return Navigator()
}
}
extension Navigator: UIViewControllerAnimatedTransitioning {
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
animate(transitionContext)
}
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
}
extension Navigator {
func setup(transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
if let fromViewController = fromViewController, let toViewController = toViewController {
_setup(fromViewController: fromViewController, toViewController: toViewController)
}
}
func start(transitionContext: UIViewControllerContextTransitioning) {
before.completion = { [unowned self] in
self.startTransition(transitionContext)
}
before.start()
}
func startTransition(transitionContext: UIViewControllerContextTransitioning) {
if let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey), let toView = transitionContext.viewForKey(UITransitionContextToViewKey) {
toView.frame = fromView.frame
transitionContext.containerView()?.insertSubview(toView, aboveSubview: fromView)
}
present.completion = {
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
fromView?.removeFromSuperview()
transitionContext.completeTransition(true)
}
present.start()
}
private func _setup(fromViewController fromViewController: UIViewController, toViewController: UIViewController) {
if let delegate = fromViewController as? Delegate {
before.animations = delegate.animationsBeforeTransition(from: fromViewController, to: toViewController)
}
// present
let fromAnimations: [Animation] = (fromViewController as? Delegate)?.animationsDuringTransition(from: fromViewController, to: toViewController) ?? []
let toAnimations: [Animation] = (toViewController as? Delegate)?.animationsDuringTransition(from: fromViewController, to: toViewController) ?? []
present.animations = fromAnimations + toAnimations
}
}
|
90464c9777051b0af22eb239374d0b20
| 34.287356 | 161 | 0.72825 | false | false | false | false |
idomizrachi/Regen
|
refs/heads/master
|
regen/main.swift
|
mit
|
1
|
//
// main.swift
// Regen
//
// Created by Ido Mizrachi on 7/7/16.
//
import Foundation
let operationTimer = OperationTimer()
operationTimer.start()
let arguments = Array(CommandLine.arguments.dropFirst())
let argumentsParser = ArgumentsParser(arguments: arguments)
switch argumentsParser.operationType {
case .version:
Version.display()
case .usage:
Usage.display()
case .localization(let parameters):
let operation = Localization.Operation(parameters: parameters)
operation.run()
print("Finished in: \(String(format: "%.5f", operationTimer.end())) seconds.")
case .images(let parameters):
let operation = Images.Operation(parameters: parameters)
operation.run()
print("Finished in: \(String(format: "%.5f", operationTimer.end())) seconds.")
}
|
98e1c95bf1926f2f7ffa7c0ce1a71f44
| 23.65625 | 82 | 0.716096 | false | false | false | false |
SwiftGen/SwiftGenKit
|
refs/heads/master
|
Tests/SwiftGenKitTests/ColorsJSONFileTests.swift
|
mit
|
1
|
//
// SwiftGenKit
// Copyright (c) 2017 Olivier Halligon
// MIT Licence
//
import XCTest
import PathKit
@testable import SwiftGenKit
class ColorsJSONFileTests: XCTestCase {
func testFileWithDefaults() throws {
let parser = ColorsParser()
parser.palettes = [try ColorsJSONFileParser().parseFile(at: Fixtures.path(for: "colors.json", sub: .colors))]
let result = parser.stencilContext()
XCTDiffContexts(result, expected: "defaults.plist", sub: .colors)
}
func testFileWithBadSyntax() {
do {
_ = try ColorsJSONFileParser().parseFile(at: Fixtures.path(for: "bad-syntax.json", sub: .colors))
XCTFail("Code did parse file successfully while it was expected to fail for bad syntax")
} catch ColorsParserError.invalidFile {
// That's the expected exception we want to happen
} catch let error {
XCTFail("Unexpected error occured while parsing: \(error)")
}
}
func testFileWithBadValue() {
do {
_ = try ColorsJSONFileParser().parseFile(at: Fixtures.path(for: "bad-value.json", sub: .colors))
XCTFail("Code did parse file successfully while it was expected to fail for bad value")
} catch ColorsParserError.invalidHexColor(path: _, string: "this isn't a color", key: "ArticleTitle"?) {
// That's the expected exception we want to happen
} catch let error {
XCTFail("Unexpected error occured while parsing: \(error)")
}
}
}
|
b845cde2cd6e3ad80b6880a85b3beecd
| 33.780488 | 113 | 0.692146 | false | true | false | false |
BennyKJohnson/OpenCloudKit
|
refs/heads/master
|
Sources/CKContainer.swift
|
mit
|
1
|
//
// CKContainer.swift
// OpenCloudKit
//
// Created by Benjamin Johnson on 6/07/2016.
//
//
import Foundation
public class CKContainer {
let convenienceOperationQueue = OperationQueue()
public let containerIdentifier: String
public init(containerIdentifier: String) {
self.containerIdentifier = containerIdentifier
}
public class func `default`() -> CKContainer {
// Get Default Container
return CKContainer(containerIdentifier: CloudKit.shared.containers.first!.containerIdentifier)
}
public lazy var publicCloudDatabase: CKDatabase = {
return CKDatabase(container: self, scope: .public)
}()
public lazy var privateCloudDatabase: CKDatabase = {
return CKDatabase(container: self, scope: .private)
}()
public lazy var sharedCloudDatabase: CKDatabase = {
return CKDatabase(container: self, scope: .shared)
}()
var isRegisteredForNotifications: Bool {
return false
}
func registerForNotifications() {}
func accountStatus(completionHandler: @escaping (CKAccountStatus, Error?) -> Void) {
guard let _ = CloudKit.shared.defaultAccount.iCloudAuthToken else {
completionHandler(.noAccount, nil)
return
}
// Verify the account is valid
completionHandler(.available, nil)
}
func schedule(convenienceOperation: CKOperation) {
convenienceOperation.queuePriority = .veryHigh
convenienceOperation.qualityOfService = .utility
add(convenienceOperation)
}
public func add(_ operation: CKOperation) {
if !(operation is CKDatabaseOperation) {
operation.container = self
convenienceOperationQueue.addOperation(operation)
} else {
fatalError("CKDatabaseOperations must be submitted to a CKDatabase")
}
}
}
|
e2c1fb01e08897a2e7c5f50d0b6c5510
| 25.890411 | 102 | 0.643403 | false | false | false | false |
dche/FlatCG
|
refs/heads/master
|
Sources/Pose.swift
|
mit
|
1
|
//
// FlatCG - Pose.swift
//
// Copyright (c) 2016 The FlatCG authors.
// Licensed under MIT License.
import simd
import GLMath
/// Types that describe poses of solid bodies in Euclidean space.
///
/// This type just records the amount of rotation from initial pose to the
/// final pose. How the rotation is performed is determined by the concrete
/// `RotationType`.
public protocol Pose: Equatable, CustomDebugStringConvertible {
associatedtype PointType: Point
associatedtype RotationType: Rotation
/// Position.
var position: PointType { get set }
/// Amount of rotation from initial pose.
var rotation: RotationType { get set }
typealias DirectionType = Normal<PointType>
static var initialDirection: DirectionType { get }
static var initialRightDirection: DirectionType { get }
/// Forward direction.
var direction: DirectionType { get set }
/// Right direction.
var rightDirection: DirectionType { get set }
//
// var objectToWorldTransform: Transform<PointType> { get }
/// Sets the forward direction to the vector from `position` to `at`.
mutating func look(at: PointType)
}
extension Pose {
public static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.position == rhs.position && lhs.rotation == rhs.rotation
}
public var debugDescription: String {
return "Pose(position: \(self.position), rotation: \(self.rotation))"
}
}
extension Pose {
/// Changes `self`'s `position` to `point`.
mutating public func move(to point: PointType) {
self.position = point
}
/// Moves `self` from current position with `vector`'s direciton and
/// length.
mutating public func move(_ vector: PointType.VectorType) {
self.move(to: self.position + vector)
}
}
extension Pose where PointType.VectorType: FloatVector2 {
/// Moves `self` along the `X` axis.
mutating public func move(x: PointType.VectorType.Component) {
self.move(PointType.VectorType(x, PointType.VectorType.Component.zero))
}
/// Moves `self` along the `Y` axis.
mutating public func move(y: PointType.VectorType.Component) {
self.move(PointType.VectorType(PointType.VectorType.Component.zero, y))
}
}
extension Pose where PointType.VectorType: FloatVector3 {
/// Moves `self` along the `X` axis.
mutating public func move(x: PointType.VectorType.Component) {
let zero = PointType.VectorType.Component.zero
self.move(PointType.VectorType(x, zero, zero))
}
/// Moves `self` along the `Y` axis.
mutating public func move(y: PointType.VectorType.Component) {
let zero = PointType.VectorType.Component.zero
self.move(PointType.VectorType(zero, y, zero))
}
/// Moves `self` along the `Z` axis.
mutating public func move(z: PointType.VectorType.Component) {
let zero = PointType.VectorType.Component.zero
self.move(PointType.VectorType(zero, zero, z))
}
}
extension Pose {
/// Changes `self`'s `rotation` to a new value given by `rotation`.
mutating public func rotate(to rotation: RotationType) {
self.rotation = rotation
}
/// Adds `amount` of rotation to `self`.
mutating public func rotate(_ amount: RotationType) {
self.rotate(to: self.rotation.compose(amount))
}
}
extension Pose where RotationType == Quaternion {
mutating public func pitch(_ radian: Float) {
self.rotate(Quaternion.pitch(radian))
}
mutating public func yaw(_ radian: Float) {
self.rotate(Quaternion.yaw(radian))
}
mutating public func roll(_ radian: Float) {
self.rotate(Quaternion.roll(radian))
}
}
extension Pose where PointType == RotationType.PointType {
mutating public func move(forward distance: DirectionType.Component) {
move(direction.vector * distance)
}
mutating public func move(backward distance: DirectionType.Component) {
move(forward: -distance)
}
mutating public func move(right distance: DirectionType.Component) {
move(rightDirection.vector * distance)
}
mutating public func move(left distance: DirectionType.Component) {
move(right: -distance)
}
}
///
public protocol HasPose: Pose {
associatedtype PoseType: Pose
var pose: PoseType { get set }
}
extension HasPose where PointType == PoseType.PointType {
public var position: PointType {
get { return pose.position }
set { pose.position = newValue }
}
public mutating func look(at point: PointType) {
pose.look(at: point)
}
}
extension HasPose where PointType == PoseType.PointType, RotationType == PoseType.RotationType {
public var rotation: RotationType {
get { return pose.rotation }
set { pose.rotation = newValue }
}
public var direction: DirectionType {
get {
return pose.direction
}
set {
pose.direction = newValue
}
}
public var rightDirection: DirectionType {
get {
return pose.rightDirection
}
set {
pose.rightDirection = newValue
}
}
public static var initialDirection: DirectionType {
return PoseType.initialDirection
}
public static var initialRightDirection: DirectionType {
return PoseType.initialRightDirection
}
}
/// Pose in 2D Euclidean space.
public struct Pose2D: Pose {
public typealias PointType = Point2D
public typealias RotationType = Rotation2D
public var position: Point2D
public var rotation: Rotation2D
public var direction: Normal2D {
get {
return Normal(vector: rotation.apply(Pose2D.initialDirection.vector))
}
set {
let v = newValue.vector
let theta = atan2(v.y, v.x) + .tau - .half_pi
self.rotation = Rotation2D(angle: theta)
}
}
public var rightDirection: Normal2D {
get {
return Normal<Point2D>(vector: rotation.apply(Pose2D.initialRightDirection.vector))
}
set {
let v = newValue.vector
let theta = atan2(v.y, v.x) + .tau
self.rotation = Rotation2D(angle: theta)
}
}
public mutating func look(at point: Point2D) {
self.direction = Normal(vector: point - self.position)
}
public static let initialDirection = Normal<Point2D>(vec2(0, 1))
public static let initialRightDirection = Normal<Point2D>(vec2(1, 0))
public init () {
self.position = Point2D.origin
self.rotation = Rotation2D.identity
}
}
/// Pose in 3D Euclidean space.
public struct Pose3D: Pose {
public typealias PointType = Point3D
public typealias RotationType = Quaternion
public var position: Point3D
public var rotation: Quaternion
mutating public func move(upward distance: Float) {
move(upDirection.vector * distance)
}
mutating public func move(downward distance: Float) {
move(upward: -distance)
}
public var direction: Normal3D {
get {
return Normal(vector: rotation.apply(Pose3D.initialDirection.vector))
}
set {
self.rotate(Quaternion(fromDirection: self.direction, to: newValue))
}
}
public var rightDirection: Normal3D {
get {
return Normal(vector: rotation.apply(Pose3D.initialRightDirection.vector))
}
set {
self.rotate(Quaternion(fromDirection: self.rightDirection, to: newValue))
}
}
public var upDirection: Normal3D {
get {
return Normal(vector: cross(rightDirection.vector, direction.vector))
}
set {
self.rotate(Quaternion(fromDirection: self.upDirection, to: newValue))
}
}
public mutating func look(at point: Point3D) {
self.direction = Normal(vector: point - self.position)
}
public static let initialDirection = Normal<Point3D>(vec3(0, 0, -1))
public static let initialRightDirection = Normal<Point3D>(vec3(1, 0, 0))
public init () {
self.position = Point3D.origin
self.rotation = Quaternion.identity
}
}
extension HasPose where PoseType == Pose3D, PointType == Point3D, RotationType == Quaternion {
public var upDirection: DirectionType {
get {
return pose.upDirection
}
set {
pose.upDirection = newValue
}
}
}
|
807f088d5806559d953055fb0660efc5
| 25.57764 | 96 | 0.643608 | false | false | false | false |
RedRoma/Lexis
|
refs/heads/develop
|
Code/Lexis/Cells/ImageCell.swift
|
apache-2.0
|
1
|
//
// ImageCell.swift
// Lexis
//
// Created by Wellington Moreno on 9/25/16.
// Copyright © 2016 RedRoma, Inc. All rights reserved.
//
import Foundation
import UIKit
class ImageCell: UITableViewCell
{
@IBOutlet weak var cardView: LexisView!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var cardLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var cardTrailingConstraint: NSLayoutConstraint!
@IBOutlet weak var photoHeightConstraint: NSLayoutConstraint!
private var pressGesture: UILongPressGestureRecognizer! = nil
private var onLongPress: ((ImageCell) -> Void)?
func setupLongPressGesture(callback: @escaping (ImageCell) -> Void)
{
removeLongPressGesture()
self.onLongPress = callback
self.pressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.onLongPressGesture(gesture:)))
self.addGestureRecognizer(pressGesture)
}
@objc
private func removeLongPressGesture()
{
if let existingGesture = pressGesture
{
self.removeGestureRecognizer(existingGesture)
}
onLongPress = nil
}
@objc
private func onLongPressGesture(gesture: UIGestureRecognizer)
{
onLongPress?(self)
}
}
|
67ca2bed991a6cedaf52a1633b775ace
| 25.632653 | 124 | 0.689655 | false | false | false | false |
realm/SwiftLint
|
refs/heads/main
|
Source/SwiftLintFramework/Rules/Style/IdentifierNameRule.swift
|
mit
|
1
|
import Foundation
import SourceKittenFramework
struct IdentifierNameRule: ASTRule, ConfigurationProviderRule {
var configuration = NameConfiguration(minLengthWarning: 3,
minLengthError: 2,
maxLengthWarning: 40,
maxLengthError: 60,
excluded: ["id"])
init() {}
static let description = RuleDescription(
identifier: "identifier_name",
name: "Identifier Name",
description: "Identifier names should only contain alphanumeric characters and " +
"start with a lowercase character or should only contain capital letters. " +
"In an exception to the above, variable names may start with a capital letter " +
"when they are declared static and immutable. Variable names should not be too " +
"long or too short.",
kind: .style,
nonTriggeringExamples: IdentifierNameRuleExamples.nonTriggeringExamples,
triggeringExamples: IdentifierNameRuleExamples.triggeringExamples,
deprecatedAliases: ["variable_name"]
)
func validate(
file: SwiftLintFile,
kind: SwiftDeclarationKind,
dictionary: SourceKittenDictionary
) -> [StyleViolation] {
guard !dictionary.enclosedSwiftAttributes.contains(.override) else {
return []
}
return validateName(dictionary: dictionary, kind: kind).map { name, offset in
guard !configuration.excluded.contains(name), let firstCharacter = name.first else {
return []
}
let isFunction = SwiftDeclarationKind.functionKinds.contains(kind)
let description = Self.description
let type = self.type(for: kind)
if !isFunction {
let allowedSymbols = configuration.allowedSymbols.union(.alphanumerics)
if !allowedSymbols.isSuperset(of: CharacterSet(charactersIn: name)) {
return [
StyleViolation(ruleDescription: description,
severity: .error,
location: Location(file: file, byteOffset: offset),
reason: "\(type) name should only contain alphanumeric " +
"characters: '\(name)'")
]
}
if let severity = severity(forLength: name.count) {
let reason = "\(type) name should be between " +
"\(configuration.minLengthThreshold) and " +
"\(configuration.maxLengthThreshold) characters long: '\(name)'"
return [
StyleViolation(ruleDescription: Self.description,
severity: severity,
location: Location(file: file, byteOffset: offset),
reason: reason)
]
}
}
let firstCharacterIsAllowed = configuration.allowedSymbols
.isSuperset(of: CharacterSet(charactersIn: String(firstCharacter)))
guard !firstCharacterIsAllowed else {
return []
}
let requiresCaseCheck = configuration.validatesStartWithLowercase
if requiresCaseCheck &&
kind != .varStatic && name.isViolatingCase && !name.isOperator {
let reason = "\(type) name should start with a lowercase character: '\(name)'"
return [
StyleViolation(ruleDescription: description,
severity: .error,
location: Location(file: file, byteOffset: offset),
reason: reason)
]
}
return []
} ?? []
}
private func validateName(
dictionary: SourceKittenDictionary,
kind: SwiftDeclarationKind
) -> (name: String, offset: ByteCount)? {
guard
var name = dictionary.name,
let offset = dictionary.offset,
kinds.contains(kind),
!name.hasPrefix("$")
else { return nil }
if
kind == .enumelement,
let parenIndex = name.firstIndex(of: "("),
parenIndex > name.startIndex
{
let index = name.index(before: parenIndex)
name = String(name[...index])
}
return (name.nameStrippingLeadingUnderscoreIfPrivate(dictionary), offset)
}
private let kinds: Set<SwiftDeclarationKind> = {
return SwiftDeclarationKind.variableKinds
.union(SwiftDeclarationKind.functionKinds)
.union([.enumelement])
}()
private func type(for kind: SwiftDeclarationKind) -> String {
if SwiftDeclarationKind.functionKinds.contains(kind) {
return "Function"
} else if kind == .enumelement {
return "Enum element"
} else {
return "Variable"
}
}
}
private extension String {
var isViolatingCase: Bool {
let firstCharacter = String(self[startIndex])
guard firstCharacter.isUppercase() else {
return false
}
guard count > 1 else {
return true
}
let secondCharacter = String(self[index(after: startIndex)])
return secondCharacter.isLowercase()
}
var isOperator: Bool {
let operators = ["/", "=", "-", "+", "!", "*", "|", "^", "~", "?", ".", "%", "<", ">", "&"]
return operators.contains(where: hasPrefix)
}
}
|
a856a5e836733fcc4bd2b90abecc855a
| 38.283784 | 99 | 0.535432 | false | true | false | false |
maletzt/Alien-Adventure
|
refs/heads/master
|
Alien Adventure/SettingsViewController.swift
|
mit
|
1
|
//
// SettingsViewController.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 10/4/15.
// Copyright © 2015 Udacity. All rights reserved.
//
import UIKit
// MARK: - SettingsViewController: UIViewController
class SettingsViewController: UIViewController {
// MARK: Properties
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var levelSegmentedControl: UISegmentedControl!
@IBOutlet weak var startGameButton: UIButton!
@IBOutlet weak var showBadgesLabel: UILabel!
@IBOutlet weak var showBadgesSwitch: UISwitch!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
let attributesDictionary: [String:AnyObject] = [
NSFontAttributeName: UIFont(name: Settings.Common.Font, size: 18)!
]
titleLabel.font = UIFont(name: Settings.Common.Font, size: 32)
showBadgesLabel.font = UIFont(name: Settings.Common.Font, size: 20)
showBadgesSwitch.onTintColor = UIColor.magentaColor()
levelSegmentedControl.setTitleTextAttributes(attributesDictionary, forState: .Normal)
Settings.Common.Level = levelSegmentedControl.selectedSegmentIndex
startGameButton.titleLabel?.font = UIFont(name: Settings.Common.Font, size: 20)
addTargets()
}
// MARK: Add Targets
func addTargets() {
startGameButton.addTarget(self, action: #selector(SettingsViewController.startGame), forControlEvents: .TouchUpInside)
showBadgesSwitch.addTarget(self, action: #selector(SettingsViewController.showBadges(_:)), forControlEvents: .ValueChanged)
levelSegmentedControl.addTarget(self, action: #selector(SettingsViewController.switchLevel(_:)), forControlEvents: .ValueChanged)
}
// MARK: Implementing Actions
func switchLevel(segmentControl: UISegmentedControl) {
Settings.Common.Level = segmentControl.selectedSegmentIndex
}
func showBadges(switchControl: UISwitch) {
if switchControl.on == true {
Settings.Common.ShowBadges = switchControl.on
}
}
func startGame() {
let alienAdventureViewController = self.storyboard!.instantiateViewControllerWithIdentifier("AlienAdventureViewController") as! AlienAdventureViewController
self.presentViewController(alienAdventureViewController, animated: true, completion: nil)
}
}
|
b8f96f55aef192ed1cf6e69c4f921dcd
| 34.385714 | 164 | 0.690226 | false | false | false | false |
Bartlebys/Bartleby
|
refs/heads/master
|
BartlebysUI/BartlebysUI/DropView.swift
|
apache-2.0
|
1
|
//
// DropView.swift
// BartlebysUI
//
// Created by Benoit Pereira da silva on 02/11/2016.
//
import Foundation
import AppKit
extension Notification.Name {
public struct DropView {
/// Posted on dropped url if there not dropDelegate set
/// The urls are passed in userInfos["urls"]
public static let droppedUrls = Notification.Name(rawValue: "org.bartlebys.notification.DropView.droppedUrls")
}
}
// The delegate that handles the droppedURLs
public protocol DropDelegate {
/// Passes the validated URLs
///
/// - Parameter urls: the URLs
func droppedURLs(urls:[URL],dropZoneIdentifier:String)
}
// An View with Delegated Drop support
// You should setup dropDelegate,supportedUTTypes, and optionaly dropZoneIdentifier/Users/bpds/Desktop/Un gros insecte.mov
open class DropView:NSView{
// MARK: Properties
@IBInspectable
open var backgroundColor: NSColor? {
didSet {
self.needsDisplay = true
}
}
@IBInspectable
open var highLightOnRollOver: Bool = true
// MARK: Drawings
open override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
guard let color = self.backgroundColor else {return}
color.setFill()
__NSRectFill(self.bounds)
}
// You can specify a zone identifier
public var dropZoneIdentifier:String=""
// Should return for example: [kUTTypeMovie as String,kUTTypeVideo as String]
public var supportedUTTypes:[String]?
//If set to true the paths that are not matching the supportedUTTypes are excluded
//else in case of unsupported UTTypes all the drop is cancelled
public var filterIrreleventUTTypes:Bool=true
// You setup the drop Delegate that will handle the URLs
public var dropDelegate:DropDelegate?
// Temp alpha storage
private var _alphas=[Int:CGFloat]()
// Active zone
private var _active:Bool=false{
didSet {
if self.highLightOnRollOver{
//needsDisplay = true
if _active==true{
self.subviews.forEach({ (view) in
self._alphas[view.hashValue]=view.alphaValue
view.alphaValue=0.30
})
}else{
self.subviews.forEach({ (view) in
view.alphaValue = self._alphas[view.hashValue] ?? 1.0
})
self._alphas.removeAll()
}
}
}
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
self.registerForDraggedTypes([NSPasteboard.PasteboardType("NSFilenamesPboardType"), NSPasteboard.PasteboardType("NSFontPboardType")])
}
internal var _fileTypeAreOk = false
internal var _droppedFilesPaths: [String]?{
didSet{
if let paths=_droppedFilesPaths{
var urls=[URL]()
for path in paths{
let url=URL(fileURLWithPath: path)
urls.append(url)
}
if let delegate=self.dropDelegate{
delegate.droppedURLs(urls: urls,dropZoneIdentifier:dropZoneIdentifier)
}else{
let notification = Notification(name: Notification.Name.DropView.droppedUrls, object: self.window, userInfo: ["urls":urls,"identifier":dropZoneIdentifier])
NotificationCenter.default.post(notification)
}
}
}
}
override open func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
if self._checkValidity(drag: sender) {
self._fileTypeAreOk = true
self._active = true
return .copy
} else {
self._fileTypeAreOk = false
self._active = false
return []
}
}
override open func draggingExited(_ sender: NSDraggingInfo?) {
self._active = false
}
override open func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
if self._fileTypeAreOk {
return .copy
} else {
return []
}
}
override open func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
if let paths = sender.draggingPasteboard().propertyList(forType: NSPasteboard.PasteboardType("NSFilenamesPboardType")) as? [String]{
if self.filterIrreleventUTTypes==false{
self._droppedFilesPaths = paths
}else{
// Filter the irrelevent paths
var validPaths=[String]()
for path in paths{
let url=URL(fileURLWithPath: path)
if self._isSupported(url){
validPaths.append(path)
}
}
self._droppedFilesPaths = validPaths
}
self._active = false
return true
}
return false
}
private func _checkValidity(drag: NSDraggingInfo) -> Bool {
if let paths = drag.draggingPasteboard().propertyList(forType: NSPasteboard.PasteboardType("NSFilenamesPboardType")) as? [String]{
var isValid = (self.filterIrreleventUTTypes==true) ? false : true
for path in paths{
let url=URL(fileURLWithPath: path)
if self.filterIrreleventUTTypes{
// Inclusive logic if there at least one valid element when consider the drop valid
isValid = isValid || self._isSupported(url)
}else{
// Exclusive logic
isValid = isValid && self._isSupported(url)
}
}
return isValid
}
return false
}
private func _isSupported(_ url:URL)->Bool{
if let supportedUTTypes=self.supportedUTTypes{
let pathExtension:CFString = url.pathExtension as CFString
let unmanagedFileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil);
if let fileUTI = unmanagedFileUTI?.takeRetainedValue(){
for t in supportedUTTypes{
let cft:CFString = t as CFString
if UTTypeConformsTo(fileUTI,cft){
return true
}
}
}
}
return false
}
}
|
cb73627d9f74fa8003e1edaa007048d9
| 30.451456 | 175 | 0.578639 | false | false | false | false |
bromas/StrategicControllers
|
refs/heads/master
|
StrategySample/MovableStrategy.swift
|
mit
|
1
|
//
// RedStrategy.swift
// StrategyPattern
//
// Created by Brian Thomas on 10/22/14.
// Copyright (c) 2014 Brian Thomas. All rights reserved.
//
import Foundation
import StrategicControllers
import UIKit
typealias MovableStrategy = movableStrategy<Int>
class movableStrategy<T> : ControllerStrategy<ColorViewController> {
var view : UIView = UIView()
var leftConstraint : NSLayoutConstraint?
var topConstraint : NSLayoutConstraint?
let startingColor : UIColor
init(color: UIColor) {
startingColor = color
super.init()
}
override func viewDidLoad() {
addViewAboveColorView()
view.backgroundColor = startingColor
controller.actionOnButtonTap = { [unowned self] in
let newCoords = randomCoords()
let animation = self.viewFrameAnimationPosition(newCoords)
self.view.layer.removeAllAnimations()
self.view.layer.addAnimation(animation, forKey: "newCoords")
}
}
func addViewAboveColorView () {
let container = controller.colorView
if let found = container {
view.setTranslatesAutoresizingMaskIntoConstraints(false)
controller.view.addSubview(view)
let constraint1 = NSLayoutConstraint.constraintsWithVisualFormat("V:[view(60)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["view": view]).first! as! NSLayoutConstraint
let constraint2 = NSLayoutConstraint.constraintsWithVisualFormat("V:|-40-[view]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["view": view]).first! as! NSLayoutConstraint
let constraint3 = NSLayoutConstraint.constraintsWithVisualFormat("H:[view(60)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["view": view]).first! as! NSLayoutConstraint
let constraint4 = NSLayoutConstraint.constraintsWithVisualFormat("H:|-\((controller.view.frame.size.width - 60) / 2)-[view]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["view": view]).first! as! NSLayoutConstraint
controller.view.addConstraint(constraint1)
controller.view.addConstraint(constraint2)
controller.view.addConstraint(constraint3)
controller.view.addConstraint(constraint4)
leftConstraint = constraint4
topConstraint = constraint2
}
}
func viewFrameAnimationPosition(newPosition: CGPoint) -> CABasicAnimation {
CATransaction.begin()
let animation = CABasicAnimation(keyPath: "position")
let newCoords = randomCoords()
let oldValue = (view.layer.presentationLayer() as! CALayer).position
animation.fromValue = NSValue(CGPoint: oldValue)
animation.duration = 0.6
animation.toValue = NSValue(CGPoint: newCoords)
CATransaction.setCompletionBlock { () -> Void in
}
CATransaction.commit()
leftConstraint?.constant = newCoords.x - 30
topConstraint?.constant = newCoords.y - 30
return animation
}
}
|
6ad8a831e98c956b0ba5b7456480fb3f
| 38.054795 | 233 | 0.728516 | false | false | false | false |
DaRkD0G/EasyHelper
|
refs/heads/master
|
EasyHelper/NSDateExtensions.swift
|
mit
|
1
|
//
// NSDateExtensions.swift
// EasyHelper
//
// Created by DaRk-_-D0G on 26/09/2015.
// Copyright © 2015 DaRk-_-D0G. All rights reserved.
//
import Foundation
/*
* Date Extension
* Inspirate by : https://github.com/malcommac/SwiftDate
*
* - Convert Numbers
* - Radians Degrees
*/
/// ############################################################ ///
/// Operations with NSDate WITH DATES (==,!=,<,>,<=,>= ///
/// ############################################################ ///
//MARK: OPERATIONS WITH DATES (==,!=,<,>,<=,>=)
extension NSDate : Comparable {}
/**
NSDate == NSDate
- returns: Bool
*/
public func == (left: NSDate, right: NSDate) -> Bool {
return (left.compare(right) == NSComparisonResult.OrderedSame)
}
/**
NSDate != NSDate
- returns: Bool
*/
public func != (left: NSDate, right: NSDate) -> Bool {
return !(left == right)
}
/**
NSDate < NSDate
- returns: Bool
*/
public func < (left: NSDate, right: NSDate) -> Bool {
return (left.compare(right) == NSComparisonResult.OrderedAscending)
}
/**
NSDate > NSDate
- returns: Bool
*/
public func > (left: NSDate, right: NSDate) -> Bool {
return (left.compare(right) == NSComparisonResult.OrderedDescending)
}
/**
NSDate <= NSDate
- returns: Bool
*/
public func <= (left: NSDate, right: NSDate) -> Bool {
return !(left > right)
}
/**
NSDate >=
- returns: Bool
*/
public func >= (left: NSDate, right: NSDate) -> Bool {
return !(left < right)
}
/// ############################################################ ///
/// Arithmetic operations with NSDate ///
/// ############################################################ ///
//MARK: ARITHMETIC OPERATIONS WITH DATES (-,-=,+,+=)
/**
NSDate - 1.day
- returns: NSDate
*/
public func - (left : NSDate, right: NSTimeInterval) -> NSDate {
return left.dateByAddingTimeInterval(-right)
}
/**
NSDate -= 1.month
*/
public func -= (inout left: NSDate, right: NSTimeInterval) {
left = left.dateByAddingTimeInterval(-right)
}
/**
NSDate + 1.year
- returns: NSDate
*/
public func + (left: NSDate, right: NSTimeInterval) -> NSDate {
return left.dateByAddingTimeInterval(right)
}
/**
NSDate += 1.month
*/
public func += (inout left: NSDate, right: NSTimeInterval) {
left = left.dateByAddingTimeInterval(right)
}
/// ############################################################ ///
/// Get days functions ///
/// ############################################################ ///
// MARK: - Get days functions
public extension NSDate {
/// Get the day component of the date
var day: Int {
get {
return components.day
}
}
/// Get the month component of the date
var month : Int {
get {
return components.month
}
}
/// Get the year component of the date
public var year : Int {
get {
return components.year
}
}
/// Get the hour component of the date
var hour: Int {
get {
return components.hour
}
}
/// Get the minute component of the date
var minute: Int {
get {
return components.minute
}
}
/// Get the second component of the date
var second: Int {
get {
return components.second
}
}
/// Get the era component of the date
var era: Int {
get {
return components.era
}
}
/// Get the week of the month component of the date
var weekOfMonth: Int {
get {
return components.weekOfMonth
}
}
/// Get the week of the month component of the date
var weekOfYear: Int {
get {
return components.weekOfYear
}
}
/// Get the weekday component of the date
var weekday: Int {
get {
return components.weekday
}
}
/// Get the weekday ordinal component of the date
var weekdayOrdinal: Int {
get {
return components.weekdayOrdinal
}
}
}
/// ############################################################ ///
/// To ( Converted ) ///
/// ############################################################ ///
public extension NSDate {
/* --------------------------------------------------------------------------- */
/* Create Day */
/* --------------------------------------------------------------------------- */
func toString (format: String) -> String {
let formatter = NSDateFormatter ()
formatter.locale = NSLocale(localeIdentifier: "tr")
formatter.dateFormat = format
return formatter.stringFromDate(self)
}
func toTimeStamp() -> String {
let timeInterval = self.timeIntervalSince1970
let result = String(format: "/Date(%.0f000)/", arguments:[timeInterval])
return result
}
}
/// ############################################################ ///
/// Create days functions ///
/// ############################################################ ///
// MARK: - Create days functions
public extension NSDate {
/* --------------------------------------------------------------------------- */
/* Create Day */
/* --------------------------------------------------------------------------- */
/**
Create a new NSDate instance based on refDate (if nil uses current date) and set components
:param: refDate reference date instance (nil to use NSDate())
:param: year year component (nil to leave it untouched)
:param: month month component (nil to leave it untouched)
:param: day day component (nil to leave it untouched)
:param: tz time zone component (it's the abbreviation of NSTimeZone, like 'UTC' or 'GMT+2', nil to use current time zone)
:returns: a new NSDate with components changed according to passed params
*/
public class func date(refDate refDate: NSDate? = nil, year: Int? = nil, month: Int? = nil, day:Int? = nil, hour: Int? = nil, minute: Int? = nil, second: Int? = nil, tz: String? = nil) -> NSDate {
let referenceDate = refDate ?? NSDate()
return referenceDate.set(year, month: month, day: day, hour: hour, minute: minute, second: second, tz: tz)
}
/* --------------------------------------------------------------------------- */
/* Create day by Today, Yesteday, Tomorrow */
/* --------------------------------------------------------------------------- */
/**
Return a new NSDate instance with the current date and time set to 00:00:00
:param: tz optional timezone abbreviation
:returns: a new NSDate instance of the today's date
*/
public class func today() -> NSDate {
let nowDate = NSDate()
return NSDate.date(refDate: nowDate, year: nowDate.year, month: nowDate.month, day: nowDate.day)
}
/**
Return a new NSDate istance with the current date minus one day
:param: tz optional timezone abbreviation
:returns: a new NSDate instance which represent yesterday's date
*/
public class func yesterday() -> NSDate {
return today()-1.day
}
/**
Return a new NSDate istance with the current date plus one day
:param: tz optional timezone abbreviation
:returns: a new NSDate instance which represent tomorrow's date
*/
public class func tomorrow() -> NSDate {
return today()+1.day
}
}
/// ############################################################ ///
/// Is ( Tested ) ///
/// ############################################################ ///
// MARK: - Is ( Tested )
public extension NSDate {
/// Return true if the date is the weekend
public var isWeekend:Bool {
let range = NSCalendar.currentCalendar().maximumRangeOfUnit(NSCalendarUnit.Weekday)
return (self.weekday == range.location || self.weekday == range.length)
}
/// Return true if current date's day is not a weekend day
public var isWeekday:Bool {
return !self.isWeekend
}
}
/// ############################################################ ///
/// Private ///
/// ############################################################ ///
// MARK: - Get days functions
public extension NSDate {
/* --------------------------------------------------------------------------- */
/* Create Day */
/* --------------------------------------------------------------------------- */
/**
Individual set single component of the current date instance
:param: year a non-nil value to change the year component of the instance
:param: month a non-nil value to change the month component of the instance
:param: day a non-nil value to change the day component of the instance
:param: hour a non-nil value to change the hour component of the instance
:param: minute a non-nil value to change the minute component of the instance
:param: second a non-nil value to change the second component of the instance
:param: tz a non-nil value (timezone abbreviation string as for NSTimeZone) to change the timezone component of the instance
:returns: a new NSDate instance with changed values
*/
private func set(year: Int? = nil, month: Int? = nil, day: Int? = nil, hour: Int? = nil, minute: Int? = nil, second: Int? = nil, tz: String? = nil) -> NSDate! {
let components = self.components
components.year = year ?? self.year
components.month = month ?? self.month
components.day = day ?? self.day
components.hour = hour ?? self.hour
components.minute = minute ?? self.minute
components.second = second ?? self.second
components.timeZone = (tz != nil ? NSTimeZone(abbreviation: tz!) : NSTimeZone.defaultTimeZone())
return NSCalendar.currentCalendar().dateFromComponents(components)
}
/* --------------------------------------------------------------------------- */
/* Components */
/* --------------------------------------------------------------------------- */
/// Specify calendrical units such as day and month
private class var componentFlags:NSCalendarUnit {
return [NSCalendarUnit.Year ,
NSCalendarUnit.Month ,
NSCalendarUnit.Day,
NSCalendarUnit.WeekOfYear,
NSCalendarUnit.Hour ,
NSCalendarUnit.Minute ,
NSCalendarUnit.Second ,
NSCalendarUnit.Weekday ,
NSCalendarUnit.WeekdayOrdinal,
NSCalendarUnit.WeekOfYear]
}
/// Return the NSDateComponents which represent current date
private var components: NSDateComponents {
return NSCalendar.currentCalendar().components(NSDate.componentFlags, fromDate: self)
}
}
|
38d820e5a24b534d4f62f307bdfa5cf6
| 32.323529 | 203 | 0.493116 | false | false | false | false |
alvarozizou/Noticias-Leganes-iOS
|
refs/heads/develop
|
NoticiasLeganes/Chat/ViewControllers/AliasVC.swift
|
mit
|
1
|
//
// AliasVC.swift
// NoticiasLeganes
//
// Created by Alvaro Informática on 16/1/18.
// Copyright © 2018 Alvaro Blazquez Montero. All rights reserved.
//
import UIKit
import Material
import Firebase
class AliasVC: InputDataViewController {
@IBOutlet weak var aliasView: UIView!
private var aliasField: ErrorTextField!
var viewModel: ChatVM!
override func viewDidLoad() {
super.viewDidLoad()
prepareAliasField()
Analytics.watchAliasChat()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func initChatTap(_ sender: Any) {
guard let textAlias = aliasField.text else {
return
}
if textAlias == "" || textAlias.count < 5 {
aliasField.isErrorRevealed = true
return
}
Auth.auth().signInAnonymously(completion: { (user, error) in
if let _error = error {
print(_error.localizedDescription)
return
}
UserDF.alias = textAlias
self.viewModel.alias = textAlias
self.viewModel.uid = Auth.auth().currentUser?.uid
self.navigationController?.popViewController(animated: true)
})
}
}
extension AliasVC {
private func prepareAliasField() {
aliasField = prepareErrorTextField(placeholder: "Alias", error: "Debe tener al menos 5 caracteres", centerInLayout: aliasView)
}
}
|
54c0efef5e77aa0fbd87cc5b5c3739d5
| 25.603448 | 134 | 0.624109 | false | false | false | false |
kevinsumios/KSiShuHui
|
refs/heads/master
|
Project/Model/Subscription+extension.swift
|
mit
|
1
|
//
// Subscription+extension.swift
// KSiShuHui
//
// Created by Kevin Sum on 30/7/2017.
// Copyright © 2017 Kevin iShuHui. All rights reserved.
//
import Foundation
import MagicalRecord
import SwiftyJSON
extension Subscription {
class func subscribe(bookId: Int16, YesOrNo: Bool) {
MagicalRecord.save(blockAndWait: { (localContext) in
var entity = Subscription.mr_findFirst(byAttribute: "bookId", withValue: bookId, in: localContext)
if entity == nil, YesOrNo {
entity = Subscription.mr_createEntity(in: localContext)
entity?.bookId = bookId
} else if entity != nil, !YesOrNo {
entity?.mr_deleteEntity(in: localContext)
}
})
}
class func isSubscribe(bookId: Int16?) -> Bool {
if Subscription.mr_findFirst(byAttribute: "bookId", withValue: bookId ?? -1) == nil {
return false
} else {
return true
}
}
}
|
d453478563757781db43f8742e168f31
| 27.571429 | 110 | 0.595 | false | false | false | false |
adamontherun/Study-iOS-With-Adam-Live
|
refs/heads/master
|
AppExtensionBirdWatcher/BirdWatcher/ViewController.swift
|
mit
|
1
|
//😘 it is 8/24/17
import UIKit
import BirdKit
import MobileCoreServices
class ViewController: UIViewController {
@IBOutlet weak var birdNameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
BirdCallGenerator.makeBirdCall()
}
@IBAction func handleShareActionTapped(_ sender: Any) {
let activityViewController = UIActivityViewController(activityItems: [birdNameLabel.text!], applicationActivities: nil)
present(activityViewController, animated: true, completion: nil)
activityViewController.completionWithItemsHandler = {
(activityType, completed, returnedItems, error) in
guard
let returnedItems = returnedItems,
returnedItems.count > 0,
let textItem = returnedItems.first as? NSExtensionItem,
let textItemProvider = textItem.attachments?.first as? NSItemProvider,
textItemProvider.hasItemConformingToTypeIdentifier(kUTTypeText as String)
else { return }
textItemProvider.loadItem(forTypeIdentifier: kUTTypeText as String, options: nil, completionHandler: { (string, error) in
guard
error == nil,
let newText = string as? String else { return }
DispatchQueue.main.async {
self.birdNameLabel.text = newText
}
})
}
}
}
|
a46a50c1d3d1d395cdb172bca60efaec
| 32.688889 | 133 | 0.605541 | false | false | false | false |
lincolnge/sparsec
|
refs/heads/master
|
sparsec/sparsec/atom.swift
|
mit
|
1
|
//
// atom.swift
// sparsec
//
// Created by Mars Liu on 15/3/10.
// Copyright (c) 2015年 Dwarf Artisan. All rights reserved.
//
import Foundation
func one<T:Equatable, S:CollectionType where S.Generator.Element==T>(one: T)->Parsec<T, S>.Parser{
var pred = equals(one)
return {(state: BasicState<S>)->(T?, ParsecStatus) in
var re = state.next(pred)
switch re {
case .Success:
return (one, ParsecStatus.Success)
case .Failed:
return (nil, ParsecStatus.Failed("Except \(one) but \(state[state.pos]) missmatch."))
case .Eof:
return (nil, ParsecStatus.Failed("Except \(one) but \(state[state.pos]) Eof."))
}
}
}
func subject<T:Equatable, S:CollectionType where S.Generator.Element==T >
(one: T, curry:(T)->(T)->Bool)->Parsec<T, S>.Parser {
var pred:(T)->Bool = curry(one)
return {(state: BasicState<S>)->(T?, ParsecStatus) in
var re = state.next(pred)
switch re {
case .Success:
return (one, ParsecStatus.Success)
case .Failed:
return (nil, ParsecStatus.Failed("Except \(one) but \(state[state.pos]) missmatch."))
case .Eof:
return (nil, ParsecStatus.Failed("Except \(one) but \(state[state.pos]) Eof."))
}
}
}
func eof<S:CollectionType>(state: BasicState<S>)->(S.Generator.Element?, ParsecStatus){
var item = state.next()
if item == nil {
return (nil, ParsecStatus.Success)
} else {
return (item, ParsecStatus.Failed("Except Eof but \(item) at \(state.pos)"))
}
}
func pack<T, S:CollectionType>(value:T?)->Parsec<T, S>.Parser {
return {(state:BasicState)->(T?, ParsecStatus) in
return (value, ParsecStatus.Success)
}
}
func fail<S:CollectionType>(message:String)->Parsec<S.Generator.Element, S>.Parser {
return {(state:BasicState)->(S.Generator.Element?, ParsecStatus) in
return (nil, ParsecStatus.Failed(message))
}
}
|
3fdb2ffe1e71fa84282494aaba5dc1e6
| 29.661538 | 98 | 0.605118 | false | false | false | false |
openhab/openhab.ios
|
refs/heads/sse-monitor-and-tracker-changes
|
openHAB/RollershutterUITableViewCell.swift
|
epl-1.0
|
1
|
// Copyright (c) 2010-2022 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
import DynamicButton
import OpenHABCore
import os.log
import UIKit
class RollershutterUITableViewCell: GenericUITableViewCell {
private let feedbackGenerator = UIImpactFeedbackGenerator(style: .light)
@IBOutlet private var downButton: DynamicButton!
@IBOutlet private var stopButton: DynamicButton!
@IBOutlet private var upButton: DynamicButton!
@IBOutlet private var customDetailText: UILabel!
required init?(coder: NSCoder) {
os_log("RollershutterUITableViewCell initWithCoder", log: .viewCycle, type: .info)
super.init(coder: coder)
initialize()
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
os_log("RollershutterUITableViewCell initWithStyle", log: .viewCycle, type: .info)
super.init(style: style, reuseIdentifier: reuseIdentifier)
initialize()
}
override func initialize() {
selectionStyle = .none
separatorInset = .zero
}
override func displayWidget() {
customTextLabel?.text = widget.labelText
customDetailText?.text = widget.labelValue ?? ""
upButton?.setStyle(.caretUp, animated: true)
stopButton?.setStyle(.stop, animated: true)
downButton?.setStyle(.caretDown, animated: true)
upButton?.addTarget(self, action: .upButtonPressed, for: .touchUpInside)
stopButton?.addTarget(self, action: .stopButtonPressed, for: .touchUpInside)
downButton?.addTarget(self, action: .downButtonPressed, for: .touchUpInside)
downButton?.highlightStokeColor = .ohHightlightStrokeColor
upButton?.highlightStokeColor = .ohHightlightStrokeColor
stopButton?.highlightStokeColor = .ohHightlightStrokeColor
}
@objc
func upButtonPressed() {
os_log("up button pressed", log: .viewCycle, type: .info)
widget.sendCommand("UP")
feedbackGenerator.impactOccurred()
}
@objc
func stopButtonPressed() {
os_log("stop button pressed", log: .viewCycle, type: .info)
widget.sendCommand("STOP")
feedbackGenerator.impactOccurred()
}
@objc
func downButtonPressed() {
os_log("down button pressed", log: .viewCycle, type: .info)
widget.sendCommand("DOWN")
feedbackGenerator.impactOccurred()
}
}
// inspired by: Selectors in swift: A better approach using extensions
// https://medium.com/@abhimuralidharan/selectors-in-swift-a-better-approach-using-extensions-aa6b0416e850
private extension Selector {
static let upButtonPressed = #selector(RollershutterUITableViewCell.upButtonPressed)
static let stopButtonPressed = #selector(RollershutterUITableViewCell.stopButtonPressed)
static let downButtonPressed = #selector(RollershutterUITableViewCell.downButtonPressed)
}
|
885539b9ffce94b77ea16391f5df7ebc
| 36.761905 | 106 | 0.715637 | false | false | false | false |
GraphQLSwift/GraphQL
|
refs/heads/main
|
Tests/GraphQLTests/StarWarsTests/StarWarsValidationTests.swift
|
mit
|
1
|
@testable import GraphQL
import XCTest
/**
* Helper function to test a query and the expected response.
*/
func validationErrors(query: String) throws -> [GraphQLError] {
let source = Source(body: query, name: "StarWars.graphql")
let ast = try parse(source: source)
return validate(schema: starWarsSchema, ast: ast)
}
class StarWarsValidationTests: XCTestCase {
func testNestedQueryWithFragment() throws {
let query = "query NestedQueryWithFragment {" +
" hero {" +
" ...NameAndAppearances" +
" friends {" +
" ...NameAndAppearances" +
" friends {" +
" ...NameAndAppearances" +
" }" +
" }" +
" }" +
"}" +
"fragment NameAndAppearances on Character {" +
" name" +
" appearsIn" +
"}"
XCTAssert(try validationErrors(query: query).isEmpty)
}
func testHeroSpaceshipQuery() throws {
let query = "query HeroSpaceshipQuery {" +
" hero {" +
" favoriteSpaceship" +
" }" +
"}" +
"fragment NameAndAppearances on Character {" +
" name" +
" appearsIn" +
"}"
XCTAssertFalse(try validationErrors(query: query).isEmpty)
}
func testHeroNoFieldsQuery() throws {
let query = "query HeroNoFieldsQuery {" +
" hero" +
"}"
XCTAssertFalse(try validationErrors(query: query).isEmpty)
}
func testHeroFieldsOnScalarQuery() throws {
let query = "query HeroFieldsOnScalarQuery {" +
" hero {" +
" name {" +
" firstCharacterOfName" +
" }" +
" }" +
"}"
XCTAssertFalse(try validationErrors(query: query).isEmpty)
}
func testDroidFieldOnCharacter() throws {
let query = "query DroidFieldOnCharacter {" +
" hero {" +
" name" +
" primaryFunction" +
" }" +
"}"
XCTAssertFalse(try validationErrors(query: query).isEmpty)
}
func testDroidFieldInFragment() throws {
let query = "query DroidFieldInFragment {" +
" hero {" +
" name" +
" ...DroidFields" +
" }" +
"}" +
"fragment DroidFields on Droid {" +
" primaryFunction" +
"}"
XCTAssert(try validationErrors(query: query).isEmpty)
}
func testDroidFieldInInlineFragment() throws {
let query = "query DroidFieldInInlineFragment {" +
" hero {" +
" name" +
" ... on Droid {" +
" primaryFunction" +
" }" +
" }" +
"}"
XCTAssert(try validationErrors(query: query).isEmpty)
}
}
|
6bfc6a518ff002aae07423de104042be
| 28.447619 | 66 | 0.464101 | false | true | false | false |
shaps80/SwiftLayout
|
refs/heads/master
|
Pod/Classes/SingleView+Size.swift
|
mit
|
1
|
//
// SingleView+Size.swift
// SwiftLayout
//
// Created by Shaps Mohsenin on 21/06/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
extension View {
/**
Sizes this view
- parameter axis: The axis to size
- parameter relation: The relation for this sizing, equal, greaterThanOrEqual, lessThanOrEqual
- parameter size: The size to set
- returns: The constraint that was added
*/
@discardableResult public func size(axis: Axis, relation: LayoutRelation, size: CGFloat, priority: LayoutPriority = LayoutPriorityDefaultHigh) -> NSLayoutConstraint {
var constraint = Constraint(view: self)
constraint.firstAttribute = sizeAttribute(for: axis)
constraint.secondAttribute = sizeAttribute(for: axis)
constraint.relation = relation
constraint.constant = size
constraint.priority = priority
let layout = constraint.constraint()
layout.isActive = true
return layout
}
/**
Sizes this view's axis relative to another view axis. Note: The axis for each view doesn't have to be the same
- parameter axis: The axis to size
- parameter otherAxis: The other axis to use for sizing
- parameter view: The second view to reference
- parameter ratio: The ratio to apply to this sizing. (e.g. 0.5 would size this view by 50% of the second view's edge)
- returns: The constraint that was added
*/
@discardableResult public func size(axis: Axis, to otherAxis: Axis, of view: View, ratio: CGFloat = 1, priority: LayoutPriority = LayoutPriorityDefaultHigh) -> NSLayoutConstraint {
var constraint = Constraint(view: self)
constraint.secondView = view
constraint.firstAttribute = sizeAttribute(for: axis)
constraint.secondAttribute = sizeAttribute(for: otherAxis)
constraint.multiplier = ratio
constraint.priority = priority
let layout = constraint.constraint()
layout.isActive = true
return layout
}
/**
Sizes the view to the specified width and height
- parameter width: The width
- parameter height: The height
- returns: The constraint that was added
*/
@discardableResult public func size(width: CGFloat, height: CGFloat, relation: LayoutRelation = .equal, priority: LayoutPriority = LayoutPriorityDefaultHigh) -> [NSLayoutConstraint] {
let horizontal = size(axis: .horizontal, relation: relation, size: width, priority: priority)
let vertical = size(axis: .vertical, relation: relation, size: height, priority: priority)
return [horizontal, vertical]
}
}
|
daef1fa451ec411c088ddece11530170
| 34.175676 | 185 | 0.706108 | false | false | false | false |
Chriskuei/Bon-for-Mac
|
refs/heads/master
|
Bon/BonViewController.swift
|
mit
|
1
|
//
// BonViewController.swift
// Bon
//
// Created by Chris on 16/5/14.
// Copyright © 2016年 Chris. All rights reserved.
//
import Cocoa
class BonViewController: NSViewController {
@IBOutlet weak var infoTableView: NSTableView!
@IBOutlet weak var usernameTextField: NSTextField!
@IBOutlet weak var passwordTextField: NSSecureTextField!
@IBOutlet weak var bonLoginView: BonLoginView!
@IBOutlet weak var settingsButton: BonButton!
var username: String = ""{
didSet {
usernameTextField.stringValue = username
BonUserDefaults.username = username
}
}
var password: String = ""{
didSet {
passwordTextField.stringValue = password
BonUserDefaults.password = password
}
}
var seconds: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.bonHighlight().cgColor
username = BonUserDefaults.username
password = BonUserDefaults.password
NotificationCenter.default.addObserver(self, selector: #selector(getOnlineInfo), name: Notification.Name(rawValue: BonConfig.BonNotification.GetOnlineInfo), object: nil)
getOnlineInfo()
}
@IBAction func onLoginButton(_ sender: AnyObject) {
bonLoginView.show(.loading)
login()
}
@IBAction func onLogoutButton(_ sender: AnyObject) {
bonLoginView.show(.loading)
forceLogout()
}
@IBAction func switchToPasswordTextField(_ sender: AnyObject) {
usernameTextField.resignFirstResponder()
passwordTextField.becomeFirstResponder()
}
@IBAction func enterKeyPressed(_ sender: AnyObject) {
onLoginButton(sender)
}
@IBAction func onSettingsButton(_ sender: BonButton) {
SettingsMenuAction.makeSettingsMenu(sender)
}
func showLoginView() {
bonLoginView.isHidden = false
}
func hideLoginView() {
bonLoginView.isHidden = true
}
// MARK: - Network operation
func login() {
username = usernameTextField.stringValue
password = passwordTextField.stringValue
let parameters = [
"action": "login",
"username": username,
"password": password,
"ac_id": "1",
"user_ip": "",
"nas_ip": "",
"user_mac": "",
"save_me": "1",
"ajax": "1"
]
BonNetwork.post(parameters, success: { (value) in
print(value)
if value.contains("login_ok,") {
delay(1) {
self.getOnlineInfo()
}
delay(1) {
self.bonLoginView.show(.loginSuccess)
}
} else if value.contains("You are already online.") || value.contains("IP has been online, please logout.") {
delay(1) {
self.getOnlineInfo()
}
delay(1) {
self.bonLoginView.show(.loginSuccess)
}
} else if value.contains("Password is error.") {
delay(1) {
self.bonLoginView.show(.passwordError)
}
} else if value.contains("User not found.") {
delay(1) {
self.bonLoginView.show(.usernameError)
}
} else if value.contains("Arrearage users.") { // E2616: Arrearage users.(已欠费)
delay(1) {
self.bonLoginView.show(.inArrearsError)
}
}
else {
delay(1) {
self.bonLoginView.show(.error)
}
}
}) { (error) in
self.bonLoginView.show(.timeout)
}
}
// MARK : - logout
func logout() {
let parameters = [
"action": "auto_logout"
]
BonNetwork.post(parameters) { (value) in
self.bonLoginView.isHidden = false
}
}
// TODO : - forcelogout
//Parse response
func forceLogout() {
username = usernameTextField.stringValue
password = passwordTextField.stringValue
BonNetwork.updateLoginState()
switch loginState {
case .offline:
delay(1) {
self.bonLoginView.showLoginState(.offline)
}
case .online:
let parameters = [
"action": "logout",
"username": username,
"password": password,
"ajax": "1"
]
BonNetwork.post(parameters) { (value) in
print(value)
delay(1) {
self.bonLoginView.show(.logoutSuccess)
}
}
}
}
// MARK : - get online info
@objc func getOnlineInfo() {
let parameters = [
"action": "get_online_info"
]
BonNetwork.post(parameters, success: { (value) in
NSLog(value)
if(value == "not_online") {
loginState = .offline
self.showLoginView()
} else {
self.hideLoginView()
loginState = .online
print(value)
let info = value.components(separatedBy: ",")
self.seconds = Int(info[1])!
self.itemsInfo = BonFormat.formatOnlineInfo(info)
self.updateItems()
}
}) { (error) in
loginState = .offline
self.showLoginView()
}
}
var items = [BonItem]()
var itemsInfo = [String]()
let itemsName = ["username", "used Data", "used Time", "balance", "daily Available Data"]
func updateItems() {
self.items = []
for index in 0...4 {
let item = BonItem(name: itemsName[index], info: itemsInfo[index])
items.append(item)
}
infoTableView.reloadData()
}
}
// MARK: - Table view
extension BonViewController: NSTableViewDataSource {
func numberOfRows(in aTableView: NSTableView) -> Int {
return items.count
}
@objc(tableView:viewForTableColumn:row:) func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
return BonCell.view(tableView, owner: self, subject: items[row])
}
}
extension BonViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
return true
}
}
|
251bd9c9cb6d16b4a7066afe9d7851f7
| 26 | 177 | 0.508405 | false | false | false | false |
sebmartin/Pipeline
|
refs/heads/master
|
Pipeline/Source/ViewModel/ViewProperty.swift
|
mit
|
1
|
//
// FormElement.swift
// Pipeline
//
// Created by Seb Martin on 2016-03-29.
// Copyright © 2016 Seb Martin. All rights reserved.
//
public struct ViewProperty<ValueType: Equatable, ViewType:UIControl> where ViewType:PipeableViewType {
public var valuePipe: Observable<ValueType>
public var viewPipe: ViewPipe<ViewType>
public var isValidPipe: Observable<Bool>
public init <
ValuePipeType: PipeType,
ViewPipeType: PipeType>
(value: ValueType, view: ViewType, valueOut: ValuePipeType, viewOut: ViewPipeType, validator: Validator<ValueType>? = nil)
where
ValuePipeType.PipeInput == ValueType, ValuePipeType.PipeOutput == ViewType.ViewValueType,
ViewPipeType.PipeInput == ViewType.ViewValueType, ViewPipeType.PipeOutput == ValueType
{
valuePipe = Observable(value)
viewPipe = ViewPipe(view)
isValidPipe = Observable(true)
let validator = validator ?? Validator<ValueType> { (value) in return true }
viewPipe |- viewOut |- validator |~ {
$0 |- self.valuePipe |- valueOut |- AnyPipe(self.viewPipe, weak: true)
$0.isValid |- self.isValidPipe
}
}
public var value: ValueType {
get {
return valuePipe.value
}
set(value) {
valuePipe.value = value
}
}
public var view: ViewType {
return viewPipe.view
}
// MARK: - Convenience initializers
// MARK: View and Value Pipe/Lambda permutations
public init <ViewPipeType: PipeType>
(value: ValueType, view: ViewType, valueOut: @escaping (ValueType)->ViewType.ViewValueType, viewOut: ViewPipeType, validator: Validator<ValueType>? = nil) where ViewPipeType.PipeInput == ViewType.ViewValueType, ViewPipeType.PipeOutput == ValueType
{
let valuePipe = Pipe(valueOut)
self.init(value: value, view: view, valueOut: valuePipe, viewOut: viewOut, validator: validator)
}
public init <ValuePipeType: PipeType>
(value: ValueType, view: ViewType, valueOut: ValuePipeType, viewOut: @escaping (ViewType.ViewValueType)->(ValueType), validator: Validator<ValueType>? = nil) where ValuePipeType.PipeInput == ValueType, ValuePipeType.PipeOutput == ViewType.ViewValueType
{
let viewPipe = Pipe(viewOut)
self.init(value: value, view: view, valueOut: valueOut, viewOut: viewPipe, validator: validator)
}
public init (value: ValueType, view: ViewType, valueOut: @escaping (ValueType)->ViewType.ViewValueType, viewOut: @escaping (ViewType.ViewValueType)->(ValueType), validator: Validator<ValueType>? = nil)
{
let valuePipe = Pipe(valueOut)
let viewPipe = Pipe(viewOut)
self.init(value: value, view: view, valueOut: valuePipe, viewOut: viewPipe, validator: validator)
}
// MARK: Validator as a lambda
public init <
ValuePipeType: PipeType,
ViewPipeType: PipeType>
(value: ValueType, view: ViewType, valueOut: ValuePipeType, viewOut: ViewPipeType, validator: @escaping (ValueType)->Bool)
where
ValuePipeType.PipeInput == ValueType, ValuePipeType.PipeOutput == ViewType.ViewValueType,
ViewPipeType.PipeInput == ViewType.ViewValueType, ViewPipeType.PipeOutput == ValueType
{
self.init(value: value, view: view, valueOut: valueOut, viewOut: viewOut, validator: Validator(validate: validator))
}
public init <ViewPipeType: PipeType>
(value: ValueType, view: ViewType, valueOut: @escaping (ValueType)->ViewType.ViewValueType, viewOut: ViewPipeType, validator: @escaping (ValueType)->Bool) where ViewPipeType.PipeInput == ViewType.ViewValueType, ViewPipeType.PipeOutput == ValueType
{
self.init(value: value, view: view, valueOut: valueOut, viewOut: viewOut, validator: Validator(validate: validator))
}
public init <ValuePipeType: PipeType>
(value: ValueType, view: ViewType, valueOut: ValuePipeType, viewOut: @escaping (ViewType.ViewValueType)->(ValueType), validator: @escaping (ValueType)->Bool) where ValuePipeType.PipeInput == ValueType, ValuePipeType.PipeOutput == ViewType.ViewValueType
{
self.init(value: value, view: view, valueOut: valueOut, viewOut: viewOut, validator: Validator(validate: validator))
}
public init (value: ValueType, view: ViewType, valueOut: @escaping (ValueType)->ViewType.ViewValueType, viewOut: @escaping (ViewType.ViewValueType)->(ValueType), validator: @escaping (ValueType)->Bool)
{
self.init(value: value, view: view, valueOut: valueOut, viewOut: viewOut, validator: Validator(validate: validator))
}
}
extension ViewProperty where ValueType == ViewType.ViewValueType {
public init(value: ValueType, view: ViewType, validator: Validator<ValueType>? = nil) {
self.init(value: value, view: view, valueOut: { return $0 }, viewOut: { return $0 }, validator: validator)
}
public init(value: ValueType, view: ViewType, validator: @escaping (ValueType)->Bool) {
self.init(value: value, view: view, valueOut: { return $0 }, viewOut: { return $0 }, validator: Validator(validate: validator))
}
}
|
0945094831d5cfddcfde958ad598e71c
| 42.901786 | 254 | 0.726866 | false | false | false | false |
tomdiggle/HexClockScreenSaver
|
refs/heads/master
|
Hex Clock/HexClock.swift
|
mit
|
1
|
//
// HexClock.swift
// Hex Clock
//
// Created by Tom Diggle on 27/08/2015.
// Copyright © 2015 Tom Diggle. All rights reserved.
//
import Cocoa
class HexClock {
let calendar: NSCalendar
init() {
self.calendar = NSCalendar.currentCalendar()
}
func stringOfCurrentTime() -> String {
let time = self.getCurrentTime()
let hour = time.hour <= 9 ? "0\(time.hour)" : "\(time.hour)"
let minute = time.minute <= 9 ? "0\(time.minute)" : "\(time.minute)"
let second = time.second <= 9 ? "0\(time.second)" : "\(time.second)"
return "\(hour)\(minute)\(second)"
}
func colorFromCurrentTime() -> NSColor {
let time = self.getCurrentTime()
return NSColor(red: time.hour, green: time.minute, blue: time.second)
}
private func getCurrentTime() -> (hour: Int, minute: Int, second: Int) {
var (hour, minute, second, nanosecond) = (0, 0, 0, 0)
let date = NSDate()
calendar.getHour(&hour, minute: &minute, second: &second, nanosecond: &nanosecond, fromDate: date)
return (hour, minute, second)
}
}
|
c09b19a691f6dc4395156298012956e4
| 27.390244 | 106 | 0.573024 | false | false | false | false |
inamiy/DebugLog
|
refs/heads/swift/2.0
|
DebugLog.all.swift
|
mit
|
1
|
//
// DDFileReader+DebugLog.swift
// DebugLog
//
// Created by Yasuhiro Inami on 2014/06/26.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import Foundation
extension DDFileReader
{
func readLogLine(index: Int) -> NSString!
{
var line: NSString!
self.resetOffset()
var lineNum = 0
self.enumerateLinesUsingBlock { (currentLine, stop) in
lineNum += 1
if lineNum == index {
line = currentLine
stop = true
}
}
let logFuncString = "LOG_OBJECT\\(.*?\\)" as NSString
var range = line.rangeOfString(logFuncString as String, options: .RegularExpressionSearch)
range.location += logFuncString.length-6
range.length -= logFuncString.length-5
line = line.substringWithRange(range).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return line
}
}
//
// DebugLog+ClassParsing.swift
// DebugLog
//
// Created by Yasuhiro Inami on 2014/06/26.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import Foundation
// Swift and Objective-C Class Parsing by @jpsim
// https://gist.github.com/jpsim/1b86d116808cb4e9bc30
extension DebugLog
{
enum ClassType {
case Swift, ObjectiveC
func toString() -> String {
switch self {
case .Swift:
return "Swift"
case .ObjectiveC:
return "Objective-C"
}
}
}
struct ParsedClass {
let type: ClassType
let name: String
let mangledName: String?
let moduleName: String?
}
static func _substr(str: String, range: Range<Int>) -> String {
let startIndex = str.startIndex.advancedBy(range.startIndex)
let endIndex = startIndex.advancedBy(range.endIndex)
return str[startIndex..<endIndex]
}
static func parseClass(aClass: AnyClass) -> ParsedClass {
// Swift mangling details found here: http://www.eswick.com/2014/06/inside-swift
let originalName = NSStringFromClass(aClass)
if !originalName.hasPrefix("_T") {
// Not a Swift symbol
return ParsedClass(type: ClassType.ObjectiveC,
name: originalName,
mangledName: nil,
moduleName: nil)
}
let originalNameLength = originalName.utf16.count
var cursor = 4
var substring = _substr(originalName, range: cursor ..< originalNameLength-cursor)
// Module
let moduleLength = (substring as NSString).integerValue
let moduleLengthLength = "\(moduleLength)".utf16.count
let moduleName = _substr(substring, range: moduleLengthLength ..< moduleLength)
// Update cursor and substring
cursor += moduleLengthLength + moduleName.utf16.count
substring = _substr(originalName, range: cursor ..< originalNameLength-cursor)
// Class name
let classLength = (substring as NSString).integerValue
let classLengthLength = "\(classLength)".utf16.count
let className = _substr(substring, range: classLengthLength ..< classLength)
return ParsedClass(type: ClassType.Swift,
name: className,
mangledName: originalName,
moduleName: moduleName)
}
}
//
// DebugLog+Printable.swift
// DebugLog
//
// Created by Yasuhiro Inami on 2014/06/22.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import Foundation
import CoreGraphics
import QuartzCore
//
// TODO:
// Some C-structs (e.g. CGAffineTransform, CATransform3D) + Printable don't work well in Xcode6-beta2
//
extension CGAffineTransform : CustomStringConvertible, CustomDebugStringConvertible
{
public var description: String
{
// return NSStringFromCGAffineTransform(self) // comment-out: requires UIKit
return "[\(a), \(b);\n \(c), \(d);\n \(tx), \(ty)]"
}
public var debugDescription: String
{
return self.description
}
}
extension CATransform3D : CustomStringConvertible, CustomDebugStringConvertible
{
public var description: String
{
return "[\(m11) \(m12) \(m13) \(m14);\n \(m21) \(m22) \(m23) \(m24);\n \(m31) \(m32) \(m33) \(m34);\n \(m41) \(m42) \(m43) \(m44)]"
}
public var debugDescription: String
{
return self.description
}
}
//
// DebugLog.swift
// DebugLog
//
// Created by Yasuhiro Inami on 2014/06/22.
// Copyright (c) 2014年 Inami Yasuhiro. All rights reserved.
//
import Foundation
public struct DebugLog
{
private static let _lock = NSObject()
private static let _dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.locale = NSLocale.currentLocale()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
return formatter
}()
private static func _currentDateString() -> String
{
return self._dateFormatter.stringFromDate(NSDate())
}
public static var printHandler: (Any!, String, String, Int) -> Void = { body, filename, functionName, line in
let dateString = DebugLog._currentDateString()
if body == nil {
print("\(dateString) [\(filename).\(functionName):\(line)]") // print functionName
return
}
if let body = body as? String {
if body.characters.count == 0 {
print("") // print break
return
}
}
print("\(dateString) [\(filename):\(line)] \(body)")
}
public static func print(body: Any! = nil, var filename: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__)
{
#if DEBUG
objc_sync_enter(_lock)
filename = ((filename as NSString).lastPathComponent as NSString).stringByDeletingPathExtension
self.printHandler(body, filename, functionName, line)
objc_sync_exit(_lock)
#endif
}
}
/// LOG() = prints __FUNCTION__
public func LOG(filename: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__)
{
#if DEBUG
DebugLog.print(nil, filename: filename, functionName: functionName, line: line)
#endif
}
/// LOG(...) = println
public func LOG(body: Any, filename: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__)
{
#if DEBUG
DebugLog.print(body, filename: filename, functionName: functionName, line: line)
#endif
}
/// LOG_OBJECT(myObject) = println("myObject = ...")
public func LOG_OBJECT(body: Any, filename: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__)
{
#if DEBUG
if let reader = DDFileReader(filePath: filename) {
let logBody = "\(reader.readLogLine(line)) = \(body)"
LOG(logBody, filename: filename, functionName: functionName, line: line)
} else {
LOG(body, filename: filename, functionName: functionName, line: line)
}
#endif
}
public func LOG_OBJECT(body: AnyClass, filename: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__)
{
#if DEBUG
_ = DDFileReader(filePath: filename)
let classInfo: DebugLog.ParsedClass = DebugLog.parseClass(body)
let classString = classInfo.moduleName != nil ? "\(classInfo.moduleName!).\(classInfo.name)" : "\(classInfo.name)"
LOG_OBJECT(classString, filename: filename, functionName: functionName, line: line)
// comment-out: requires method name demangling
// LOG_OBJECT("\(class_getName(body))", filename: filename, functionName: functionName, line: line)
#endif
}
//
// DDFileReader.swift
// DDFileReader
//
// Created by Yasuhiro Inami on 2014/06/22.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import Foundation
//
// Swift port of DDFileReader by Dave DeLong
//
// objective c - How to read data from NSFileHandle line by line? - Stack Overflow
// http://stackoverflow.com/a/3711079/666371
//
public class DDFileReader
{
public var lineDelimiter = "\n"
public var chunkSize = 128
public let filePath: NSString
private let _fileHandle: NSFileHandle!
private let _totalFileLength: CUnsignedLongLong
private var _currentOffset: CUnsignedLongLong = 0
public init?(filePath: NSString)
{
self.filePath = filePath
if let fileHandle = NSFileHandle(forReadingAtPath: filePath as String) {
self._fileHandle = fileHandle
self._totalFileLength = self._fileHandle.seekToEndOfFile()
}
else {
self._fileHandle = nil
self._totalFileLength = 0
return nil
}
}
deinit
{
if let _fileHandle = self._fileHandle {
_fileHandle.closeFile()
}
}
public func readLine() -> NSString?
{
if self._currentOffset >= self._totalFileLength {
return nil
}
self._fileHandle.seekToFileOffset(self._currentOffset)
let newLineData = self.lineDelimiter.dataUsingEncoding(NSUTF8StringEncoding)
let currentData = NSMutableData()
var shouldReadMore = true
autoreleasepool {
while shouldReadMore {
if self._currentOffset >= self._totalFileLength {
break
}
var chunk = self._fileHandle.readDataOfLength(self.chunkSize)
let newLineRange = chunk.rangeOfData(newLineData!)
if newLineRange.location != NSNotFound {
chunk = chunk.subdataWithRange(NSMakeRange(0, newLineRange.location+newLineData!.length))
shouldReadMore = false
}
currentData.appendData(chunk)
self._currentOffset += CUnsignedLongLong(chunk.length)
}
}
let line = NSString(data: currentData, encoding:NSUTF8StringEncoding)
return line
}
public func readTrimmedLine() -> NSString?
{
let characterSet = NSCharacterSet(charactersInString: self.lineDelimiter)
return self.readLine()?.stringByTrimmingCharactersInSet(characterSet)
}
public func enumerateLinesUsingBlock(closure: (line: NSString, stop: inout Bool) -> Void)
{
var line: NSString? = nil
var stop = false
while stop == false {
line = self.readLine()
if line == nil { break }
closure(line: line!, stop: &stop)
}
}
public func resetOffset()
{
self._currentOffset = 0
}
}
extension NSData
{
private func rangeOfData(dataToFind: NSData) -> NSRange
{
var searchIndex = 0
var foundRange = NSRange(location: NSNotFound, length: dataToFind.length)
for index in 0...length-1 {
let bytes_ = UnsafeBufferPointer(start: UnsafePointer<CUnsignedChar>(self.bytes), count: self.length)
let searchBytes_ = UnsafeBufferPointer(start: UnsafePointer<CUnsignedChar>(dataToFind.bytes), count: self.length)
if bytes_[index] == searchBytes_[searchIndex] {
if foundRange.location == NSNotFound {
foundRange.location = index
}
searchIndex += 1
if searchIndex >= dataToFind.length {
return foundRange
}
}
else {
searchIndex = 0
foundRange.location = NSNotFound
}
}
return foundRange
}
}
|
31aab466a1a369e725fb7a0257eff1ad
| 27.60095 | 139 | 0.591147 | false | false | false | false |
aestesis/Aether
|
refs/heads/master
|
Project/sources/Services/Spotify.swift
|
apache-2.0
|
1
|
//
// Spotify.swift
// Alib
//
// Created by renan jegouzo on 18/03/2017.
// Copyright © 2017 aestesis. All rights reserved.
//
import Foundation
public class Spotify {
static let apiSearch="https://api.spotify.com/v1/search?q=$artist&type=artist"
public static func searchArtist(name:String,fn:@escaping ((Any?)->())) {
let url = apiSearch.replacingOccurrences(of:"$artist",with:name.addingPercentEncoding(withAllowedCharacters:.alphanumerics)!)
Web.getJSON(url, { r in
if let json = r as? JSON {
fn(json)
} else if let err = r as? Alib.Error {
fn(Error(err))
}
})
}
}
|
0d0cc39f24599b790a27a8edf0474ca7
| 28.565217 | 133 | 0.601471 | false | false | false | false |
uphold/uphold-sdk-ios
|
refs/heads/master
|
Source/Model/Reserve.swift
|
mit
|
1
|
import Foundation
import PromiseKit
import SwiftClient
/// Reserve model.
open class Reserve: BaseModel {
/**
Gets the ledger.
- returns: A paginator with the array of deposits.
*/
open func getLedger() -> Paginator<Deposit> {
let request = self.adapter.buildRequest(request: ReserveService.getLedger(range: Header.buildRangeHeader(start: Paginator<Deposit>.DEFAULT_START, end: Paginator<Deposit>.DEFAULT_OFFSET - 1)))
let paginator: Paginator<Deposit> = Paginator(countClosure: { () -> Promise<Int> in
return Promise { fulfill, reject in
self.adapter.buildRequest(request: ReserveService.getLedger(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in
guard let count = Header.getTotalNumberOfResults(headers: response.headers) else {
reject(UnexpectedResponseError(message: "Content-Type header should not be nil."))
return
}
fulfill(count)
})
}
},
elements: self.adapter.buildResponse(request: request),
hasNextPageClosure: { (currentPage) -> Promise<Bool> in
return Promise { fulfill, reject in
self.adapter.buildRequest(request: ReserveService.getLedger(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in
guard let count = Header.getTotalNumberOfResults(headers: response.headers) else {
reject(UnexpectedResponseError(message: "Content-Type header should not be nil."))
return
}
fulfill((currentPage * Paginator<Deposit>.DEFAULT_OFFSET) < count)
})
}
},
nextPageClosure: { (range) -> Promise<[Deposit]> in
let request = self.adapter.buildRequest(request: ReserveService.getLedger(range: range))
let promise: Promise<[Deposit]> = self.adapter.buildResponse(request: request)
return promise
})
return paginator
}
/**
Gets the reserve summary of all the obligations and assets within it.
- returns: A promise with the reserve summary of all the obligations and assets within it.
*/
open func getStatistics() -> Promise<[ReserveStatistics]> {
let request = self.adapter.buildRequest(request: ReserveService.getStatistics())
return self.adapter.buildResponse(request: request)
}
/**
Gets the information of any transaction.
- parameter transactionId: The id of the transaction.
- returns: A promise with the transaction.
*/
open func getTransactionById(transactionId: String) -> Promise<Transaction> {
let request = self.adapter.buildRequest(request: ReserveService.getReserveTransactionById(transactionId: transactionId))
return self.adapter.buildResponse(request: request)
}
/**
Gets information of all the transactions from the beginning of time.
- returns: A paginator with the array of transactions.
*/
open func getTransactions() -> Paginator<Transaction> {
let request = self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: Header.buildRangeHeader(start: Paginator<Transaction>.DEFAULT_START, end: Paginator<Transaction>.DEFAULT_OFFSET - 1)))
let paginator: Paginator<Transaction> = Paginator(countClosure: { () -> Promise<Int> in
return Promise { fulfill, reject in
self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in
guard let count = Header.getTotalNumberOfResults(headers: response.headers) else {
reject(UnexpectedResponseError(message: "Content-Type header should not be nil."))
return
}
fulfill(count)
})
}
},
elements: self.adapter.buildResponse(request: request),
hasNextPageClosure: { (currentPage) -> Promise<Bool> in
return Promise { fulfill, reject in
self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in
guard let count = Header.getTotalNumberOfResults(headers: response.headers) else {
reject(UnexpectedResponseError(message: "Content-Type header should not be nil."))
return
}
fulfill((currentPage * Paginator<Transaction>.DEFAULT_OFFSET) < count)
})
}
},
nextPageClosure: { (range) -> Promise<[Transaction]> in
let request = self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: range))
let promise: Promise<[Transaction]> = self.adapter.buildResponse(request: request)
return promise
})
return paginator
}
}
|
44cc7cc693fa6eec3b8dade6b20b5b6d
| 43.819672 | 220 | 0.600768 | false | false | false | false |
NinjaIshere/GKGraphKit
|
refs/heads/master
|
GKGraphKit/GKAction.swift
|
agpl-3.0
|
1
|
/**
* Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program located at the root of the software package
* in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
*
* GKAction
*
* Represents Action Nodes, which are repetitive relationships between Entity Nodes.
*/
import Foundation
@objc(GKAction)
public class GKAction: GKNode {
/**
* init
* Initializes GKAction with a given type.
* @param type: String
*/
override public init(type: String) {
super.init(type: type)
}
/**
* subjects
* Retrieves an Array of GKEntity Objects.
* @return Array<GKEntity>
*/
public var subjects: Array<GKEntity> {
get {
var nodes: Array<GKEntity> = Array<GKEntity>()
graph.managedObjectContext.performBlockAndWait {
var node: GKManagedAction = self.node as GKManagedAction
for item: AnyObject in node.subjectSet {
nodes.append(GKEntity(entity: item as GKManagedEntity))
}
}
return nodes
}
set(value) {
assert(false, "[GraphKit Error: Subjects may not be set.]")
}
}
/**
* objects
* Retrieves an Array of GKEntity Objects.
* @return Array<GKEntity>
*/
public var objects: Array<GKEntity> {
get {
var nodes: Array<GKEntity> = Array<GKEntity>()
graph.managedObjectContext.performBlockAndWait {
var node: GKManagedAction = self.node as GKManagedAction
for item: AnyObject in node.objectSet {
nodes.append(GKEntity(entity: item as GKManagedEntity))
}
}
return nodes
}
set(value) {
assert(false, "[GraphKit Error: Objects may not be set.]")
}
}
/**
* addSubject
* Adds a GKEntity Model Object to the Subject Set.
* @param entity: GKEntity!
* @return Bool of the result, true if added, false otherwise.
*/
public func addSubject(entity: GKEntity!) -> Bool {
var result: Bool = false
graph.managedObjectContext.performBlockAndWait {
var node: GKManagedAction = self.node as GKManagedAction
result = node.addSubject(entity.node as GKManagedEntity);
}
return result
}
/**
* removeSubject
* Removes a GKEntity Model Object from the Subject Set.
* @param entity: GKEntity!
* @return Bool of the result, true if removed, false otherwise.
*/
public func removeSubject(entity: GKEntity!) -> Bool {
var result: Bool = false
graph.managedObjectContext.performBlockAndWait {
var node: GKManagedAction = self.node as GKManagedAction
result = node.removeSubject(entity.node as GKManagedEntity);
}
return result
}
/**
* addObject
* Adds a GKEntity Object to the Object Set.
* @param entity: GKEntity!
* @return Bool of the result, true if added, false otherwise.
*/
public func addObject(entity: GKEntity!) -> Bool {
var result: Bool = false
graph.managedObjectContext.performBlockAndWait {
var node: GKManagedAction = self.node as GKManagedAction
result = node.addObject(entity.node as GKManagedEntity);
}
return result
}
/**
* removeObject
* Removes a GKEntity Model Object from the Object Set.
* @param entity: GKEntity!
* @return Bool of the result, true if removed, false otherwise.
*/
public func removeObject(entity: GKEntity!) -> Bool {
var result: Bool = false
graph.managedObjectContext.performBlockAndWait {
var node: GKManagedAction = self.node as GKManagedAction
result = node.removeObject(entity.node as GKManagedEntity);
}
return result
}
/**
* delete
* Marks the Model Object to be deleted from the Graph.
*/
public func delete() {
graph.managedObjectContext.performBlockAndWait {
var node: GKManagedAction = self.node as GKManagedAction
node.delete()
}
}
/**
* init
* Initializes GKAction with a given GKManagedAction.
* @param action: GKManagedAction!
*/
internal init(action: GKManagedAction!) {
super.init(node: action)
}
/**
* createImplementorWithType
* Initializes GKManagedAction with a given type.
* @param type: String
* @return GKManagedAction
*/
override internal func createImplementorWithType(type: String) -> GKManagedNode {
return GKManagedAction(type: type);
}
}
|
f3a1d36b5ce95028ea938c328366673c
| 31.10119 | 89 | 0.622103 | false | false | false | false |
DungntVccorp/Game
|
refs/heads/master
|
GameServer/Sources/GameServer/ClientHander.swift
|
mit
|
1
|
//
// ClientHander.swift
// GameServer
//
// Created by Nguyen Dung on 9/30/16.
//
//
import Dispatch
import Foundation
import Socks
class ClientHander: NSObject {
private var client : TCPClient!
private var close : Bool = false
private var ClientMessage : Array<Array<UInt8>>!
var uuid : String!
convenience init(client : TCPClient) {
self.init()
self.client = client
self.uuid = UUID().uuidString
self.ClientMessage = Array<Array<UInt8>>()
print("Client: \(self.client.socket.address)")
DispatchQueue(label: "\(self.client.ipAddress()) : \(self.client.socket.address.port) : receive").async {
while !self.close{
do{
let data = try self.client.receiveAll()
if(data.count == 0){
print("Client disconnect and remove form connect list")
self.close = true
}else{
self.ClientMessage.append(data)
if(data.count == 61){
DispatchQueue.main.async {
//Timer.scheduledTimer(timeInterval: 45, target: self, selector: #selector(ClientHander.onSendTest), userInfo: nil, repeats: true)
self.sendMessage(msg: "DONE");
}
}
}
}catch{
print(error)
self.close = true
}
}
do{
try self.client.close()
GSShare.sharedInstance.removeClient(client: self)
}catch{
print(error)
}
}
}
deinit {
self.client = nil
self.uuid = nil
self.ClientMessage = nil
print("REMOVE CLASS")
}
func onSendTest(){
print("Send Test Message")
self.sendMessage(msg: "test \n")
}
func sendMessage(msg : String){
sendMessage(data: msg.data(using: String.Encoding.utf8)!)
}
func sendMessage(data : Data){
sendMessage(data: data.bytes)
}
func sendMessage(bytes : [UInt8]){
do{
try self.client.send(bytes: Data)
}catch{
print(error)
}
}
}
|
19b8b691a427d569f3b424703b3b8c70
| 27.72619 | 162 | 0.479486 | false | false | false | false |
honghaoz/CrackingTheCodingInterview
|
refs/heads/master
|
Swift/LeetCode.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import Foundation
import UIKit
// 228. Summary Ranges
// Given a sorted integer array without duplicates, return the summary of its ranges.
// For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
// [-1, 0, 1, 2, 4, 5, 6, 8, 9, 11, 12, 15]
// [1, 1, 1, 2, 1, 1, 2, 1, 2, 1, 3]
// [-2, 0, 1, 2, 4, 5, 6, 8, 9, 11, 12, 15]
// [2, 1, 1, 2, 1, 1, 2, 1, 2, 1, 3]
// [] -> []
// [1] -> ["1"]
// [1, 2] -> ["1->2"]
// [1, 3] -> ["1", "3"]
// [1, 2, 3] -> ["1->3"]
// [1, 2, 4] -> ["1->2", "4"]
// [1, 3, 4] -> ["1", "3->4"]
class Solution1 {
func summaryRanges(nums: [Int]) -> [String] {
var result: [String] = []
var start: Int!
var last: Int!
for num in nums {
if start == nil {
start = num
last = num
continue
}
// Continues
if (num - last) == 1 {
last = num
continue
}
// Breaks
else if (num - last) > 1 {
if start == last {
result.append("\(start)")
} else {
result.append("\(start)->\(last)")
}
start = num
last = num
continue
}
}
if start != nil {
if start == last {
result.append("\(start)")
} else {
result.append("\(start)->\(last)")
}
}
return result
}
}
func check<T where T: Equatable>(a: T, _ b: T) -> UIColor {
if a == b {
return .greenColor()
}
return .redColor()
}
//typealias A = Array where Element: Equatable
//extension Array where Element: Equatable {
//
//}
extension Array: Equatable {}
public func ==<T>(lhs: [T], rhs: [T]) -> Bool {
if T.self is Equatable {
}
// guard let lhs = lhs as? [Equatable] else {
//
// }
guard lhs.count == rhs.count else {
return false
}
return true
}
check(1, 1)
print([1] == [1])
Solution1().summaryRanges([])
check(Solution1().summaryRanges([1]), ["1"])
Solution1().summaryRanges([1, 2])
Solution1().summaryRanges([1, 3])
check(Solution1().summaryRanges([1, 2, 3]), ["1->3"])
Solution1().summaryRanges([1, 2, 4])
Solution1().summaryRanges([1, 2, 4, 5])
Solution1().summaryRanges([1, 2, 4, 6])
Solution1().summaryRanges([1, 2, 4, 7, 8])
|
b2cd30afde679abab81a5d1dcdd4e99c
| 18.831776 | 85 | 0.527333 | false | false | false | false |
GitHubStuff/SwiftIntervals
|
refs/heads/master
|
Pods/SwiftDate/Sources/SwiftDate/Date+Math.swift
|
apache-2.0
|
7
|
//
// SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones.
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - Shortcuts to convert Date to DateInRegion
public extension Date {
/// Return the current absolute datetime in local's device region (timezone+calendar+locale)
///
/// - returns: a new `DateInRegion` instance object which express passed absolute date in the context of the local device's region
public func inLocalRegion() -> DateInRegion {
return DateInRegion(absoluteDate: self)
}
/// Return the current absolute datetime in UTC/GMT timezone. `Calendar` and `Locale` are set automatically to the device's current settings.
///
/// - returns: a new `DateInRegion` instance object which express passed absolute date in UTC timezone
public func inGMTRegion() -> DateInRegion {
return DateInRegion(absoluteDate: self, in: Region.GMT())
}
/// Return the current absolute datetime in the context of passed `Region`.
///
/// - parameter region: region you want to use to express `self` date.
///
/// - returns: a new `DateInRegion` which represent `self` in the context of passed `Region`
public func inRegion(region: Region? = nil) -> DateInRegion {
return DateInRegion(absoluteDate: self, in: region)
}
/// Create a new Date object which is the sum of passed calendar components in `DateComponents` to `self`
///
/// - parameter components: components to set
///
/// - returns: a new `Date`
public func add(components: DateComponents) -> Date {
let date: DateInRegion = self.inDateDefaultRegion() + components
return date.absoluteDate
}
/// Create a new Date object which is the sum of passed calendar components in dictionary of `Calendar.Component` values to `self`
///
/// - parameter components: components to set
///
/// - returns: a new `Date`
public func add(components: [Calendar.Component: Int]) -> Date {
let date: DateInRegion = self.inDateDefaultRegion() + components
return date.absoluteDate
}
/// Enumerate dates between two intervals by adding specified time components and return an array of dates.
/// `startDate` interval will be the first item of the resulting array. The last item of the array is evaluated automatically.
///
/// - throws: throw `.DifferentCalendar` if dates are expressed in a different calendar, '.FailedToCalculate'
///
/// - Parameters:
/// - startDate: starting date
/// - endDate: ending date
/// - components: components to add
/// - Returns: an array of DateInRegion objects
public static func dates(between startDate: Date, and endDate: Date, increment components: DateComponents) -> [Date] {
var dates = [startDate]
var currentDate = startDate
repeat {
currentDate = currentDate.add(components: components)
dates.append(currentDate)
} while (currentDate <= endDate)
return dates
}
}
// MARK: - Sum of Dates and Date & Components
public func - (lhs: Date, rhs: DateComponents) -> Date {
return lhs + (-rhs)
}
public func + (lhs: Date, rhs: DateComponents) -> Date {
return lhs.add(components: rhs)
}
public func + (lhs: Date, rhs: TimeInterval) -> Date {
return lhs.addingTimeInterval(rhs)
}
public func - (lhs: Date, rhs: TimeInterval) -> Date {
return lhs.addingTimeInterval(-rhs)
}
public func + (lhs: Date, rhs: [Calendar.Component : Int]) -> Date {
return lhs.add(components: DateInRegion.componentsFrom(values: rhs))
}
public func - (lhs: Date, rhs: [Calendar.Component : Int]) -> Date {
return lhs.add(components: DateInRegion.componentsFrom(values: rhs, multipler: -1))
}
public func - (lhs: Date, rhs: Date) -> TimeInterval {
return DateTimeInterval(start: lhs, end: rhs).duration
}
|
b31a5cae0d8a02fa1dcc0408b801c4ee
| 37.275591 | 142 | 0.726805 | false | false | false | false |
meninsilicium/apple-swifty
|
refs/heads/development
|
Operators.swift
|
mpl-2.0
|
1
|
//
// author: fabrice truillot de chambrier
// created: 25.07.2014
//
// license: See license.txt
//
// © 2014-2015, men in silicium sàrl
//
import Foundation
import CoreGraphics
import Darwin.C.math
// Documentation: http://www.unicode.org/charts/
// Documentation: http://www.unicode.org/charts/PDF/U2200.pdf
// MARK: operator definitions
// not
prefix operator ¬ {}
// complement
prefix operator ∁ {}
// and
infix operator ⋀ { associativity left precedence 120 }
// nand
infix operator !&& { associativity left precedence 120 }
infix operator ⊼ { associativity left precedence 120 }
// or
infix operator ⋁ { associativity left precedence 110 }
// nor
infix operator !|| { associativity left precedence 110 }
infix operator ⊽ { associativity left precedence 110 }
// xor
infix operator ^^ { associativity left precedence 110 }
infix operator ⊻ { associativity left precedence 110 }
// nxor
infix operator !^^ { associativity left precedence 110 }
// element of
infix operator ∈ { associativity none precedence 130 }
// not element of
infix operator !∈ { associativity none precedence 130 }
infix operator ∉ { associativity none precedence 130 }
// contains
infix operator ∋ { associativity none precedence 130 }
// doesn't contain
infix operator !∋ { associativity none precedence 130 }
infix operator ∌ { associativity none precedence 130 }
// exists
prefix operator ∃ {}
// doesn't exist
prefix operator !∃ {}
prefix operator ∄ {}
// MARK: not, ¬
func not( value: Bool ) -> Bool {
return !value
}
func not<T: BooleanType>( value: T ) -> Bool {
return !value
}
prefix func ¬( value: Bool ) -> Bool {
return !value
}
prefix func ¬<T: BooleanType>( value: T ) -> Bool {
return !value
}
// MARK: bit not
func bitnot( value: Int ) -> Int {
return ~value
}
func bitnot( value: UInt ) -> UInt {
return ~value
}
// MARK: complement, ∁
public prefix func ∁( value: Int ) -> Int {
return ~value
}
public prefix func ∁( value: UInt ) -> UInt {
return ~value
}
// MARK: - and, ⋀
func and( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return lhs && rhs
}
func and<L: BooleanType>( lhs: L, @autoclosure rhs: () -> Bool ) -> Bool {
return lhs && rhs
}
func and<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return lhs && rhs
}
func ⋀( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return lhs && rhs
}
func ⋀<L: BooleanType>( lhs: L, @autoclosure rhs: () -> Bool ) -> Bool {
return lhs && rhs
}
func ⋀<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return lhs && rhs
}
// MARK: nand, !&&, ⊼
func nand( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs && rhs)
}
func nand<L: BooleanType>( lhs: L, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs && rhs)
}
func nand<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return !(lhs && rhs)
}
public func !&&( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs && rhs)
}
func ⊼( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs && rhs)
}
func ⊼<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return !(lhs && rhs)
}
// MARK: - bit and
func band( lhs: Int, rhs: Int ) -> Int {
return lhs & rhs
}
func band( lhs: UInt, rhs: UInt ) -> UInt {
return lhs & rhs
}
// MARK: - or, ⋁
func or( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return lhs || rhs
}
func or<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return lhs || rhs
}
func ⋁( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return lhs || rhs
}
func ⋁<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return lhs || rhs
}
// MARK: nor, !||, ⊽
func nor( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs || rhs)
}
func nor<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return !(lhs || rhs)
}
public func !||( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs || rhs)
}
func ⊽( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs || rhs)
}
public func !||<L: BooleanType>( lhs: L, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs || rhs)
}
func ⊽<L: BooleanType>( lhs: L, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs || rhs)
}
public func !||<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return !(lhs || rhs)
}
func ⊽<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return !(lhs || rhs)
}
// MARK: - bit or
func bor( lhs: Int, rhs: Int ) -> Int {
return lhs | rhs
}
func bor( lhs: UInt, rhs: UInt ) -> UInt {
return lhs | rhs
}
// MARK: - xor, ^^, ⊻
func xor( lhs: Bool, rhs: Bool ) -> Bool {
return (lhs || rhs) && !(lhs && rhs)
//return (lhs && !rhs) || (!lhs && rhs)
}
func xor<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return (lhs || rhs) && !(lhs && rhs)
}
public func ^^( lhs: Bool, rhs: Bool ) -> Bool {
return (lhs || rhs) && !(lhs && rhs)
}
public func ^^<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return (lhs || rhs) && !(lhs && rhs)
}
func ⊻( lhs: Bool, rhs: Bool ) -> Bool {
return (lhs || rhs) && !(lhs && rhs)
}
func ⊻<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return (lhs || rhs) && !(lhs && rhs)
}
// MARK: - nxor, !^^
func nxor( lhs: Bool, rhs: Bool ) -> Bool {
return !(lhs ^^ rhs)
}
func nxor<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return !(lhs ^^ rhs)
}
public func !^^( lhs: Bool, rhs: Bool ) -> Bool {
return !(lhs ^^ rhs)
}
public func !^^<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return !(lhs ^^ rhs)
}
// MARK: - elementOf, ∈
func elementOf<S: SequenceType where S.Generator.Element: Equatable>( value: S.Generator.Element, sequence: S ) -> Bool {
return contains( sequence, value )
}
public func ∈<S: SequenceType where S.Generator.Element: Equatable>( value: S.Generator.Element, sequence: S ) -> Bool {
return contains( sequence, value )
}
func !∈<S: SequenceType where S.Generator.Element: Equatable>( value: S.Generator.Element, sequence: S ) -> Bool {
return !contains( sequence, value )
}
public func ∉<S: SequenceType where S.Generator.Element: Equatable>( value: S.Generator.Element, sequence: S ) -> Bool {
return !contains( sequence, value )
}
// MARK: - contains, ∋
public func ∋<S: SequenceType where S.Generator.Element: Equatable>( sequence: S, value: S.Generator.Element ) -> Bool {
return contains( sequence, value )
}
public func !∋<S: SequenceType where S.Generator.Element: Equatable>( sequence: S, value: S.Generator.Element ) -> Bool {
return !contains( sequence, value )
}
public func ∌<S: SequenceType where S.Generator.Element: Equatable>( sequence: S, value: S.Generator.Element ) -> Bool {
return !contains( sequence, value )
}
// MARK: - exists, ∃
func exists<T>( value: T? ) -> Bool {
return (value != nil) && !(value is NSNull)
}
func isNil<T>( value: T? ) -> Bool {
return (value == nil) || (value is NSNull)
}
func isNull<T>( value: T? ) -> Bool {
return (value == nil) || (value is NSNull)
}
public prefix func ∃<T>( value: T? ) -> Bool {
return value != nil
}
public prefix func !∃<T>( value: T? ) -> Bool {
return value == nil
}
public prefix func ∄<T>( value: T? ) -> Bool {
return value == nil
}
// MARK: - promote, ➚
prefix operator ➚ {}
prefix func ➚( value: Int8 ) -> Int {
return Int( value )
}
prefix func ➚( value: Int16 ) -> Int {
return Int( value )
}
prefix func ➚( value: Int32 ) -> Int {
return Int( value )
}
prefix func ➚( value: Int ) -> Int {
return Int( value )
}
prefix func ➚( value: UInt8 ) -> UInt {
return UInt( value )
}
prefix func ➚( value: UInt16 ) -> UInt {
return UInt( value )
}
prefix func ➚( value: UInt32 ) -> UInt {
return UInt( value )
}
prefix func ➚( value: UInt ) -> UInt {
return UInt( value )
}
prefix func ➚( value: Float ) -> Double {
return Double( value )
}
prefix func ➚( value: Double ) -> Double {
return Double( value )
}
// MARK: - demote, ➘
prefix operator ➘ {}
prefix func ➘( value: Int ) -> Int {
return Int( value )
}
prefix func ➘( value: Int64 ) -> Int {
return Int( value )
}
prefix func ➘( value: UInt ) -> UInt {
return UInt( value )
}
prefix func ➘( value: UInt64 ) -> UInt {
return UInt( value )
}
prefix func ➘( value: Float ) -> Float {
return Float( value )
}
prefix func ➘( value: Double ) -> Float {
return Float( value )
}
prefix func ➘( value: CGFloat ) -> Float {
return Float( value )
}
// MARK: - square root, √
prefix operator √ {}
public prefix func √( value: Float ) -> Float {
return sqrtf( value )
}
public prefix func √( value: Double ) -> Double {
return sqrt( value )
}
// MARK: cube root, ∛
prefix operator ∛ {}
prefix func ∛( value: Float ) -> Float {
return cbrtf( value )
}
prefix func ∛( value: Double ) -> Double {
return cbrt( value )
}
|
1c8d1e866f9346541f5a829abfcb854d
| 19.960829 | 121 | 0.611081 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker
|
refs/heads/master
|
Pods/HXPHPicker/Sources/HXPHPicker/Core/Extension/Core+PHAsset.swift
|
mit
|
1
|
//
// Core+PHAsset.swift
// HXPHPicker
//
// Created by Slience on 2021/6/9.
//
import Photos
extension PHAsset: HXPickerCompatible {
var isImageAnimated: Bool {
var isAnimated: Bool = false
let fileName = value(forKey: "filename") as? String
if fileName != nil {
isAnimated = fileName!.hasSuffix("GIF")
}
if #available(iOS 11, *) {
if playbackStyle == .imageAnimated {
isAnimated = true
}
}
return isAnimated
}
var isLivePhoto: Bool {
var isLivePhoto: Bool = false
if #available(iOS 9.1, *) {
isLivePhoto = mediaSubtypes == .photoLive
if #available(iOS 11, *) {
if playbackStyle == .livePhoto {
isLivePhoto = true
}
}
}
return isLivePhoto
}
/// 如果在获取到PHAsset之前还未下载的iCloud,之后下载了还是会返回存在
var inICloud: Bool {
if let isCloud = isCloudPlaceholder, isCloud {
return true
}
var isICloud = false
if mediaType == .image {
let options = PHImageRequestOptions()
options.isSynchronous = true
options.deliveryMode = .fastFormat
options.resizeMode = .fast
AssetManager.requestImageData(for: self, options: options) { (result) in
switch result {
case .failure(let error):
if let inICloud = error.info?.inICloud {
isICloud = inICloud
}
default:
break
}
}
return isICloud
}else {
return !isLocallayAvailable
}
}
var isCloudPlaceholder: Bool? {
if let isICloud = self.value(forKey: "isCloudPlaceholder") as? Bool {
return isICloud
}
return nil
}
var isLocallayAvailable: Bool {
if let isCloud = isCloudPlaceholder, isCloud {
return false
}
let resourceArray = PHAssetResource.assetResources(for: self)
let isLocallayAvailable = resourceArray.first?.value(forKey: "locallyAvailable") as? Bool ?? true
return isLocallayAvailable
}
@discardableResult
func checkAdjustmentStatus(completion: @escaping (Bool) -> Void) -> PHContentEditingInputRequestID {
requestContentEditingInput(with: nil) { (input, info) in
if let isCancel = info[PHContentEditingInputCancelledKey] as? Int, isCancel == 1 {
return
}
let avAsset = input?.audiovisualAsset
var isAdjusted: Bool = false
if let path = avAsset != nil ? avAsset?.description : input?.fullSizeImageURL?.path {
if path.contains("/Mutations/") {
isAdjusted = true
}
}
completion(isAdjusted)
}
}
}
public extension HXPickerWrapper where Base: PHAsset {
var isImageAnimated: Bool {
base.isImageAnimated
}
var isLivePhoto: Bool {
base.isLivePhoto
}
var inICloud: Bool {
base.inICloud
}
var isCloudPlaceholder: Bool? {
base.isCloudPlaceholder
}
var isLocallayAvailable: Bool {
base.isLocallayAvailable
}
@discardableResult
func checkAdjustmentStatus(
completion: @escaping (Bool) -> Void
) -> PHContentEditingInputRequestID {
base.checkAdjustmentStatus(completion: completion)
}
}
|
0e8acde8853109516ca0cb0d64449023
| 28.040323 | 105 | 0.550125 | false | false | false | false |
batoulapps/QamarDeen
|
refs/heads/dev
|
QamarDeen/QamarDeen/Services/Points.swift
|
mit
|
1
|
//
// Points.swift
// QamarDeen
//
// Created by Mazyad Alabduljaleel on 12/28/16.
// Copyright © 2016 Batoul Apps. All rights reserved.
//
import Foundation
/// Points
/// class which holds the points calculation
private final class Points {
static func `for`(_ fast: Fast) -> Int {
guard let rawValue = fast.type, let fastKind = Fast.Kind(rawValue: rawValue) else {
return 0
}
switch fastKind {
case .none: return 0
case .forgiveness: return 100
case .vow: return 250
case .reconcile: return 400
case .voluntary: return 500
case .mandatory: return 500
}
}
static func `for`(_ charity: Charity) -> Int {
guard let rawValue = charity.type, let charityKind = Charity.Kind(rawValue: rawValue) else {
return 0
}
switch charityKind {
case .smile: return 25
default: return 100
}
}
static func `for`(_ prayer: Prayer) -> Int {
guard let methodValue = prayer.method,
let method = Prayer.Method(rawValue: methodValue),
let kindValue = prayer.type,
let kind = Prayer.Kind(rawValue: kindValue)
else
{
return 0
}
switch (method, kind) {
case (.alone, .shuruq): return 200
case (.alone, .qiyam): return 300
case (.alone, _): return 100
case (.group, .qiyam): return 300
case (.group, _): return 400
case (.aloneWithVoluntary, _): return 200
case (.groupWithVoluntary, _): return 500
case (.late, _): return 25
case (.excused, _): return 300
default: return 0
}
}
static func `for`(_ reading: Reading) -> Int {
return reading.ayahCount * 2
}
}
/// Extensions
/// convenience access to point calculation through model classes
// MARK: CountableAction
extension Collection where Iterator.Element: CountableAction {
var points: Int {
return map { $0.points }
.reduce(0, +)
}
}
// MARK: Fasting
extension Fast: CountableAction {
var points: Int {
return Points.for(self)
}
}
// MARK: Charity
extension Charity: CountableAction {
var points: Int {
return Points.for(self)
}
}
// MARK: Prayer
extension Prayer: CountableAction {
var points: Int {
return Points.for(self)
}
}
/// MARK: Reading
extension Reading: CountableAction {
var points: Int {
return Points.for(self)
}
}
// MARK: Day
extension Day: CountableAction {
var charityCollection: [Charity] {
return charities?.flatMap { $0 as? Charity } ?? []
}
var prayerCollection: [Prayer] {
return prayers?.flatMap { $0 as? Prayer } ?? []
}
var readingsCollection: [Reading] {
return readings?.flatMap { $0 as? Reading } ?? []
}
var points: Int {
return [
fast?.points ?? 0,
prayerCollection.points,
charityCollection.points,
readingsCollection.points
].reduce(0, +)
}
}
|
f8725257af08974842670c12a1f7ec3b
| 22.222222 | 100 | 0.53439 | false | false | false | false |
PedroTrujilloV/TIY-Assignments
|
refs/heads/master
|
34--First-Contact/Friends/Friends/PersonDetailViewController.swift
|
cc0-1.0
|
1
|
//
// PersonDetailViewController.swift
// Friends
//
// Created by Ben Gohlke on 11/19/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import RealmSwift
class PersonDetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
@IBOutlet weak var friendCountLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
let realm = try! Realm()
var person: Person?
var allPeople: Results<Person>!
override func viewDidLoad()
{
super.viewDidLoad()
allPeople = realm.objects(Person).filter("name != %@", person!.name).sorted("name")
updateFriendCountLabel()
}
func updateFriendCountLabel()
{
friendCountLabel.text = "\(person!.name) has \(person!.friendCount) friend\(person!.friendCount == 1 ? "" : "s")"
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UITableView Data Source
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return allPeople.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
return "Add some friends"
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("FriendCell", forIndexPath: indexPath)
let aPossibleFriend = allPeople[indexPath.row]
cell.textLabel?.text = aPossibleFriend.name
let results = person!.friends.filter("name == %@", aPossibleFriend.name)
if results.count == 1
{
cell.accessoryType = .Checkmark
}
else
{
cell.accessoryType = .None
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let cell = tableView.cellForRowAtIndexPath(indexPath)
if cell?.accessoryType == UITableViewCellAccessoryType.None
{
cell?.accessoryType = .Checkmark
try! realm.write { () -> Void in
self.person!.friends.append(self.allPeople[indexPath.row])
self.person!.friendCount++
}
updateFriendCountLabel()
}
else
{
cell?.accessoryType = .None
try! realm.write { () -> Void in
let index = self.person!.friends.indexOf(self.allPeople[indexPath.row])
self.person!.friends.removeAtIndex(index!)
self.person!.friendCount--
}
updateFriendCountLabel()
}
}
}
|
8d45cf097c9c188cf8f7b230e9695ca9
| 28.95 | 121 | 0.616566 | false | false | false | false |
hollisliu/Spacetime-Rhapsody
|
refs/heads/master
|
Spacetime Rhapsody.playgroundbook/Contents/Sources/TouchHandler.swift
|
mit
|
1
|
//
// TouchHandler.swift
// Fabric
//
// Created by Hanjie Liu on 3/30/17.
// Copyright © 2017 Hanjie Liu. All rights reserved.
//
import Foundation
import SceneKit
public extension UniverseViewController {
private func computeWoldClippingZFromScreenPointY(screenPoint p: CGFloat) -> CGFloat{
let z1 = fabricVanishPoint.z
let z0 = fabricZero.z
let y1 = fabricVanishPoint.y
let y0 = fabricZero.y
let a = -(z1 - z0)
let z = a * ((SCNFloat(p) - y1) / (y0 - y1)) + z1
return CGFloat(z)
}
func handlePan(_ gestureRecognize: UIPanGestureRecognizer){
let p = gestureRecognize.location(in: scnView)
// add touch points to queue for velocity calculation
previousTouchedPoints.enqueue(point: p)
switch gestureRecognize.state{
case .began:
let hitResults = scnView.hitTest(p, options: nil)
if hitResults.count > 0 {
let result = hitResults[0]
let node = result.node
// avoid moving the spacetime fabic
if (node.name == Constants.fabricName) {
return
}
selectedNode = node
objectPicked = true
if (selectedNode?.physicsBody?.type == .static) {
// play sound effect
playFabricSound(node: selectedNode!)
}
}
case .changed:
// move objects
if objectPicked {
// enter scene
if (selectedNode?.physicsBody?.type == .none){
let body = SCNPhysicsBody(type: .dynamic, shape: SCNPhysicsShape(geometry: selectedNode!.geometry!, options: nil))
body.isAffectedByGravity = false
body.friction = 0
body.damping = 0
//body.angularVelocity.y = 0.5
switch selectedNode!.name! {
case "earth":
body.mass = 1
case "mars":
body.mass = 0.8
case "venus":
body.mass = 0.7
case "jupiter":
body.mass = 3
case "neptune":
body.mass = 2
default:
break
}
selectedNode!.physicsBody = body
// play sound effect
playFabricSound(node: selectedNode!)
}
// remove velocity when select an object
let v = selectedNode?.physicsBody?.velocity.norm()
if (v != 0) {
selectedNode?.physicsBody?.type = .static
}
let z = computeWoldClippingZFromScreenPointY(screenPoint: p.y)
let worldPoint = scnView.unprojectPoint(SCNVector3(p.x, p.y, z))
let action = SCNAction.move(to: worldPoint, duration: Constants.refreshRate)
selectedNode?.runAction(action)
}
// change camera angle
else {
let fingers = gestureRecognize.numberOfTouches
// pitch camera
if (fingers == 2) {
// positive velocity means downwards
let v = gestureRecognize.velocity(in: scnView).y
if (v < 0) {
camera?.eulerAngles.x += 0.008
camera?.position.y -= 0.1
} else {
camera?.eulerAngles.x -= 0.008
camera?.position.y += 0.1
}
}
}
case .ended:
if objectPicked {
// apply force
let head = previousTouchedPoints.first()
let z0 = computeWoldClippingZFromScreenPointY(screenPoint: head.y)
let p0 = scnView.unprojectPoint(SCNVector3(head.x, head.y, z0))
let z1 = computeWoldClippingZFromScreenPointY(screenPoint: p.y)
let p1 = scnView.unprojectPoint(SCNVector3(p.x, p.y, z1))
let dx = p1 - p0
let dt = SCNFloat(Constants.touchSampleRate) / Constants.screenRefreshRate
var vel = dx / dt
// avoid flying error
if (dx.norm() < 1) {
selectedNode?.physicsBody?.type = .dynamic
return
}
// smoothing factor to avoid quick swipe resulting in huge velocity
let fineTuneFactor = Constants.fingerStrengthFactor / log(vel.norm())
vel = (vel / vel.norm()) * fineTuneFactor
selectedNode?.physicsBody?.type = .dynamic
selectedNode?.physicsBody?.velocity = vel
}
previousTouchedPoints.clear()
objectPicked = false
default: break
}
}
/// camera zoom
func handlePintch(_ gestureRecognize: UIPinchGestureRecognizer) {
switch gestureRecognize.state {
case .changed:
let s = gestureRecognize.scale
if (s > 1) {
// zoom in
if (camera!.camera!.xFov < 40) {break}
camera?.camera?.xFov -= 0.9
camera?.camera?.yFov -= 0.9
} else {
if (s == 1) {return}
//zoom out
if (camera!.camera!.xFov > 100) {break}
camera?.camera?.xFov += 1.1
camera?.camera?.yFov += 1.1
}
default:
break
}
}
}
|
f59e7500e216cf9653df34bc3db64110
| 33.043478 | 134 | 0.442369 | false | false | false | false |
wdkk/CAIM
|
refs/heads/master
|
AR/caimar00/CAIMMetal/CAIMMetalShader.swift
|
mit
|
15
|
//
// CAIMMetalView.swift
// CAIM Project
// https://kengolab.net/CreApp/wiki/
//
// Copyright (c) Watanabe-DENKI Inc.
// https://wdkk.co.jp/
//
// This software is released under the MIT License.
// https://opensource.org/licenses/mit-license.php
//
#if os(macOS) || (os(iOS) && !arch(x86_64))
import Foundation
import Metal
// Metalライブラリでコードを読み込むのを簡単にするための拡張
public extension MTLLibrary
{
static func make( with code:String ) -> MTLLibrary? {
return try! CAIMMetal.device?.makeLibrary( source: code, options:nil )
}
}
// シェーダオブジェクトクラス
public class CAIMMetalShader
{
// Metalシェーダ関数オブジェクト
public private(set) var function:MTLFunction?
// デフォルトライブラリでシェーダ関数作成
public init( _ shader_name:String ) {
guard let lib:MTLLibrary = CAIMMetal.device?.makeDefaultLibrary() else { return }
function = lib.makeFunction( name: shader_name )
}
// 外部ライブラリファイルでシェーダ関数作成
public init( libname:String, shaderName shader_name:String ) {
let lib_path = Bundle.main.path(forResource: libname, ofType: "metallib")!
guard let lib:MTLLibrary = try! CAIMMetal.device?.makeLibrary( filepath: lib_path ) else { return }
function = lib.makeFunction( name: shader_name )
}
// クラス名指定でバンドル元を指定し(たとえば外部frameworkなど)そこにそこに含まれるdefault.metallibを用いてシェーダ関数作成
public init( class cls:AnyClass, shaderName shader_name:String ) {
let bundle = Bundle(for: cls.self )
guard let lib:MTLLibrary = try! CAIMMetal.device?.makeDefaultLibrary(bundle: bundle) else { return }
function = lib.makeFunction( name: shader_name )
}
// クラス名指定でバンドル元を指定し(たとえば外部frameworkなど)そこにそこに含まれるdefault.metallibを用いてシェーダ関数作成
public init( class cls:AnyClass, libname:String, shaderName shader_name:String ) {
let lib_path = Bundle(for: cls.self ).path(forResource: libname, ofType: "metallib")!
guard let lib:MTLLibrary = try! CAIMMetal.device?.makeLibrary( filepath: lib_path ) else { return }
function = lib.makeFunction( name: shader_name )
}
// コード文字列でシェーダ関数作成
public init( code:String, shaderName shader_name:String ) {
guard let lib:MTLLibrary = try! CAIMMetal.device?.makeLibrary( source: code, options:nil ) else { return }
function = lib.makeFunction( name: shader_name )
}
// MTLLibraryでシェーダ関数作成
public init( mtllib:MTLLibrary, shaderName shader_name:String ) {
function = mtllib.makeFunction( name: shader_name )
}
}
#endif
|
008408f6505b612618ed86db41e17d39
| 34.28169 | 114 | 0.684631 | false | false | false | false |
liangbo707/LB-SwiftProject
|
refs/heads/master
|
LBPersonalApp/Main/SinaOAuth/LBSinaOAuthController.swift
|
apache-2.0
|
1
|
//
// LBSinaOAuthController.swift
// LBPersonalApp
//
// Created by MR on 16/6/15.
// Copyright © 2016年 LB. All rights reserved.
//
import UIKit
import SVProgressHUD
class LBSinaOAuthController: UIViewController{
// MARK:父类方法
override func loadView() {
webView.delegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
title = "what are you 弄啥勒"
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
webView.loadRequest(NSURLRequest(URL: LBNetworkTool.sharedInstance.oauthURL()))
}
// MARK:关闭页面
func close(){
SVProgressHUD.dismiss()
dismissViewControllerAnimated(true, completion: nil)
}
// MARK:填充密码
func autoFill(){
// 创建js代码
let js = "document.getElementById('userId').value='13009374527'; document.getElementById('passwd').value='lb8522707';"
// 让webView执行js代码
webView.stringByEvaluatingJavaScriptFromString(js)
}
// MARK: 加载accessToken
func loadAccessToken(code: String){
LBNetworkTool.sharedInstance.loadAccessToken(code) { (result, error) -> () in
if error != nil || result == nil {
SVProgressHUD.showWithStatus("你的网络不给力")
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue(), { () -> Void in
self.close() //闭包要用self
})
return
}
let userAccount = LBUserAccount(dict: result!)
userAccount.saveAccount()
NSNotificationCenter.defaultCenter().postNotificationName(LBSwitchRootVCNotification, object: false)
SVProgressHUD.dismiss()
self.close()
}
}
// MARK:懒加载
private lazy var webView = UIWebView()
}
// MARK:扩展webview 协议
extension LBSinaOAuthController : UIWebViewDelegate{
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let urlString = request.URL!.absoluteString
// 如果不是回调的url 继续加载
if !urlString.hasPrefix(LBNetworkTool.sharedInstance.redirect_URI){
return true
}
//可选绑定
if let query = request.URL!.query {// query 是url中参数字符串
let codeStr = "code="
if query.hasPrefix(codeStr){ //授权
let nsQuery = query as NSString
let code = nsQuery.substringFromIndex(codeStr.characters.count)
loadAccessToken(code)
}else{ //取消授权
close()
}
}
return false
}
func webViewDidStartLoad(webView: UIWebView) {
SVProgressHUD.showWithStatus("正在加载...")
}
func webViewDidFinishLoad(webView: UIWebView) {
SVProgressHUD.dismiss()
}
/*
授权成功 : code=e33906d3d2943f7ee4397e93788ffc5b
授权失败 : URL: https://m.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330&from=844b&vit=fps
*/
}
|
889e9d13b567aff2d11b9878ce3a41c1
| 34.602151 | 173 | 0.629909 | false | false | false | false |
jhend11/Coinvert
|
refs/heads/master
|
Coinvert/Coinvert/MenuTransitionManager.swift
|
lgpl-3.0
|
1
|
//
// MenuTransitionManager.swift
// Menu
//
// Created by Mathew Sanders on 9/7/14.
// Copyright (c) 2014 Mat. All rights reserved.
//
import UIKit
class MenuTransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
private var presenting = false
// MARK: UIViewControllerAnimatedTransitioning protocol methods
// animate a change from one viewcontroller to another
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
// get reference to our fromView, toView and the container view that we should perform the transition in
let container = transitionContext.containerView()
// create a tuple of our screens
let screens : (from:UIViewController, to:UIViewController) = (transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!, transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!)
// assign references to our menu view controller and the 'bottom' view controller from the tuple
// remember that our menuViewController will alternate between the from and to view controller depending if we're presenting or dismissing
let menuViewController = !self.presenting ? screens.from as MenuViewController : screens.to as MenuViewController
let bottomViewController = !self.presenting ? screens.to as UIViewController : screens.from as UIViewController
let menuView = menuViewController.view
let bottomView = bottomViewController.view
// prepare menu items to slide in
if (self.presenting){
self.offStageMenuController(menuViewController)
}
// add the both views to our view controller
container.addSubview(bottomView)
container.addSubview(menuView)
let duration = self.transitionDuration(transitionContext)
// perform the animation!
UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: nil, animations: {
if (self.presenting){
self.onStageMenuController(menuViewController) // onstage items: slide in
}
else {
self.offStageMenuController(menuViewController) // offstage items: slide out
}
}, completion: { finished in
// tell our transitionContext object that we've finished animating
transitionContext.completeTransition(true)
// bug: we have to manually add our 'to view' back http://openradar.appspot.com/radar?id=5320103646199808
UIApplication.sharedApplication().keyWindow!.addSubview(screens.to.view)
})
}
func offStage(amount: CGFloat) -> CGAffineTransform {
return CGAffineTransformMakeTranslation(amount, 0)
}
func offStageMenuController(menuViewController: MenuViewController){
menuViewController.view.alpha = 0
// setup paramaters for 2D transitions for animations
let topRowOffset :CGFloat = 111
let middle1RowOffset :CGFloat = 223
let middle2RowOffset :CGFloat = 334
let bottomRowOffset :CGFloat = 446
menuViewController.bitcoinIcon.transform = self.offStage(topRowOffset)
menuViewController.bitcoinLabel.transform = self.offStage(topRowOffset)
menuViewController.litecoinIcon.transform = self.offStage(topRowOffset)
menuViewController.litecoinLabel.transform = self.offStage(topRowOffset)
menuViewController.dogecoinIcon.transform = self.offStage(middle1RowOffset)
menuViewController.dogecoinLabel.transform = self.offStage(middle1RowOffset)
// menuViewController.darcoinIcon.transform = self.offStage(-middle1RowOffset)
// menuViewController.darkcoinLabel.transform = self.offStage(-middle1RowOffset)
//
//
// menuViewController.feathercoinIcon.transform = self.offStage(-middle2RowOffset)
// menuViewController.feathercoinLabel.transform = self.offStage(-middle2RowOffset)
//
// menuViewController.namecoinIcon.transform = self.offStage(middle2RowOffset)
// menuViewController.namecoinLabel.transform = self.offStage(middle2RowOffset)
//
// menuViewController.peercoinIcon.transform = self.offStage(-bottomRowOffset)
// menuViewController.peercoinLabel.transform = self.offStage(-bottomRowOffset)
//
// menuViewController.blackcoinIcon.transform = self.offStage(bottomRowOffset)
// menuViewController.blackcoinLabel.transform = self.offStage(bottomRowOffset)
}
func onStageMenuController(menuViewController: MenuViewController){
// prepare menu to fade in
menuViewController.view.alpha = 1
menuViewController.bitcoinIcon.transform = CGAffineTransformIdentity
menuViewController.bitcoinLabel.transform = CGAffineTransformIdentity
menuViewController.litecoinIcon.transform = CGAffineTransformIdentity
menuViewController.litecoinLabel.transform = CGAffineTransformIdentity
menuViewController.dogecoinIcon.transform = CGAffineTransformIdentity
menuViewController.dogecoinLabel.transform = CGAffineTransformIdentity
// menuViewController.darcoinIcon.transform = CGAffineTransformIdentity
// menuViewController.darkcoinLabel.transform = CGAffineTransformIdentity
//
// menuViewController.feathercoinIcon.transform = CGAffineTransformIdentity
// menuViewController.feathercoinLabel.transform = CGAffineTransformIdentity
//
// menuViewController.namecoinIcon.transform = CGAffineTransformIdentity
// menuViewController.namecoinLabel.transform = CGAffineTransformIdentity
//
// menuViewController.peercoinIcon.transform = CGAffineTransformIdentity
// menuViewController.peercoinLabel.transform = CGAffineTransformIdentity
//
// menuViewController.blackcoinIcon.transform = CGAffineTransformIdentity
// menuViewController.blackcoinLabel.transform = CGAffineTransformIdentity
}
// return how many seconds the transiton animation will take
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return 0.6
}
// MARK: UIViewControllerTransitioningDelegate protocol methods
// return the animataor when presenting a viewcontroller
// rememeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = true
return self
}
// return the animator used when dismissing from a viewcontroller
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = false
return self
}
}
|
3c5e62bc7ccea491c66ef975050b22ad
| 45.135802 | 233 | 0.706583 | false | false | false | false |
itechline/bonodom_new
|
refs/heads/master
|
SlideMenuControllerSwift/MessageTableCell.swift
|
mit
|
1
|
//
// MessageItemViewController.swift
// Bonodom
//
// Created by Attila Dan on 06/06/16.
// Copyright © 2016 Itechline. All rights reserved.
//
import UIKit
import SwiftyJSON
struct MessageTableCellData {
init(date: String, fel_vezeteknev: String, fel_keresztnev: String, ingatlan_varos: String, ingatlan_utca: String, hash: String, uid: Int) {
self.date = date
self.fel_keresztnev = fel_keresztnev
self.fel_vezeteknev = fel_vezeteknev
self.ingatlan_varos = ingatlan_varos
self.ingatlan_utca = ingatlan_utca
self.hash = hash
self.uid = uid
}
var date: String
var fel_vezeteknev: String
var fel_keresztnev: String
var ingatlan_varos: String
var ingatlan_utca: String
var hash: String
var uid: Int
}
class MessageTableCell: BaseTableViewCell {
@IBOutlet weak var name_text: UILabel!
@IBOutlet weak var date_text: UILabel!
@IBOutlet weak var adress_text: UILabel!
@IBOutlet weak var profile_picture: UIImageView!
@IBOutlet weak var name: UILabel!
override func awakeFromNib() {
//self.dataText?.font = UIFont.boldSystemFontOfSize(16)
//self.dataText?.textColor = UIColor(hex: "000000")
}
override class func height() -> CGFloat {
return 57
}
override func setData(data: Any?) {
if let data = data as? MessageTableCellData {
self.name_text.text = data.fel_vezeteknev + " " + data.fel_keresztnev
self.date_text.text = data.date
self.adress_text.text = data.ingatlan_varos + " " + data.ingatlan_utca
}
}
}
|
1aefab4330effa71f1f2cb984a904de0
| 27.338983 | 143 | 0.633373 | false | false | false | false |
Fenrikur/ef-app_ios
|
refs/heads/master
|
Domain Model/EurofurenceModel/Public/Default Dependency Implementations/Core Data Store/Model Adaptation/ReadAnnouncementEntity+Adaptation.swift
|
mit
|
3
|
import Foundation
extension ReadAnnouncementEntity: EntityAdapting {
typealias AdaptedType = AnnouncementIdentifier
static func makeIdentifyingPredicate(for model: AnnouncementIdentifier) -> NSPredicate {
return NSPredicate(format: "announcementIdentifier == %@", model.rawValue)
}
func asAdaptedType() -> AnnouncementIdentifier {
guard let announcementIdentifier = announcementIdentifier else {
abandonDueToInconsistentState()
}
return AnnouncementIdentifier(announcementIdentifier)
}
func consumeAttributes(from value: AnnouncementIdentifier) {
announcementIdentifier = value.rawValue
}
}
|
6dc523d988e9a24a59a8882a20b3f814
| 28.826087 | 92 | 0.72449 | false | false | false | false |
s4cha/Matrix
|
refs/heads/master
|
CNNApp/ConvolutionalNeuralNetwork.swift
|
mit
|
1
|
//
// ConvolutionalNeuralNetwork.swift
// CNNApp
//
// Created by Sacha Durand Saint Omer on 20/06/2017.
// Copyright © 2017 freshOS. All rights reserved.
//
import Foundation
struct Params {
struct Convolution {
static let numberOfFeatures = 1
static let sizeOfOfFeatures = 3
}
struct Pooling {
static let windowSize = 2
static let stride = 2
}
struct FullyConnected {
static let numberOfNeurons = 3
}
static let learningRate: Float = 2
}
class ConvolutionalNeuralNetwork {
var previousGlobalErrorRate:Float = 1
var previousPrediction = [Float]()
var previousResult:Float = 0
// var previousErrorRate:Float = 1
// var Xweights = [Float]()
var linearVotes = [Float]()
var minError:Float = 1
let convolution = ConvolutionLayer()
let reLU = RectifiedLinearUnitLayer()
let pooling = PoolingLayer()
let fullyConectedLayer = FullyConectedLayer()
func train(with trainingData: [(Matrix<Float>, [Float])]) {
var previouslyChangedThatWeight = false
for _ in 0...10 { //M
var isReducingGlobalErrorRate = true
var tunedWeightIndex = 0
var windex = 0
var bestWeight:Float = -1
while isReducingGlobalErrorRate {
var errors:Float = 0
for sample in trainingData {
let matrix = sample.0
let minusMatrix = replace(value: 0, by: -1, in: matrix)
let correctPrediction = sample.1
let prediction = predict(minusMatrix)
let numberOfPredictions:Float = 2
// print(correctPrediction)
// print("🤔 prediction : \(prediction)")
let errorRate = (abs(correctPrediction[0]-prediction[0])
+ abs(correctPrediction[1]-prediction[1]))
/ numberOfPredictions
// print(errorRate)
// print("🤔 ERRROR : \(errorRate)")
errors += errorRate
}
let globalErrorRate = errors / Float(trainingData.count)
print(" 🚨 Global Error :\(globalErrorRate)")
print("previousErrorRate :\(previousGlobalErrorRate)")
print("Tryin with weight[0] : ------- \(fullyConectedLayer.weights[0])")
// print("weights[1] = :\(fullyConectedLayer.weights[1])")
if globalErrorRate == 0 {
break
}
if globalErrorRate < 0.2 {
break
}
minError = min(previousGlobalErrorRate,minError)
if previousGlobalErrorRate > minError {
print("wtf")
}
let isReducingError = globalErrorRate < previousGlobalErrorRate
let reachedEndOfWeight = fullyConectedLayer.weights[windex][tunedWeightIndex] == 1
print("isReducingError : ------- \(isReducingError)")
if isReducingError {
previousGlobalErrorRate = globalErrorRate
bestWeight = fullyConectedLayer.weights[windex][tunedWeightIndex]
}
// if isReducingError && !reachedEndOfWeight {
// fullyConectedLayer.weights[windex][tunedWeightIndex] += Params.learningRate
// }
if reachedEndOfWeight {
// Keep best weight
fullyConectedLayer.weights[windex][tunedWeightIndex] = bestWeight
// GO TRY ADJUST NEXT PARAM
tunedWeightIndex += 1
fullyConectedLayer.weights[windex][tunedWeightIndex] += Params.learningRate
bestWeight = -1
} else {
// keep going
fullyConectedLayer.weights[windex][tunedWeightIndex] += Params.learningRate
}
if fullyConectedLayer.weights[windex][tunedWeightIndex] > 1 {
print("wtf")
}
if tunedWeightIndex == 3 && windex == 0 {
// isReducingGlobalErrorRate = false //Break
windex = 1
tunedWeightIndex = 0
// previousGlobalErrorRate = globalErrorRate
}
//
if tunedWeightIndex == 3 && windex == 1 {
isReducingGlobalErrorRate = false
}
}
}
print("Trained")
print("Found Weights")
print("weight[0] : ------- \(fullyConectedLayer.weights[0])")
print("weight[1] : ------- \(fullyConectedLayer.weights[1])")
}
func predict(_ matrix: Matrix<Float>) -> [Float] {
let feature1: Matrix<Float> = [
[1,-1],
[-1,1],
]
let c1 = convolution.runOn(matrix: matrix, withFeature: feature1)
// print("Convolution")
// print(c1)
// ReLU
let r1 = reLU.runOn(matrix: c1)
// print("RelU")
// print(r1)
// Pooling
var p1 = pooling.runOn(matrix: r1)
p1 = replace(value: 0, by: -1, in: p1)
// print("Pooling")
// print(p1)
let prediction = fullyConectedLayer.runOn(matrices: [p1])
//
// print("Prediction")
// print(prediction)
//
return prediction
}
}
// TODO pick random filters 1 per pass and see wchich ones are the best at clasifying Xs and Os
class FullyConectedLayer {
var linearVotes = [Float]()
var predictions = [Float]()
var weights: [[Float]] = [[Float](), [Float]()]
var weightedVotes: [[Float]] = [[Float](), [Float]()]
func runOn(matrices: [Matrix<Float>]) -> [Float] {
linearVotes = [Float]()
for m in matrices {
for i in 0..<m.backing.count {
for j in 0..<m.backing.count {
linearVotes.append(m[i,j])
}
}
}
// print("linearVotes")
// print(linearVotes)
// Initialize with defaut weights of 1
for i in 0..<2 {
if weights[i].isEmpty {
for _ in linearVotes {
weights[i].append(-1)
}
}
}
// print("weights")
// print(weights)
// Clean weightedVotes
weightedVotes = [[Float](), [Float]()]
// Weighted Votes
for k in 0..<2 {
for (i,v) in linearVotes.enumerated() {
let weight = weights[k][i]
weightedVotes[k].append(v*weight)
}
}
//
// print("weightedVotes")
// print(weightedVotes)
//
var predictions = [Float]()
for i in 0..<2 {
var addition:Float = 0
for v in weightedVotes[i] {
addition += v
}
let result = addition / Float(weightedVotes[i].count)
predictions.append(result)
}
return predictions
}
}
|
4969cbd268b6a80f2455393fd9bd7e13
| 27.029412 | 95 | 0.480588 | false | false | false | false |
mseemann/D2Layers
|
refs/heads/master
|
Example/Tests/OrdinalScaleTest.swift
|
mit
|
1
|
//
// OrdinalScaleTest.swift
// D2Layers
//
// Created by Michael Seemann on 24.11.15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import Quick
import Nimble
@testable import D2Layers
class OrdinalScaleSpec: QuickSpec {
override func spec() {
describe("domain"){
it("should default to an empty array"){
let scale = OrdinalScale<Int, String>()
expect(scale.domain().count) == 0
}
it("should forget previous values if domain ist set"){
let x = OrdinalScale<Int, String>().range(["foo", "bar"])
expect(x.scale(1)) == "foo"
expect(x.scale(0)) == "bar"
expect(x.domain()) == [1, 0]
x.domain([0, 1])
expect(x.scale(0)) == "foo" // it changed!
expect(x.scale(1)) == "bar"
expect(x.domain()) == [0, 1]
}
it("should order domain values by the order in which they are seen") {
let x = OrdinalScale<String, String>()
x.scale("foo")
x.scale("bar")
x.scale("baz")
expect(x.domain()) == ["foo", "bar", "baz"]
x.domain(["baz", "bar"])
x.scale("foo")
expect(x.domain()) == ["baz", "bar", "foo"]
x.domain(["baz", "foo"])
expect(x.domain()) == ["baz", "foo"]
x.domain([])
x.scale("foo")
x.scale("bar")
expect(x.domain()) == ["foo", "bar"]
}
}
describe("range"){
it("should default to an empty array"){
let x = OrdinalScale<Int, String>()
expect(x.range().count) == 0
}
it("should apend new input values to the domain"){
let x = OrdinalScale<Int, String>().range(["foo", "bar"])
expect(x.scale(0)) == "foo"
expect(x.domain()) == [0]
expect(x.scale(1)) == "bar"
expect(x.domain()) == [0, 1]
expect(x.scale(0)) == "foo"
expect(x.domain()) == [0, 1]
}
it("should remember previous values if the range is set"){
let x = OrdinalScale<Int, String>()
expect(x.scale(0)).to(beNil())
expect(x.scale(1)).to(beNil())
x.range(["foo", "bar"])
expect(x.scale(0)) == "foo"
expect(x.scale(1)) == "bar"
}
it("should work like a circle structure"){
let x = OrdinalScale<Int, String>().range(["a", "b", "c"])
expect(x.scale(0)) == "a"
expect(x.scale(1)) == "b"
expect(x.scale(2)) == "c"
expect(x.scale(3)) == "a"
expect(x.scale(4)) == "b"
expect(x.scale(5)) == "c"
expect(x.scale(2)) == "c"
expect(x.scale(1)) == "b"
expect(x.scale(0)) == "a"
}
}
describe("rangePoints"){
it("computes discrete points in a continuous range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:0, stop:120)
expect(x.range()) == [0, 60, 120]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:0, stop:120, padding:1)
expect(x.range()) == [20, 60, 100]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:0, stop:120, padding:2)
expect(x.range()) == [30, 60, 90]
}
it("correctly handles empty domains") {
let x = try! OrdinalScale<String, Double>().domain([]).rangePoints(start:0, stop:120)
expect(x.range()) == []
expect(x.scale("b")).to(beNil())
expect(x.domain()) == []
}
it("correctly handles singleton domains") {
let x = try! OrdinalScale<String, Double>().domain(["a"]).rangePoints(start:0, stop:120)
expect(x.range()) == [60]
expect(x.scale("b")).to(beNil())
expect(x.domain()) == ["a"]
}
it("can be set to a descending range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:120, stop:0)
expect(x.range()) == [120, 60, 0]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:120, stop:0, padding:1)
expect(x.range()) == [100, 60, 20]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:120, stop:0, padding:2)
expect(x.range()) == [90, 60, 30]
}
it("has a rangeBand of zero") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:0, stop:120)
expect(x.rangeBand) == 0
}
it("returns undefined for values outside the domain") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:0, stop:1)
expect(x.scale("d")).to(beNil())
expect(x.scale("e")).to(beNil())
expect(x.scale("f")).to(beNil())
}
it("does not implicitly add values to the domain") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:0, stop:1)
x.scale("d")
x.scale("e")
expect(x.domain()) == ["a", "b", "c"]
}
it("supports realy double values") {
let o = try! OrdinalScale<Double, Double>().domain([1, 2, 3, 4]).rangePoints(start:0, stop:100)
expect(o.range()[1]) == 100/3
}
}
describe("rangeRoundPoints") {
it("computes discrete points in a continuous range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:120)
expect(x.range()) == [0, 60, 120]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:120, padding:1)
expect(x.range()) == [20, 60, 100]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:120, padding:2);
expect(x.range()) == [30, 60, 90]
}
it("rounds to the nearest equispaced integer values") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:119)
expect(x.range()) == [1, 60, 119]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:119, padding:1)
expect(x.range()) == [21, 60, 99]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:119, padding:2)
expect(x.range()) == [31, 60, 89]
}
it("correctly handles empty domains") {
let x = try! OrdinalScale<String, Double>().domain([]).rangeRoundPoints(start:0, stop:119)
expect(x.range()) == []
expect(x.scale("b")).to(beNil())
expect(x.domain()) == []
}
it("correctly handles singleton domains") {
let x = try! OrdinalScale<String, Double>().domain(["a"]).rangeRoundPoints(start:0, stop:119)
expect(x.range()) == [60]
expect(x.scale("b")).to(beNil())
expect(x.domain()) == ["a"]
}
it("can be set to a descending range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:119, stop:0)
expect(x.range()) == [119, 60, 1]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:119, stop:0, padding:1)
expect(x.range()) == [99, 60, 21]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:119, stop:0, padding:2)
expect(x.range()) == [89, 60, 31]
}
it("has a rangeBand of zero") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:119)
expect(x.rangeBand) == 0
}
it("returns nul for values outside the domain") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:1)
expect(x.scale("d")).to(beNil())
expect(x.scale("e")).to(beNil())
expect(x.scale("f")).to(beNil())
}
it("does not implicitly add values to the domain") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:1)
x.scale("d")
x.scale("e")
expect(x.domain()) == ["a", "b", "c"]
}
}
describe("rangeBands") {
it("computes discrete bands in a continuous range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:0, stop:120)
expect(x.range()) == [0, 40, 80]
expect(x.rangeBand) == 40
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:0, stop:120, padding:0.2, outerPadding:0.2)
expect(x.range()) == [7.5, 45, 82.5]
expect(x.rangeBand) == 30
}
// FIXME currently not possible - maybe every range-funktion must be an object to recompute the ranges with the original values.
// it("setting domain recomputes range bands") {
// let x = try! OrdinalScale<String, Double>().rangeBands(start:0, stop:100).domain(["a", "b", "c"])
// expect(x.range()) == [1, 34, 67]
// expect(x.rangeBand) == 33
// x.domain(["a", "b", "c", "d"])
// expect(x.range()) == [0, 25, 50, 75]
// expect(x.rangeBand) == 25
// }
it("can be set to a descending range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:120, stop:0)
expect(x.range()) == [80, 40, 0]
expect(x.rangeBand) == 40
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:120, stop:0, padding:0.2, outerPadding:0.2)
expect(x.range()) == [82.5, 45, 7.5]
expect(x.rangeBand) == 30
}
it("can specify a different outer padding") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:120, stop:0, padding:0.2, outerPadding:0.1)
expect(x.range()) == [84, 44, 4]
expect(x.rangeBand) == 32
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:120, stop:0, padding:0.2, outerPadding:1)
expect(x.range()) == [75, 50, 25]
expect(x.rangeBand) == 20
}
it("returns undefined for values outside the domain") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:0, stop:1)
expect(x.scale("d")).to(beNil())
expect(x.scale("e")).to(beNil())
expect(x.scale("f")).to(beNil())
}
it("does not implicitly add values to the domain") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:0, stop:1)
x.scale("d")
x.scale("e")
expect(x.domain()) == ["a", "b", "c"]
}
}
describe("rangeRoundBands"){
it("computes discrete rounded bands in a continuous range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:0, stop:100)
expect(x.range()) == [1, 34, 67]
expect(x.rangeBand) == 33
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:0, stop:100, padding:0.2, outerPadding:0.2)
expect(x.range()) == [7, 38, 69]
expect(x.rangeBand) == 25
}
it("can be set to a descending range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:100, stop:0)
expect(x.range()) == [67, 34, 1]
expect(x.rangeBand) == 33
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:100, stop:0, padding:0.2, outerPadding:0.2)
expect(x.range()) == [69, 38, 7]
expect(x.rangeBand) == 25
}
it("can specify a different outer padding") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:120, stop:0, padding:0.2, outerPadding:0.1)
expect(x.range()) == [84, 44, 4]
expect(x.rangeBand) == 32
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:120, stop:0, padding:0.2, outerPadding:1)
expect(x.range()) == [75, 50, 25]
expect(x.rangeBand) == 20
}
it("returns undefined for values outside the domain"){
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:0, stop:1)
expect(x.scale("d")).to(beNil())
expect(x.scale("e")).to(beNil())
expect(x.scale("f")).to(beNil())
}
it("does not implicitly add values to the domain") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:0, stop:1)
x.scale("d")
x.scale("e")
expect(x.domain()) == ["a", "b", "c"]
}
}
describe("rangeExtent") {
it("returns the continuous range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:20, stop:120)
expect(x.rangeExtent) == [20, 120]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:10, stop:110)
expect(x.rangeExtent) == [10, 110]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:0, stop:100)
expect(x.rangeExtent) == [0, 100]
x = OrdinalScale<String, Double>().domain(["a", "b", "c"]).range([0, 20, 100])
expect(x.rangeExtent) == [0, 100]
}
it("can handle descending ranges") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:100, stop:0)
expect(x.rangeExtent) == [0, 100]
}
}
}
}
|
4601a5785a4dd0947b75307eb751be93
| 44.997183 | 149 | 0.450426 | false | false | false | false |
marcelvoss/MVFollow
|
refs/heads/master
|
MVFollow/Follow.swift
|
mit
|
1
|
//
// Follow.swift
// Example
//
// Created by Marcel Voß on 09/12/2016.
// Copyright © 2016 Marcel Voß. All rights reserved.
//
import UIKit
import Accounts
import Social
class Follow: NSObject {
var availableAccounts: [ACAccount]?
/// Generates a UIAlertController with action sheet style, including actions for every Twitter account that was found in the ACAccountStore. The actions are configured as well and will follow the specified user with an account selected by the user.
///
/// - Parameters:
/// - accounts: The account array that shall be used to generate the action sheet.
/// - username: The username that shall be followed.
/// - Returns: A UIAlertController with action sheet style.
func actionSheet(accounts: [ACAccount]?, username: String) -> UIAlertController? {
if let accountArray = accounts {
let actionSheet = UIAlertController(title: nil, message: "Choose account for following @\(username)", preferredStyle: .actionSheet)
for account in accountArray {
actionSheet.addAction(UIAlertAction(title: account.username, style: .default, handler: { (action) in
self.follow(username: username, account: account, completionHandler: { (success, error) in
actionSheet.dismiss(animated: true, completion: {
if error != nil {
let alertController = UIAlertController(title: "Error", message: "Couldn't follow @\(username). \(error!.localizedDescription).", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
}
})
})
}))
}
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
return actionSheet
}
return nil
}
/// Retrieves an array of ACAccounts with the ACAccountTypeIdentifierTwitter.
///
/// - Parameter completionHandler: A closure with an array of ACAccounts, a boolean determining wether the retrival was succesful and an error instance containing a more described error description.
func accounts(completionHandler:@escaping ([ACAccount]?, Bool, Error?) -> Void) {
let accountStore = ACAccountStore()
let accountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
accountStore.requestAccessToAccounts(with: accountType, options: nil) {(granted: Bool, error: Error?) -> Void in
if granted {
let accounts = accountStore.accounts(with: accountType) as? [ACAccount]
self.availableAccounts = accounts
completionHandler(accounts, true, error)
}
completionHandler(nil, false, error)
}
}
/// Follows the user with the specified username with the specified account.
///
/// - Parameters:
/// - username: The user to follow.
/// - account: The account that shall follow.
/// - completionHandler: A closure containing a boolean for determining wether following was successful and an error instance containing a more described error description.
func follow(username: String, account: ACAccount, completionHandler:@escaping (Bool, Error?) -> Void) {
let requestParameters = ["follow": "true", "screen_name": username]
performFollowRequest(account: account, parameters: requestParameters, completionHandler: { (error) in
if error == nil {
completionHandler(false, error)
} else {
completionHandler(true, error)
}
})
}
/// Opens the profile of the specified user in an installed Twitter client or in Safari.
///
/// - Parameter username: The user's Twitter handle.
/// - Returns: A boolean determining wether it was possible to open the Twitter profile.
func showProfile(username: String) -> Bool {
if canOpenApplication(identifier: "twitter://") {
// Twitter.app
return openApplication(string: "twitter://user?screen_name=\(username)")
} else if canOpenApplication(identifier: "tweetbot://") {
// Tweetbot
return openApplication(string: "tweetbot:///user_profile/\(username)")
} else if canOpenApplication(identifier: "twitterrific://") {
// Twitterrific
return openApplication(string: "twitterrific:///profile?screen_name=\(username)")
} else {
// Web
return openApplication(string: "http://twitter.com/\(username)")
}
}
// MARK: - Private
private func openApplication(string: String) -> Bool {
var successful = false
if let url = URL(string: string) {
UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
successful = success
})
}
return successful
}
private func canOpenApplication(identifier: String) -> Bool {
if let url = URL(string: identifier) {
return UIApplication.shared.canOpenURL(url)
}
return false
}
private func performFollowRequest(account: ACAccount?, parameters: [String:String], completionHandler:@escaping (Error?) -> Void) {
let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .POST,
url: URL(string: "https://api.twitter.com/1.1/friendships/create.json"), parameters: parameters)
request?.account = account
request?.perform(handler: { (data, response, error) in
let statusCode = response?.statusCode
if error == nil && (statusCode == 200 || statusCode == 201) {
completionHandler(nil)
} else {
completionHandler(error)
}
})
}
}
|
ea288a1a5cf3c4cce165623b2447f8b2
| 44.543478 | 252 | 0.611138 | false | false | false | false |
MTR2D2/TIY-Assignments
|
refs/heads/master
|
ToDo/ToDo/TodoTableViewController.swift
|
cc0-1.0
|
1
|
//
// TodoTableViewController.swift
// ToDo
//
// Created by Michael Reynolds on 10/20/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import CoreData
class TodoTableViewController: UITableViewController, UITextFieldDelegate
{
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var itemDescription = Array<ToDoCore>()
override func viewDidLoad()
{
super.viewDidLoad()
title = "Task List"
let fetchRequest = NSFetchRequest(entityName: "ToDoCore")
do
{
let fetchResults = try managedObjectContext.executeFetchRequest(fetchRequest) as? [ToDoCore]
itemDescription = fetchResults!
}
catch
{
let nserror = error as NSError
NSLog("Unresoved error \(nserror), \(nserror.userInfo)")
abort()
}
// 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 numberOfSectionsInTableView(tableView: UITableView) -> Int
{
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
// #warning Incomplete implementation, return the number of rows
return itemDescription.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ToDoList", forIndexPath: indexPath) as! ToDoCell
// Configure the cell...
let aTask = itemDescription[indexPath.row]
if aTask.something == nil
{
cell.toDoText.becomeFirstResponder()
}
else
{
cell.toDoText.text = aTask.something
}
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
return true
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == .Delete
{
// Delete the row from the data source
let aTask = itemDescription[indexPath.row]
itemDescription.removeAtIndex(indexPath.row)
managedObjectContext.deleteObject(aTask)
saveContext()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: TextField Delegate
func textFieldShouldReturn(toDoText: UITextField) -> Bool
{
var rc = false //rc stands for return code
if toDoText.text != ""
{
rc = true
let contentView = toDoText.superview
let cell = contentView?.superview as! ToDoCell
let indexPath = tableView.indexPathForCell(cell)
// tableView, here is the cell, give me the indexPath
let aTask = itemDescription[indexPath!.row]
aTask.something = toDoText.text
toDoText.resignFirstResponder()
saveContext()
}
return rc
}
// MARK: Action Handlers
@IBAction func newTask(sender: UIBarButtonItem)
{
let aTask = NSEntityDescription.insertNewObjectForEntityForName("ToDoCore", inManagedObjectContext: managedObjectContext) as! ToDoCore
itemDescription.append(aTask)
tableView.reloadData()
// saveContext()
}
@IBAction func doneButton(sender: UIButton)
{
let contentView = sender.superview
let cell = contentView?.superview as! ToDoCell
let indexPath = tableView.indexPathForCell(cell)
// tableView, here is the cell, give me the indexPath
let aTask = itemDescription[indexPath!.row]
if sender.currentTitle == "☑"
{
cell.backgroundColor = UIColor.whiteColor()
sender.setTitle("☐", forState: UIControlState.Normal)
aTask.done = false
}
else
{
cell.backgroundColor = UIColor.greenColor()
sender.setTitle("☑", forState: UIControlState.Normal)
aTask.done = true
}
}
//MARK: - Private
func saveContext()
{
do
{
try managedObjectContext.save()
}
catch
{
let nserror = error as NSError
NSLog("Unresoved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
|
3ce4112471dfcfe811a0bf2960733326
| 30.050251 | 155 | 0.630685 | false | false | false | false |
huangboju/Eyepetizer
|
refs/heads/master
|
Eyepetizer/Eyepetizer/Controllers/MenuViewController.swift
|
mit
|
1
|
//
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
class MenuViewController: UIViewController, GuillotineMenu {
let titles = ["我的缓存", "功能开关", "我要投稿", "更多应用"]
private let menuViewCellId = "menuViewCellId"
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = UIColor.clearColor()
tableView.tableHeaderView = MenuHeaderView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 200))
tableView.sectionHeaderHeight = 200
tableView.rowHeight = 70
tableView.separatorStyle = .None
tableView.delegate = self
tableView.dataSource = self
return tableView
}()
lazy var dismissButton: UIButton! = {
let dismissButton = UIButton(frame: CGRect(x: 0, y: 0, width: 80, height: 40))
dismissButton.setImage(R.image.ic_action_menu(), forState: .Normal)
dismissButton.addTarget(self, action: #selector(dismissButtonTapped), forControlEvents: .TouchUpInside)
return dismissButton
}()
lazy var titleLabel: UILabel! = {
var titleLabel = UILabel()
titleLabel.numberOfLines = 1
titleLabel.text = "petizer"
titleLabel.textColor = UIColor.blackColor()
titleLabel.sizeToFit()
return titleLabel
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clearColor()
let blurEffect = UIBlurEffect(style: .Light)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = view.bounds
view.addSubview(blurView)
view.addSubview(tableView)
tableView.snp_makeConstraints { make in
make.left.right.bottom.equalTo(view)
make.top.equalTo(view).offset(TOP_BAR_HEIGHT)
}
}
func dismissButtonTapped(sende: UIButton) {
presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension MenuViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titles.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(menuViewCellId)
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: menuViewCellId)
}
cell?.backgroundColor = UIColor.clearColor()
cell?.contentView.backgroundColor = UIColor.clearColor()
cell?.selectionStyle = .None
cell?.textLabel?.textAlignment = .Center
cell?.textLabel?.text = titles[indexPath.row]
return cell!
}
}
|
2dc56a434fe3d4c40c51122e46db90a4
| 35.814815 | 120 | 0.664319 | false | false | false | false |
fitpay/fitpay-ios-sdk
|
refs/heads/develop
|
FitpaySDK/PaymentDevice/SyncQueue/SyncRequest.swift
|
mit
|
1
|
import Foundation
public typealias SyncRequestCompletion = (EventStatus, Error?) -> Void
open class SyncRequest {
static var syncManager: SyncManagerProtocol = SyncManager.sharedInstance
public let requestTime: Date
public let syncId: String?
public private(set) var syncStartTime: Date?
public var syncInitiator: SyncInitiator?
public var notification: NotificationDetail? {
didSet {
FitpayNotificationsManager.sharedInstance.updateRestClientForNotificationDetail(self.notification)
}
}
var isEmptyRequest: Bool {
return user == nil || deviceInfo == nil || paymentDevice == nil
}
var user: User?
var deviceInfo: Device?
var paymentDevice: PaymentDevice?
var completion: SyncRequestCompletion?
private var state = SyncRequestState.pending
// MARK: - Lifecycle
/// Creates sync request.
///
/// - Parameters:
/// - requestTime: time as Date object when request was made. Used for filtering unnecessary syncs. Defaults to Date().
/// - syncId: sync identifier used for not running duplicates
/// - user: User object.
/// - deviceInfo: DeviceInfo object.
/// - paymentDevice: PaymentDevice object.
/// - initiator: syncInitiator Enum object. Defaults to .NotDefined.
/// - notificationAsc: NotificationDetail object.
public init(requestTime: Date = Date(), syncId: String? = nil, user: User, deviceInfo: Device, paymentDevice: PaymentDevice, initiator: SyncInitiator = .notDefined, notification: NotificationDetail? = nil) {
self.requestTime = requestTime
self.syncId = syncId
self.user = user
self.deviceInfo = deviceInfo
self.paymentDevice = paymentDevice
self.syncInitiator = initiator
self.notification = notification
}
/// Create sync request from Notificatoin
///
/// This can be created with no parameters but will never sync as a deviceId is required moving forward
///
/// - Parameters:
/// - notification: Notification Detail created from a FitPay notification
/// - initiator: where the sync is coming from, defaulting to notification
/// - user: The user associated with the notification, defaulting to nil
public init(notification: NotificationDetail? = nil, initiator: SyncInitiator = .notification, user: User? = nil) {
self.requestTime = Date()
self.syncId = notification?.syncId
self.user = user
let deviceInfo = Device()
deviceInfo.deviceIdentifier = notification?.deviceId
self.deviceInfo = deviceInfo
self.paymentDevice = nil
self.syncInitiator = initiator
self.notification = notification
if !SyncRequest.syncManager.synchronousModeOn && isEmptyRequest {
assert(false, "You should pass all params to SyncRequest in parallel sync mode.")
}
}
// MARK: - Internal Functions
func update(state: SyncRequestState) {
if state == .inProgress && syncStartTime == nil {
syncStartTime = Date()
}
self.state = state
}
func syncCompleteWith(status: EventStatus, error: Error?) {
completion?(status, error)
}
func isSameUserAndDevice(otherRequest: SyncRequest) -> Bool {
return user?.id == otherRequest.user?.id && deviceInfo?.deviceIdentifier == otherRequest.deviceInfo?.deviceIdentifier
}
}
|
d1669d08c459236dc03f7914e1b089ce
| 35.75 | 211 | 0.65788 | false | false | false | false |
Asura19/SwiftAlgorithm
|
refs/heads/master
|
SwiftAlgorithm/SwiftAlgorithm/LC054.swift
|
mit
|
1
|
//
// LC054.swift
// SwiftAlgorithm
//
// Created by phoenix on 2022/2/23.
// Copyright © 2022 Phoenix. All rights reserved.
//
import Foundation
struct MatrixSpiralIterator {
typealias Index = (row: Int, col: Int, idx: Int)
let rowCount: Int
let colCount: Int
private var top: Int
private var left: Int
private var bottom: Int
private var right: Int
private let total: Int
init(rowCount: Int, colCount: Int) {
assert(rowCount >= 1 && colCount >= 1)
self.rowCount = rowCount
self.colCount = colCount
self.top = 0
self.left = 0
self.bottom = rowCount - 1
self.right = colCount - 1
total = rowCount * colCount
}
var current: Index?
mutating func next() -> Index? {
guard var c = current else {
current = (0, 0, 0)
return self.current
}
if c.idx == total - 1 {
return nil
}
if rowCount == 1 {
current = c.col < right ? (0, c.col + 1, c.idx + 1) : nil
return current
}
if colCount == 1 {
current = c.row < bottom ? (c.row + 1, 0, c.idx + 1) : nil
return current
}
if c.row == top && c.col < right {
c.col += 1
}
else if c.col == right && c.row < bottom {
c.row += 1
}
else if c.row == bottom && c.col > left {
c.col -= 1
}
else if c.col == left && c.row > top {
c.row -= 1
}
if c.row == top, c.col == left {
top += 1
left += 1
bottom -= 1
right -= 1
c.row = top
c.col = left
}
c.idx += 1
current = c
return current
}
}
extension LeetCode {
static func printMatrixBySpiral<T>(_ matrix: [[T]]) {
guard isMatrix(matrix) else {
assert(false, "not a matrix")
return
}
let rowCount = matrix.count
let colCount = matrix[0].count
var iterator = MatrixSpiralIterator(rowCount: rowCount, colCount: colCount)
while let index = iterator.next() {
print("\(index.idx): \(matrix[index.row][index.col])")
}
}
private static func isMatrix<T>(_ matrix: [[T]]) -> Bool {
if matrix.count == 0 { return false }
let colCount = matrix[0].count
return matrix.filter { $0.count != colCount }.count == 0
}
}
|
96df5a80bcd1d4409f42aeec6fc2c7ae
| 23.257143 | 83 | 0.485669 | false | false | false | false |
Bruno-Furtado/holt_winters
|
refs/heads/master
|
HoltWinters/main.swift
|
mit
|
1
|
//
// main.swift
// HoltWinters
//
// Created by Bruno Tortato Furtado on 03/05/16.
// Copyright © 2016 Bruno Tortato Furtado. All rights reserved.
//
import Foundation
let dataFileName = "input.txt"
let forecastingFileName = "forecasting.csv"
let errorsFileName = "errors.csv"
let s: Int = 3
let alpha: Float = 0.3
let beta: Float = 0.3
let gamma: Float = 0.3
print("Processing has been started.")
print("Waiting...")
let controller = Controller(dataFileName: dataFileName, s: s, alpha: alpha, beta: beta, gamma: gamma)
controller.saveResultAtFiles(forecastingFileName, errorsFileName: errorsFileName, forecastingCompletion:
{ (forecastingSaved) in
if (forecastingSaved) {
print("Forecasting has been saved successfully.")
} else {
print("Forecasting has not been saved.")
}
}) { (errorsSaved) in
if (errorsSaved) {
print("Erros has been saved successfully.")
} else {
print("Erros has not been saved.")
}
}
print("")
|
75b84463f876d5b7bdf5d2631dd5bf82
| 23.65 | 104 | 0.686294 | false | false | false | false |
FoodForTech/Handy-Man
|
refs/heads/1.0.0
|
HandyMan/HandyMan/Features/Login/Views/LoginAnimateView.swift
|
mit
|
1
|
//
// LoginAnimateView.swift
// HandyMan
//
// Created by Don Johnson on 5/3/16.
// Copyright © 2016 Don Johnson. All rights reserved.
//
import UIKit
final class LoginAnimateView: DesignableView {
override func draw(_ rect: CGRect) {
if let color = backgroundColor {
color.setFill()
}
UIRectFill(rect)
let layer = CAShapeLayer()
let path = CGMutablePath()
_ = CGMutablePath.addEllipse(path)
_ = CGMutablePath.addRect(path)
layer.path = path
layer.fillRule = kCAFillRuleEvenOdd
self.layer.mask = layer
}
}
|
aa722fd9285fbbcb6c5042f00b3a9214
| 20.633333 | 54 | 0.577812 | false | false | false | false |
visenze/visearch-sdk-swift
|
refs/heads/master
|
ViSearchSDK/Carthage/Checkouts/visenze-tracking-swift/ViSenzeAnalytics/ViSenzeAnalytics/Classes/Helper/SettingHelper.swift
|
mit
|
1
|
//
// SettingHelper.swift
// ViSenzeAnalytics
//
// Created by Hung on 8/9/20.
// Copyright © 2020 ViSenze. All rights reserved.
//
import UIKit
open class SettingHelper: NSObject {
public static func setBoolSettingProp(propName: String , newValue: Bool) -> Void {
let userDefault = UserDefaults.standard
userDefault.set(newValue, forKey: propName)
}
public static func getBoolSettingProp (propName: String) -> Bool? {
let userDefault = UserDefaults.standard
return userDefault.bool(forKey: propName)
}
public static func getInt64Prop(propName: String) -> Int64 {
if let storeString = getStringSettingProp(propName: propName) {
if let num = Int64(storeString) {
return num
}
}
return 0;
}
public static func setInt64Prop(propName: String, newValue: Int64) {
return setSettingProp(propName: propName, newValue: String(newValue))
}
/// Set a property , store in userDefault
///
/// - parameter propName: property name
/// - parameter newValue: new value for property
public static func setSettingProp(propName: String , newValue: Any?) -> Void {
let userDefault = UserDefaults.standard
userDefault.set(newValue, forKey: propName)
}
/// retrieve setting in userdefault as String
///
/// - parameter propName: name of property
///
/// - returns: value as String?
public static func getStringSettingProp (propName: String) -> String? {
let userDefault = UserDefaults.standard
return userDefault.string(forKey: propName)
}
}
|
0c3c34d8b748c2a59b788d3752c018a4
| 29.053571 | 86 | 0.639335 | false | false | false | false |
RaviDesai/RSDRestServices
|
refs/heads/master
|
Pod/Classes/ModelResourceProtocol.swift
|
mit
|
1
|
//
// ModelResourceProtocol.swift
// Pods
//
// Created by Ravi Desai on 1/8/16.
//
//
import Foundation
import RSDSerialization
public enum ModelResourceVersionRepresentation {
case URLVersioning
case CustomRequestHeader
case CustomContentType
}
public protocol ModelResource : ModelItem {
typealias T : ModelItem = Self
static var resourceApiEndpoint: String { get }
static var resourceName: String { get }
static var resourceVersion: String { get }
static var resourceVersionRepresentedBy: ModelResourceVersionRepresentation { get }
static var resourceVendor: String { get }
static func getAll(session: APISession, completionHandler: ([T]?, NSError?) -> ())
static func get(session: APISession, resourceId: NSUUID, completionHandler: (T?, NSError?) -> ())
func save(session: APISession, completionHandler: (T?, NSError?) -> ())
func create(session: APISession, completionHandler: (T?, NSError?) -> ())
func delete(session: APISession, completionHandler: (NSError?) -> ())
}
private let invalidId = NSError(domain: "com.github.RaviDesai", code: 48118002, userInfo: [NSLocalizedDescriptionKey: "Invalid ID", NSLocalizedFailureReasonErrorKey: "Invalid ID"])
public extension ModelResource {
static var customResourceHeaderWithVendorAndVersion: String {
get {
return "\(resourceVendor).v\(resourceVersion)"
}
}
static var versionedResourceEndpoint: String {
get {
if resourceVersionRepresentedBy == ModelResourceVersionRepresentation.URLVersioning {
return "\(Self.resourceApiEndpoint)/v\(Self.resourceVersion)/\(Self.resourceName)"
}
return "\(Self.resourceApiEndpoint)/\(Self.resourceName)"
}
}
static var additionalHeadersForRequest: [String: String]? {
get {
if resourceVersionRepresentedBy == ModelResourceVersionRepresentation.CustomRequestHeader {
return ["api-version": resourceVersion]
}
return nil
}
}
static func getAll(session: APISession, completionHandler: ([T]?, NSError?)->()) {
let endpoint = APIEndpoint.GET(URLAndParameters(url: Self.versionedResourceEndpoint))
let parser = APIJSONSerializableResponseParser<T>(versionRepresentation: Self.resourceVersionRepresentedBy, vendor: Self.resourceVendor, version: Self.resourceVersion)
let request = APIRequest(baseURL: session.baseURL, endpoint: endpoint, bodyEncoder: nil, responseParser: parser, additionalHeaders: Self.additionalHeadersForRequest)
let call = APICall(session: session, request: request)
call.executeRespondWithArray(completionHandler)
}
static func get(session: APISession, resourceId: NSUUID, completionHandler: (T?, NSError?) -> ()) {
let uuid = resourceId.UUIDString
let endpoint = APIEndpoint.GET(URLAndParameters(url: "\(Self.versionedResourceEndpoint)/\(uuid)"))
let parser = APIJSONSerializableResponseParser<T>(versionRepresentation: Self.resourceVersionRepresentedBy, vendor: Self.resourceVendor, version: Self.resourceVersion)
let request = APIRequest(baseURL: session.baseURL, endpoint: endpoint, bodyEncoder: nil, responseParser: parser, additionalHeaders: Self.additionalHeadersForRequest)
let call = APICall(session: session, request: request)
call.executeRespondWithObject(completionHandler)
}
func save(session: APISession, completionHandler: (T?, NSError?) -> ()) {
if let uuid = self.id?.UUIDString {
let endpoint = APIEndpoint.PUT(URLAndParameters(url: "\(Self.versionedResourceEndpoint)/\(uuid)"))
let parser = APIJSONSerializableResponseParser<T>(versionRepresentation: Self.resourceVersionRepresentedBy, vendor: Self.resourceVendor, version: Self.resourceVersion)
let encoder = APIJSONBodyEncoder(model: self)
let request = APIRequest(baseURL: session.baseURL, endpoint: endpoint, bodyEncoder: encoder, responseParser: parser, additionalHeaders: Self.additionalHeadersForRequest)
let call = APICall(session: session, request: request)
call.executeRespondWithObject(completionHandler)
} else {
completionHandler(nil, invalidId)
}
}
func create(session: APISession, completionHandler: (T?, NSError?) -> ()) {
if self.id?.UUIDString == nil {
let endpoint = APIEndpoint.POST(URLAndParameters(url: Self.versionedResourceEndpoint))
let parser = APIJSONSerializableResponseParser<T>(versionRepresentation: Self.resourceVersionRepresentedBy, vendor: Self.resourceVendor, version: Self.resourceVersion)
let encoder = APIJSONBodyEncoder(model: self)
let request = APIRequest(baseURL: session.baseURL, endpoint: endpoint, bodyEncoder: encoder, responseParser: parser, additionalHeaders: Self.additionalHeadersForRequest)
let call = APICall(session: session, request: request)
call.executeRespondWithObject(completionHandler)
} else {
completionHandler(nil, invalidId)
}
}
func delete(session: APISession, completionHandler: (NSError?) -> ()) {
if let uuid = self.id?.UUIDString {
let endpoint = APIEndpoint.DELETE(URLAndParameters(url: "\(Self.versionedResourceEndpoint)/\(uuid)"))
let parser = APIJSONSerializableResponseParser<T>(versionRepresentation: Self.resourceVersionRepresentedBy, vendor: Self.resourceVendor, version: Self.resourceVersion)
let encoder = APIJSONBodyEncoder(model: self)
let request = APIRequest(baseURL: session.baseURL, endpoint: endpoint, bodyEncoder: encoder, responseParser: parser, additionalHeaders: Self.additionalHeadersForRequest)
let call = APICall(session: session, request: request)
call.execute(completionHandler)
} else {
completionHandler(invalidId)
}
}
}
|
ba758aae1aa47ac2de65edc605eb6293
| 51.025862 | 181 | 0.702188 | false | false | false | false |
Dougly/2For1
|
refs/heads/master
|
2for1/UIViewExtension.swift
|
mit
|
1
|
//
// ViewExtension.swift
// 2for1
//
// Created by Douglas Galante on 12/24/16.
// Copyright © 2016 Flatiron. All rights reserved.
//
import UIKit
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
func constrain(_ view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
view.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
view.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
view.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
view.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
}
class func applyGradient(to view: UIView, topColor: UIColor, bottomColor: UIColor) {
let gradient: CAGradientLayer = CAGradientLayer()
gradient.bounds = view.bounds
gradient.frame = view.bounds
gradient.colors = [topColor.cgColor , bottomColor.cgColor]
view.layer.insertSublayer(gradient, at: 0)
}
}
|
a913efb3c2617ff9c30b1aeaea16345f
| 27.186047 | 88 | 0.65099 | false | false | false | false |
andrewBatutin/SwiftYamp
|
refs/heads/master
|
Pods/ByteBackpacker/ByteBackpacker/ByteBackpacker.swift
|
mit
|
1
|
/*
This file is part of ByteBackpacker Project. It is subject to the license terms in the LICENSE file found in the top-level directory of this distribution and at https://github.com/michaeldorner/ByteBackpacker/blob/master/LICENSE. No part of ByteBackpacker Project, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the LICENSE file.
*/
import Foundation
public typealias Byte = UInt8
public enum ByteOrder {
case bigEndian
case littleEndian
static let nativeByteOrder: ByteOrder = (Int(CFByteOrderGetCurrent()) == Int(CFByteOrderLittleEndian.rawValue)) ? .littleEndian : .bigEndian
}
open class ByteBackpacker {
private static let referenceTypeErrorString = "TypeError: Reference Types are not supported."
open class func unpack<T: Any>(_ valueByteArray: [Byte], byteOrder: ByteOrder = .nativeByteOrder) -> T {
assert(!(T.self is AnyClass), ByteBackpacker.referenceTypeErrorString)
let bytes = (byteOrder == .littleEndian) ? valueByteArray : valueByteArray.reversed()
return bytes.withUnsafeBufferPointer {
return $0.baseAddress!.withMemoryRebound(to: T.self, capacity: 1) {
$0.pointee
}
}
}
open class func unpack<T: Any>(_ valueByteArray: [Byte], toType type: T.Type, byteOrder: ByteOrder = .nativeByteOrder) -> T {
assert(!(T.self is AnyClass), ByteBackpacker.referenceTypeErrorString)
let bytes = (byteOrder == .littleEndian) ? valueByteArray : valueByteArray.reversed()
return bytes.withUnsafeBufferPointer {
return $0.baseAddress!.withMemoryRebound(to: T.self, capacity: 1) {
$0.pointee
}
}
}
open class func pack<T: Any>( _ value: T, byteOrder: ByteOrder = .nativeByteOrder) -> [Byte] {
assert(!(T.self is AnyClass), ByteBackpacker.referenceTypeErrorString)
var value = value // inout works only for var not let types
let valueByteArray = withUnsafePointer(to: &value) {
Array(UnsafeBufferPointer(start: $0.withMemoryRebound(to: Byte.self, capacity: 1){$0}, count: MemoryLayout<T>.size))
}
return (byteOrder == .littleEndian) ? valueByteArray : valueByteArray.reversed()
}
}
public extension Data {
func toByteArray() -> [Byte] {
let count = self.count / MemoryLayout<Byte>.size
var array = [Byte](repeating: 0, count: count)
copyBytes(to: &array, count:count * MemoryLayout<Byte>.size)
return array
}
}
|
ee03f44353ba6a8bf7f8b25c2cf4ea0e
| 38.318182 | 398 | 0.674759 | false | false | false | false |
f2m2/f2m2-swift-forms
|
refs/heads/master
|
FormGenerator/FormGenerator/FormGenerator/FormController.swift
|
mit
|
3
|
//
// FormSerializerClasses.swift
// FormSerializer
//
// Created by Michael L Mork on 12/1/14.
// Copyright (c) 2014 f2m2. All rights reserved.
//
import Foundation
import UIKit
/**
Simple convenience extensions on FormControllerProtocol-conforming UIViewController; tableview is provided and added.
*/
extension UIViewController: FormControllerProtocol {
/**
Convenience on convenience; provide only the form data data.
:param: data FormObjectProtocol-conforming objects.
:return: FormController a formController.
*/
public func newFormController (data: [FormObjectProtocol]) -> FormController {
return newFormController(data, headerView: nil)
}
/**
Provide data and a header view for a tableview which is added to self.
:param: data FormObjectProtocol-conforming objects.
:param: headerView an optional custom header for the tableView
:return: FormController a formController.
*/
public func newFormController (data: [FormObjectProtocol], headerView: UIView?) -> FormController {
let tableView = UITableView(frame: CGRectZero)
view.addSubview(tableView)
layout(tableView, view) { (TableView, View) -> () in
TableView.edges == inset(View.edges, 20, 0, 0, 0); return
}
if let headerView = headerView as UIView! {
tableView.tableHeaderView = headerView
}
let formController = FormController(data: data, tableView: tableView)
formController.delegate = self
return formController
}
}
/**
The EntityController holds the FormSerializationProtocol collection.
It sorts this collection in order to find the data which will be displayed.
It sorts to find the number of sections.
It sets its displayed data values as the interface is manipulated.
Meant-For-Consumption functions include:
/// - init: init with FormSerializationProtocol-conforming objects.
/// - validateForm: Validate all FormObjectProtocol objects which implement isValid().
/// - assembleSubmissionDictionary: Assemble a network SubmissionDictionary from the values set on the display data which are implementing the key variable in FormObjectProtocol.
/// - updateDataModelWithIdentifier: Update a FormObjectProtocolObject with a value and its user - given identifier.
*/
@objc public class FormController: NSObject, UITableViewDataSource, UITableViewDelegate {
let data: [FormObjectProtocol]
var delegate: FormControllerProtocol?
var tableView: UITableView
var customFormObjects: [String: FormObjectProtocol] = [String: FormObjectProtocol]()
var sectionHeaderTitles: [String] = [String]()
lazy var displayData: [FormObjectProtocol] = {
var mData = self.data
mData = sorted(mData) {
f0, f01 in
//Display order here.
return f0.rowIdx < f01.rowIdx
}
var nData = mData.filter { (T) -> Bool in
//filter whether to display here.
T.displayed == true
}
return nData
}()
/********
public
********/
/**
init with data conforming to the FormSerializationProtocol.
:param: data An array of objects conforming to the FormSerializationProtocol
:returns: self
*/
init(data: [FormObjectProtocol], tableView: UITableView) {
self.data = data
self.tableView = tableView
super.init()
tableView.registerClass(FormCell.self, forCellReuseIdentifier: "Cell")
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
}
/**
Update the data model with identifier and the new value.
:param: identifier A string assigned to a given
:param: newValue Whatever type of anyObject the user desires to set on the given identifier's FormObjectProtocol object.
*/
func updateDataModelWithIdentifier(identifier: String, newValue: AnyObject) {
// if let formObject = customFormObjects?[identifier] as FormObjectProtocol? {
println("update data model: \(customFormObjects)")
updateDataModel(customFormObjects[identifier])
}
/**
Update the data model with a unique ForhObjectProtocol object.
:param: object A FormObjectProtocol object
*/
func updateDataModel(object: FormObjectProtocol?) {
if let object = object as FormObjectProtocol? {
let index = collectionIndexOfObjectInSection(object.rowIdx, itemIndexInSection: object.sectionIdx)
self.displayData.removeAtIndex(index)
self.displayData.insert(object, atIndex: index)
/*
This is an example of optional chaining.
The delegate may or may not exist (an optional), and it may or may not be implementing formValueChanged.
This is what the question marks are delineating.
*/
self.delegate?.formValueChanged?(object)
let indexPath = NSIndexPath(forRow: object.rowIdx, inSection: object.sectionIdx)
if object.reloadOnValueChange == true {
println("\n reloading index at row: \n\n indexPath row: \(indexPath.row) \n indexPath section: \(indexPath.section) \n\n")
tableView.reloadRowsAtIndexPaths([indexPath as NSIndexPath], withRowAnimation: UITableViewRowAnimation.None)
}
//tableView.reloadData()
}
}
/**
Check form objects implementing this method for being valid
:return: An array of validation error strings to be presented however the user wishes.
*/
func validateFormItems(formItemIsValid: FieldNeedsValidation) -> (Bool) {
var isValid = true
var dataThatValidates = data.filter { (filtered: FormObjectProtocol) -> Bool in
filtered.needsValidation == true
}
for protocolObject in dataThatValidates {
if let formIsValid = formItemIsValid(value: protocolObject) as Bool? {
if formIsValid == false {
isValid = false
}
}
}
return isValid
}
/**
Assemble a urlRequest form dictionary.
:return: a urlRequest form dictionary.
*/
func assembleSubmissionDictionary() -> NSDictionary {
var nData = data.filter { (FieldObject) -> Bool in
//Get data which is not being displayed; its value is required and already provided.
FieldObject.displayed == false
}
//Append the display data to nData.
nData += displayData
var filteredData = nData.filter { (T) -> Bool in
var hasKey = false
if let keyAsString = T.key as String? {
if countElements(keyAsString) > 0 {
hasKey = true
}
}
return hasKey == true
}
let mDict: NSMutableDictionary = NSMutableDictionary()
for kV in filteredData {
mDict.setValue(kV.value, forKey: kV.key)
}
return mDict.copy() as NSDictionary
}
/********
private
********/
/**
Compute number of sections for the data.
:return: number of sections for the data.
*/
private func numberOfSections() -> (Int) {
var prevIdx = 0
var mSectionsCount: NSMutableDictionary = NSMutableDictionary()
for data in displayData {
var numSectionsForIdx = mSectionsCount[String(data.sectionIdx)] as Int!
if let sectionsCount = numSectionsForIdx as Int! {
var section = sectionsCount
mSectionsCount.setValue(++section, forKey: String(data.sectionIdx))
} else {
mSectionsCount.setValue(0, forKey: String(data.sectionIdx))
}
++prevIdx
}
return mSectionsCount.allKeys.count
}
func numberOfItemsInSection(section: Int) -> (Int) {
return displayDataForSection(section).count
}
/**
Called in CellForRowAtIndexPath.
:param: FormCell The cell to configure to display its data for the display data for section and row.
:param: NSIndexPath Pretty standard, really.
*/
private func formCellForRowAtIndexPath(cell: UITableViewCell, indexPath: NSIndexPath) {
if let cell = cell as? FormCell {
let displayData = displayDataForSection(indexPath.section)
//A sanity check
if indexPath.row < displayData.count {
var field = displayData[indexPath.row]
requestViewObject(field, cell: cell, {value in
/*
Upon a value change, set the field's value to the new value and replace the current model's object.
*/
field.value = value
self.updateDataModel(field)
})
}
}
}
/**
Filter the display data for the corresponding section.
:param: The section idx.
:returns: Array of
*/
private func displayDataForSection(sectionIdx: Int) -> ([FormObjectProtocol]) {
var dataForSection = displayData.filter { (T) -> Bool in
return T.sectionIdx == sectionIdx
}
dataForSection = dataForSection.sorted { (previous, current) -> Bool in
previous.rowIdx < current.rowIdx
}
return dataForSection
}
/**
Determine the enum then call the associated function, passing an optional UI element. (the cell will create one on its own otherwise)
:param: FormObjectProtocol: an FOP conforming object
:param: FormCell: a form cell
:param: ValueDidChange:
*/
private func requestViewObject(field: FormObjectProtocol, cell: FormCell, valueChangeCallback: FieldDidChange) {
//update the custom field values
if let fieldId = field.identifier as String! {
if fieldId != "" {
customFormObjects.updateValue(field, forKey: fieldId)
println("field added to customFormObjects: \(customFormObjects)")
}
}
let type = UIType(rawValue: field.uiType)
switch type! {
case .TypeNone:
return
case .TypeTextField:
cell.addTextField(delegate?.textFieldForFormObject?(field, aTextField: UITextField()))
case .TypeASwitch:
println("switch value bein set to: \(field.value)")
let aNewSwitch = UISwitch()
aNewSwitch.setOn(field.value as Bool, animated: true)
cell.addSwitch(delegate?.accompanyingLabel?(field, aLabel: UILabel()), aSwitch: delegate?.switchForFormObject?(field, aSwitch: aNewSwitch))
case .TypeCustomView:
cell.addCustomView(delegate?.customViewForFormObject?(field, aView: UIView()))
}
cell.valueDidChange = valueChangeCallback
}
private func collectionIndexOfObjectInSection(section: Int, itemIndexInSection: Int) -> (Int) {
let map = sectionsMap()
var totalCount = 0
for key in map.allKeys {
let count = key.integerValue
let sectionIdx = map[String(key as NSString)] as Int
if sectionIdx < section {
totalCount += count
}
if sectionIdx == section {
totalCount += itemIndexInSection
}
}
return totalCount
}
private func sectionsMap () -> (NSDictionary) {
var prevIdx = 0
var mSectionsCount: NSMutableDictionary = NSMutableDictionary()
for data in displayData {
var numSectionsForIdx = mSectionsCount[String(data.sectionIdx)] as Int!
if let sectionsCount = numSectionsForIdx as Int! {
var section = sectionsCount
mSectionsCount.setValue(++section, forKey: String(data.sectionIdx))
} else {
mSectionsCount.setValue(0, forKey: String(data.sectionIdx))
}
++prevIdx
}
return mSectionsCount.copy() as NSDictionary
}
/*
**************************
tableView delegate methods
**************************
*/
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfItemsInSection(section) // filteredArrayCount
}
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return numberOfSections()
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: AnyObject? = tableView.dequeueReusableCellWithIdentifier("Cell")
formCellForRowAtIndexPath(cell as UITableViewCell, indexPath: indexPath)
return cell as UITableViewCell
}
public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var title = ""
if section < sectionHeaderTitles.count {
title = sectionHeaderTitles[section]
}
return title
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let displayData = displayDataForSection(indexPath.section)
//A sanity check
if indexPath.row < displayData.count {
var field = displayData[indexPath.row]
delegate?.didSelectFormObject?(field)
}
}
}
|
e3239ec3bfba3381baecc9c8f42110e0
| 28.809055 | 178 | 0.563561 | false | false | false | false |
MIPsoft/miauth-ios-sampleApp
|
refs/heads/master
|
miauth-ios-sampleApp/MiauthClient.swift
|
mit
|
1
|
//
// miauthClient.swift
// miauth-ios-sampleApp
//
// Created by developer on 03/04/16.
// Copyright © 2016 MIPsoft. All rights reserved.
//
import Foundation
import UIKit
enum AuthenticationState {
case Unknown
case Ok
case Fail
}
class MiauthClient {
static let sharedInstance = MiauthClient()
var registeredCallback: [()->()] = []
var authenticationState: AuthenticationState = .Unknown
var authenticationData: [String: String] = [:]
init() {
}
private func miauthIsInstalled() -> Bool {
if let miauthURL:NSURL = NSURL(string:"miauth://test") {
let application:UIApplication = UIApplication.sharedApplication()
if (application.canOpenURL(miauthURL)) {
return true
}
}
return false
}
func buttonTitle() -> String {
if !miauthIsInstalled() {
return "Asenna miauth-sovellus";
}
else {
return "Tunnistaudu miauth-sovelluksella"
}
}
func authenticate( callback:()->() ) -> Bool {
if let miauthURL:NSURL = NSURL(string:"miauth://authenticate?callbackurl=com.mipsoft.miauth-ios-sampleApp&app=miAuth-esimerkkiohjelma") {
let application:UIApplication = UIApplication.sharedApplication()
registeredCallback = [callback]
application.openURL(miauthURL);
return true
}
return false
}
func callBackURL(url: NSURL, fromApplication: String?) -> Bool {
if fromApplication == "com.mipsoft.miauth" {
print("Received \(url) from \(fromApplication) host=\(url.host)")
//TODO: Dynaaminen parseri
if url.host == "authentication" {
authenticationState = .Fail
authenticationData = [:]
if let params = NSURLComponents(URL: url, resolvingAgainstBaseURL: false)?.queryItems,
data = params.filter({ $0.name == "status" }).first,
value = data.value {
if value=="true" {
authenticationState = .Ok
}
authenticationData[data.name] = data.value
}
for key:String in ["name","email","address"] {
if let params = NSURLComponents(URL: url, resolvingAgainstBaseURL: false)?.queryItems,
data = params.filter({ $0.name == key}).first,
value = data.value {
authenticationData[data.name] = value
}
}
} //authenticate
if ( registeredCallback.count>0 ) {
let function: ()->() = registeredCallback[0]
function()
}
return false;
}
return true;
}
}
|
0461bb607412adbe1626f4b5b9dd617b
| 29.8125 | 145 | 0.526031 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
refs/heads/develop
|
Rocket.Chat/Views/Chat/New Chat/ChatItems/MessageReplyThreadChatItem.swift
|
mit
|
1
|
//
// MessageReplyThreadChatItem.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 17/04/19.
// Copyright © 2019 Rocket.Chat. All rights reserved.
//
import Foundation
import DifferenceKit
import RocketChatViewController
final class MessageReplyThreadChatItem: BaseMessageChatItem, ChatItem, Differentiable {
var isSequential: Bool = false
var relatedReuseIdentifier: String {
return ThreadReplyCollapsedCell.identifier
}
init(user: UnmanagedUser?, message: UnmanagedMessage?, sequential: Bool = false) {
super.init(user: user, message: message)
isSequential = sequential
}
internal var threadName: String? {
guard
!isSequential,
let message = message
else {
return nil
}
return message.mainThreadMessage
}
var differenceIdentifier: String {
return message?.identifier ?? ""
}
func isContentEqual(to source: MessageReplyThreadChatItem) -> Bool {
guard let message = message, let sourceMessage = source.message else {
return false
}
return message == sourceMessage
}
}
|
85e4ae232ac8e844730d7ffce5ba9228
| 24.042553 | 87 | 0.660153 | false | false | false | false |
Detailscool/YHRefresh
|
refs/heads/master
|
YHRefreshDemo/DemoViewController.swift
|
mit
|
1
|
//
// DemoViewController.swift
// YHRefresh
//
// Created by HenryLee on 16/8/30.
// Copyright © 2016年 HenryLee. All rights reserved.
//
import UIKit
import YHRefresh
class DemoViewController: UITableViewController {
var numbers = [Int]()
var s = 0
var style : YHRefreshStyle
init(style:YHRefreshStyle) {
self.style = style
super.init(style: .plain)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Test
/*
tableView.rowHeight = 10;
tableView.tableFooterView = UIView()
tableView.contentInset.bottom = 50
let bottomView = UIView(frame: CGRect(x: 0, y: yh_ScreenH - 50, width: yh_ScreenW, height: 50))
bottomView.backgroundColor = UIColor.redColor()
UIApplication.sharedApplication().keyWindow!.addSubview(bottomView)
*/
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
for i in s..<s+20 {
numbers.append(i)
}
switch style{
case .normalHeader :
tableView.yh_header = YHRefreshNormalHeader.header(self, selector: #selector(DemoViewController.loadData))
case .springHeader :
tableView.yh_header = YHRefreshSpringHeader.header(self, selector: #selector(DemoViewController.loadData))
case .gifHeader :
let header = YHRefreshGifHeader.header(self, selector: #selector(DemoViewController.loadData))
var refreshingImages = [UIImage]()
for i in 1...3 {
let image = UIImage(named: String(format:"dropdown_loading_0%zd", i))
refreshingImages.append(image!)
}
var nomalImages = [UIImage]()
for i in 1...60 {
let image = UIImage(named: String(format:"dropdown_anim__000%zd", i))
nomalImages.append(image!)
}
header.setGifHeader(nomalImages, state: YHRefreshState.normal)
header.setGifHeader(refreshingImages, state: YHRefreshState.willRefresh)
header.setGifHeader(refreshingImages, state: YHRefreshState.refreshing)
tableView.yh_header = header
case .materialHeader :
let header = YHRefreshMaterialHeader.header(self, selector: #selector(DemoViewController.loadData))
header.shouldStayOnWindow = true
tableView.yh_header = header
case .normalFooter :
tableView.yh_footer = YHRefreshNormalFooter.footer(self, selector: #selector(DemoViewController.loadData))
case .autoFooter :
tableView.yh_footer = YHRefreshAutoFooter.footer(self, selector: #selector(DemoViewController.loadData))
case .gifFooter :
let footer = YHRefreshGifFooter.footer(self, selector: #selector(DemoViewController.loadData))
var refreshingImages = [UIImage]()
for i in 1...3 {
let image = UIImage(named: String(format:"dropdown_loading_0%zd", i))
refreshingImages.append(image!)
}
var nomalImages = [UIImage]()
for i in 1...60 {
let image = UIImage(named: String(format:"dropdown_anim__000%zd", i))
nomalImages.append(image!)
}
footer.setGifFooter(nomalImages, state: YHRefreshState.normal)
footer.setGifFooter(refreshingImages, state: YHRefreshState.willRefresh)
footer.setGifFooter(refreshingImages, state: YHRefreshState.refreshing)
tableView.yh_footer = footer
}
// tableView.yh_footer?.showNoMoreData()
}
@objc func loadData() {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double((Int64)(2 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: { () -> Void in
self.s += 20
for i in self.s..<self.s+20 {
self.numbers.append(i)
}
self.tableView.reloadData()
switch self.style {
case .normalHeader :
self.tableView.yh_header?.endRefreshing()
case .springHeader :
self.tableView.yh_header?.endRefreshing()
case .gifHeader :
self.tableView.yh_header?.endRefreshing()
case .materialHeader :
self.tableView.yh_header?.endRefreshing()
case .normalFooter :
self.tableView.yh_footer?.endRefreshing()
case .autoFooter :
self.tableView.yh_footer?.endRefreshing()
case .gifFooter :
self.tableView.yh_footer?.endRefreshing()
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numbers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier")
cell!.textLabel?.text = "\(indexPath.row)"
cell?.textLabel?.textColor = UIColor.white
return cell!
}
func colorforIndex(_ index: Int) -> UIColor {
let itemCount = numbers.count - 1
let color = (CGFloat(index) / CGFloat(itemCount)) * 0.6
return UIColor(red: color, green: 0.0, blue: 1.0, alpha: 1.0)
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = colorforIndex(indexPath.row)
}
}
|
9200347eeaccceba86b95d8fffeae54f
| 33.139785 | 151 | 0.562677 | false | false | false | false |
ethanneff/iOS-Swift-Animated-Reorder-And-Indent
|
refs/heads/master
|
NotesApp/Task.swift
|
mit
|
1
|
//
// Tasks.swift
// NotesApp
//
// Created by Ethan Neff on 4/4/16.
// Copyright © 2016 Ethan Neff. All rights reserved.
//
import Foundation
class Task: NSObject, NSCoding, DataCompleteable, DataCollapsible, DataIndentable, DataTagable {
// PROPERTIES
var title: String
var body: String?
var tags: [Tag] = []
var indent: Int = 0
var collapsed: Bool = false
var children: Int = 0
var completed: Bool = false
override var description: String {
return "\(title) \(indent) \(collapsed)" // | \(collapsed)"
}
// INIT
init?(title: String, body: String?, tags: [Tag], indent: Int, collapsed: Bool, children: Int, completed: Bool) {
self.title = title
self.body = body
self.tags = tags
self.indent = indent
self.collapsed = collapsed
self.children = children
self.completed = completed
super.init()
if title.isEmpty {
return nil
}
}
convenience init?(title: String) {
self.init(title: title, body: nil, tags: [], indent: 0, collapsed: false, children: 0, completed: false)
}
convenience init?(title: String, indent: Int) {
self.init(title: title, body: nil, tags: [], indent: indent, collapsed: false, children: 0, completed: false)
}
// METHODS
class func loadTestData() -> [Task] {
var array = [Task]()
array.append(Task(title: "0", indent: 0)!)
array.append(Task(title: "1", indent: 1)!)
array.append(Task(title: "2", indent: 1)!)
array.append(Task(title: "3", indent: 2)!)
array.append(Task(title: "4", indent: 3)!)
array.append(Task(title: "5", indent: 2)!)
array.append(Task(title: "6", indent: 0)!)
array.append(Task(title: "7", indent: 1)!)
array.append(Task(title: "8", indent: 2)!)
array.append(Task(title: "9", indent: 0)!)
array.append(Task(title: "1.0.0", indent: 0)!)
array.append(Task(title: "1.1.0", indent: 1)!)
array.append(Task(title: "1.2.0", indent: 1)!)
array.append(Task(title: "1.2.1", indent: 2)!)
array.append(Task(title: "1.2.2", indent: 2)!)
array.append(Task(title: "1.3.0", indent: 1)!)
array.append(Task(title: "1.3.1", indent: 2)!)
array.append(Task(title: "1.3.2", indent: 2)!)
array.append(Task(title: "1.4.0", indent: 1)!)
array.append(Task(title: "2.0.0", indent: 0)!)
array.append(Task(title: "2.1.0", indent: 1)!)
array.append(Task(title: "2.2.0", indent: 1)!)
array.append(Task(title: "2.2.2", indent: 2)!)
array.append(Task(title: "2.3.0", indent: 1)!)
array.append(Task(title: "2.3.1", indent: 2)!)
array.append(Task(title: "2.3.2", indent: 2)!)
array.append(Task(title: "2.4.0", indent: 1)!)
array.append(Task(title: "3.0.0", indent: 0)!)
array.append(Task(title: "3.1.0", indent: 1)!)
array.append(Task(title: "3.1.1", indent: 2)!)
array.append(Task(title: "3.1.2", indent: 2)!)
array.append(Task(title: "3.1.3", indent: 2)!)
array.append(Task(title: "3.2.0", indent: 1)!)
array.append(Task(title: "4.0.0", indent: 0)!)
array.append(Task(title: "5.0.0", indent: 0)!)
array.append(Task(title: "5.1.0", indent: 1)!)
array.append(Task(title: "5.2.0", indent: 1)!)
array.append(Task(title: "5.2.1", indent: 2)!)
array.append(Task(title: "5.2.2", indent: 2)!)
array.append(Task(title: "5.3.0", indent: 1)!)
array.append(Task(title: "5.4.0", indent: 1)!)
array.append(Task(title: "6.0.0", indent: 0)!)
array.append(Task(title: "6.1.0", indent: 1)!)
array.append(Task(title: "6.2.0", indent: 1)!)
array.append(Task(title: "6.2.1", indent: 2)!)
array.append(Task(title: "6.2.2", indent: 2)!)
array.append(Task(title: "6.3.0", indent: 1)!)
array.append(Task(title: "6.4.0", indent: 1)!)
array.append(Task(title: "8.0.0", indent: 0)!)
array.append(Task(title: "7.0.0", indent: 0)!)
array.append(Task(title: "7.1.0", indent: 1)!)
array.append(Task(title: "7.1.1", indent: 2)!)
array.append(Task(title: "7.1.2", indent: 2)!)
array.append(Task(title: "7.1.3", indent: 2)!)
array.append(Task(title: "7.2.0", indent: 1)!)
array.append(Task(title: "7.2.1", indent: 2)!)
array.append(Task(title: "7.2.2", indent: 2)!)
array.append(Task(title: "9.0.0", indent: 0)!)
// array.append(Task(title: "9.1.0", indent: 0)!)
// array.append(Task(title: "9.1.1", indent: 0)!)
// array.append(Task(title: "9.1.2", indent: 0)!)
// array.append(Task(title: "9.1.3", indent: 0)!)
// array.append(Task(title: "9.2.0", indent: 0)!)
// array.append(Task(title: "9.0.0", indent: 0)!)
// array.append(Task(title: "9.0.0", indent: 0)!)
// array.append(Task(title: "9.1.0", indent: 0)!)
// array.append(Task(title: "9.1.1", indent: 0)!)
// array.append(Task(title: "9.1.2", indent: 0)!)
// array.append(Task(title: "9.1.3", indent: 0)!)
// array.append(Task(title: "9.2.0", indent: 0)!)
array.append(Task(title: "envision who you want to become in 2 minutes", indent: 0)!)
return array
}
// SAVE
struct PropertyKey {
static let title = "title"
static let body = "body"
static let tags = "tags"
static let indent = "indent"
static let collapsed = "collapsed"
static let children = "children"
static let completed = "completed"
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(title, forKey: PropertyKey.title)
aCoder.encodeObject(body, forKey: PropertyKey.body)
aCoder.encodeObject(tags, forKey: PropertyKey.tags)
aCoder.encodeObject(indent, forKey: PropertyKey.indent)
aCoder.encodeObject(collapsed, forKey: PropertyKey.collapsed)
aCoder.encodeObject(children, forKey: PropertyKey.children)
aCoder.encodeObject(completed, forKey: PropertyKey.completed)
}
required convenience init?(coder aDecoder: NSCoder) {
let title = aDecoder.decodeObjectForKey(PropertyKey.title) as! String
let body = aDecoder.decodeObjectForKey(PropertyKey.body) as! String
let tags = aDecoder.decodeObjectForKey(PropertyKey.tags) as! [Tag]
let indent = aDecoder.decodeObjectForKey(PropertyKey.indent) as! Int
let collapsed = aDecoder.decodeObjectForKey(PropertyKey.collapsed) as! Bool
let children = aDecoder.decodeObjectForKey(PropertyKey.children) as! Int
let completed = aDecoder.decodeObjectForKey(PropertyKey.completed) as! Bool
self.init(title: title, body: body, tags: tags, indent: indent, collapsed: collapsed, children: children, completed: completed)
}
}
|
19b60ba59f073fea157169d8df3a0e94
| 39.803797 | 131 | 0.635179 | false | false | false | false |
mmllr/CleanTweeter
|
refs/heads/master
|
CleanTweeter/UseCases/NewPost/UI/Presenter/TagAndMentionHighlightingTransformer.swift
|
mit
|
1
|
import Foundation
class TagAndMentionHighlightingTransformer : ValueTransformer {
let resourceFactory: ResourceFactory
init(factory: ResourceFactory) {
self.resourceFactory = factory
super.init()
}
override class func transformedValueClass() -> AnyClass {
return NSAttributedString.self
}
override class func allowsReverseTransformation() -> Bool {
return false
}
override func transformedValue(_ value: Any?) -> Any? {
guard let transformedValue = value as! String? else {
return nil
}
return transformedValue.findRangesWithPattern("((@|#)([A-Z0-9a-z(é|ë|ê|è|à|â|ä|á|ù|ü|û|ú|ì|ï|î|í)_]+))|(http(s)?://([A-Z0-9a-z._-]*(/)?)*)").reduce(NSMutableAttributedString(string: transformedValue)) {
let string = $0
let length = transformedValue.distance(from: $1.lowerBound, to: $1.upperBound)
let range = NSMakeRange(transformedValue.distance(from: transformedValue.startIndex, to: $1.lowerBound), length)
string.addAttribute(resourceFactory.highlightingAttribute.0, value: self.resourceFactory.highlightingAttribute.1, range: range)
return string
}
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToNSAttributedStringKey(_ input: String) -> NSAttributedString.Key {
return NSAttributedString.Key(rawValue: input)
}
|
03b18801fdb2a4951da019544a3bd069
| 33.864865 | 204 | 0.744186 | false | false | false | false |
pgherveou/PromiseKit
|
refs/heads/master
|
Swift Sources/CLLocationManager+Promise.swift
|
mit
|
1
|
import CoreLocation.CLLocationManager
private class LocationManager: CLLocationManager, CLLocationManagerDelegate {
let fulfiller: ([CLLocation]) -> Void
let rejecter: (NSError) -> Void
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
fulfiller(locations as [CLLocation])
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
rejecter(error)
}
init(_ fulfiller: ([CLLocation]) -> Void, _ rejecter: (NSError) -> Void) {
self.fulfiller = fulfiller
self.rejecter = rejecter
super.init()
PMKRetain(self)
delegate = self
}
}
private class AuthorizationCatcher: CLLocationManager, CLLocationManagerDelegate {
let fulfill: (CLAuthorizationStatus) -> Void
init(fulfiller: (CLAuthorizationStatus)->(), auther: (CLLocationManager)->()) {
fulfill = fulfiller
super.init()
let status = CLLocationManager.authorizationStatus()
if status == .NotDetermined {
delegate = self
PMKRetain(self)
auther(self)
} else {
fulfill(status)
}
}
private func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status != .NotDetermined {
fulfill(status)
PMKRelease(self)
}
}
}
private func auther(requestAuthorizationType: CLLocationManager.RequestAuthorizationType)(manager: CLLocationManager)
{
func hasInfoPListKey(key: String) -> Bool {
let value = NSBundle.mainBundle().objectForInfoDictionaryKey("NSLocationAlwaysUsageDescription") as? String ?? ""
return !value.isEmpty
}
#if os(iOS)
switch requestAuthorizationType {
case .Automatic:
let always = hasInfoPListKey("NSLocationAlwaysUsageDescription")
let whenInUse = hasInfoPListKey("NSLocationWhenInUseUsageDescription")
if hasInfoPListKey("NSLocationAlwaysUsageDescription") {
manager.requestAlwaysAuthorization()
} else {
manager.requestWhenInUseAuthorization()
}
case .WhenInUse:
manager.requestWhenInUseAuthorization()
break
case .Always:
manager.requestAlwaysAuthorization()
break
}
#endif
}
extension CLLocationManager {
public enum RequestAuthorizationType {
case Automatic
case Always
case WhenInUse
}
/**
Returns the most recent CLLocation.
@param requestAuthorizationType We read your Info plist and try to
determine the authorization type we should request automatically. If you
want to force one or the other, change this parameter from its default
value.
*/
public class func promise(requestAuthorizationType: RequestAuthorizationType = .Automatic) -> Promise<CLLocation> {
let p: Promise<[CLLocation]> = promise(requestAuthorizationType: requestAuthorizationType)
return p.then { (locations)->CLLocation in
return locations[locations.count - 1]
}
}
/**
Returns the first batch of location objects a CLLocationManager instance
provides.
*/
public class func promise(requestAuthorizationType: RequestAuthorizationType = .Automatic) -> Promise<[CLLocation]> {
return promise(yield: auther(requestAuthorizationType))
}
private class func promise(yield: (CLLocationManager)->() = { _ in }) -> Promise<[CLLocation]> {
let deferred = Promise<[CLLocation]>.defer()
let manager = LocationManager(deferred.fulfill, deferred.reject)
yield(manager)
manager.startUpdatingLocation()
deferred.promise.finally {
manager.delegate = nil
manager.stopUpdatingLocation()
PMKRelease(manager)
}
return deferred.promise
}
/**
Cannot error, despite the fact this might be more useful in some
circumstances, we stick with our decision that errors are errors
and errors only. Thus your catch handler is always catching failures
and not being abused for logic.
*/
public class func requestAuthorization(type: RequestAuthorizationType = .Automatic) -> Promise<CLAuthorizationStatus> {
let d = Promise<CLAuthorizationStatus>.defer()
AuthorizationCatcher(fulfiller: d.fulfill, auther: auther(type))
return d.promise
}
@availability(*, deprecated=1.3.0)
public class func requestAlwaysAuthorization() -> Promise<CLAuthorizationStatus> {
return requestAuthorization(type: .Always)
}
}
|
f15b99cd2b0d1a62ca8a11fe53811432
| 32.683453 | 123 | 0.672149 | false | false | false | false |
mahuiying0126/MDemo
|
refs/heads/master
|
BangDemo/BangDemo/Modules/Home/viewModel/MHomeViewModel.swift
|
mit
|
1
|
//
// MHomeViewModel.swift
// BangDemo
//
// Created by yizhilu on 2017/7/24.
// Copyright © 2017年 Magic. All rights reserved.
//
import UIKit
typealias courseDidSelectModelBlock = (_ cellModel : HomeCourseModel) -> ()
class MHomeViewModel: NSObject,UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
/** *cell点击事件 */
var cellDidSelectEvent : courseDidSelectModelBlock?
func numberOfSections(in collectionView: UICollectionView) -> Int{
return self.dataArray.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
let tempArray:NSArray = self.dataArray[section] as! NSArray
return tempArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let cell :HomeCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: MHomeViewController.reuseIdentifier, for: indexPath as IndexPath) as! HomeCollectionViewCell
let array = self.dataArray[indexPath.section] as! NSArray
let model = array[indexPath.row] as! HomeCourseModel
cell.cellForModel(model)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
return CGSize.init(width: Screen_width * 0.5, height: Screen_width * 0.41 )
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView{
var view = UICollectionReusableView();
if kind == UICollectionElementKindSectionHeader {
let headView = collectionView .dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: MHomeViewController.reusableView, for: indexPath) as! HomeHeadCollectionReusableView
view = headView
headView.moreBtnBlock = {
///更多课程
}
if indexPath.section == 0 {
headView.recommandLabel?.text = "热门课程"
headView.recommadIcon?.image = UIImage.init(named: "热")
}else{
headView.recommandLabel?.text = "小编推荐"
headView.recommadIcon?.image = UIImage.init(named: "荐")
}
}
return view
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
return CGSize.init(width: Screen_width, height: 50.0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
return 0
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let tempArray = self.dataArray[indexPath.section] as! NSArray
let model = tempArray[indexPath.row] as! HomeCourseModel
self.cellDidSelectEvent!(model)
}
lazy var dataArray : Array<Any> = {
let tempArray = Array<Any>()
return tempArray
}()
}
|
334c8da5d6f5ade1ca1801409ed3a6ae
| 40.252874 | 195 | 0.683477 | false | false | false | false |
overtake/TelegramSwift
|
refs/heads/master
|
Telegram-Mac/GIFPlayerView.swift
|
gpl-2.0
|
1
|
//
// GIFPlayerView.swift
// Telegram-Mac
//
// Created by keepcoder on 10/11/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import AVFoundation
import SwiftSignalKit
final class CIStickerContext : CIContext {
deinit {
var bp:Int = 0
bp += 1
}
}
private class AlphaFrameFilter: CIFilter {
static var kernel: CIColorKernel? = {
return CIColorKernel(source: """
kernel vec4 alphaFrame(__sample s, __sample m) {
return vec4( s.rgb, m.r );
}
""")
}()
var inputImage: CIImage?
var maskImage: CIImage?
override var outputImage: CIImage? {
let kernel = AlphaFrameFilter.kernel!
guard let inputImage = inputImage, let maskImage = maskImage else {
return nil
}
let args = [inputImage as AnyObject, maskImage as AnyObject]
return kernel.apply(extent: inputImage.extent, arguments: args)
}
}
let sampleBufferQueue = DispatchQueue.init(label: "sampleBufferQueue", qos: DispatchQoS.background, attributes: [])
private let veryLongTimeInterval = CFTimeInterval(8073216000)
struct AVGifData : Equatable {
let asset: AVURLAsset
let track: AVAssetTrack
let animatedSticker: Bool
let swapOnComplete: Bool
private init(asset: AVURLAsset, track: AVAssetTrack, animatedSticker: Bool, swapOnComplete: Bool) {
self.asset = asset
self.track = track
self.swapOnComplete = swapOnComplete
self.animatedSticker = animatedSticker
}
static func dataFrom(_ path: String?, animatedSticker: Bool = false, swapOnComplete: Bool = false) -> AVGifData? {
let new = link(path: path, ext: "mp4")
if let new = new {
let avAsset = AVURLAsset(url: URL(fileURLWithPath: new))
let t = avAsset.tracks(withMediaType: .video).first
if let t = t {
return AVGifData(asset: avAsset, track: t, animatedSticker: animatedSticker, swapOnComplete: swapOnComplete)
}
}
return nil
}
static func ==(lhs: AVGifData, rhs: AVGifData) -> Bool {
return lhs.asset.url == rhs.asset.url && lhs.animatedSticker == rhs.animatedSticker
}
}
private final class TAVSampleBufferDisplayLayer : AVSampleBufferDisplayLayer {
deinit {
}
}
class GIFPlayerView: TransformImageView {
enum LoopActionResult {
case pause
}
private let sampleLayer:TAVSampleBufferDisplayLayer = TAVSampleBufferDisplayLayer()
private var _reader:Atomic<AVAssetReader?> = Atomic(value:nil)
private var _asset:Atomic<AVURLAsset?> = Atomic(value:nil)
private let _output:Atomic<AVAssetReaderTrackOutput?> = Atomic(value:nil)
private let _track:Atomic<AVAssetTrack?> = Atomic(value:nil)
private let _needReset:Atomic<Bool> = Atomic(value:false)
private let _timer:Atomic<CFRunLoopTimer?> = Atomic(value:nil)
private let _loopAction:Atomic<(()->LoopActionResult)?> = Atomic(value:nil)
private let _timebase:Atomic<CMTimebase?> = Atomic(value:nil)
private let _stopRequesting:Atomic<Bool> = Atomic(value:false)
private let _swapNext:Atomic<Bool> = Atomic(value:true)
private let _data:Atomic<AVGifData?> = Atomic(value:nil)
func setLoopAction(_ action:(()->LoopActionResult)?) {
_ = _loopAction.swap(action)
}
private let maskLayer = CAShapeLayer()
var positionFlags: LayoutPositionFlags? {
didSet {
if let positionFlags = positionFlags {
let path = CGMutablePath()
let minx:CGFloat = 0, midx = frame.width/2.0, maxx = frame.width
let miny:CGFloat = 0, midy = frame.height/2.0, maxy = frame.height
path.move(to: NSMakePoint(minx, midy))
var topLeftRadius: CGFloat = .cornerRadius
var bottomLeftRadius: CGFloat = .cornerRadius
var topRightRadius: CGFloat = .cornerRadius
var bottomRightRadius: CGFloat = .cornerRadius
if positionFlags.contains(.top) && positionFlags.contains(.left) {
bottomLeftRadius = .cornerRadius * 3 + 2
}
if positionFlags.contains(.top) && positionFlags.contains(.right) {
bottomRightRadius = .cornerRadius * 3 + 2
}
if positionFlags.contains(.bottom) && positionFlags.contains(.left) {
topLeftRadius = .cornerRadius * 3 + 2
}
if positionFlags.contains(.bottom) && positionFlags.contains(.right) {
topRightRadius = .cornerRadius * 3 + 2
}
path.addArc(tangent1End: NSMakePoint(minx, miny), tangent2End: NSMakePoint(midx, miny), radius: bottomLeftRadius)
path.addArc(tangent1End: NSMakePoint(maxx, miny), tangent2End: NSMakePoint(maxx, midy), radius: bottomRightRadius)
path.addArc(tangent1End: NSMakePoint(maxx, maxy), tangent2End: NSMakePoint(midx, maxy), radius: topRightRadius)
path.addArc(tangent1End: NSMakePoint(minx, maxy), tangent2End: NSMakePoint(minx, midy), radius: topLeftRadius)
maskLayer.path = path
layer?.mask = maskLayer
} else {
layer?.mask = nil
}
}
}
override init() {
super.init()
sampleLayer.actions = ["onOrderIn":NSNull(),"sublayers":NSNull(),"bounds":NSNull(),"frame":NSNull(),"position":NSNull(),"contents":NSNull(),"opacity":NSNull(), "transform": NSNull()
]
sampleLayer.videoGravity = .resizeAspect
sampleLayer.backgroundColor = NSColor.clear.cgColor
layer?.addSublayer(sampleLayer)
}
func setVideoLayerGravity(_ gravity: AVLayerVideoGravity) {
sampleLayer.videoGravity = gravity
}
var controlTimebase: CMTimebase? {
return sampleLayer.controlTimebase
}
var isHasData: Bool {
return _data.modify({$0}) != nil
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layout() {
super.layout()
sampleLayer.frame = bounds
}
override func setFrameSize(_ newSize: NSSize) {
super.setFrameSize(newSize)
sampleLayer.frame = bounds
}
func set(data: AVGifData?, timebase:CMTimebase? = nil) -> Void {
assertOnMainThread()
if data != _data.swap(data) {
_ = _timebase.swap(timebase)
let _data = self._data
let layer:AVSampleBufferDisplayLayer = self.sampleLayer
let reader = self._reader
let output = self._output
let reset = self._needReset
let stopRequesting = self._stopRequesting
let swapNext = self._swapNext
let track = self._track
let asset = self._asset
let timer = self._timer
let timebase = self._timebase
let loopAction = self._loopAction
if let data = data {
let _ = track.swap(data.track)
let _ = asset.swap(data.asset)
_ = stopRequesting.swap(false)
if data.swapOnComplete {
_ = timebase.swap(self.controlTimebase)
}
_ = swapNext.swap(true)
} else {
_ = asset.swap(nil)
_ = track.swap(nil)
_ = stopRequesting.swap(true)
_ = swapNext.swap(false)
return
}
layer.requestMediaDataWhenReady(on: sampleBufferQueue, using: {
if stopRequesting.swap(false) {
if let controlTimebase = layer.controlTimebase, let current = timer.swap(nil) {
CMTimebaseRemoveTimer(controlTimebase, timer: current)
_ = timebase.swap(nil)
}
layer.stopRequestingMediaData()
layer.flushAndRemoveImage()
var reader = reader.swap(nil)
Queue.concurrentBackgroundQueue().async {
reader?.cancelReading()
reader = nil
}
return
}
if swapNext.swap(false) {
_ = output.swap(nil)
var reader = reader.swap(nil)
Queue.concurrentBackgroundQueue().async {
reader?.cancelReading()
reader = nil
}
}
if let readerValue = reader.with({ $0 }), let outputValue = output.with({ $0 }) {
let affineTransform = track.with { $0?.preferredTransform.inverted() }
if let affineTransform = affineTransform {
layer.setAffineTransform(affineTransform)
}
while layer.isReadyForMoreMediaData {
if !stopRequesting.with({ $0 }) {
if readerValue.status == .reading, let sampleBuffer = outputValue.copyNextSampleBuffer() {
layer.enqueue(sampleBuffer)
continue
}
_ = stopRequesting.modify { _ in _data.with { $0 } == nil }
break
} else {
break
}
}
if readerValue.status == .completed || readerValue.status == .cancelled {
if reset.swap(false) {
let loopActionResult = loopAction.with({ $0?() })
if let loopActionResult = loopActionResult {
switch loopActionResult {
case .pause:
return
}
}
let result = restartReading(_reader: reader, _asset: asset, _track: track, _output: output, _needReset: reset, _timer: timer, layer: layer, _timebase: timebase)
if result {
layer.flush()
}
}
}
} else if !stopRequesting.modify({$0}) {
let result = restartReading(_reader: reader, _asset: asset, _track: track, _output: output, _needReset: reset, _timer: timer, layer: layer, _timebase: timebase)
if result {
layer.flush()
}
}
})
}
}
func reset(with timebase:CMTimebase? = nil, _ resetImage: Bool = true) {
// if resetImage {
sampleLayer.flushAndRemoveImage()
// } else {
// sampleLayer.flush()
// }
_ = _swapNext.swap(true)
_ = _timebase.swap(timebase)
}
deinit {
_ = _stopRequesting.swap(true)
}
required convenience init(frame frameRect: NSRect) {
self.init()
}
}
fileprivate func restartReading(_reader:Atomic<AVAssetReader?>, _asset:Atomic<AVURLAsset?>, _track:Atomic<AVAssetTrack?>, _output:Atomic<AVAssetReaderTrackOutput?>, _needReset:Atomic<Bool>, _timer:Atomic<CFRunLoopTimer?>, layer: AVSampleBufferDisplayLayer, _timebase:Atomic<CMTimebase?>) -> Bool {
if let timebase = layer.controlTimebase, let timer = _timer.modify({$0}) {
_ = _timer.swap(nil)
CMTimebaseRemoveTimer(timebase, timer: timer)
}
if let asset = _asset.modify({$0}), let track = _track.modify({$0}) {
let _ = _reader.swap(try? AVAssetReader(asset: asset))
if let reader = _reader.modify({$0}) {
var params:[String:Any] = [:]
params[kCVPixelBufferPixelFormatTypeKey as String] = kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
let _ = _output.swap(AVAssetReaderTrackOutput(track: track, outputSettings: params))
if let output = _output.modify({$0}) {
output.alwaysCopiesSampleData = false
if reader.canAdd(output) {
reader.add(output)
var timebase:CMTimebase? = _timebase.swap(nil)
if timebase == nil {
CMTimebaseCreateWithMasterClock( allocator: kCFAllocatorDefault, masterClock: CMClockGetHostTimeClock(), timebaseOut: &timebase )
CMTimebaseSetRate(timebase!, rate: 1.0)
}
if let timebase = timebase {
reader.timeRange = CMTimeRangeMake(start: CMTimebaseGetTime(timebase), duration: asset.duration)
let runLoop = CFRunLoopGetMain()
var context = CFRunLoopTimerContext()
context.info = UnsafeMutableRawPointer(Unmanaged.passRetained(_needReset).toOpaque())
let timer = CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent(), veryLongTimeInterval, 0, 0, {
(cfRunloopTimer, info) -> Void in
if let info = info {
let s = Unmanaged<Atomic<Bool>>.fromOpaque(info).takeUnretainedValue()
_ = s.swap(true)
}
}, &context);
if let timer = timer, let runLoop = runLoop {
_ = _timer.swap(timer)
CMTimebaseAddTimer(timebase, timer: timer, runloop: runLoop)
CFRunLoopAddTimer(runLoop, timer, CFRunLoopMode.defaultMode);
CMTimebaseSetTimerNextFireTime(timebase, timer: timer, fireTime: asset.duration, flags: 0)
}
layer.controlTimebase = timebase
}
reader.startReading()
return true
}
}
}
}
return false
}
/*
if isAnimatedSticker {
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
var newSampleBuffer:CMSampleBuffer? = nil
if let imageBuffer = imageBuffer {
let sourceImage = CIImage(cvImageBuffer: imageBuffer)
var cvPixelBuffer: CVPixelBuffer?
let videoSize = CGSize(width: 400, height: 400)
CVPixelBufferCreate(nil, 400, 400, kCVPixelFormatType_32BGRA, nil, &cvPixelBuffer)
if let cvPixelBuffer = cvPixelBuffer {
let sourceRect = CGRect(origin: .zero, size: videoSize)
let alphaRect = sourceRect.offsetBy(dx: 0, dy: sourceRect.height)
let filter = AlphaFrameFilter()
filter.inputImage = sourceImage.cropped(to: alphaRect)
.transformed(by: CGAffineTransform(translationX: 0, y: -sourceRect.height))
filter.maskImage = sourceImage.cropped(to: sourceRect)
let outputImage = filter.outputImage!
context.render(outputImage, to: cvPixelBuffer)
var formatRef: CMVideoFormatDescription?
let _ = CMVideoFormatDescriptionCreateForImageBuffer(allocator: kCFAllocatorDefault, imageBuffer: cvPixelBuffer, formatDescriptionOut: &formatRef)
var sampleTimingInfo: CMSampleTimingInfo = CMSampleTimingInfo()
CMSampleBufferGetSampleTimingInfo(sampleBuffer, at: 0, timingInfoOut: &sampleTimingInfo)
CMSampleBufferCreateReadyWithImageBuffer(allocator: nil, imageBuffer: cvPixelBuffer, formatDescription: formatRef!, sampleTiming: &sampleTimingInfo, sampleBufferOut: &newSampleBuffer)
if let newSampleBuffer = newSampleBuffer {
sampleBuffer = newSampleBuffer
}
}
}
}
*/
|
dee0f6636cdeb5e0b8c28464ba2bc17b
| 36.487585 | 297 | 0.542301 | false | false | false | false |
JadenGeller/Generational
|
refs/heads/master
|
Sources/Cycle.swift
|
mit
|
1
|
//
// Cycle.swift
// Generational
//
// Created by Jaden Geller on 12/28/15.
// Copyright © 2015 Jaden Geller. All rights reserved.
//
public struct CyclicSequence<Base: CollectionType>: SequenceType {
private let base: Base
public init(_ base: Base) {
self.base = base
}
public func generate() -> CyclicGenerator<Base> {
return CyclicGenerator(base)
}
}
public struct CyclicGenerator<Base: CollectionType>: GeneratorType {
private let base: Base
private var index: Base.Index
public init(_ base: Base) {
self.base = base
self.index = base.startIndex
}
public mutating func next() -> Base.Generator.Element? {
let value = base[index]
index = index.successor()
if index == base.endIndex { index = base.startIndex }
return value
}
}
extension CollectionType {
func cycle() -> CyclicSequence<Self> {
return CyclicSequence(self)
}
}
|
1e56a8b98f7ac9f9376b4aca25f7d565
| 22.333333 | 68 | 0.624106 | false | false | false | false |
zef/Fly
|
refs/heads/master
|
Sources/FlyRequest.swift
|
mit
|
1
|
import HTTPStatus
public enum HTTPMethod: String {
case GET, PUT, POST, DELETE
// Patch?
}
public struct FlyRequest {
public let path: String
public let method: HTTPMethod
public var parameters = [String: String]()
public init(_ path: String, method: HTTPMethod = .GET) {
self.path = path
self.method = method
}
}
public struct FlyResponse {
public var request: FlyRequest = FlyRequest("")
public var status: HTTPStatus = HTTPStatus.OK
public var body: String = ""
public init() { }
public init(status: HTTPStatus) {
self.status = status
}
public init(body: String) {
self.body = body
}
}
extension FlyResponse: StringLiteralConvertible {
public typealias UnicodeScalarLiteralType = StringLiteralType
public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self.init(stringLiteral: value)
}
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(stringLiteral: value)
}
public init(stringLiteral value: StringLiteralType) {
self.init(body: value)
}
}
|
02db638b562850baec69e27809a0d13a
| 24.22449 | 91 | 0.686084 | false | false | false | false |
IBM-Swift/BluePic
|
refs/heads/master
|
BluePic-iOS/BluePic/Views/ImageFeedTableViewCell.swift
|
apache-2.0
|
1
|
/**
* Copyright IBM Corporation 2016, 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import UIKit
import SDWebImage
class ImageFeedTableViewCell: ProfileTableViewCell {
override func setupDataWith(_ image: Image) {
super.setupDataWith(image)
//set the photographerNameLabel's text
let ownerNameString = NSLocalizedString("by", comment: "") + " \(image.user.name)"
self.photographerNameLabel.text = ownerNameString
}
}
class ProfileTableViewCell: UITableViewCell {
//image view used to display image
@IBOutlet weak var userImageView: UIImageView!
//textView that displays the caption of the photo
@IBOutlet weak var captionTextView: UITextView!
//the view that is shown while we wait for the image to download and display
@IBOutlet weak var loadingView: UIView!
//label that displays the photographer's name
@IBOutlet weak var photographerNameLabel: UILabel!
//label shows the number of tags an image has
@IBOutlet weak var numberOfTagsLabel: UILabel!
//label that displays the amount of time since the photo was taken
@IBOutlet weak var timeSincePostedLabel: UILabel!
//constraint for top of textView
@IBOutlet weak var topConstraint: NSLayoutConstraint!
//string that is added to the numberOfTagsLabel at the end if there are multiple tags
fileprivate let kNumberOfTagsPostFix_MultipleTags = NSLocalizedString("Tags", comment: "")
//String that is added to the numberOfTagsLabel at the end if there is one tag
fileprivate let kNumberOfTagsPostFix_OneTag = NSLocalizedString("Tag", comment: "")
var defaultAttributes = [NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 13.0)]
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = UITableViewCellSelectionStyle.none
let style = NSMutableParagraphStyle()
style.alignment = .center
defaultAttributes[NSAttributedStringKey.paragraphStyle] = style
}
/// Method sets up the data for the profile collection view cell
///
/// - parameter image: Image object to use for populating UI
func setupDataWith(_ image: Image) {
let numOfTags = image.tags.count
if numOfTags == 0 {
self.numberOfTagsLabel.isHidden = true
} else if numOfTags == 1 {
self.numberOfTagsLabel.isHidden = false
self.numberOfTagsLabel.text = "\(numOfTags)" + " " + self.kNumberOfTagsPostFix_OneTag
} else {
self.numberOfTagsLabel.isHidden = false
self.numberOfTagsLabel.text = "\(numOfTags)" + " " + self.kNumberOfTagsPostFix_MultipleTags
}
//set the image view's image
self.setImageView(image.url, fileName: image.fileName)
//label that displays the photos caption
_ = self.setCaptionText(image: image)
//set the time since posted label's text
if let ts = image.timeStamp {
self.timeSincePostedLabel.text = Date.timeSinceDateString(ts)
} else {
self.timeSincePostedLabel.text = ""
}
}
func setCaptionText(image: Image) -> Bool {
let cutoffLength = 40
if image.caption == CameraDataManager.SharedInstance.kEmptyCaptionPlaceHolder {
self.captionTextView.text = ""
self.captionTextView.textContainerInset = UIEdgeInsets.zero
return false
} else if image.caption.count >= cutoffLength {
if !image.isExpanded {
let moreText = "...more"
let abc: String = (image.caption as NSString).substring(with: NSRange(location: 0, length: cutoffLength)) + moreText
let attributedString = NSMutableAttributedString(string: abc, attributes: defaultAttributes)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.gray, range: NSRange(location: cutoffLength, length: 7))
self.captionTextView.attributedText = attributedString
} else {
self.captionTextView.attributedText = NSMutableAttributedString(string: image.caption, attributes: defaultAttributes)
}
self.captionTextView.textContainerInset = UIEdgeInsets(top: 8.0, left: 0, bottom: 8.0, right: 0)
return true
} else {
self.captionTextView.attributedText = NSMutableAttributedString(string: image.caption, attributes: defaultAttributes)
self.captionTextView.textContainerInset = UIEdgeInsets(top: 8.0, left: 0, bottom: 8.0, right: 0)
return false
}
}
/**
Method sets up the image view with the url provided or a locally cached verion of the image
- parameter url: String?
- parameter fileName: String?
*/
func setImageView(_ url: String?, fileName: String?) {
self.loadingView.isHidden = false
//first try to set image view with locally cached image (from a photo the user has posted during the app session)
let locallyCachedImage = self.tryToSetImageViewWithLocallyCachedImage(fileName)
//then try to set the imageView with a url, using the locally cached image as the placeholder (if there is one)
self.tryToSetImageViewWithURL(url, placeHolderImage: locallyCachedImage)
}
/**
Method trys to set the image view with a locally cached image if there is one and then returns the locally cached image
- parameter fileName: String?
- returns: UIImage?
*/
fileprivate func tryToSetImageViewWithLocallyCachedImage(_ fileName: String?) -> UIImage? {
//check if file name and facebook user id aren't nil
if let fName = fileName {
//generate id which is a concatenation of the file name and facebook user id
let id = fName + CurrentUser.facebookUserId
//check to see if there is an image cached in the camera data manager's picturesTakenDuringAppSessionById cache
if let img = BluemixDataManager.SharedInstance.imagesTakenDuringAppSessionById[id] {
//hide loading placeholder view
self.loadingView.isHidden = true
//set image view's image to locally cached image
self.userImageView.image = img
return img
}
}
return nil
}
/**
Method trys to set the image view with a url to an image and sets the placeholder to a locally cached image if its not nil
- parameter url: String?
- parameter placeHolderImage: UIImage?
*/
fileprivate func tryToSetImageViewWithURL(_ url: String?, placeHolderImage: UIImage?) {
let urlString = url ?? ""
//check if string is empty, if it is, then its not a valid url
if urlString != "" {
//check if we can turn the string into a valid URL
if let nsurl = URL(string: urlString) {
//if placeHolderImage parameter isn't nil, then set image with URL and use placeholder image
if let image = placeHolderImage {
self.setImageViewWithURLAndPlaceHolderImage(nsurl, placeHolderImage: image)
}
//else dont use placeholder image and
else {
self.setImageViewWithURL(nsurl)
}
}
}
}
/**
Method sets the imageView with a url to an image and uses a locally cached image
- parameter url: URL
- parameter placeHolderImage: UIImage
*/
fileprivate func setImageViewWithURLAndPlaceHolderImage(_ url: URL, placeHolderImage: UIImage) {
self.userImageView.sd_setImage(with: url, placeholderImage: placeHolderImage, options: [.delayPlaceholder]) { image, error, _, _ in
self.loadingView.isHidden = image != nil && error == nil
}
}
/**
Method sets the imageView with a url to an image using no placeholder
- parameter url: URL
*/
fileprivate func setImageViewWithURL(_ url: URL) {
self.userImageView.sd_setImage(with: url) { (image, error, _, _) in
self.loadingView.isHidden = image != nil && error == nil
}
}
}
|
9bada55b24d94d02eb2682aa7881772e
| 37.112069 | 156 | 0.660936 | false | false | false | false |
T1ger/LeetCode
|
refs/heads/master
|
src/subsets_ii/solution1.swift
|
mit
|
3
|
class Solution {
func subsetsWithDup(_ nums: [Int]) -> [[Int]] {
var res = [[Int]]()
var path = [Int]()
let nums = nums.sorted(by: <)
subsetsWithDupHelper(&res, path, nums, 0)
return res
}
private func subsetsWithDupHelper(_ res: inout [[Int]], _ path: [Int], _ nums: [Int], _ startIndex: Int) {
res.append(path)
var list = path
for i in startIndex ..< nums.count {
if i != 0 && i != startIndex && nums[i] == nums[i-1] {
continue
}
list.append(nums[i])
subsetsWithDupHelper(&res, list, nums, i + 1)
list.removeLast()
}
}
}
|
80df905d5f2f78626058099339f1e56b
| 25.785714 | 110 | 0.430412 | false | false | false | false |
tsaievan/XYReadBook
|
refs/heads/master
|
XYReadBook/XYReadBook/Classes/Views/Profile/XYSettingController.swift
|
mit
|
1
|
//
// XYSettingController.swift
// XYReadBook
//
// Created by tsaievan on 2017/9/3.
// Copyright © 2017年 tsaievan. All rights reserved.
//
import UIKit
fileprivate let kSettingCellId = "kSettingCellId"
class XYSettingController: XYViewController {
lazy var tableView = UITableView()
var cellInfo = [[XYElement]]()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
fileprivate func setupUI() {
if let info = XYProfileElementVM.settingElements() {
cellInfo = info
}
setupTableView()
}
fileprivate func setupTableView() {
tableView = UITableView(frame: view.bounds, style: .grouped)
tableView.showsVerticalScrollIndicator = false
tableView.showsHorizontalScrollIndicator = false
tableView.isPagingEnabled = false
tableView.bounces = false
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.register(XYSettingCell.self, forCellReuseIdentifier: kSettingCellId)
}
}
// MARK: - 数据源方法, 代理方法
extension XYSettingController: UITableViewDataSource, UITableViewDelegate{
///< 返回组数
func numberOfSections(in tableView: UITableView) -> Int {
return cellInfo.count
}
///< 返回行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellInfo[section].count
}
///< 返回cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:kSettingCellId , for: indexPath) as? XYSettingCell
let model = cellInfo[indexPath.section][indexPath.row]
if let cell = cell {
cell.model = model
cell.accViewName = model.accessViewName
return cell
}
return UITableViewCell()
}
///< 返回cell高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
///< 返回组尾高度
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10
}
///< 返回组头高度
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.2
}
}
|
a397bf97a61b5208f12a93c81d08f1d4
| 28.222222 | 114 | 0.65188 | false | false | false | false |
weblogng/example-weblogng-WNGTwitter
|
refs/heads/master
|
WNGTwitter/AuthView.swift
|
apache-2.0
|
1
|
import UIKit
import Accounts
import Social
import SwifteriOS
// our AuthView is assigned to the first UIViewController in the Main.storyboard
class AuthView: UIViewController
{
@IBAction func doTwitterLogin(sender : AnyObject) {
let account = ACAccountStore()
let accountType = account.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
account.requestAccessToAccountsWithType(accountType, options: nil,
completion: { (granted, error) in
if (granted) {
let arrayOfAccount: NSArray = account.accountsWithAccountType(accountType)
if (arrayOfAccount.count > 0) {
let twitterAccount = arrayOfAccount.lastObject as ACAccount
let swifter = Swifter(account: twitterAccount)
self.fetchTwitterHomeStream(swifter)
}
} else {
self.alert("Unable to login")
}
}
)
}
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// Keeping things DRY by creating a simple alert method that we can reuse for generic errors
func alert(message: String)
{
// This is the iOS8 way of doing alerts. For older versions, look into UIAlertView
var alert = UIAlertController(
title: nil,
message: message,
preferredStyle: UIAlertControllerStyle.Alert
)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
// More DRY code, fetch the users home timeline if all went well
func fetchTwitterHomeStream(swifter: Swifter)
{
let failureHandler: ((NSError) -> Void) = {
error in
self.alert(error.localizedDescription)
}
swifter.getStatusesHomeTimelineWithCount(20, sinceID: nil, maxID: nil, trimUser: true, contributorDetails: false, includeEntities: true, success: {
(statuses: [JSONValue]?) in
// Successfully fetched timeline, so lets create and push the table view
let tweetsViewController = self.storyboard!.instantiateViewControllerWithIdentifier("RecentTweets") as RecentTweets
if statuses != nil {
tweetsViewController.tweets = statuses!
self.presentViewController(tweetsViewController, animated: true, completion: nil)
}
}, failure: failureHandler)
}
}
|
0dffb6b58c4687b43693730bad284035
| 35.302632 | 155 | 0.610366 | false | false | false | false |
Caiflower/SwiftWeiBo
|
refs/heads/master
|
花菜微博/花菜微博/Classes/ViewModel(视图模型)/CFStatusViewModel.swift
|
apache-2.0
|
1
|
//
// CFStatusViewModel.swift
// 花菜微博
//
// Created by 花菜ChrisCai on 2016/12/23.
// Copyright © 2016年 花菜ChrisCai. All rights reserved.
//
import Foundation
/// 微博视图模型
/**
如果没有任何父类,如果希望在开发时调试,输出调试信息
1. 遵守 CustomStringConvertible 协议
2. 实现 description 计算属性
*/
// 设置微博属性文本
let originalStatusTextFont = UIFont.systemFont(ofSize: 15)
let retweetedStatusTextFont = UIFont.systemFont(ofSize: 14)
class CFStatusViewModel: CustomStringConvertible {
/// 模型数据
var status: CFStatus
/// 会员图标
var memberIcon: UIImage?
/// 认证图标
var vipIcon: UIImage?
/// 转发
var retweetStr: String?
/// 评论
var commentStr: String?
/// 点赞
var likeStr: String?
/// 配图视图尺寸
var pictureViewSize = CGSize.zero
/// 图片模型数组
/// 如果是被转发的微博,原创的一定没有配图
var picUrls: [CFStatusPicture]? {
return status.retweeted_status?.pic_urls ?? status.pic_urls
}
/// 缓存高度
var rowHeight: CGFloat = 0
/// 微博正文属性文本
var retweetedAttrText: NSAttributedString?
/// 被转发的微博属性文本
var statusAttrText: NSAttributedString?
init(model: CFStatus) {
self.status = model
setMemberlevel()
setVerifiedType()
setCountString()
// 有原创的计算原创的,有转发的计算转发的
pictureViewSize = calculatePictureViewSize(count: picUrls?.count ?? 0)
// 设置正文属性文本
statusAttrText = CFEmoticonHelper.sharedHelper.emoticonString(targetString: status.text ?? "", font: originalStatusTextFont)
// 获取转发文本
let text = "@" + (status.retweeted_status?.user?.screen_name ?? "") + ":" + (status.retweeted_status?.text ?? "")
// 设置转发属性文本
retweetedAttrText = CFEmoticonHelper.sharedHelper.emoticonString(targetString: text, font: retweetedStatusTextFont)
// 计算高度
updateRowHeight()
}
/// 设置会员等级
func setMemberlevel() {
if let mbrank = self.status.user?.mbrank {
if mbrank > 0 && mbrank < 7 {
let imageName = "common_icon_membership_level" + "\(mbrank)"
memberIcon = UIImage(named: imageName)
}
}
}
/// 设置用户认证类型
fileprivate func setVerifiedType() {
// 认证类型 -1: 没有认证, 0: 认证用户, 2,3,5:企业认证,220:达人认证
switch self.status.user?.verified_type ?? -1{
case 0:
vipIcon = UIImage(named: "avatar_vip")
case 2,3,5:
vipIcon = UIImage(named: "avatar_enterprise_vip")
case 220:
vipIcon = UIImage(named: "avatar_grassroot")
default:
break
}
}
fileprivate func setCountString() {
retweetStr = countString(count: self.status.reposts_count, defaultString: "转发")
commentStr = countString(count: self.status.comments_count, defaultString: "评论")
likeStr = countString(count: self.status.attitudes_count, defaultString: "赞")
}
/// 设置转发,评论,点赞的描述
///
/// - Parameters:
/// - count: 转发,评论,点赞的数量
/// - defaultString: 默认文字
/// - Returns: 描述文字
fileprivate func countString(count: Int, defaultString: String) -> String {
if count == 0 {
return defaultString
}
if count < 10000 {
return count.description
}
return String(format: "%.2f 万", Double(count) / 10000)
}
/// 计算微博配图视图的大小
///
/// - Parameter count: 图片个数
/// - Returns: 配图尺寸
fileprivate func calculatePictureViewSize(count: Int) -> CGSize {
if count == 0 {
return CGSize.zero
}
// 计算行数
let row = (count - 1) / 3 + 1
// 计算高度
let height = CFStatusPictureViewOutterMargin + CGFloat(row - 1) * CFStatusPictureViewInnerMargin + CGFloat(row) * CFStatusPictureItemWidth
return CGSize(width: CFStatusPictureViewWidth, height: height)
}
/// 计算单张配图视图的尺寸
///
/// - Parameter image: 单张的配图
func updatePictureViewSize(image: UIImage) {
var size = image.size
// 宽度太宽或者太窄处理
let minWidth: CGFloat = 100
let maxWidth: CGFloat = 300
if size.width > maxWidth {
size.width = maxWidth
size.height = size.width / image.size.width * image.size.height
}
if size.width < minWidth {
size.width = minWidth
size.height = size.width / image.size.width * image.size.height
if size.height > maxWidth {
size.height = maxWidth
}
}
// 添加顶部间距
size.height += CFStatusPictureViewOutterMargin
pictureViewSize = size
// 重新计算行高
updateRowHeight()
}
fileprivate func updateRowHeight() {
// 原创微博 顶部分隔(12) + 间距(12) + 头像高度(34) + 间距(12) + 正文(计算) + 配图高度(计算) + 间距(12) + 底部工具视图高度(36)
// 转发微博 顶部分隔(12) + 间距(12) + 头像高度(34) + 间距(12) + 正文(计算) + 间距(12) + 间距(12) + 被转发的正文(计算) + 配图高度(计算) + 间距(12) + 底部工具视图高度(36)
// 定义行高
var rowHeight: CGFloat = 0
// label最大宽度
let maxWidth: CGFloat = UIScreen.main.cf_screenWidth - 2 * CFCommonMargin
let viewSize = CGSize(width: maxWidth, height: CGFloat(MAXFLOAT))
// 顶部高度
let topHeight: CGFloat = CFCommonMargin * 2 + CFStatusIconViewHeight + CFCommonMargin
rowHeight += topHeight
if let text = statusAttrText {
let textHeight = text.boundingRect(with: viewSize, options: [.usesLineFragmentOrigin], context: nil).height
rowHeight += CGFloat(ceilf(Float(textHeight)))
}
// 被转发的微博
if status.retweeted_status != nil {
if let text = retweetedAttrText {
let textHeight = text.boundingRect(with: viewSize, options: [.usesLineFragmentOrigin], context: nil).height
rowHeight += CGFloat(ceilf(Float(textHeight)))
rowHeight += CFCommonMargin * 2
}
}
rowHeight += pictureViewSize.height + CFCommonMargin + CFStatusToolbarHeight
self.rowHeight = rowHeight
}
var description: String {
return self.status.description
}
}
|
cd8d35b2e487939868b22e4d82389bd7
| 29.676617 | 146 | 0.580765 | false | false | false | false |
obozhdi/handy_extensions
|
refs/heads/master
|
HandyExtensions/HandyExtensions/Extensions/UIImage+TintLinearGradient.swift
|
unlicense
|
1
|
import UIKit
extension UIImage {
func tintWithLinearGradientColors(colorsArr: [CGColor?]) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
let context = UIGraphicsGetCurrentContext()
context!.translateBy(x: 0, y: self.size.height)
context!.scaleBy(x: 1.0, y: -1.0)
context!.setBlendMode(.normal)
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
let colors = colorsArr as CFArray
let space = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradient(colorsSpace: space, colors: colors, locations: nil)
context?.clip(to: rect, mask: self.cgImage!)
context!.drawLinearGradient(gradient!, start: CGPoint(x: 0, y: 0), end: CGPoint(x: 0, y: self.size.height), options: CGGradientDrawingOptions(rawValue: 0))
let gradientImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return gradientImage!
}
}
|
1ee1a45284ac3f9e2615271ed1103bc9
| 35.111111 | 159 | 0.70359 | false | false | false | false |
google-research/swift-tfp
|
refs/heads/master
|
Tests/TFPTests/FrontendTests.swift
|
apache-2.0
|
1
|
// Copyright 2019 Google LLC
//
// 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
//
// https://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.
@testable import LibTFP
import SIL
import XCTest
@available(macOS 10.13, *)
final class FrontendTests: XCTestCase {
func testAssertRecovery() {
func makeCheck(_ cond: String) -> String {
return """
@_silgen_name("f") func f(x: Tensor<Float>, y: Tensor<Float>, i: Int) {
assert(\(cond))
}
"""
}
// NB: Variable number 0 is the result
let xVar = ListExpr.var(ListVar(1))
let yVar = ListExpr.var(ListVar(2))
let iVar = IntExpr.var(IntVar(3))
let asserts: [(String, BoolExpr)] = [
("x.rank == 2", .intEq(.length(of: xVar), 2)),
("x.rank == y.rank", .intEq(.length(of: xVar), .length(of: yVar))),
("x.rank == y.rank + 4", .intEq(.length(of: xVar), .add(.length(of: yVar), .literal(4)))),
("x.shape == y.shape", .listEq(xVar, yVar)),
("x.shape[1] == y.shape[2]", .intEq(.element(1, of: xVar), .element(2, of: yVar))),
("x.shape[0] == y.shape[0] + y.shape[1] * y.shape[2] / y.shape[3]",
.intEq(.element(0, of: xVar), .add(
.element(0, of: yVar),
.div(
.mul(.element(1, of: yVar), .element(2, of: yVar)),
.element(3, of: yVar))
))),
("x.shape[0] > y.shape[0]", .intGt(.element(0, of: xVar), .element(0, of: yVar))),
("x.shape[0] >= y.shape[0]", .intGe(.element(0, of: xVar), .element(0, of: yVar))),
("x.shape[0] < y.shape[0]", .intLt(.element(0, of: xVar), .element(0, of: yVar))),
("x.shape[0] <= y.shape[0]", .intLe(.element(0, of: xVar), .element(0, of: yVar))),
("x.shape == y.shape", .listEq(xVar, yVar)),
("x.shape == [1, 2 + y.shape[0], i]",
.listEq(xVar, .literal([1, .add(2, .element(0, of: yVar)), iVar]))),
]
for (cond, expectedExpr) in asserts {
withSIL(forSource: makeCheck(cond)) { module, _ in
for function in module.functions {
if function.blocks.count != 1 { continue }
guard let summary = abstract(function, inside: [:]) else { continue }
guard case let .bool(.var(retVarName)) = summary.retExpr else { continue }
for assertedExpr in summary.constraints.compactMap({ $0.exprWithoutCond }) {
if case .boolEq(.var(retVarName), expectedExpr) = assertedExpr {
return
}
}
}
XCTFail("Failed to find \(expectedExpr)")
}
}
}
static var allTests = [
("testAssertRecovery", testAssertRecovery),
]
}
|
059b8944bc2189c648b5b4086328117d
| 40.054054 | 96 | 0.583608 | false | true | false | false |
PureSwift/Bluetooth
|
refs/heads/master
|
Sources/BluetoothGATT/ATTError.swift
|
mit
|
1
|
//
// ATTError.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 4/12/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
/**
The possible errors returned by a GATT server (a remote peripheral) during Bluetooth low energy ATT transactions.
These error constants are based on the Bluetooth ATT error codes, defined in the Bluetooth 4.0 specification.
For more information about these errors, see the Bluetooth 4.0 specification, Volume 3, Part F, Section 3.4.1.1.
*/
@frozen
public enum ATTError: UInt8, Error {
/// Invalid Handle
///
/// The attribute handle given was not valid on this server.
case invalidHandle = 0x01
/// Read Not Permitted
///
/// The attribute cannot be read.
case readNotPermitted = 0x02
/// Write Not Permitted
///
/// The attribute cannot be written.
case writeNotPermitted = 0x03
/// Invalid PDU
///
/// The attribute PDU was invalid.
case invalidPDU = 0x04
/// Insufficient Authentication
///
/// The attribute requires authentication before it can be read or written.
case insufficientAuthentication = 0x05
/// Request Not Supported
///
/// Attribute server does not support the request received from the client.
case requestNotSupported = 0x06
/// Invalid Offset
///
/// Offset specified was past the end of the attribute.
case invalidOffset = 0x07
/// Insufficient Authorization
///
/// The attribute requires authorization before it can be read or written.
case insufficientAuthorization = 0x08
/// Prepare Queue Full
///
/// Too many prepare writes have been queued.
case prepareQueueFull = 0x09
/// Attribute Not Found
///
/// No attribute found within the given attribute handle range.
case attributeNotFound = 0x0A
/// Attribute Not Long
///
/// The attribute cannot be read or written using the *Read Blob Request*.
case attributeNotLong = 0x0B
/// Insufficient Encryption Key Size
///
/// The *Encryption Key Size* used for encrypting this link is insufficient.
case insufficientEncryptionKeySize = 0x0C
/// Invalid Attribute Value Length
///
/// The attribute value length is invalid for the operation.
case invalidAttributeValueLength = 0x0D
/// Unlikely Error
///
/// The attribute request that was requested has encountered an error that was unlikely,
/// and therefore could not be completed as requested.
case unlikelyError = 0x0E
/// Insufficient Encryption
///
/// The attribute requires encryption before it can be read or written.
case insufficientEncryption = 0x0F
/// Unsupported Group Type
///
/// The attribute type is not a supported grouping attribute as defined by a higher layer specification.
case unsupportedGroupType = 0x10
/// Insufficient Resources
///
/// Insufficient Resources to complete the request.
case insufficientResources = 0x11
}
// MARK: - CustomStringConvertible
extension ATTError: CustomStringConvertible {
public var description: String {
return name
}
}
// MARK: - Description Values
public extension ATTError {
var name: String {
switch self {
case .invalidHandle:
return "Invalid Handle"
case .readNotPermitted:
return "Read Not Permitted"
case .writeNotPermitted:
return "Write Not Permitted"
case .invalidPDU:
return "Invalid PDU"
case .insufficientAuthentication:
return "Insufficient Authentication"
case .requestNotSupported:
return "Request Not Supported"
case .invalidOffset:
return "Invalid Offset"
case .insufficientAuthorization:
return "Insufficient Authorization"
case .prepareQueueFull:
return "Prepare Queue Full"
case .attributeNotFound:
return "Attribute Not Found"
case .attributeNotLong:
return "Attribute Not Long"
case .insufficientEncryptionKeySize:
return "Insufficient Encryption Key Size"
case .invalidAttributeValueLength:
return "Invalid Attribute Value Length"
case .unlikelyError:
return "Unlikely Error"
case .insufficientEncryption:
return "Insufficient Encryption"
case .unsupportedGroupType:
return "Unsupported Group Type"
case .insufficientResources:
return "Insufficient Resources"
}
}
var errorDescription: String {
switch self {
case .invalidHandle:
return "The attribute handle given was not valid on this server."
case .readNotPermitted:
return "The attribute cannot be read."
case .writeNotPermitted:
return "The attribute cannot be written."
case .invalidPDU:
return "The attribute PDU was invalid."
case .insufficientAuthentication:
return "The attribute requires authentication before it can be read or written."
case .requestNotSupported:
return "Attribute server does not support the request received from the client."
case .invalidOffset:
return "Offset specified was past the end of the attribute."
case .insufficientAuthorization:
return "The attribute requires authorization before it can be read or written."
case .prepareQueueFull:
return "Too many prepare writes have been queued."
case .attributeNotFound:
return "No attribute found within the given attri- bute handle range."
case .attributeNotLong:
return "The attribute cannot be read using the Read Blob Request."
case .insufficientEncryptionKeySize:
return "The Encryption Key Size used for encrypting this link is insufficient."
case .invalidAttributeValueLength:
return "The attribute value length is invalid for the operation."
case .unlikelyError:
return "The attribute request that was requested has encountered an error that was unlikely, and therefore could not be completed as requested."
case .insufficientEncryption:
return "The attribute requires encryption before it can be read or written."
case .unsupportedGroupType:
return "The attribute type is not a supported grouping attribute as defined by a higher layer specification."
case .insufficientResources:
return "Insufficient Resources to complete the request."
}
}
}
// MARK: - CustomNSError
import Foundation
extension ATTError: CustomNSError {
public static var errorDomain: String {
return "org.pureswift.Bluetooth.ATTError"
}
public var errorCode: Int {
return Int(rawValue)
}
public var errorUserInfo: [String: Any] {
return [
NSLocalizedDescriptionKey: name,
NSLocalizedFailureReasonErrorKey: errorDescription
]
}
}
|
b96f0c998c0fa8d215d3d5b7eb6c097d
| 33.642534 | 156 | 0.61651 | false | false | false | false |
iankunneke/TIY-Assignmnts
|
refs/heads/master
|
22-SwiftBriefing/22-SwiftBriefing/MyViewController.swift
|
cc0-1.0
|
1
|
//
// MyViewController.swift
// 22-SwiftBriefing
//
// Created by ian kunneke on 7/15/15.
// Copyright (c) 2015 The Iron Yard. All rights reserved.
//
import UIKit
class MyViewController: UIViewController
{
@IBOutlet weak var agentNameTextField: UITextField!
@IBOutlet weak var agentPasswordTextField: UITextField!
@IBOutlet weak var greetingLabel: UILabel!
@IBOutlet weak var missionBriefingTextView: UITextView!
@IBAction func authenticateAgent (sender: AnyObject)
{
if agentNameTextField .isFirstResponder()
{
agentNameTextField .resignFirstResponder()
}
if !agentNameTextField.text.isEmpty && !agentPasswordTextField.text.isEmpty && agentNameTextField.text.componentsSeparatedByString(" ").count == 2
{
let agentName = agentNameTextField.text
let nameComponents = agentName.componentsSeparatedByString(" ")
greetingLabel.text = "Good Evening, Agent \(nameComponents[1])"
missionBriefingTextView.text = "This mission will be an arduous one, fraught with peril. You will cover much strange and unfamiliar territory. Should you choose to accept this mission, Agent \(nameComponents[1]), you will certainly be disavowed, but you will be doing your country a great service. This message will self destruct in 5 seconds."
self.view.backgroundColor = UIColor.greenColor()
}
else
{
self.view.backgroundColor = UIColor.redColor()
}
}
override func viewDidLoad()
{
super.viewDidLoad()
self.agentNameTextField.text = ""
self.agentPasswordTextField.text = ""
self.missionBriefingTextView.text = ""
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
if !agentNameTextField.text.isEmpty && !agentPasswordTextField.text.isEmpty
{
resignFirstResponder()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
}
|
a4b1e4e5915934cf17637a47e56caeb2
| 30.987013 | 356 | 0.662201 | false | false | false | false |
smud/TextUserInterface
|
refs/heads/master
|
Sources/TextUserInterface/Extensions/Creature+Info.swift
|
apache-2.0
|
1
|
//
// Creature+Info.swift
//
// This source file is part of the SMUD open source project
//
// Copyright (c) 2016 SMUD project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SMUD project authors
//
import Foundation
import Smud
extension Creature {
var textUserInterfaceData: CreatureData { return pluginData() }
func look() {
guard let room = room else {
send("You aren't standing in any room.")
return
}
let map = room.areaInstance.textUserInterfaceData.renderedAreaMap?.fragment(near: room, playerRoom: room, horizontalRooms: 3, verticalRooms: 3) ?? ""
send(room.title, "\n", room.description.wrapping(aroundTextColumn: map, totalWidth: 76, rightMargin: 1, bottomMargin: 1))
for creature in room.creatures {
if let mobile = creature as? Mobile {
print(mobile.shortDescription)
} else {
print(creature.name, " is standing here.")
}
}
}
func send(items: [Any], separator: String = "", terminator: String = "", isPrompt: Bool = false) {
for session in textUserInterfaceData.sessions {
session.send(items: items, separator: separator, terminator: terminator)
}
}
func send(_ items: Any..., separator: String = "", terminator: String = "\n", isPrompt: Bool = false) {
send(items: items, separator: separator, terminator: terminator)
}
}
|
4b901fdee67b47e1bacf9bd0f16b06f0
| 32.595745 | 157 | 0.632046 | false | false | false | false |
dvlproad/CJUIKit
|
refs/heads/master
|
CJBaseUIKit-Swift/CJAlert/CJAlertView.swift
|
mit
|
1
|
//
// CJAlertView.m
// CJUIKitDemo
//
// Created by ciyouzen on 2016/3/11.
// Copyright © 2016年 dvlproad. All rights reserved.
//
import UIKit
import CoreText
import SnapKit
class CJAlertView: UIView {
private var _flagImageViewHeight: CGFloat = 0.0
private var _titleLabelHeight: CGFloat = 0.0
private var _messageLabelHeight: CGFloat = 0.0
private var _bottomPartHeight: CGFloat = 0.0 //底部区域高度(包含底部按钮及可能的按钮上部的分隔线及按钮下部与边缘的距离)
private(set) var size: CGSize = CGSize.zero
//第一个视图(一般为flagImageView,如果flagImageView不存在,则为下一个即titleLabel,以此类推)与顶部的间隔
private(set) var firstVerticalInterval: CGFloat = 0
//第二个视图与第一个视图的间隔
private(set) var secondVerticalInterval: CGFloat = 0
//第三个视图与第二个视图的间隔
private(set) var thirdVerticalInterval: CGFloat = 0
//底部buttons视图与其上面的视图的最小间隔(上面的视图一般为message;如果不存在message,则是title;如果再不存在,则是flagImage)
private(set) var bottomMinVerticalInterval: CGFloat = 0
var flagImageView: UIImageView?
var titleLabel: UILabel?
var messageScrollView: UIScrollView?
var messageContainerView: UIView?
var messageLabel: UILabel?
var cancelButton: UIButton?
var okButton: UIButton?
var cancelHandle: (()->())?
var okHandle: (()->())?
// MARK: - ClassMethod
class func alertViewWithSize(size: CGSize,
flagImage: UIImage!,
title: String,
message: String,
cancelButtonTitle: String,
okButtonTitle: String,
cancelHandle:(()->())?,
okHandle: (()->())?) -> CJAlertView
{
//①创建
let alertView: CJAlertView = CJAlertView.init(size: size, firstVerticalInterval: 15, secondVerticalInterval: 10, thirdVerticalInterval: 10, bottomMinVerticalInterval: 10)
//②添加 flagImage、titleLabel、messageLabel
//[alertView setupFlagImage:flagImage title:title message:message configure:configure]; //已拆解成以下几个方法
if flagImage != nil {
alertView.addFlagImage(flagImage, CGSize(width: 38, height: 38))
}
if title.count > 0 {
alertView.addTitleWithText(title, font: UIFont.systemFont(ofSize: 18.0), textAlignment: .center, margin: 20, paragraphStyle: nil)
}
if message.count > 0 {
let paragraphStyle: NSMutableParagraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = .byCharWrapping
paragraphStyle.lineSpacing = 4
alertView.addMessageWithText(message, font: UIFont.systemFont(ofSize: 14.0), textAlignment: .center, margin: 20, paragraphStyle: paragraphStyle)
}
//③添加 cancelButton、okButton
alertView.addBottomButtons(actionButtonHeight: 50, cancelButtonTitle: cancelButtonTitle, okButtonTitle: okButtonTitle, cancelHandle: cancelHandle, okHandle: okHandle)
return alertView;
}
// MARK: - Init
// required init?(coder aDecoder: NSCoder) {
// super.init(coder: aDecoder)
// }
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
* 创建alertView
* @brief 这里所说的三个视图范围为:flagImageView(有的话,一定是第一个)、titleLabel(有的话,有可能一或二)、messageLabel(有的话,有可能一或二或三)
*
* @param size alertView的大小
* @param firstVerticalInterval 第一个视图(一般为flagImageView,如果flagImageView不存在,则为下一个即titleLabel,以此类推)与顶部的间隔
* @param secondVerticalInterval 第二个视图与第一个视图的间隔(如果少于两个视图,这个值设为0即可)
* @param thirdVerticalInterval 第三个视图与第二个视图的间隔(如果少于三个视图,这个值设为0即可)
* @param bottomMinVerticalInterval 底部buttons区域视图与其上面的视图的最小间隔(上面的视图一般为message;如果不存在message,则是title;如果再不存在,则是flagImage)
*
* @return alertView
*/
init(size: CGSize,
firstVerticalInterval: CGFloat,
secondVerticalInterval: CGFloat,
thirdVerticalInterval: CGFloat,
bottomMinVerticalInterval: CGFloat)
{
super.init(frame: CGRect.zero)
self.backgroundColor = UIColor.white
self.layer.cornerRadius = 3
self.size = size
self.firstVerticalInterval = firstVerticalInterval
self.secondVerticalInterval = secondVerticalInterval
self.thirdVerticalInterval = thirdVerticalInterval
self.bottomMinVerticalInterval = bottomMinVerticalInterval
}
/// 添加指示图标
func addFlagImage(_ flagImage: UIImage, _ imageViewSize: CGSize) {
if self.flagImageView == nil {
let flagImageView: UIImageView = UIImageView.init()
self.addSubview(flagImageView)
self.flagImageView = flagImageView;
}
self.flagImageView!.image = flagImage;
self.flagImageView?.snp.makeConstraints({ (make) in
make.centerX.equalTo(self);
make.width.equalTo(imageViewSize.width);
make.top.equalTo(self).offset(self.firstVerticalInterval);
make.height.equalTo(imageViewSize.height);
})
_flagImageViewHeight = imageViewSize.height;
if (self.titleLabel != nil) {
//由于约束部分不一样,使用update会增加一个新约束,又没设置优先级,从而导致约束冲突。而如果用remake的话,又需要重新设置之前已经设置过的,否则容易缺失。所以使用masnory时候,使用优先级比较合适
self.titleLabel!.snp.updateConstraints({ (make) in
make.top.equalTo(self.flagImageView!.snp_bottom).offset(self.secondVerticalInterval);
})
}
if self.messageScrollView != nil {
self.messageScrollView!.snp.updateConstraints { (make) in
if self.titleLabel != nil {
make.top.equalTo(self.titleLabel!.snp_bottom).offset(self.thirdVerticalInterval);
} else {
make.top.greaterThanOrEqualTo(self.flagImageView!.snp_bottom).offset(self.secondVerticalInterval);
}
}
}
}
// MARK: - AddView
///添加title
func addTitleWithText(_ text: String? = "",
font: UIFont,
textAlignment: NSTextAlignment,
margin titleLabelLeftOffset: CGFloat,
paragraphStyle: NSMutableParagraphStyle?)
{
if self.size.equalTo(CGSize.zero) {
return
}
if self.titleLabel == nil {
let titleLabel: UILabel = UILabel(frame: CGRect.zero)
//titleLabel.backgroundColor = [UIColor purpleColor];
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .center
titleLabel.textColor = UIColor.black
self.addSubview(titleLabel)
self.titleLabel = titleLabel
}
// if text == nil {
// text = ""
// //若为nil,则设置[[NSMutableAttributedString alloc] initWithString:labelText]的时候会崩溃
// }
let titleLabelMaxWidth: CGFloat = self.size.width-2*titleLabelLeftOffset
let titleLabelMaxSize: CGSize = CGSize(width: titleLabelMaxWidth, height: CGFloat.greatestFiniteMagnitude)
let titleTextSize: CGSize = CJAlertView.getTextSize(from: text!, with: font, maxSize: titleLabelMaxSize, lineBreakMode: .byCharWrapping, paragraphStyle: paragraphStyle)
var titleTextHeight: CGFloat = titleTextSize.height
let lineStringArray: [NSString] = CJAlertView.getLineStringArray(labelText: text!, font: font, maxTextWidth: titleLabelMaxWidth)
let lineCount: NSInteger = lineStringArray.count
var lineSpacing: CGFloat = paragraphStyle?.lineSpacing ?? 0
if lineSpacing == 0 {
lineSpacing = 2
}
titleTextHeight += CGFloat(lineCount)*lineSpacing
if paragraphStyle == nil {
self.titleLabel!.text = text
} else {
let attributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.paragraphStyle: paragraphStyle!,
NSAttributedString.Key.font: font,
//NSAttributedString.Key.foregroundColor: textColor,
//NSAttributedString.Key.kern: 1.5f //字体间距
]
let attributedText: NSMutableAttributedString = NSMutableAttributedString(string: text!)
attributedText.addAttributes(attributes, range: NSMakeRange(0, text!.count))
//[attributedText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
self.titleLabel!.attributedText = attributedText
}
self.titleLabel!.font = font
self.titleLabel!.textAlignment = textAlignment
self.titleLabel!.snp.makeConstraints({ (make) in
make.centerX.equalTo(self);
make.left.equalTo(self).offset(titleLabelLeftOffset);
if self.flagImageView != nil {
make.top.equalTo(self.flagImageView!.snp_bottom).offset(self.secondVerticalInterval);
} else {
make.top.greaterThanOrEqualTo(self).offset(self.firstVerticalInterval);//优先级
}
make.height.equalTo(titleTextHeight);
})
_titleLabelHeight = titleTextHeight
if self.messageScrollView != nil {
self.messageScrollView?.snp.updateConstraints({ (make) in
if self.flagImageView != nil {
make.top.equalTo(self.titleLabel!.snp_bottom).offset(self.thirdVerticalInterval);
} else {
make.top.equalTo(self.titleLabel!.snp_bottom).offset(self.secondVerticalInterval);
}
})
}
}
// MARK: - Private
//以下获取textSize方法取自NSString+CJTextSize
class func getTextSize(from string: String, with font: UIFont, maxSize: CGSize, lineBreakMode: NSLineBreakMode, paragraphStyle: NSMutableParagraphStyle?) -> CGSize {
var paragraphStyle = paragraphStyle
if (string.count == 0) {
return CGSize.zero
}
if paragraphStyle == nil {
paragraphStyle = NSParagraphStyle.default as? NSMutableParagraphStyle
paragraphStyle?.lineBreakMode = lineBreakMode
}
let attributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.paragraphStyle: paragraphStyle!,
NSAttributedString.Key.font: font
]
let options: NSStringDrawingOptions = .usesLineFragmentOrigin
let textRect: CGRect = string.boundingRect(with: maxSize, options: options, attributes: attributes, context: nil)
let size: CGSize = textRect.size
return CGSize(width: ceil(size.width), height: ceil(size.height))
}
///获取每行的字符串组成的数组
class func getLineStringArray(labelText: String, font: UIFont, maxTextWidth: CGFloat) -> [NSString] {
//convert UIFont to a CTFont
let fontName: CFString = font.fontName as CFString
let fontSize: CGFloat = font.pointSize
let fontRef: CTFont = CTFontCreateWithName(fontName, fontSize, nil);
let attString: NSMutableAttributedString = NSMutableAttributedString.init(string: labelText)
attString.addAttribute(kCTFontAttributeName as NSAttributedString.Key, value: fontRef, range: NSMakeRange(0, attString.length))
let framesetter: CTFramesetter = CTFramesetterCreateWithAttributedString(attString)
let path: CGMutablePath = CGMutablePath();
path.addRect(CGRect(x: 0, y: 0, width: maxTextWidth, height: 100000))
let frame: CTFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil)
let lines: NSArray = CTFrameGetLines(frame)
let lineStringArray: NSMutableArray = NSMutableArray.init()
for line in lines {
let lineRef: CTLine = line as! CTLine
let lineRange: CFRange = CTLineGetStringRange(lineRef)
let range: NSRange = NSRange(location: lineRange.location, length: lineRange.length)
let startIndex = labelText.index(labelText.startIndex, offsetBy: range.location)
let endIndex = labelText.index(startIndex, offsetBy: range.length)
let lineString: String = String(labelText[startIndex ..< endIndex])
lineStringArray.add(lineString)
}
return lineStringArray as! [NSString]
}
///添加message的方法(paragraphStyle:当需要设置message行距、缩进等的时候才需要设置,其他设为nil即可)
func addMessageWithText(_ text: String? = "",
font: UIFont,
textAlignment: NSTextAlignment,
margin messageLabelLeftOffset: CGFloat,
paragraphStyle: NSMutableParagraphStyle?)
{
//NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
//paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
//paragraphStyle.lineSpacing = lineSpacing;
//paragraphStyle.headIndent = 10;
if self.size.equalTo(CGSize.zero) {
return
}
if self.messageScrollView == nil {
let scrollView: UIScrollView = UIScrollView()
//scrollView.backgroundColor = [UIColor redColor];
self.addSubview(scrollView)
self.messageScrollView = scrollView
let containerView: UIView = UIView()
//containerView.backgroundColor = [UIColor greenColor];
scrollView.addSubview(containerView)
self.messageContainerView = containerView
let messageTextColor: UIColor = UIColor(red: 136/255.0, green: 136/255.0, blue: 136/255.0, alpha: 1)
//#888888
let messageLabel: UILabel = UILabel(frame: CGRect.zero)
messageLabel.numberOfLines = 0
//UITextView *messageLabel = [[UITextView alloc] initWithFrame:CGRectZero];
//messageLabel.editable = NO;
messageLabel.textAlignment = .center
messageLabel.textColor = messageTextColor
containerView.addSubview(messageLabel)
self.messageLabel = messageLabel
}
let messageLabelMaxWidth: CGFloat = self.size.width-2*messageLabelLeftOffset
let messageLabelMaxSize: CGSize = CGSize(width: messageLabelMaxWidth, height: CGFloat.greatestFiniteMagnitude)
let messageTextSize: CGSize = CJAlertView.getTextSize(from: text!, with: font, maxSize: messageLabelMaxSize, lineBreakMode: .byCharWrapping, paragraphStyle: paragraphStyle)
var messageTextHeight: CGFloat = messageTextSize.height
let lineStringArray: [NSString] = CJAlertView.getLineStringArray(labelText: text!, font: font, maxTextWidth: messageLabelMaxWidth)
let lineCount: NSInteger = lineStringArray.count
var lineSpacing: CGFloat = paragraphStyle!.lineSpacing
if lineSpacing == 0 {
lineSpacing = 2
}
messageTextHeight += CGFloat(lineCount)*lineSpacing
if (paragraphStyle == nil) {
self.messageLabel!.text = text;
} else {
let attributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.paragraphStyle: paragraphStyle!,
NSAttributedString.Key.font: font,
//NSAttributedString.Key.foregroundColor: textColor,
//NSAttributedString.Key.kern: 1.5f //字体间距
]
let attributedText: NSMutableAttributedString = NSMutableAttributedString(string: text!)
attributedText.addAttributes(attributes, range: NSMakeRange(0, text!.count))
//[attributedText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
self.messageLabel!.attributedText = attributedText
}
self.messageLabel!.font = font
self.messageLabel!.textAlignment = textAlignment
self.messageScrollView?.snp.makeConstraints({ (make) in
make.centerX.equalTo(self);
make.left.equalTo(self).offset(messageLabelLeftOffset);
if (self.titleLabel != nil) {
if (self.flagImageView != nil) {
make.top.equalTo(self.titleLabel!.snp_bottom).offset(self.thirdVerticalInterval);
} else {
make.top.equalTo(self.titleLabel!.snp_bottom).offset(self.secondVerticalInterval);
}
} else if (self.flagImageView != nil) {
make.top.greaterThanOrEqualTo(self.flagImageView!.snp_bottom).offset(self.secondVerticalInterval);//优先级
} else {
make.top.greaterThanOrEqualTo(self).offset(self.firstVerticalInterval);//优先级
}
make.height.equalTo(messageTextHeight);
})
self.messageContainerView!.snp.makeConstraints({ (make) in
make.left.right.equalTo(self.messageScrollView!)
make.top.bottom.equalTo(self.messageScrollView!)
make.width.equalTo(self.messageScrollView!.snp_width)
make.height.equalTo(messageTextHeight)
})
self.messageLabel?.snp.makeConstraints({ (make) in
make.left.right.equalTo(self.messageContainerView!);
make.top.equalTo(self.messageContainerView!);
make.height.equalTo(messageTextHeight);
})
_messageLabelHeight = messageTextHeight;
}
///添加 message 的边框等(几乎不会用到)
func addMessageLayer(borderWidth: CGFloat, borderColor: CGColor?, cornerRadius: CGFloat) {
assert((self.messageScrollView != nil), "请先添加messageScrollView")
self.messageScrollView!.layer.borderWidth = borderWidth
if borderColor != nil {
self.messageScrollView!.layer.borderColor = borderColor
}
self.messageScrollView!.layer.cornerRadius = cornerRadius
}
///添加底部按钮
/**
* 添加底部按钮方法①:按指定布局添加底部按钮
*
* @param bottomButtons 要添加的按钮组合(得在外部额外实现点击后的关闭alert操作)
* @param actionButtonHeight 按钮高度
* @param bottomInterval 按钮与底部的距离
* @param axisType 横排还是竖排
* @param fixedSpacing 两个控件间隔
* @param leadSpacing 第一个控件与边缘的间隔
* @param tailSpacing 最后一个控件与边缘的间隔
*/
func addBottomButtons(bottomButtons: [UIButton],
actionButtonHeight: CGFloat, //withHeight
bottomInterval: CGFloat,
axisType: NSLayoutConstraint.Axis,
fixedSpacing: CGFloat,
leadSpacing: CGFloat,
tailSpacing: CGFloat
)
{
let buttonCount: Int = bottomButtons.count
if axisType == .horizontal {
_bottomPartHeight = 0+actionButtonHeight+bottomInterval
} else {
_bottomPartHeight = leadSpacing+CGFloat(buttonCount)*(actionButtonHeight+fixedSpacing)-fixedSpacing+tailSpacing
}
for bottomButton in bottomButtons {
self.addSubview(bottomButton)
}
// if buttonCount > 1 {
// bottomButtons.snp.makeConstraints { (make) in
// make.bottom.equalTo(-bottomInterval)
// make.height.equalTo(actionButtonHeight)
// }
// bottomButtons.snp.distributeViews(along: axisType, withFixedSpacing: fixedSpacing, leadSpacing: leadSpacing, tailSpacing: tailSpacing)
// } else {
// bottomButtons.snp.makeConstraints { (make) in
// make.bottom.equalTo(-bottomInterval)
// make.height.equalTo(actionButtonHeight)
// make.left.equalTo(self).offset(leadSpacing)
// make.right.equalTo(self).offset(-tailSpacing)
// }
// }
}
///只添加一个按钮
func addOnlyOneBottomButton(_ bottomButton: UIButton,
withHeight actionButtonHeight: CGFloat,
bottomInterval: CGFloat,
leftOffset: CGFloat,
rightOffset: CGFloat)
{
_bottomPartHeight = 0 + actionButtonHeight + bottomInterval
self.addSubview(bottomButton)
bottomButton.snp.makeConstraints { (make) in
make.bottom.equalTo(-bottomInterval);
make.height.equalTo(actionButtonHeight);
make.left.equalTo(self).offset(leftOffset);
make.right.equalTo(self).offset(-rightOffset);
}
}
func addBottomButtons(actionButtonHeight: CGFloat,
cancelButtonTitle: String,
okButtonTitle: String,
cancelHandle: (()->())?,
okHandle: (()->())?)
{
let lineColor: UIColor = UIColor(red: 229/255.0, green: 229/255.0, blue: 229/255.0, alpha: 1)
//#e5e5e5
let cancelTitleColor: UIColor = UIColor(red: 136/255.0, green: 136/255.0, blue: 136/255.0, alpha: 1)
//#888888
let okTitleColor: UIColor = UIColor(red: 66/255.0, green: 135/255.0, blue: 255/255.0, alpha: 1)
//#4287ff
self.cancelHandle = cancelHandle
self.okHandle = okHandle
let existCancelButton: Bool = cancelButtonTitle.count > 0
let existOKButton: Bool = okButtonTitle.count > 0
if existCancelButton == false && existOKButton == false {
return
}
var cancelButton: UIButton?
if existCancelButton {
cancelButton = UIButton(type: .custom)
cancelButton!.backgroundColor = UIColor.clear
cancelButton!.setTitle(cancelButtonTitle, for: .normal)
cancelButton!.setTitleColor(cancelTitleColor, for: .normal)
cancelButton!.titleLabel!.font = UIFont.systemFont(ofSize: 14)
cancelButton!.addTarget(self, action: #selector(cancelButtonAction(button:)), for: .touchUpInside)
self.cancelButton = cancelButton
}
var okButton: UIButton?
if existOKButton {
okButton = UIButton(type: .custom)
okButton!.backgroundColor = UIColor.clear
okButton!.setTitle(okButtonTitle, for: .normal)
okButton!.setTitleColor(okTitleColor, for: .normal)
okButton!.titleLabel!.font = UIFont.systemFont(ofSize: 14)
okButton!.addTarget(self, action: #selector(okButtonAction(button:)), for: .touchUpInside)
self.okButton = okButton
}
let lineView: UIView = UIView()
lineView.backgroundColor = lineColor
self.addSubview(lineView)
lineView.snp.makeConstraints { (make) in
make.left.right.equalTo(self)
make.bottom.equalTo(self).offset(-actionButtonHeight-1)
make.height.equalTo(1)
}
_bottomPartHeight = actionButtonHeight+1
if (existCancelButton == true && existOKButton == true) {
self.addSubview(cancelButton!)
cancelButton!.snp.makeConstraints { (make) in
make.left.equalTo(self)
make.width.equalTo(self).multipliedBy(0.5)
make.bottom.equalTo(self)
make.height.equalTo(actionButtonHeight)
}
let actionSeprateLineView: UIView = UIView.init()
actionSeprateLineView.backgroundColor = lineColor
self.addSubview(actionSeprateLineView)
actionSeprateLineView.snp.makeConstraints { (make) in
make.left.equalTo(cancelButton!.snp_right)
make.width.equalTo(1)
make.top.bottom.equalTo(cancelButton!)
}
self.addSubview(okButton!)
okButton!.snp.makeConstraints { (make) in
make.left.equalTo(actionSeprateLineView.snp_right)
make.right.equalTo(self)
make.bottom.equalTo(self)
make.height.equalTo(actionButtonHeight)
}
} else if (existCancelButton == true) {
self.addSubview(cancelButton!)
cancelButton!.snp.makeConstraints { (make) in
make.left.equalTo(self)
make.width.equalTo(self).multipliedBy(1)
make.bottom.equalTo(self)
make.height.equalTo(actionButtonHeight)
}
} else if (existOKButton == true) {
self.addSubview(okButton!)
okButton!.snp.makeConstraints { (make) in
make.right.equalTo(self)
make.width.equalTo(self).multipliedBy(1)
make.bottom.equalTo(self)
make.height.equalTo(actionButtonHeight)
}
}
}
// MARK: - 文字颜色等Option
///更改 Title 文字颜色
func updateTitleTextColor(_ textColor: UIColor) {
self.titleLabel?.textColor = textColor
}
///更改 Message 文字颜色
func updateMessageTextColor(_ textColor: UIColor) {
self.messageLabel?.textColor = textColor
}
///更改底部 Cancel 按钮的文字颜色
func updateCancelButtonTitleColor(normalTitleColor: UIColor, highlightedTitleColor: UIColor) {
self.cancelButton?.setTitleColor(normalTitleColor, for: .normal)
self.cancelButton?.setTitleColor(highlightedTitleColor, for: .highlighted)
}
///更改底部 OK 按钮的文字颜色
func updateOKButtonTitleColor(normalTitleColor: UIColor, highlightedTitleColor: UIColor) {
self.okButton?.setTitleColor(normalTitleColor, for: .normal)
self.okButton?.setTitleColor(highlightedTitleColor, for: .highlighted)
}
// MARK: - Event
/**
* 显示 alert 弹窗
*
* @param shouldFitHeight 是否需要自动适应高度(否:会以之前指定的size的height来显示)
* @param blankBGColor 空白区域的背景颜色
*/
func showWithShouldFitHeight(_ shouldFitHeight: Bool, blankBGColor: UIColor) {
self.checkAndUpdateVerticalInterval()
var fixHeight: CGFloat = 0
if (shouldFitHeight == true) {
let minHeight: CGFloat = self.getMinHeight()
fixHeight = minHeight
} else {
fixHeight = self.size.height
}
self.showWithFixHeight(&fixHeight, blankBGColor: blankBGColor)
}
/**
* 显示弹窗并且是以指定高度显示的
*
* @param fixHeight 高度
* @param blankBGColor 空白区域的背景颜色
*/
func showWithFixHeight(_ fixHeight: inout CGFloat, blankBGColor: UIColor) {
self.checkAndUpdateVerticalInterval()
let minHeight: CGFloat = self.getMinHeight()
if fixHeight < minHeight {
let warningString: String = String(format: "CJ警告:您设置的size高度小于视图本身的最小高度%.2lf,会导致视图显示不全,请检查", minHeight)
print("\(warningString)")
}
let maxHeight: CGFloat = UIScreen.main.bounds.height-60
if fixHeight > maxHeight {
fixHeight = maxHeight
//NSString *warningString = [NSString stringWithFormat:@"CJ警告:您设置的size高度超过视图本身的最大高度%.2lf,会导致视图显示不全,已自动缩小", maxHeight];
//NSLog(@"%@", warningString);
if self.messageScrollView != nil {
let minHeightWithoutMessageLabel: CGFloat = self.firstVerticalInterval + _flagImageViewHeight + self.secondVerticalInterval + _titleLabelHeight + self.thirdVerticalInterval + self.bottomMinVerticalInterval + _bottomPartHeight;
_messageLabelHeight = fixHeight - minHeightWithoutMessageLabel
self.messageScrollView?.snp.updateConstraints({ (make) in
make.height.equalTo(_messageLabelHeight)
})
}
}
let popupViewSize: CGSize = CGSize(width: self.size.width, height: fixHeight)
self.cj_popupInCenterWindow(animationType: .normal, popupViewSize: popupViewSize, blankBGColor: blankBGColor, showPopupViewCompleteBlock: nil, tapBlankViewCompleteBlock: nil)
}
///获取当前alertView最小应有的高度值
func getMinHeight() -> CGFloat {
var minHeightWithMessageLabel: CGFloat = self.firstVerticalInterval + _flagImageViewHeight + self.secondVerticalInterval + _titleLabelHeight + self.thirdVerticalInterval + _messageLabelHeight + self.bottomMinVerticalInterval + _bottomPartHeight
minHeightWithMessageLabel = ceil(minHeightWithMessageLabel);
return minHeightWithMessageLabel;
}
/**
* 通过检查位于bottomButtons上view的个数来判断并修正之前设置的VerticalInterval(防止比如有时候只设置两个view,thirdVerticalInterval却不为0)
* @brief 问题来源:比如少于三个视图,thirdVerticalInterval却没设为0,此时如果不通过此方法检查并修正,则容易出现高度计算错误的问题
*/
func checkAndUpdateVerticalInterval() {
var upViewCount: Int = 0
if self.flagImageView != nil {
upViewCount += 1
}
if self.titleLabel != nil {
upViewCount += 1
}
if self.messageScrollView != nil {
upViewCount += 1
}
if upViewCount == 2 {
self.thirdVerticalInterval = 0
} else if upViewCount == 1 {
self.secondVerticalInterval = 0
}
}
// MARK: - Private
@objc func cancelButtonAction(button: UIButton) {
self.dismiss(0)
self.cancelHandle?()
}
@objc func okButtonAction(button: UIButton) {
self.dismiss(0)
self.okHandle?()
}
func dismiss(_ delay: CGFloat) {
let time = DispatchTime.now() + 1.5
DispatchQueue.main.asyncAfter(deadline: time) {
self.cj_hidePopupView(.normal)
}
}
}
//
//@implementation CJAlertView
//
//
//
//
///* //已拆解成以下几个方法
//- (void)setupFlagImage:(UIImage *)flagImage
// title:(NSString *)title
// message:(NSString *)message
//{
// if (CGSizeEqualToSize(self.size, CGSizeZero)) {
// return;
// }
//
// UIColor *messageTextColor = [UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1]; //#888888
//
//
// if (flagImage) {
// UIImageView *flagImageView = [[UIImageView alloc] init];
// flagImageView.image = flagImage;
// [self addSubview:flagImageView];
// [flagImageView mas_makeConstraints:^(MASConstraintMaker *make) {
// make.centerX.equalTo(self);
// make.width.equalTo(38);
// make.top.equalTo(self).offset(25);
// make.height.equalTo(38);
// }];
// _flagImageView = flagImageView;
// }
//
//
// // titleLabel
// CGFloat titleLabelLeftOffset = 20;
// UIFont *titleLabelFont = [UIFont systemFontOfSize:18.0];
// CGFloat titleLabelMaxWidth = self.size.width - 2*titleLabelLeftOffset;
// CGSize titleLabelMaxSize = CGSizeMake(titleLabelMaxWidth, CGFLOAT_MAX);
// CGSize titleTextSize = [CJAlertView getTextSizeFromString:title withFont:titleLabelFont maxSize:titleLabelMaxSize mode:NSLineBreakByCharWrapping];
// CGFloat titleTextHeight = titleTextSize.height;
//
// UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
// //titleLabel.backgroundColor = [UIColor clearColor];
// titleLabel.numberOfLines = 0;
// titleLabel.textAlignment = NSTextAlignmentCenter;
// titleLabel.font = titleLabelFont;
// titleLabel.textColor = [UIColor blackColor];
// titleLabel.text = title;
// [self addSubview:titleLabel];
// [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
// make.centerX.equalTo(self);
// make.left.equalTo(self).offset(titleLabelLeftOffset);
// if (self.flagImageView) {
// make.top.equalTo(self.flagImageView.mas_bottom).offset(10);
// } else {
// make.top.equalTo(self).offset(25);
// }
// make.height.equalTo(titleTextHeight);
// }];
// _titleLabel = titleLabel;
//
//
// // messageLabel
// CGFloat messageLabelLeftOffset = 20;
// UIFont *messageLabelFont = [UIFont systemFontOfSize:15.0];
// CGFloat messageLabelMaxWidth = self.size.width - 2*messageLabelLeftOffset;
// CGSize messageLabelMaxSize = CGSizeMake(messageLabelMaxWidth, CGFLOAT_MAX);
// CGSize messageTextSize = [CJAlertView getTextSizeFromString:message withFont:messageLabelFont maxSize:messageLabelMaxSize mode:NSLineBreakByCharWrapping];
// CGFloat messageTextHeight = messageTextSize.height;
//
// UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectZero];
// //messageLabel.backgroundColor = [UIColor clearColor];
// messageLabel.numberOfLines = 0;
// messageLabel.textAlignment = NSTextAlignmentCenter;
// messageLabel.font = messageLabelFont;
// messageLabel.textColor = messageTextColor;
// messageLabel.text = message;
// [self addSubview:messageLabel];
// [messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
// make.centerX.equalTo(self);
// make.left.equalTo(self).offset(messageLabelLeftOffset);
// make.top.equalTo(titleLabel.mas_bottom).offset(10);
// make.height.equalTo(messageTextHeight);
// }];
// _messageLabel = messageLabel;
//}
//*/
//
//
//
//@end
|
7a64e2984dce5bcd1886a13a6182f58c
| 39.98773 | 252 | 0.621943 | false | false | false | false |
AppCron/ACInteractor
|
refs/heads/master
|
Tests/ACInteractorTests/LazyInteractorTests.swift
|
apache-2.0
|
1
|
import XCTest
@testable import ACInteractor
class LazyInteractorTests: XCTestCase {
let testDependency = "testDependency"
let testFactory = {return TestInteractor(dependency: "testDependency")}
var lazyInteractor: LazyInteractor<TestInteractor>!
override func setUp() {
super.setUp()
lazyInteractor = LazyInteractor(factory: testFactory)
}
// MARK: - Init
func testInit_doesNotInitializeLazyInstance()
{
// Assert
XCTAssertNil(lazyInteractor.lazyInstance)
}
// MARK: - getInteractor
func testGetInteractor_returnsInstanceBuiltWithFactory()
{
// Act
let interactor = lazyInteractor.getInteractor()
// Assert
XCTAssertEqual(interactor.dependency, testDependency)
}
func testGetInteractor_alwaysReturnsSameInstance()
{
// Act
let firstInteractor = lazyInteractor.getInteractor()
let secondInteractor = lazyInteractor.getInteractor()
// Assert
XCTAssert(firstInteractor === secondInteractor)
}
// MARK: - execute
func testExceute_callsExecuteOfInteractor()
{
// Arrange
let request = TestInteractor.Request()
// Act
lazyInteractor.execute(request)
// Assert
let interactor = lazyInteractor.lazyInstance
XCTAssertEqual(interactor?.executedRequests.count, 1)
XCTAssert(interactor?.executedRequests.first === request)
}
func testExecute_alwaysUsesSameInteractorInstance() {
// Arrange
let firstRequest = TestInteractor.Request()
let secondRequest = TestInteractor.Request()
// Act
lazyInteractor.execute(firstRequest)
lazyInteractor.execute(secondRequest)
// Assert
let interactor = lazyInteractor.lazyInstance
XCTAssertEqual(interactor?.executedRequests.count, 2)
XCTAssert(interactor?.executedRequests.first === firstRequest)
XCTAssert(interactor?.executedRequests.last === secondRequest)
}
}
|
dba6ffb736c62b0d193bfafa63b69f67
| 26.883117 | 75 | 0.639497 | false | true | false | false |
crazypoo/PTools
|
refs/heads/master
|
Pods/CollectionViewPagingLayout/Lib/TransformCurve.swift
|
mit
|
1
|
//
// TransformCurve.swift
// CollectionViewPagingLayout
//
// Created by Amir Khorsandi on 2/16/20.
// Copyright © 2020 Amir Khorsandi. All rights reserved.
//
import UIKit
/// Curve function type for transforming
public enum TransformCurve {
case linear
case easeIn
case easeOut
}
public extension TransformCurve {
/// Converting linear progress to curve progress
/// input and output are between 0 and 1
///
/// - Parameter progress: the current linear progress
/// - Returns: Curved progress based on self
func computeFromLinear(progress: CGFloat) -> CGFloat {
switch self {
case .linear:
return progress
case .easeIn, .easeOut:
let logValue = progress * 9
let value: CGFloat
if self == .easeOut {
value = 1 - log10(1 + (9 - logValue))
} else {
value = log10(1 + logValue)
}
return value
}
}
}
|
ac8a610a2b379c402fa3b47942287998
| 22.809524 | 58 | 0.582 | false | false | false | false |
ZeeQL/ZeeQL3
|
refs/heads/develop
|
Sources/ZeeQL/Access/Join.swift
|
apache-2.0
|
1
|
//
// Join.swift
// ZeeQL
//
// Created by Helge Hess on 18/02/2017.
// Copyright © 2017 ZeeZide GmbH. All rights reserved.
//
/**
* Used by `Relationship` objects to connect two entities. Usually
* source/destination are the primary and foreign keys forming the
* relationship.
*/
public struct Join : Equatable, SmartDescription {
public enum Semantic : Hashable {
case fullOuterJoin, innerJoin, leftOuterJoin, rightOuterJoin
}
// TBD: rather do unowned?
public weak var source : Attribute?
public weak var destination : Attribute?
public let sourceName : String?
public let destinationName : String?
public init(source: Attribute, destination: Attribute) {
self.source = source
self.destination = destination
self.sourceName = source.name
self.destinationName = destination.name
}
public init(source: String, destination: String) {
self.sourceName = source
self.destinationName = destination
}
public init(join: Join, disconnect: Bool = false) {
if disconnect {
sourceName = join.sourceName ?? join.source?.name
destinationName = join.destinationName ?? join.destination?.name
}
else {
source = join.source
destination = join.destination
sourceName = join.sourceName
destinationName = join.destinationName
}
}
public func references(property: Property) -> Bool {
// TODO: look into data-path for flattened relationships
// TODO: call ==
return property === source || property === destination
}
// MARL: - resolve objects in models
public mutating func connectToEntities(from: Entity, to: Entity) {
if let n = sourceName { source = from[attribute: n] }
if let n = destinationName { destination = to [attribute: n] }
}
public mutating func disconnect() {
source = nil
destination = nil
}
public var isConnected : Bool {
if sourceName != nil && source == nil { return false }
if destinationName != nil && destination == nil { return false }
return true
}
// MARK: - operations
public var inverse : Join {
if let ndest = source, let nsource = destination {
return Join(source: nsource, destination: ndest)
}
return Join(source : destinationName ?? "ERROR",
destination : sourceName ?? "ERROR")
}
public func isReciprocalTo(join other: Join) -> Bool {
/* fast check (should work often) */
if let msource = self.source,
let osource = other.source,
let mdest = self.destination,
let odest = other.destination
{
if msource === odest && mdest === osource { return true }
}
/* slow check */
// hm
guard let msn = sourceName ?? source?.name else { return false }
guard let odn = other.destinationName ?? other.destination?.name
else { return false }
guard msn == odn else { return false }
guard let osn = other.sourceName ?? other.source?.name else { return false }
guard let mdn = destinationName ?? destination?.name else { return false }
guard osn == mdn else { return false }
return true
}
// MARK: - Description
public func appendToDescription(_ ms: inout String) {
ms += " "
ms += shortDescription
}
var shortDescription : String {
let fromKey: String?, toKey: String?
if let s = source { fromKey = s.name }
else if let s = sourceName { fromKey = "'\(s)'" }
else { fromKey = nil }
if let s = destination { toKey = s.name }
else if let s = destinationName { toKey = "'\(s)'" }
else { toKey = nil }
if let from = fromKey, let to = toKey { return "\(from)=>\(to)" }
else if let from = fromKey { return "\(from)=>?" }
else if let to = toKey { return "?=>\(to)" }
else { return "?" }
}
// MARK: - Equatable
public static func ==(lhs: Join, rhs: Join) -> Bool {
/* fast check (should work often) */
if lhs.source === rhs.source && lhs.destination === rhs.destination {
return true
}
/* slow check */
// TODO: call ==
return false
}
public func isEqual(to object: Any?) -> Bool {
guard let other = object as? Join else { return false }
return self == other
}
}
extension Join {
// Maybe that should be public API, but then framework users don't usually
// have to deal with this.
func source(in entity: Entity) -> Attribute? {
if let attr = source { return attr }
if let name = sourceName, let attr = entity[attribute: name] { return attr }
return nil
}
func destination(in entity: Entity) -> Attribute? {
if let attr = destination { return attr }
if let name = destinationName,
let attr = entity[attribute: name] { return attr }
return nil
}
}
|
e40b2d21cb507498e11605c67f2e3b53
| 28.32948 | 80 | 0.592826 | false | false | false | false |
PedroTrujilloV/TIY-Assignments
|
refs/heads/master
|
19--Keep-On-The-Sunny-Side/Forecaster/Forecaster/CityCell.swift
|
cc0-1.0
|
1
|
//
// GitHubFriendCell.swift
// GitHub Friends
//
// Created by Pedro Trujillo on 10/27/15.
// Copyright © 2015 Pedro Trujillo. All rights reserved.
//
import UIKit
class CityCell: UITableViewCell
{
let WeatherLabelEmoji:UILabel = UILabel(frame: CGRect(x: 5, y: 10, width: 100, height: 60))
let TemperatureLabel:UILabel = UILabel(frame: CGRect(x: UIScreen.mainScreen().bounds.width * 6/10, y: 0, width: 100, height: 80))
let SummaryLabel:UILabel = UILabel(frame: CGRect(x: UIScreen.mainScreen().bounds.width * 3/10, y: 40, width: UIScreen.mainScreen().bounds.width * 3/10, height: 40))
let NameLabel:UILabel = UILabel(frame: CGRect(x: UIScreen.mainScreen().bounds.width * 3/10, y: 5, width: UIScreen.mainScreen().bounds.width * 3/10, height: 40))
var weekDays = ["1":"Sunday","2":"Monday","3":"Tuesday","4":"Wednesday","5":"Thursday","6":"Friday","7":"Saturday","0":"Today"]
override func awakeFromNib()
{
super.awakeFromNib()
// Initialization codes
}
override func setSelected(selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setTemperaturLabel(temperature:String = "0")
{
TemperatureLabel.text = temperature+"°F"
// WeatherLabelEmoji.center.y = (imageView?.center.y)!
TemperatureLabel.font = UIFont(name: "AvenirNextCondensed-Bold", size: 45)//-Next-Condensed
TemperatureLabel.textAlignment = .Center
TemperatureLabel.textColor = UIColor.blackColor()
self.addSubview(TemperatureLabel)
}
func setSummaryLabel(summary:String = "0")
{
if summary.characters.count < 7
{
self.SummaryLabel.font = UIFont(name: "AvenirNextCondensed-Bold", size: 30)//-Next-Condensed
}
else
{
if summary.characters.count < 9
{
self.SummaryLabel.font = UIFont(name: "AvenirNextCondensed-Bold", size: 24)//-Next-Condensed
}
else
{
self.SummaryLabel.font = UIFont(name: "AvenirNextCondensed-Bold", size: 18)//-Next-Condensed
self.SummaryLabel.numberOfLines = 2
}
}
SummaryLabel.text = summary
SummaryLabel.textAlignment = .Center
SummaryLabel.textColor = UIColor.grayColor()
self.addSubview(SummaryLabel)
}
func setNameLabel(name:String = "0")
{
if name.characters.count < 8
{
NameLabel.font = UIFont(name: "AvenirNextCondensed", size: 30)//-Next-Condensed
}
else
{
NameLabel.font = UIFont(name: "AvenirNextCondensed", size: 15)//-Next-Condensed
}
NameLabel.text = name
NameLabel.textAlignment = .Center
NameLabel.textColor = UIColor.blackColor()
self.addSubview(NameLabel)
}
func loadImage(wEmoji:String = "fog" , ImagePath:String = "gravatar.png")
{
//var cosa = "⚡️🌙☀️⛅️☁️💧💦☔️💨❄️🔥🌌⛄️⚠️❗️🌁🚀"
let dictEmoji:Dictionary = [ "clear-day": "☀️","clear-night": "🌙", "rain":"☔️", "snow":"❄️", "sleet":"💦", "wind":"💨","fog":"🌁", "cloudy":"☁️", "partly-cloudy-day":"⛅️", "partly-cloudy-night":"🌌", "hail":"⛄️", "thunderstorm":"⚡️", "tornado":"⚠️","rocket":"🚀"]
WeatherLabelEmoji.text = dictEmoji[wEmoji]
// WeatherLabelEmoji.center.y = (imageView?.center.y)!
WeatherLabelEmoji.font = UIFont(name: "HelveticaNeue-Bold", size: 80)
WeatherLabelEmoji.textAlignment = .Center
WeatherLabelEmoji.textColor = UIColor.cyanColor()
self.imageView!.image = UIImage(named: ImagePath)
self.addSubview(WeatherLabelEmoji)
// WeatherLabelEmoji.center.x = (imageView?.frame.size.width)!/2
// WeatherLabelEmoji.center.y = (imageView?.center.y)! - ((imageView?.frame.size.height)!/2)
}
func getDateDayString(wdate:String = "0") -> String //http://stackoverflow.com/questions/28875356/how-to-get-next-10-days-from-current-date-in-swift
{//http://stackoverflow.com/questions/25533147/get-day-of-week-using-nsdate-swift
let date = NSDate(timeIntervalSince1970: NSTimeInterval(wdate)! ) //1415637900 )
if wdate == "0"
{
return wdate
}
else
{
let formatter = NSDateFormatter()
formatter.dateFormat = "YYYY-MM-dd"
let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let myComponents = myCalendar.components(.Weekday, fromDate: date)
let weekDay = myComponents.weekday
//let newDate = formatter.stringFromDate(date)
return self.weekDays[weekDay.description]!
}
}
}
|
fe28a9c4547c90ae682d6d456469b897
| 32.726667 | 266 | 0.582922 | false | false | false | false |
vulgur/WeeklyFoodPlan
|
refs/heads/master
|
WeeklyFoodPlan/WeeklyFoodPlan/Views/Food/FoodCells/FoodHeaderViewCell.swift
|
mit
|
1
|
//
// FoodHeaderViewCell.swift
// WeeklyFoodPlan
//
// Created by vulgur on 2017/2/19.
// Copyright © 2017年 MAD. All rights reserved.
//
import UIKit
import ImagePicker
protocol FoodHeaderViewCellDelegate {
func didInputName(_ name: String)
func didToggleFavorButton()
func didTapHeaderImageView(_ imageView: UIImageView)
}
class FoodHeaderViewCell: UITableViewCell {
@IBOutlet var headerImageView: UIImageView!
@IBOutlet var headerLabel: UILabel!
@IBOutlet var favorButton: UIButton!
static let placeholderText = "输入美食名称".localized()
var delegate: FoodHeaderViewCellDelegate?
private var headerTextField: UITextField = UITextField()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let tapLabel = UITapGestureRecognizer(target: self, action: #selector(headerLabelTapped))
headerLabel.addGestureRecognizer(tapLabel)
headerLabel.isUserInteractionEnabled = true
headerLabel.isHidden = false
headerImageView.isUserInteractionEnabled = true
let tapImageView = UITapGestureRecognizer(target: self, action: #selector(headerImageViewTapped))
headerImageView.addGestureRecognizer(tapImageView)
favorButton.addTarget(self, action: #selector(toggleButton), for: .touchUpInside)
headerTextField.isHidden = true
}
func setFavorButtonState(_ isFavored: Bool) {
if isFavored {
favorButton.setImage(#imageLiteral(resourceName: "heart"), for: .normal)
} else {
favorButton.setImage(#imageLiteral(resourceName: "unheart"), for: .normal)
}
}
@objc private func toggleButton() {
delegate?.didToggleFavorButton()
}
@objc private func headerImageViewTapped() {
delegate?.didTapHeaderImageView(headerImageView)
}
@objc private func headerLabelTapped() {
let frame = headerLabel.frame
headerLabel.isHidden = true
self.contentView.addSubview(headerTextField)
headerTextField.frame = frame
headerTextField.backgroundColor = UIColor.white
headerTextField.textAlignment = .center
headerTextField.delegate = self
headerTextField.isHidden = false
headerTextField.becomeFirstResponder()
}
}
extension FoodHeaderViewCell: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if headerLabel.text == FoodHeaderViewCell.placeholderText {
textField.text = ""
} else {
textField.text = headerLabel.text
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
headerLabel.isHidden = false
if let text = textField.text {
if text.isEmpty {
headerLabel.text = FoodHeaderViewCell.placeholderText
} else {
headerLabel.text = text
delegate?.didInputName(text)
}
}
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
headerLabel.isHidden = false
if let text = textField.text {
if text.isEmpty {
headerLabel.text = FoodHeaderViewCell.placeholderText
} else {
headerLabel.text = text
delegate?.didInputName(text)
}
}
textField.removeFromSuperview()
}
}
|
a962f669320bf721b93acfceaa981ee0
| 31.299065 | 105 | 0.651331 | false | false | false | false |
MessageKit/MessageKit
|
refs/heads/main
|
Sources/Views/Cells/AudioMessageCell.swift
|
mit
|
1
|
// MIT License
//
// Copyright (c) 2017-2019 MessageKit
//
// 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 AVFoundation
import UIKit
/// A subclass of `MessageContentCell` used to display video and audio messages.
open class AudioMessageCell: MessageContentCell {
// MARK: Open
/// Responsible for setting up the constraints of the cell's subviews.
open func setupConstraints() {
playButton.constraint(equalTo: CGSize(width: 25, height: 25))
playButton.addConstraints(
left: messageContainerView.leftAnchor,
centerY: messageContainerView.centerYAnchor,
leftConstant: 5)
activityIndicatorView.addConstraints(centerY: playButton.centerYAnchor, centerX: playButton.centerXAnchor)
durationLabel.addConstraints(
right: messageContainerView.rightAnchor,
centerY: messageContainerView.centerYAnchor,
rightConstant: 15)
progressView.addConstraints(
left: playButton.rightAnchor,
right: durationLabel.leftAnchor,
centerY: messageContainerView.centerYAnchor,
leftConstant: 5,
rightConstant: 5)
}
open override func setupSubviews() {
super.setupSubviews()
messageContainerView.addSubview(playButton)
messageContainerView.addSubview(activityIndicatorView)
messageContainerView.addSubview(durationLabel)
messageContainerView.addSubview(progressView)
setupConstraints()
}
open override func prepareForReuse() {
super.prepareForReuse()
progressView.progress = 0
playButton.isSelected = false
activityIndicatorView.stopAnimating()
playButton.isHidden = false
durationLabel.text = "0:00"
}
/// Handle tap gesture on contentView and its subviews.
open override func handleTapGesture(_ gesture: UIGestureRecognizer) {
let touchLocation = gesture.location(in: self)
// compute play button touch area, currently play button size is (25, 25) which is hardly touchable
// add 10 px around current button frame and test the touch against this new frame
let playButtonTouchArea = CGRect(
playButton.frame.origin.x - 10.0,
playButton.frame.origin.y - 10,
playButton.frame.size.width + 20,
playButton.frame.size.height + 20)
let translateTouchLocation = convert(touchLocation, to: messageContainerView)
if playButtonTouchArea.contains(translateTouchLocation) {
delegate?.didTapPlayButton(in: self)
} else {
super.handleTapGesture(gesture)
}
}
// MARK: - Configure Cell
open override func configure(
with message: MessageType,
at indexPath: IndexPath,
and messagesCollectionView: MessagesCollectionView)
{
super.configure(with: message, at: indexPath, and: messagesCollectionView)
guard let dataSource = messagesCollectionView.messagesDataSource else {
fatalError(MessageKitError.nilMessagesDataSource)
}
let playButtonLeftConstraint = messageContainerView.constraints.filter { $0.identifier == "left" }.first
let durationLabelRightConstraint = messageContainerView.constraints.filter { $0.identifier == "right" }.first
if !dataSource.isFromCurrentSender(message: message) {
playButtonLeftConstraint?.constant = 12
durationLabelRightConstraint?.constant = -8
} else {
playButtonLeftConstraint?.constant = 5
durationLabelRightConstraint?.constant = -15
}
guard let displayDelegate = messagesCollectionView.messagesDisplayDelegate else {
fatalError(MessageKitError.nilMessagesDisplayDelegate)
}
let tintColor = displayDelegate.audioTintColor(for: message, at: indexPath, in: messagesCollectionView)
playButton.imageView?.tintColor = tintColor
durationLabel.textColor = tintColor
progressView.tintColor = tintColor
if case .audio(let audioItem) = message.kind {
durationLabel.text = displayDelegate.audioProgressTextFormat(
audioItem.duration,
for: self,
in: messagesCollectionView)
}
displayDelegate.configureAudioCell(self, message: message)
}
// MARK: Public
/// The play button view to display on audio messages.
public lazy var playButton: UIButton = {
let playButton = UIButton(type: .custom)
let playImage = UIImage.messageKitImageWith(type: .play)
let pauseImage = UIImage.messageKitImageWith(type: .pause)
playButton.setImage(playImage?.withRenderingMode(.alwaysTemplate), for: .normal)
playButton.setImage(pauseImage?.withRenderingMode(.alwaysTemplate), for: .selected)
return playButton
}()
/// The time duration label to display on audio messages.
public lazy var durationLabel: UILabel = {
let durationLabel = UILabel(frame: CGRect.zero)
durationLabel.textAlignment = .right
durationLabel.font = UIFont.systemFont(ofSize: 14)
durationLabel.text = "0:00"
return durationLabel
}()
public lazy var activityIndicatorView: UIActivityIndicatorView = {
let activityIndicatorView = UIActivityIndicatorView(style: .medium)
activityIndicatorView.hidesWhenStopped = true
activityIndicatorView.isHidden = true
return activityIndicatorView
}()
public lazy var progressView: UIProgressView = {
let progressView = UIProgressView(progressViewStyle: .default)
progressView.progress = 0.0
return progressView
}()
}
|
4b5bcd54efac8eb0c38cd57984fe4054
| 37.901235 | 113 | 0.745795 | false | false | false | false |
soapyigu/LeetCode_Swift
|
refs/heads/master
|
DP/HouseRobberII.swift
|
mit
|
1
|
/**
* Question Link: https://leetcode.com/problems/house-robber-ii/
* Primary idea: Dynamic Programming, dp[i] = max(dp[i - 1], dp[i - 2], + nums[i])
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class HouseRobberII {
func rob(_ nums: [Int]) -> Int {
guard nums.count != 1 else {
return nums[0]
}
return max(helper(nums, 0, nums.count - 2), helper(nums, 1, nums.count - 1))
}
fileprivate func helper(_ nums: [Int], _ start: Int, _ end: Int) -> Int {
if start > end {
return 0
}
var prev = 0, current = 0
for i in start...end {
(current, prev) = (max(prev + nums[i], current), current)
}
return current
}
}
|
546c674d8873340349866a1238b184bc
| 25.133333 | 84 | 0.49553 | false | false | false | false |
ZacharyKhan/ZKNavigationController
|
refs/heads/master
|
ZKNavigationController/Classes/ZKNavigationController.swift
|
mit
|
1
|
//
// ZKNavigationController.swift
// ZKNavigationPopup
//
// Created by Zachary Khan on 7/25/16.
// Copyright © 2016 ZacharyKhan. All rights reserved.
//
import UIKit
import CoreGraphics
import Foundation
public class ZKNavigationController: UINavigationController {
var shown : Bool! = false
public func showAlert(PopupView: ZKNavigationPopupView?) {
if !self.shown {
print("NOTHIN SHOWN, GO AHEAD!")
let view = PopupView!
self.shown = true
let coverBarView = UIView(frame: CGRect(x: 0, y: -20, width: self.navigationBar.frame.width, height: 9))
coverBarView.backgroundColor = view.backgroundColor!
coverBarView.alpha = 0
self.navigationBar.addSubview(coverBarView)
dispatch_async(dispatch_get_main_queue(), {
UIView.animateWithDuration(1.2, animations: {
self.navigationBar.addSubview(view)
coverBarView.alpha = 1.0
view.alpha = 1.0
}, completion: { (val) in
UIView.animateWithDuration(0.65, delay: 0.3, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.65, options: .CurveEaseInOut, animations: {
coverBarView.frame = CGRect(x: 0, y: -20, width: self.navigationBar.frame.width, height: 20)
view.frame.origin.y += 55
}, completion: { (val) in
UIView.animateWithDuration(0.85, delay: 1, options: .CurveEaseIn, animations: {
view.alpha = 0
coverBarView.alpha = 0
}, completion: { (value) in
view.removeFromSuperview()
coverBarView.removeFromSuperview()
self.shown = false
})
})
})
})
} else {
print("UH OH! THERE'S ALREADY A NOTIFICATION SHOWN!")
}
}
}
|
7f4469e43ad7affc30722a01a24fd6d7
| 38.12069 | 167 | 0.48545 | false | false | false | false |
wtrumler/FluentSwiftAssertions
|
refs/heads/master
|
FluentSwiftAssertions/ComparableExtension.swift
|
mit
|
1
|
//
// ComparableExtension.swift
// FluentSwiftAssertions
//
// Created by Wolfgang Trumler on 13.05.17.
// Copyright © 2017 Wolfgang Trumler. All rights reserved.
//
import Foundation
import XCTest
extension Comparable {
public var should : Self {
return self
}
public func beGreaterThan<T : Comparable>(_ expression2: @autoclosure () throws -> T,
_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line,
assertionFunction: @escaping (_ expr1: @autoclosure () throws -> T, _ expr2: @autoclosure () throws -> T, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertGreaterThan) {
assertionFunction(self as! T, expression2, message, file, line)
}
public func beGreaterThanOrEqualTo<T : Comparable>(_ expression2: @autoclosure () throws -> T,
_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line,
assertionFunction: @escaping (_ expr1: @autoclosure () throws -> T, _ expr2: @autoclosure () throws -> T, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertGreaterThanOrEqual) {
assertionFunction(self as! T, expression2, message, file, line)
}
public func beLessThan<T : Comparable>(_ expression2: @autoclosure () throws -> T,
_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line,
assertionFunction: @escaping (_ expr1: @autoclosure () throws -> T, _ expr2: @autoclosure () throws -> T, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertLessThan) {
assertionFunction(self as! T, expression2, message, file, line)
}
public func beLessThanOrEqualTo<T : Comparable>(_ expression2: @autoclosure () throws -> T,
_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line,
assertionFunction: @escaping (_ expr1: @autoclosure () throws -> T, _ expr2: @autoclosure () throws -> T, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertLessThanOrEqual) {
assertionFunction(self as! T, expression2, message, file, line)
}
}
|
c0a664e859253a3ca362eccdafc05126
| 50.301887 | 254 | 0.539169 | false | false | false | false |
prebid/prebid-mobile-ios
|
refs/heads/master
|
PrebidMobileTests/RenderingTests/Tests/3dPartyWrappers/OpenMeasurement/OXMOpenMeasurementEventTrackerTest.swift
|
apache-2.0
|
1
|
/* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
class PBMOpenMeasurementEventTrackerTest: XCTestCase {
private var logToFile: LogToFileLock?
override func tearDown() {
logToFile = nil
super.tearDown()
}
func testEventsForWebViewSession() {
let measurement = PBMOpenMeasurementWrapper()
measurement.jsLib = "{}"
let webViewSession = measurement.initializeWebViewSession(WKWebView(), contentUrl: nil)
XCTAssertNotNil(webViewSession)
XCTAssertNotNil(webViewSession?.eventTracker)
let pbmTracker = webViewSession?.eventTracker as? PBMOpenMeasurementEventTracker
XCTAssertNotNil(pbmTracker)
XCTAssertNotNil(pbmTracker?.adEvents)
XCTAssertNil(pbmTracker?.mediaEvents)
}
func testEventsForNativeVideoSession() {
let measurement = PBMOpenMeasurementWrapper()
measurement.jsLib = "{}"
let verificationParams = PBMVideoVerificationParameters()
let resource = PBMVideoVerificationResource()
resource.url = "openx.com"
resource.vendorKey = "OpenX"
resource.params = "no params"
verificationParams.verificationResources.add(resource)
let nativeVideoSession = measurement.initializeNativeVideoSession(UIView(), verificationParameters:verificationParams)
XCTAssertNotNil(nativeVideoSession)
XCTAssertNotNil(nativeVideoSession?.eventTracker)
let pbmTracker = nativeVideoSession?.eventTracker as? PBMOpenMeasurementEventTracker
XCTAssertNotNil(pbmTracker)
XCTAssertNotNil(pbmTracker?.adEvents)
XCTAssertNotNil(pbmTracker?.mediaEvents)
}
func testInvalidSession() {
logToFile = .init()
var pbmTracker = PBMOpenMeasurementEventTracker(session: OMIDPrebidorgAdSession())
XCTAssertNotNil(pbmTracker)
XCTAssertNotNil(pbmTracker.session)
UtilitiesForTesting.checkLogContains("Open Measurement can't create ad events with error")
pbmTracker = PBMOpenMeasurementEventTracker()
XCTAssertNotNil(pbmTracker)
XCTAssertNil(pbmTracker.session)
logToFile = nil
logToFile = .init()
pbmTracker.trackEvent(PBMTrackingEvent.request)
UtilitiesForTesting.checkLogContains("Measurement Session is missed")
}
}
|
ed4b23f29e61f987771510ae0e283cbd
| 34.517647 | 126 | 0.690626 | false | true | false | false |
blokadaorg/blokada
|
refs/heads/main
|
ios/App/Repository/PermsRepo.swift
|
mpl-2.0
|
1
|
//
// This file is part of Blokada.
//
// 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 https://mozilla.org/MPL/2.0/.
//
// Copyright © 2021 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import Foundation
import Combine
typealias Granted = Bool
class PermsRepo: Startable {
var dnsProfilePerms: AnyPublisher<Granted, Never> {
writeDnsProfilePerms.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher()
}
var vpnProfilePerms: AnyPublisher<Granted, Never> {
writeVpnProfilePerms.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher()
}
var notificationPerms: AnyPublisher<Granted, Never> {
writeNotificationPerms.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher()
}
private lazy var notification = Services.notification
private lazy var dialog = Services.dialog
private lazy var systemNav = Services.systemNav
private lazy var sheetRepo = Repos.sheetRepo
private lazy var netxRepo = Repos.netxRepo
private lazy var dnsProfileActivatedHot = Repos.cloudRepo.dnsProfileActivatedHot
private lazy var enteredForegroundHot = Repos.stageRepo.enteredForegroundHot
private lazy var successfulPurchasesHot = Repos.paymentRepo.successfulPurchasesHot
private lazy var accountTypeHot = Repos.accountRepo.accountTypeHot
fileprivate let writeDnsProfilePerms = CurrentValueSubject<Granted?, Never>(nil)
fileprivate let writeVpnProfilePerms = CurrentValueSubject<Granted?, Never>(nil)
fileprivate let writeNotificationPerms = CurrentValueSubject<Granted?, Never>(nil)
private var previousAccountType: AccountType? = nil
private let bgQueue = DispatchQueue(label: "PermsRepoBgQueue")
private var cancellables = Set<AnyCancellable>()
func start() {
onDnsProfileActivated()
onForeground_checkNotificationPermsAndClearNotifications()
onVpnPerms()
onPurchaseSuccessful_showActivatedSheet()
onAccountTypeUpgraded_showActivatedSheet()
}
func maybeDisplayDnsProfilePermsDialog() -> AnyPublisher<Ignored, Error> {
return dnsProfilePerms.first()
.tryMap { granted -> Ignored in
if !granted {
throw "show the dns profile dialog"
} else {
return true
}
}
.tryCatch { _ in
self.displayDnsProfilePermsInstructions()
.tryMap { _ in throw "we never know if dns profile has been chosen" }
}
.eraseToAnyPublisher()
}
func maybeAskVpnProfilePerms() -> AnyPublisher<Granted, Error> {
return accountTypeHot.first()
.flatMap { it -> AnyPublisher<Granted, Error> in
if it == .Plus {
return self.vpnProfilePerms.first()
.tryMap { granted -> Ignored in
if !granted {
throw "ask for vpn profile"
} else {
return true
}
}
.eraseToAnyPublisher()
} else {
return Just(true)
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
}
.tryCatch { _ in self.netxRepo.createVpnProfile() }
.eraseToAnyPublisher()
}
func askNotificationPerms() -> AnyPublisher<Granted, Error> {
return notification.askForPermissions()
.tryCatch { err in
self.dialog.showAlert(
message: L10n.notificationPermsDenied,
header: L10n.notificationPermsHeader,
okText: L10n.dnsprofileActionOpenSettings,
okAction: { self.systemNav.openAppSettings() }
)
}
.eraseToAnyPublisher()
}
func askForAllMissingPermissions() -> AnyPublisher<Ignored, Error> {
return sheetRepo.dismiss()
.delay(for: 0.3, scheduler: self.bgQueue)
.flatMap { _ in self.notification.askForPermissions() }
.tryCatch { err in
// Notification perm is optional, ask for others
return Just(true)
}
.flatMap { _ in self.maybeAskVpnProfilePerms() }
.delay(for: 0.3, scheduler: self.bgQueue)
.flatMap { _ in self.maybeDisplayDnsProfilePermsDialog() }
// Show the activation sheet again to confirm user choices, and propagate error
.tryCatch { err -> AnyPublisher<Ignored, Error> in
return Just(true)
.delay(for: 0.3, scheduler: self.bgQueue)
.tryMap { _ -> Ignored in
self.sheetRepo.showSheet(.Activated)
throw err
}
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
func displayNotificationPermsInstructions() -> AnyPublisher<Ignored, Error> {
return dialog.showAlert(
message: L10n.notificationPermsDesc,
header: L10n.notificationPermsHeader,
okText: L10n.dnsprofileActionOpenSettings,
okAction: { self.systemNav.openAppSettings() }
)
}
private func displayDnsProfilePermsInstructions() -> AnyPublisher<Ignored, Error> {
return dialog.showAlert(
message: L10n.dnsprofileDesc,
header: L10n.dnsprofileHeader,
okText: L10n.dnsprofileActionOpenSettings,
okAction: { self.systemNav.openSystemSettings() }
)
}
private func onDnsProfileActivated() {
dnsProfileActivatedHot
.sink(onValue: { it in self.writeDnsProfilePerms.send(it) })
.store(in: &cancellables)
}
private func onForeground_checkNotificationPermsAndClearNotifications() {
enteredForegroundHot
.flatMap { _ in self.notification.getPermissions() }
// When entering foreground also clear all notifications.
// It's so that we do not clutter the lock screen.
// We do have any notifications that need to stay after entering fg.
.map { allowed in
if allowed {
self.notification.clearAllNotifications()
}
return allowed
}
.sink(onValue: { it in self.writeNotificationPerms.send(it) })
.store(in: &cancellables)
}
private func onVpnPerms() {
netxRepo.permsHot
.sink(onValue: { it in self.writeVpnProfilePerms.send(it) })
.store(in: &cancellables)
}
// Will display Activated sheet on successful purchase.
// This will happen on any purchase by user or if necessary perms are missing.
// It will ignore StoreKit auto restore if necessary perms are granted.
private func onPurchaseSuccessful_showActivatedSheet() {
// successfulPurchasesHot
// .flatMap { it -> AnyPublisher<(Account, UserInitiated, Granted, Granted), Never> in
// let (account, userInitiated) = it
// return Publishers.CombineLatest4(
// Just(account), Just(userInitiated),
// self.dnsProfilePerms, self.vpnProfilePerms
// )
// .eraseToAnyPublisher()
// }
// .map { it -> Granted in
// let (account, userinitiated, dnsAllowed, vpnAllowed) = it
// if dnsAllowed && (account.type != "plus" || vpnAllowed) && !userinitiated {
// return true
// } else {
// return false
// }
// }
// .sink(onValue: { permsOk in
// if !permsOk {
// self.sheetRepo.showSheet(.Activated)
// }
// })
// .store(in: &cancellables)
}
// We want user to notice when they upgrade.
// From Libre to Cloud or Plus, as well as from Cloud to Plus.
// In the former case user will have to grant several permissions.
// In the latter case, probably just the VPN perm.
// If user is returning, it may be that he already has granted all perms.
// But we display the Activated sheet anyway, as a way to show that upgrade went ok.
// This will also trigger if StoreKit sends us transaction (on start) that upgrades.
private func onAccountTypeUpgraded_showActivatedSheet() {
accountTypeHot
.filter { now in
if self.previousAccountType == nil {
self.previousAccountType = now
return false
}
let prev = self.previousAccountType
self.previousAccountType = now
if prev == .Libre && now != .Libre {
return true
} else if prev == .Cloud && now == .Plus {
return true
} else {
return false
}
}
.sink(onValue: { _ in self.sheetRepo.showSheet(.Activated)} )
.store(in: &cancellables)
}
}
|
fc96e45dcd95febf695cec40f660423e
| 36.220833 | 93 | 0.611217 | false | false | false | false |
hhsolar/MemoryMaster-iOS
|
refs/heads/master
|
MemoryMaster/Utility/Transition/SlideOutAnimationController.swift
|
mit
|
1
|
import UIKit
class SlideOutAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from) {
let containerView = transitionContext.containerView
let duration = transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, animations: {
fromView.center.y -= containerView.bounds.size.height
fromView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
}, completion: { finished in
transitionContext.completeTransition(finished)
})
}
}
}
|
e2193553dea184ca38511dab7cfabaf1
| 40.55 | 107 | 0.756919 | false | false | false | false |
EmmaXiYu/SE491
|
refs/heads/master
|
DonateParkSpot/DonateParkSpot/BuyDetailController.swift
|
apache-2.0
|
1
|
//
// BuyDetailController.swift
// DonateParkSpot
//
// Created by Rafael Guerra on 10/29/15.
// Copyright © 2015 Apple. All rights reserved.
//
import UIKit
import MapKit
import Parse
class BuyDetailController : UIViewController, MKMapViewDelegate {
var spot : Spot?
//var ownerName:String = ""
//var ownerId:String = ""
@IBOutlet weak var map: MKMapView!
@IBOutlet weak var type: UILabel!
@IBOutlet weak var rate: UILabel!
@IBOutlet weak var timeToLeave: UILabel!
@IBOutlet weak var minDonation: UILabel!
@IBOutlet weak var donation: UIStepper!
let locationManager=CLLocationManager()
override func viewDidLoad() {
if spot != nil {
self.title = spot!.owner!.email! + "'s Spot"
if spot!.type == 1 {
type.text = "Paid Spot"
rate.text = "U$ " + spot!.rate.description + "0"
timeToLeave.text = spot!.timeToLeave?.description
minDonation.text = "U$ " + spot!.minDonation.description + ".00"
}else{
type.text = "Free Spot"
rate.text = "Free"
timeToLeave.text = "Zero Minutes"
minDonation.text = "U$ " + spot!.minDonation.description + ".00"
}
donation.minimumValue = Double(spot!.minDonation)
donation.maximumValue = 1.79e307
donation.stepValue = 1
self.map.delegate = self
self.locationManager.desiredAccuracy=kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
let pinLocation: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: (spot?.location.latitude)!, longitude: (spot?.location.longitude)!)
let region=MKCoordinateRegion(center: pinLocation, span: MKCoordinateSpan(latitudeDelta: 0.004, longitudeDelta: 0.004))
self.map.setRegion(region, animated: true)
let annotation = CustomerAnnotation(coordinate: pinLocation,spotObject: spot!, title :(spot!.owner!.email!),subtitle: (spot!.owner?.objectId)!)
//annotation.subtitle = "Rating bar here"
self.map.addAnnotation(annotation)
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation
) -> MKAnnotationView!{
if let a = annotation as? CustomerAnnotation {
let pinAnnotationView = MKPinAnnotationView(annotation: a, reuseIdentifier: "myPin")
//let ownerID:String = a.subtitle!
let spot = a.spot
let ownerScore = a.spot.owner?.getRatingAsSeller()
let name = a.title!
let ownerID:String = (a.spot.owner?.objectId)!
a.subtitle = String(ownerScore!)
let pic = UIImageView (image: UIImage(named: "test.png"))
pinAnnotationView.canShowCallout = true
pinAnnotationView.draggable = false
pinAnnotationView.canShowCallout = true
pinAnnotationView.animatesDrop = true
pinAnnotationView.pinColor = MKPinAnnotationColor.Purple
let query = PFUser.query()
do{ let user = try query!.getObjectWithId(ownerID) as! PFUser
if let userPicture = user["Image"] as? PFFile {
userPicture.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
if error == nil {
pic.image = UIImage(data:imageData!)
}
}
}
}
catch{
//Throw exception here
}
pic.frame = CGRectMake(0, 0, 40, 40);
pinAnnotationView.leftCalloutAccessoryView = pic
pinAnnotationView.frame = CGRectMake(0,0,500,500)
return pinAnnotationView
}
return nil
}
@IBAction func upDown(sender: UIStepper) {
minDonation.text = "U$ " + sender.value.description + "0"
}
@IBAction func buy() {
if(IsValidBuyer() == true){
let user = PFUser.currentUser()
let query = PFQuery.init(className: "Bid")
query.whereKey("user", equalTo: user!)
query.whereKey("spot", equalTo: spot!.toPFObject())
query.whereKey("StatusId", notEqualTo: 4) // 4 is cancel by bid owner
do{
let results = try query.findObjects()
if results.count > 0 {
let alert = UIAlertView.init(title: "Bid already made", message: "You cannot bid twice on a Spot. You can cancel your current Bid and bid again for this Spot", delegate: nil, cancelButtonTitle: "OK")
alert.show()
return
}
}catch{
}
let bid = Bid()
bid.bidder = user
bid.value = donation.value
bid.spot = spot
bid.statusId = 1
bid.toPFObjet().saveInBackgroundWithBlock{
(success: Bool, error: NSError?) -> Void in
if(success){
print(success)
}else{
print(error)
}
}
updateSpot((self.spot?.spotId)!, status : 1)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
func IsValidBuyer()->Bool
{
var IsValid = true
var msg = ""
if(spot?.owner?.email == PFUser.currentUser()?.email)
{
IsValid = false
msg = "You can not Bid your Own Spot" + "\r\n"
}
if(msg.characters.count > 0)
{
let alertController = UIAlertController(title: "Validation Error", message: msg, preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion:nil)
}
return IsValid
}
func updateSpot(spotid : String, status :Int)-> Void
{
let prefQuery = PFQuery(className: "Spot")
prefQuery.getObjectInBackgroundWithId(spotid){
(prefObj: PFObject?, error: NSError?) -> Void in
if error != nil {
print(error)
} else if let prefObj = prefObj {
prefObj["StatusId"] = status
prefObj.saveInBackground()
}
}
}
}
|
481b9afc0b9b561156d9abe6095e31f1
| 36.2 | 219 | 0.527731 | false | false | false | false |
jdbateman/Lendivine
|
refs/heads/master
|
Lendivine/CountriesAPI.swift
|
mit
|
1
|
//
// CountriesAPI.swift
// Lendivine
//
// Created by john bateman on 3/9/16.
// Copyright © 2016 John Bateman. All rights reserved.
//
// An extension of RESTCountries providing a wrapper api that acquires data on countries using the RestCountries API: http://restcountries.eu/,
// JSON data returned by rest queries is converted to core data manage objects on the main thread in this extension.
import Foundation
import CoreData
extension RESTCountries {
/*
@brief Get a collection of Country objects representing all countries.
@discussion Parses the data returned from the RESTCountries api into a collection of Country objects. Invokes the https://restcountries.eu/rest/v1/all endpoint.
@return A collection of Country objects, else nil if an error occurred.
*/
func getCountries(completionHandler: (countries: [Country]?, error: NSError?) -> Void) {
/* 1. Specify parameters */
// none
// set up http header parameters
// none
/* 2. Make the request */
//let apiEndpoint = "name/canada"
let apiEndpoint = "all"
taskForGETMethod(baseUrl: "https://restcountries.eu/rest/v1/", method: apiEndpoint, headerParameters: nil, queryParameters: nil) { JSONResult, error in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
// didn't work. bubble up error.
completionHandler(countries: nil, error: error)
} else {
// parse the json response
var countries = [Country]()
if let returnData = JSONResult as! [[String:AnyObject]]? {
// Ensure cored data operations happen on the main thread.
dispatch_async(dispatch_get_main_queue()) {
// Convert each dictionary in the response data into a Country object.
for dictionary in returnData {
let country:Country = Country(dictionary: dictionary, context: CoreDataContext.sharedInstance().countriesContext)
countries.append(country)
}
completionHandler(countries: countries, error: nil)
}
}
else {
completionHandler(countries: nil, error: error)
}
}
}
}
}
|
12d340138bfd852a91ff7eefcc08266a
| 40.852459 | 168 | 0.571708 | false | false | false | false |
a2/passcards
|
refs/heads/master
|
Sources/PasscardsServer/PasscardsServer+Vanity.swift
|
mit
|
1
|
import Foundation
import MongoKitten
import Kitura
import Shove
extension PasscardsServer {
func makeVanityRouter() -> Router {
let router = Router()
router.all(middleware: BodyParser())
router.get("/:passId", handler: getPass)
router.post("/:passId", handler: uploadPass)
router.put("/:passId", handler: updatePass)
return router
}
func getPass(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws {
guard let passName = request.parameters["passId"],
let vanityId = parseVanityId(from: passName),
let pass = try passes.findOne(matching: "vanityId" == vanityId)
else {
try response.status(.notFound).end()
return
}
guard case .binary(_, let data) = pass["data"], !data.isEmpty else {
try response.status(.noContent).end()
return
}
response.headers["Content-Type"] = "application/vnd.apple.pkpass"
if let updatedAt = pass["updatedAt"].dateValue {
response.headers["Last-Modified"] = rfc2616DateFormatter.string(from: updatedAt)
}
try response.send(data: Data(data)).end()
}
func isAuthorized(request: RouterRequest) -> Bool {
return request.headers["Authorization"] == "Token \(updateToken)"
}
func uploadPass(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws {
guard isAuthorized(request: request) else {
try response.status(.unauthorized).end()
return
}
guard let passName = request.parameters["passId"],
let vanityId = parseVanityId(from: passName)
else {
try response.status(.badRequest).end()
return
}
guard try passes.findOne(matching: "vanityId" == vanityId) == nil else {
response.headers["Location"] = request.url
try response.status(.seeOther).end()
return
}
guard case .some(.multipart(let parts)) = request.body else {
try response.status(.badRequest).end()
return
}
guard let authenticationToken = findString(in: parts, byName: "authenticationToken"),
let passTypeIdentifier = findString(in: parts, byName: "passTypeIdentifier"),
let serialNumber = findString(in: parts, byName: "serialNumber"),
let bodyData = findData(in: parts, byName: "file")
else {
try response.status(.badRequest).end()
return
}
var bodyBytes = [UInt8](repeating: 0, count: bodyData.count)
_ = bodyBytes.withUnsafeMutableBufferPointer { bufferPtr in bodyData.copyBytes(to: bufferPtr) }
let pass: Document = [
"vanityId": ~vanityId,
"authenticationToken": ~authenticationToken,
"passTypeIdentifier": ~passTypeIdentifier,
"serialNumber": ~serialNumber,
"updatedAt": ~Date(),
"data": BSON.Value.binary(subtype: .generic, data: bodyBytes),
]
try passes.insert(pass)
try response.status(.created).end()
}
func updatePass(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws {
guard isAuthorized(request: request) else {
try response.status(.unauthorized).end()
return
}
guard let passName = request.parameters["passId"],
let vanityId = parseVanityId(from: passName)
else {
try response.status(.badRequest).end()
return
}
guard var pass = try passes.findOne(matching: "vanityId" == vanityId) else {
try response.status(.notFound).end()
return
}
guard case .some(.multipart(let parts)) = request.body,
let bodyData = findData(in: parts, byName: "file")
else {
try response.status(.badRequest).end()
return
}
var bodyBytes = [UInt8](repeating: 0, count: bodyData.count)
_ = bodyBytes.withUnsafeMutableBufferPointer { bufferPtr in bodyData.copyBytes(to: bufferPtr) }
pass["data"] = .binary(subtype: .generic, data: bodyBytes)
pass["updatedAt"] = ~Date()
try passes.update(matching: "vanityId" == vanityId, to: pass)
let payload = "{\"aps\":{}}".data(using: .utf8)!
var notification = PushNotification(payload: payload)
notification.topic = pass["passTypeIdentifier"].stringValue
for installation in try installations.find(matching: "passId" == pass["_id"]) {
let deviceToken = installation["deviceToken"].string
shoveClient.send(notification: notification, to: deviceToken)
}
try response.status(.OK).end()
}
}
|
475ebf41b8c16437691ca02f094634f6
| 35.074074 | 106 | 0.598973 | false | false | false | false |
bearjaw/RBSRealmBrowser
|
refs/heads/master
|
Pod/Classes/BrowserTools.swift
|
mit
|
1
|
//
// RBSTools.swift
// Pods
//
// Created by Max Baumbach on 03/05/2017.
//
//
import AVFoundation
import RealmSwift
final class BrowserTools {
private static let localVersion = "v0.5.0"
static func stringForProperty(_ property: Property, object: Object) -> String {
if property.isArray || property.type == .linkingObjects {
return arrayString(for: property, object: object)
}
return handleSupportedTypes(for: property, object: object)
}
static func previewText(for properties: [Property], object: Object) -> String {
properties.prefix(2).reduce(into: "") { result, property in
result += previewText(for: property, object: object)
}
}
static func previewText(for property: Property, object: Object) -> String {
guard property.type != .object, property.type != .data else { return "\(property.name):\t\t Value not supported" }
return """
\(property.name): \(handleSupportedTypes(for: property, object: object))
"""
}
static func checkForUpdates() {
guard !isPlayground() else { return }
let url = "https://img.shields.io/cocoapods/v/RBSRealmBrowser.svg"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request,
completionHandler: { data, response, _ in
guard let callback = response as? HTTPURLResponse else {
return
}
guard let data = data, callback.statusCode == 200 else { return }
let websiteData = String(data: data, encoding: .utf8)
guard let gitVersion = websiteData?.contains(localVersion) else {
return
}
if !gitVersion {
print("""
🚀 A new version of RBSRealmBrowser is now available:
https://github.com/bearjaw/RBSRealmBrowser/blob/master/CHANGELOG.md
""")
}
}).resume()
}
private static func isPlayground() -> Bool {
guard let isInPlayground = (Bundle.main.bundleIdentifier?.hasPrefix("com.apple.dt.playground")) else {
return false
}
return isInPlayground
}
private static func arrayString(for property: Property, object: Object) -> String {
if property.isArray || property.type == .linkingObjects {
let array = object.dynamicList(property.name)
return "\(array.count) objects ->"
}
return ""
}
// Disabled
// swiftlint:disable cyclomatic_complexity
private static func handleSupportedTypes(for property: Property, object: Object) -> String {
switch property.type {
case .bool:
if let value = object[property.name] as? Bool {
return value.humanReadable
}
case .int, .float, .double:
if let number = object[property.name] as? NSNumber {
return number.humanReadable
}
case .string:
if let string = object[property.name] as? String {
return string
}
case .object:
if let objectData = object[property.name] as? Object {
return objectData.humanReadable
}
return "nil"
case .any, .data, .linkingObjects:
let data = object[property.name]
return "\(data.debugDescription)"
case .date:
if let date = object[property.name] as? Date {
return "\(date)"
}
case .objectId:
if let id = object[property.name] as? ObjectId {
return id.stringValue
}
case .decimal128:
if let decimal = object[property.name] as? Decimal128 {
return "\(decimal)"
}
default:
return "\(object[property.name] as Any)"
}
return "Unsupported type"
}
}
struct RealmStyle {
static let tintColor = UIColor(red:0.35, green:0.34, blue:0.62, alpha:1.0)
}
|
2bc0c500ab5a52ed725edcaf1205b5dc
| 35.934426 | 122 | 0.521971 | false | false | false | false |
D-32/DMSwipeCards
|
refs/heads/master
|
DMSwipeCards/Classes/DMSwipeCard.swift
|
mit
|
1
|
//
// DMSwipeCard.swift
// Pods
//
// Created by Dylan Marriott on 18/12/16.
//
//
import Foundation
import UIKit
protocol DMSwipeCardDelegate: class {
func cardSwipedLeft(_ card: DMSwipeCard)
func cardSwipedRight(_ card: DMSwipeCard)
func cardTapped(_ card: DMSwipeCard)
}
class DMSwipeCard: UIView {
weak var delegate: DMSwipeCardDelegate?
var obj: Any!
var leftOverlay: UIView?
var rightOverlay: UIView?
private let actionMargin: CGFloat = 120.0
private let rotationStrength: CGFloat = 320.0
private let rotationAngle: CGFloat = CGFloat(Double.pi) / CGFloat(8.0)
private let rotationMax: CGFloat = 1
private let scaleStrength: CGFloat = -2
private let scaleMax: CGFloat = 1.02
private var xFromCenter: CGFloat = 0.0
private var yFromCenter: CGFloat = 0.0
private var originalPoint = CGPoint.zero
override init(frame: CGRect) {
super.init(frame: frame)
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(dragEvent(gesture:)))
panGesture.delegate = self
self.addGestureRecognizer(panGesture)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapEvent(gesture:)))
tapGesture.delegate = self
self.addGestureRecognizer(tapGesture)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureOverlays() {
self.configureOverlay(overlay: self.leftOverlay)
self.configureOverlay(overlay: self.rightOverlay)
}
private func configureOverlay(overlay: UIView?) {
if let o = overlay {
self.addSubview(o)
o.alpha = 0.0
}
}
@objc func dragEvent(gesture: UIPanGestureRecognizer) {
xFromCenter = gesture.translation(in: self).x
yFromCenter = gesture.translation(in: self).y
switch gesture.state {
case .began:
self.originalPoint = self.center
break
case .changed:
let rStrength = min(xFromCenter / self.rotationStrength, rotationMax)
let rAngle = self.rotationAngle * rStrength
let scale = min(1 - fabs(rStrength) / self.scaleStrength, self.scaleMax)
self.center = CGPoint(x: self.originalPoint.x + xFromCenter, y: self.originalPoint.y + yFromCenter)
let transform = CGAffineTransform(rotationAngle: rAngle)
let scaleTransform = transform.scaledBy(x: scale, y: scale)
self.transform = scaleTransform
self.updateOverlay(xFromCenter)
break
case .ended:
self.afterSwipeAction()
break
default:
break
}
}
@objc func tapEvent(gesture: UITapGestureRecognizer) {
self.delegate?.cardTapped(self)
}
private func afterSwipeAction() {
if xFromCenter > actionMargin {
self.rightAction()
} else if xFromCenter < -actionMargin {
self.leftAction()
} else {
UIView.animate(withDuration: 0.3) {
self.center = self.originalPoint
self.transform = CGAffineTransform.identity
self.leftOverlay?.alpha = 0.0
self.rightOverlay?.alpha = 0.0
}
}
}
private func updateOverlay(_ distance: CGFloat) {
var activeOverlay: UIView?
if (distance > 0) {
self.leftOverlay?.alpha = 0.0
activeOverlay = self.rightOverlay
} else {
self.rightOverlay?.alpha = 0.0
activeOverlay = self.leftOverlay
}
activeOverlay?.alpha = min(fabs(distance)/100, 1.0)
}
private func rightAction() {
let finishPoint = CGPoint(x: 500, y: 2 * yFromCenter + self.originalPoint.y)
UIView.animate(withDuration: 0.3, animations: {
self.center = finishPoint
}) { _ in
self.removeFromSuperview()
}
self.delegate?.cardSwipedRight(self)
}
private func leftAction() {
let finishPoint = CGPoint(x: -500, y: 2 * yFromCenter + self.originalPoint.y)
UIView.animate(withDuration: 0.3, animations: {
self.center = finishPoint
}) { _ in
self.removeFromSuperview()
}
self.delegate?.cardSwipedLeft(self)
}
}
extension DMSwipeCard: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
|
9ebc243ebca1f957e9d9d528ea37202b
| 26.129252 | 154 | 0.726429 | false | false | false | false |
ideafamily/Emonar
|
refs/heads/master
|
Emonar/ArchiveViewController.swift
|
mit
|
1
|
//
// ArchiveViewController.swift
// Emonar
//
// Created by ZengJintao on 3/8/16.
// Copyright © 2016 ZengJintao. All rights reserved.
//
import UIKit
class ArchiveViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var archiveTableView: UITableView!
var dataArray = FileManager.sharedInstance.getAllLocalRecordFileFromStorage()
var recordFileIndex:Int!
override func viewDidLoad() {
super.viewDidLoad()
let backButton = UIBarButtonItem()
backButton.title = ""
navigationItem.backBarButtonItem = backButton
// navigationItem.titleView
self.navigationController?.navigationBar.titleTextAttributes = [
NSForegroundColorAttributeName: UIColor.white
]
navigationController!.navigationBar.barTintColor = UIColor.black
}
override func viewWillAppear(_ animated: Bool) {
archiveTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ArchiveTableViewCell", for: indexPath) as! ArchiveTableViewCell
let index = dataArray.count - indexPath.row - 1
cell.recordNameLabel.text = self.dataArray[index].name
cell.timeLengthLabel.text = self.dataArray[index].recordLength
cell.dateLabel.text = self.dataArray[index].currentDate
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let index = dataArray.count - indexPath.row - 1
if editingStyle == .delete {
// Delete the row from the data source
dataArray.remove(at: indexPath.row)
FileManager.sharedInstance.deleteRecordFileFromStorage(index)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let index = dataArray.count - indexPath.row - 1
self.recordFileIndex = index
self.performSegue(withIdentifier: "goToReplay", sender: self)
tableView.deselectRow(at: indexPath, animated: true)
}
@IBAction func mainPressed(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
// 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.
if segue.identifier == "goToReplay" {
let destination = segue.destination as! ArchiveReplayViewController
let indexPath = archiveTableView.indexPathForSelectedRow!.row
let index = dataArray.count - indexPath - 1
destination.audioName = dataArray[index].name
destination.recordFileIndex = self.recordFileIndex
// print("indexpath is \(archiveTableView.indexPathForSelectedRow!.row)")
}
}
}
|
07f421e12d0fabfc452d6896159e0dcf
| 35.524752 | 129 | 0.676606 | false | false | false | false |
dtartaglia/MVVM_Redux
|
refs/heads/master
|
MVVM Redux/Flow.swift
|
mit
|
1
|
//
// Flow.swift
// MVVM Redux
//
// Created by Daniel Tartaglia on 1/16/16.
// Copyright © 2016 Daniel Tartaglia. All rights reserved.
//
import Foundation
struct AppState {
var detailState = DetailState()
}
struct DetailState {
var firstName: String = ""
var lastName: String = ""
var amount: Double = 0.0
var resultText: String {
return firstName + " " + lastName + "\n" + "$" + String(amount)
}
}
enum DetailAction {
case NameChanged(String?)
case AmountChanged(String?)
}
private let combinedReducer = CombinedReducer([DetailReducer()])
struct DetailReducer: Reducer {
typealias ReducerStateType = DetailState
func handleAction(state: ReducerStateType, action: Action) -> ReducerStateType {
var result = state
switch action as! DetailAction {
case .NameChanged(let newName):
if let newName = newName {
result.firstName = extractFirstName(newName)
result.lastName = extractLastName(newName)
}
else {
result.firstName = ""
result.lastName = ""
}
case .AmountChanged(let newAmount):
if let newAmount = newAmount, let value = Double(newAmount) {
result.amount = value
}
else {
result.amount = 0.0
}
}
return result;
}
}
func extractFirstName(nameText: String) -> String {
let names = nameText.componentsSeparatedByString(" ").filter { !$0.isEmpty }
var result = ""
if names.count == 1 {
result = names[0]
}
else if names.count > 1 {
result = names[0..<names.count - 1].joinWithSeparator(" ")
}
return result
}
func extractLastName(nameText: String) -> String {
let names = nameText.componentsSeparatedByString(" ").filter { !$0.isEmpty }
var result = ""
if names.count > 1 {
result = names.last!
}
return result
}
let mainStore = MainStore(reducer: combinedReducer, state: DetailState())
|
c82a221464225adb25ccececc2482d82
| 20.235294 | 81 | 0.68144 | false | false | false | false |
morbrian/udacity-nano-onthemap
|
refs/heads/master
|
OnTheMap/ParseClient.swift
|
mit
|
1
|
//
// ParseClient.swift
// OnTheMap
//
// Created by Brian Moriarty on 4/24/15.
// Copyright (c) 2015 Brian Moriarty. All rights reserved.
//
import Foundation
// ParseClient
// Provides simple api layer on top of WebClient designed to encapsulate
// the common patterns associated with REST apis based on the Parse framework.
public class ParseClient {
private var applicationId: String!
private var restApiKey: String!
private var StandardHeaders: [String:String] {
return [
"X-Parse-Application-Id":applicationId,
"X-Parse-REST-API-Key":restApiKey
]
}
private var webClient: WebClient!
// Initialize with app specific keys and id
// client: insteance of a WebClient
// applicationId: valid ID provided to this App for use with the Parse service.
// restApiKey: a developer API Key provided by registering with the Parse service.
public init(client: WebClient, applicationId: String, restApiKey: String) {
self.webClient = client
self.applicationId = applicationId
self.restApiKey = restApiKey
}
// Fetch a list of objects from the Parse service for the specified class type.
// className: the object model classname of the data type on Parse
// limit: maximum number of objects to fetch
// skip: number of objects to skip before fetching the limit.
// orderedBy: name of an attribute on the object model to sort results by.
// whereClause: Parse formatted query where clause to constrain query results.
public func fetchResultsForClassName(className: String, limit: Int = 50, skip: Int = 0, orderedBy: String = ParseJsonKey.UpdatedAt,
whereClause: String? = nil,
completionHandler: (resultsArray: [[String:AnyObject]]?, error: NSError?) -> Void) {
var parameterList: [String:AnyObject] = [ParseParameter.Limit:limit, ParseParameter.Skip: skip, ParseParameter.Order: orderedBy]
if let whereClause = whereClause {
parameterList[ParseParameter.Where] = whereClause
}
if let request = webClient.createHttpRequestUsingMethod(WebClient.HttpGet, forUrlString: "\(ParseClient.ObjectUrl)/\(className)",
includeHeaders: StandardHeaders,
includeParameters: parameterList) {
webClient.executeRequest(request) { jsonData, error in
if let resultsArray = jsonData?.valueForKey(ParseJsonKey.Results) as? [[String:AnyObject]] {
completionHandler(resultsArray: resultsArray, error: nil)
} else if let error = error {
completionHandler(resultsArray: nil, error: error)
} else if let errorMessage = jsonData?.valueForKey(ParseJsonKey.Error) as? String {
completionHandler(resultsArray: nil, error: ParseClient.errorForCode(.ParseServerError, message: errorMessage))
} else {
completionHandler(resultsArray: nil, error: ParseClient.errorForCode(.ResponseContainedNoResultObject))
}
}
} else {
completionHandler(resultsArray: nil, error: WebClient.errorForCode(.UnableToCreateRequest))
}
}
// Create an object of the specified class type.
// PRE: properties MUST NOT already contain an objectId, createdAt, or updatedAt properties.
// className: the object model classname of the data type on Parse
// withProperties: key value pair attributes of the new object.
// completionHandler - objectId: the ID of the newly create object
// completionHandler - createdAt: the time of creation for newly created object.
public func createObjectOfClassName(className: String, withProperties properties: [String:AnyObject],
completionHandler: (objectId: String?, createdAt: String?, error: NSError?) -> Void) {
performHttpMethod(WebClient.HttpPost, ofClassName: className, withProperties: properties) { jsonData, error in
if let objectId = jsonData?.valueForKey(ParseJsonKey.ObjectId) as? String,
createdAt = jsonData?.valueForKey(ParseJsonKey.CreateAt) as? String {
completionHandler(objectId: objectId, createdAt: createdAt, error: nil)
} else if let error = error {
completionHandler(objectId: nil, createdAt: nil, error: error)
} else if let errorMessage = jsonData?.valueForKey(ParseJsonKey.Error) as? String {
completionHandler(objectId: nil, createdAt: nil, error: ParseClient.errorForCode(.ParseServerError, message: errorMessage))
} else {
let responseError = ParseClient.errorForCode(.ResponseForCreateIsMissingExpectedValues)
completionHandler(objectId: nil, createdAt: nil, error: responseError)
}
}
}
// Delete an object of the specified class type with the given objectId
// className: the object model classname of the data type on Parse
public func deleteObjectOfClassName(className: String, objectId: String? = nil, completionHandler: (error: NSError?) -> Void) {
performHttpMethod(WebClient.HttpDelete, ofClassName: className, objectId: objectId) { jsonData, error in
completionHandler(error: error)
}
}
// Update an object of the specified class type and objectId with the new properties.
// className: the object model classname of the data type on Parse
// withProperties: key value pair attributes to update the object.
// objectId: the unique id of the object to update.
// completionHandler - updatedAt: the time object is updated when update successful
public func updateObjectOfClassName(className: String, withProperties properties: [String:AnyObject], objectId: String? = nil,
completionHandler: (updatedAt: String?, error: NSError?) -> Void) {
print("Raw Data: \(properties)")
performHttpMethod(WebClient.HttpPut, ofClassName: className, withProperties: properties, objectId: objectId) { jsonData, error in
if let updatedAt = jsonData?.valueForKey(ParseJsonKey.UpdatedAt) as? String {
completionHandler(updatedAt: updatedAt, error: nil)
} else if error != nil {
completionHandler(updatedAt: nil, error: error)
} else {
let responseError = ParseClient.errorForCode(.ResponseForUpdateIsMissingExpectedValues)
completionHandler(updatedAt: nil, error: responseError)
}
}
}
// Perform an HTTP/HTTPS request with the specified configuration and content.
// method: the HTTP method to use
// ofClassName: the PARSE classname targeted by the request.
// withProperties: the data properties
// objectId: the objectId targeted by the request
// requestHandler - jsonData: the parsed body content of the response
private func performHttpMethod(method: String, ofClassName className: String, withProperties properties: [String:AnyObject] = [String:AnyObject](),
objectId: String? = nil, requestHandler: (jsonData: AnyObject?, error: NSError?) -> Void ) {
do {
let body = try NSJSONSerialization.dataWithJSONObject(properties, options: NSJSONWritingOptions.PrettyPrinted)
var targetUrlString = "\(ParseClient.ObjectUrl)/\(className)"
if let objectId = objectId {
targetUrlString += "/\(objectId)"
}
if let request = webClient.createHttpRequestUsingMethod(method, forUrlString: targetUrlString,
withBody: body, includeHeaders: StandardHeaders) {
webClient.executeRequest(request, completionHandler: requestHandler)
} else {
requestHandler(jsonData: nil, error: WebClient.errorForCode(.UnableToCreateRequest))
}
} catch {
requestHandler(jsonData: nil, error: ParseClient.errorForCode(ErrorCode.ParseServerError))
}
}
}
// MARK: - Constants
extension ParseClient {
static let BaseUrl = "https://api.parse.com"
static let BasePath = "/1/classes"
static let ObjectUrl = BaseUrl + BasePath
// use reverse-sort by Updated time as default
static let DefaultSortOrder = "-\(ParseJsonKey.UpdatedAt)"
struct DateFormat {
static let ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SZZZZZ"
}
struct Locale {
static let EN_US_POSIX = "en_US_POSIX"
}
static var DateFormatter: NSDateFormatter {
let dateFormatter = NSDateFormatter()
let enUSPosixLocale = NSLocale(localeIdentifier: ParseClient.Locale.EN_US_POSIX)
dateFormatter.locale = enUSPosixLocale
dateFormatter.dateFormat = ParseClient.DateFormat.ISO8601
return dateFormatter
}
struct ParseParameter {
static let Limit = "limit"
static let Skip = "skip"
static let Order = "order"
static let Where = "where"
}
struct ParseJsonKey {
static let Results = "results"
static let Error = "error"
static let Count = "count"
static let ObjectId = "objectId"
static let CreateAt = "createdAt"
static let UpdatedAt = "updatedAt"
}
struct Logic {
static let LessThan = "lt"
static let GreaterThan = "gt"
}
}
// MARK: - Errors {
extension ParseClient {
private static let ErrorDomain = "ParseClient"
private enum ErrorCode: Int, CustomStringConvertible {
case ResponseContainedNoResultObject = 1
case ResponseForCreateIsMissingExpectedValues
case ResponseForUpdateIsMissingExpectedValues
case ParseServerError
var description: String {
switch self {
case ResponseContainedNoResultObject: return "Server did not send any results."
case ResponseForCreateIsMissingExpectedValues: return "Response for Creating Object did not return an error but did not contain expected properties either."
case ResponseForUpdateIsMissingExpectedValues: return "Response for Updating Object did not return an error but did not contain expected properties either."
default: return "Unknown Error"
}
}
}
// createErrorWithCode
// helper function to simplify creation of error object
private static func errorForCode(code: ErrorCode, var message: String? = nil) -> NSError {
if message == nil {
message = code.description
}
let userInfo = [NSLocalizedDescriptionKey : message!]
return NSError(domain: ParseClient.ErrorDomain, code: code.rawValue, userInfo: userInfo)
}
}
|
7b1354b37e18d8a28f9fc587d54239a7
| 46.454936 | 168 | 0.653039 | false | false | false | false |
DrabWeb/Komikan
|
refs/heads/master
|
Komikan/Komikan/KMFavouriteButton.swift
|
gpl-3.0
|
1
|
//
// KMFavouriteButton.swift
// Komikan
//
// Created by Seth on 2016-02-13.
//
import Cocoa
class KMFavouriteButton: NSButton {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
// Set the alternate and regular images to the star
self.image = NSImage(named: "Star");
self.alternateImage = NSImage(named: "Star");
// Set the alternate and regular images to be vibrant
self.image?.isTemplate = true;
self.alternateImage?.isTemplate = true;
// Set the target to this
self.target = self;
// Set the action to update the button
self.action = #selector(KMFavouriteButton.updateButton);
}
/// Updates the button based on its state
func updateButton() {
// If state is true...
if(Bool(self.state as NSNumber)) {
// Animate the buttons alpha value to 1
self.animator().alphaValue = 1;
}
else {
// Animate the buttons alpha value to 0.2
self.animator().alphaValue = 0.2;
}
}
}
|
5f47ca0d3064b1886452d4575187021a
| 25.697674 | 64 | 0.573171 | false | false | false | false |
levantAJ/ResearchKit
|
refs/heads/master
|
TestVoiceActions/PromptCollectionViewController.swift
|
mit
|
1
|
//
// PromptCollectionViewController.swift
// TestVoiceActions
//
// Created by Le Tai on 8/25/16.
// Copyright © 2016 Snowball. All rights reserved.
//
import UIKit
final class PromptCollectionViewController: UICollectionViewController {
var shakeManager: ShakeManager!
var currentIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.scrollEnabled = false
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: true)
shakeManager = ShakeManager()
currentIndex = 0
shakeManager.shakeLeft = {
guard self.currentIndex > 0 else {
ShakeManager.vibrate()
return
}
self.currentIndex = self.currentIndex - 1
self.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: self.currentIndex, inSection: 0), atScrollPosition: .None, animated: true)
}
shakeManager.shakeRight = {
guard self.currentIndex < 4 else {
ShakeManager.vibrate()
return
}
self.currentIndex = self.currentIndex + 1
self.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: self.currentIndex, inSection: 0), atScrollPosition: .None, animated: true)
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
shakeManager = nil
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PromptCellectuonViewCell", forIndexPath: indexPath) as! PromptCellectuonViewCell
cell.promptImageView.image = UIImage(named: "p\(indexPath.row+1).png")
return cell
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return view.frame.size
}
}
final class PromptCellectuonViewCell: UICollectionViewCell {
@IBOutlet weak var promptImageView: UIImageView!
}
|
9654c299bac4e3f3bdc400e01da186c1
| 32.807229 | 154 | 0.659301 | false | false | false | false |
qihuang2/Game3
|
refs/heads/master
|
Game3/Utility/GameKitHelper.swift
|
mit
|
1
|
//
// GameKitHelper.swift
// Game2
//
// Created by Qi Feng Huang on 9/9/15.
// Copyright © 2015 Qi Feng Huang. All rights reserved.
//
import GameKit
import Foundation
let singleton = GameKitHelper()
let PresentAuthenticationViewController = "PresentAuthenticationViewController"
class GameKitHelper: NSObject, GKGameCenterControllerDelegate {
var authenticationViewController: UIViewController?
var lastError:NSError?
var gameCenterEnabled:Bool
class var sharedInstance:GameKitHelper{
return singleton
}
override init(){
gameCenterEnabled = true
super.init()
}
func authenticateLocalPlayer(){
let player = GKLocalPlayer.localPlayer()
player.authenticateHandler = {(viewController,error) in
self.lastError = error
if viewController != nil{
self.authenticationViewController = viewController
NSNotificationCenter.defaultCenter().postNotificationName(PresentAuthenticationViewController, object: self)
}
else if player.authenticated{
self.gameCenterEnabled = true
}
else {
self.gameCenterEnabled = false
}
}
}
func reportScores(score:Int64, forLeaderBoardId leaderBoardId: String){
if !gameCenterEnabled{
print("player not authenticated")
return
}
let scoreReporter = GKScore(leaderboardIdentifier: leaderBoardId)
scoreReporter.value = score
scoreReporter.context = 0
let scores = [scoreReporter]
GKScore.reportScores(scores){(error) in
self.lastError = error
}
}
func showGKGameCenterViewController(viewController:GameViewController!){
let gameCenterViewController = GKGameCenterViewController()
gameCenterViewController.gameCenterDelegate = self
gameCenterViewController.viewState = .Leaderboards
viewController.presentViewController(gameCenterViewController, animated: true, completion: nil)
}
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) {
gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}
}
|
b087f4426922b9e32519753a05a7496b
| 30.133333 | 124 | 0.667666 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.