repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
debugsquad/nubecero | nubecero/Firebase/Database/Model/FDatabaseModelUserSession.swift | 1 | 2908 | import Foundation
class FDatabaseModelUserSession:FDatabaseModel
{
enum Property:String
{
case status = "status"
case token = "token"
case version = "version"
case timestamp = "timestamp"
case ttl = "ttl"
}
let status:MSession.Status
let token:String
let version:String
let timestamp:TimeInterval
let ttl:Int
private let kEmpty:String = ""
private let kNoTime:TimeInterval = 0
private let kFirstTtl = 0
init(token:String?, version:String, ttl:Int?)
{
if let receivedToken:String = token
{
self.token = receivedToken
}
else
{
self.token = kEmpty
}
if let receivedTtl:Int = ttl
{
self.ttl = receivedTtl
}
else
{
self.ttl = kFirstTtl
}
self.version = version
status = MSession.Status.active
timestamp = NSDate().timeIntervalSince1970
super.init()
}
required init(snapshot:Any)
{
let snapshotDict:[String:Any]? = snapshot as? [String:Any]
if let statusInt:Int = snapshotDict?[Property.status.rawValue] as? Int
{
if let status:MSession.Status = MSession.Status(rawValue:statusInt)
{
self.status = status
}
else
{
self.status = MSession.Status.unknown
}
}
else
{
self.status = MSession.Status.unknown
}
if let token:String = snapshotDict?[Property.token.rawValue] as? String
{
self.token = token
}
else
{
self.token = kEmpty
}
if let version:String = snapshotDict?[Property.version.rawValue] as? String
{
self.version = version
}
else
{
self.version = kEmpty
}
if let timestamp:TimeInterval = snapshotDict?[Property.timestamp.rawValue] as? TimeInterval
{
self.timestamp = timestamp
}
else
{
self.timestamp = kNoTime
}
if let ttl:Int = snapshotDict?[Property.ttl.rawValue] as? Int
{
self.ttl = ttl
}
else
{
self.ttl = kFirstTtl
}
super.init()
}
override init()
{
fatalError()
}
override func modelJson() -> Any
{
let json:[String:Any] = [
Property.status.rawValue:status.rawValue,
Property.token.rawValue:token,
Property.version.rawValue:version,
Property.timestamp.rawValue:timestamp,
Property.ttl.rawValue:ttl,
]
return json
}
}
| mit | c7d3f1576cb830a086d3776104564497 | 22.079365 | 99 | 0.499312 | 4.895623 | false | false | false | false |
LexLoki/UIAnimation | UIAnimation/UIAnimation.swift | 1 | 15672 | //
// UIAnimation.swift
// Created by Pietro Ribeiro Pepe on 3/31/16.
// The MIT License (MIT)
// Copyright © 2016 Pietro Ribeiro Pepe.
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
extension UIView{
/**
* Executes an 'UIAnimation' on the view
*
* - Parameter animation: A 'UIAnimation'
*/
func runAnimation(_ animation : UIAnimation, completion : @escaping ()->Void = {}){
animation.execute(self,completion)
}
/**
* Removes all the 'UIAnimation' that are running on the view
*/
func removeAllAnimations(){
layer.removeAllAnimations()
}
/// Not implemented
func removeAnimationForKey(key : String){
}
}
/**
* Specifies an animation cycle that can be executed by an UIView
*
* - Movement
* - Rotation
* - Actions sequentially
* - Actions concurrently
* - Repeat
* - RunBlock
* - WaitTime
* - Fades
* - FollowPoints
* - Shake
*/
class UIAnimation : NSObject{
/**
* Creates an action that moves an UIView's center point to a given point
*
* - Parameter point: A 'CGPoint' value specifying where the 'UIView' should move
* - Parameter duration: A 'NSTimerInverval' specifying the duration of the movement
*/
class func moveTo(point : CGPoint, duration : TimeInterval) -> UIAnimation{
return UIAnimation(data: NSDictionary(objects: [NSValue(cgPoint: point),false], forKeys: ["point" as NSCopying,"isBy" as NSCopying]), duration, _handleMovement)
}
/**
* Creates an action that moves an UIView's by a given distance
*
* - Parameter point: A 'CGPoint' value specifying how much the 'UIView' should move
* - Parameter duration: A 'NSTimerInverval' specifying the duration of the movement
*/
class func moveBy(point : CGPoint, duration : TimeInterval) -> UIAnimation{
return UIAnimation(data: NSDictionary(objects: [NSValue(cgPoint: point),true], forKeys: ["point" as NSCopying,"isBy" as NSCopying]), duration, _handleMovement)
}
/**
* Creates an action that rotates the UIView's to a given angle
*
* - Parameter angle: A 'CGFloat' value specifying the angle the 'UIView' should rotate to, in degrees
* - Parameter duration: A 'NSTimerInverval' specifying the duration of the rotation
*/
class func rotateTo(angle : CGFloat, duration : TimeInterval) -> UIAnimation{
return UIAnimation(data: NSDictionary(objects: [angle,false], forKeys: ["angle" as NSCopying,"isBy" as NSCopying]), duration, _handleRotation)
}
/**
* Creates an action that rotates clockwise the UIView's by a relative value.
*
* - Parameter angle: A 'CGFloat' value specifying the ammount the UIView should rotate, in degrees
* - Parameter duration: A 'NSTimerInverval' specifying the duration of the rotation
*/
class func rotateBy(angle : CGFloat, duration : TimeInterval) -> UIAnimation{
return UIAnimation(data: NSDictionary(objects: [angle,true], forKeys: ["angle" as NSCopying,"isBy" as NSCopying]), duration, _handleRotation)
}
/**
* Creates an action that adjusts the alpha value of a view by a relative value
*
* - Parameter alpha: A 'CGFloat' value specifying the ammount to add to a view's alpha value
* - Parameter duration: A 'NSTimerInverval' specifying the duration of the rotation
*/
class func fadeAlphaBy(alpha : CGFloat, duration : TimeInterval) -> UIAnimation{
return UIAnimation(data: NSDictionary(objects: [alpha,true], forKeys: ["alpha" as NSCopying,"isBy" as NSCopying]), duration, _handleAlpha)
}
/**
* Creates an action that adjusts the alpha value of a view to a given value
*
* - Parameter alpha: A 'CGFloat' value specifying the new value of the view's alpha
* - Parameter duration: A 'NSTimerInverval' specifying the duration of the rotation
*/
class func fadeAlphaTo(_ alpha : CGFloat, duration : TimeInterval) -> UIAnimation{
return UIAnimation(data: NSDictionary(objects: [alpha,false], forKeys: ["alpha" as NSCopying,"isBy" as NSCopying]), duration, _handleAlpha)
}
/**
* Creates an action that changes a view's alpha value to 1.0
*
* - Parameter duration: A 'NSTimerInverval' specifying the duration of the rotation
*/
class func fadeInWithDuration(duration : TimeInterval) -> UIAnimation{
return fadeAlphaTo(1, duration: duration)
}
/**
* Creates an action that changes a view's alpha value to 0.0
*
* - Parameter duration: A 'NSTimerInverval' specifying the duration of the rotation
*/
class func fadeOutWithDuration(duration : TimeInterval) -> UIAnimation{
return fadeAlphaTo(0, duration: duration)
}
/**
* Creates an action that runs a collection of actions sequentially
*
* - Parameter animations: An array of 'UIAnimation'
*/
class func sequence(animations : [UIAnimation]) -> UIAnimation{
var c : TimeInterval = 0
for a in animations{
c += a.time
}
return UIAnimation(data: NSDictionary(object: animations, forKey: "animations" as NSCopying), c, _handleSequence)
}
/**
* Creates an action that runs a collection of actions concurrently
*
* - Parameter animations: An array of 'UIAnimation'
*/
class func group(animations : [UIAnimation]) -> UIAnimation{
var c : TimeInterval = 0
for a in animations{
if a.time>c{
c = a.time
}
}
return UIAnimation(data: NSDictionary(object: animations, forKey: "animations" as NSCopying), c, _handleGroup)
}
/**
* Creates an action that repeats another action a specified number of times
*
* - Parameter animation: The action to repeat
* - Parameter count: how many times it should repeat
*/
class func repeatAnimation(animation : UIAnimation, count : Int) -> UIAnimation{
return UIAnimation(data: NSDictionary(objects: [animation,count], forKeys: ["animation" as NSCopying,"repTime" as NSCopying]), animation.time*TimeInterval(count), _handleRepeat)
}
/**
* Creates an action that repeats another action forever
*
* - Parameter animation: The action to repeat
*/
class func repeatAnimationForever(animation : UIAnimation) -> UIAnimation{
return repeatAnimation(animation: animation, count: -1)
}
/**
* Creates an action that executes a block
*
* - Parameter block: The '()->Void' block to be executed
*/
class func runBlock(block : @escaping ()->Void) -> UIAnimation{
return UIAnimation(data: NSDictionary(object: BlockWrapper(block), forKey: "block" as NSCopying), 0, _handleBlock)
}
/**
* Creates an action that idles for a specified period of time
*
* - Parameter duration: A 'NSTimeInterval' with how many seconds it should idle
*/
class func waitForDuration(duration : TimeInterval) -> UIAnimation{
return UIAnimation(data: NSDictionary(), duration, _handleWait)
}
/**
* Creates an action that moves a view to collection of points, sequentially
*
* - Parameter points: The collection of points the view should move to
* - Parameter speed: The absolute speed of the view's movement
*/
class func followPoints(points : [CGPoint], withSpeed speed : CGFloat) -> UIAnimation{
var v = [NSValue]()
for p in points{
v.append(NSValue(cgPoint: p))
}
return UIAnimation(data: NSDictionary(objects: [speed,v], forKeys: ["speed" as NSCopying,"points" as NSCopying]), 0, _handlePath)
}
/**
* Creates an action that shakes a view random positions, based on the given frequence and force
*
* - Parameter force: A 'CGPPoint' specifying the distance the view will move, from its center position, when shaking
* - Parameter frequence: A 'CGFloat' specifying how many shakes per second the view should do
* - Parameter duration: A 'NSTimeInterval' specifying the estimated total duration of the shake animation (might differ a little)
*/
class func shake(force : CGPoint, frequence : CGFloat, duration : TimeInterval) -> UIAnimation{
let eachDuration = TimeInterval(1.0/frequence)
return UIAnimation(data: NSDictionary(objects: [eachDuration,Int(duration/eachDuration),NSValue(cgPoint: force)], forKeys: ["eachTime" as NSCopying,"quant" as NSCopying,"force" as NSCopying]), duration, _handleShake)
}
/**
* Creates an aciton that removes a view from its superview
*/
class func removeFromSuperview() -> UIAnimation{
return UIAnimation(data: [:], 0, { (v, _, comp) -> Void in
v.removeFromSuperview()
comp?()
})
}
private class BlockWrapper{
let block: ()->Void
init(_ block: @escaping ()->Void){
self.block = block
}
}
class PrivateTimer : NSObject{
@objc class func runTimer(timer : Timer){
(timer.userInfo as! BlockWrapper).block()
}
}
/// Duration of the animation
private let time : TimeInterval
/// Information of the animation
private let data : NSDictionary
/// The function to be called when a UIView runs the animation
private let handler : (UIView,UIAnimation,(()->Void)?)->Void
private init(data : NSDictionary, _ time : TimeInterval, _ handler : @escaping (UIView,UIAnimation,(()->Void)?)->Void){
self.time = time
self.data = data
self.handler = handler
}
func execute(_ view : UIView, _ completion : @escaping ()->Void){
handler(view,self,completion)
}
class private func _handleMovement(view : UIView, _ anim : UIAnimation, _ comp: (()->Void)?){
var p = (anim.data["point"] as! NSValue).cgPointValue
if (anim.data["isBy"] as! Bool){
p.x = view.center.x+p.x; p.y = view.center.y+p.y
}
UIView.animate(withDuration: anim.time, animations: { () -> Void in
view.center = p
}) { (v) -> Void in
if v{ comp?() }
}
}
class private func _handlePath(view : UIView, _ anim : UIAnimation, _ comp: (()->Void)?){
_runPath(view, anim.data["speed"] as! CGFloat, anim.data["points"] as! [NSValue], 0, comp)
}
class private func _handleRotation(view : UIView, _ anim : UIAnimation, _ comp: (()->Void)?){
let a = (anim.data["angle"] as! CGFloat) / 180.0 * CGFloat.pi
UIView.animate(withDuration: anim.time, animations: { () -> Void in
view.transform = (anim.data["isBy"] as! Bool) ? view.transform.rotated(by: a) : CGAffineTransform(rotationAngle: a)
}) { (v) -> Void in
if v{ comp?() }
}
}
class private func _handleAlpha(view : UIView, _ anim : UIAnimation, _ comp: (()->Void)?){
var a = anim.data["alpha"] as! CGFloat
if anim.data["isBy"] as! Bool{
a += view.alpha
}
UIView.animate(withDuration: anim.time, animations: { () -> Void in
view.alpha = a
}) { (v) -> Void in
if v{ comp?() }
}
}
class private func _handleSequence(view : UIView, _ anim : UIAnimation, _ comp: (()->Void)?){
_run(view, anim.data["animations"] as! [UIAnimation], 0, comp)
}
class private func _handleGroup(view : UIView, _ anim : UIAnimation, _ comp: (()->Void)?){
let anims = anim.data["animations"] as! [UIAnimation]
var n_comp = 0
for a in anims{
a.handler(view,a,{ () -> Void in
n_comp += 1
if(n_comp == anims.count){
comp?()
}})}
}
class private func _handleRepeat(view : UIView, _ anim : UIAnimation, _ comp: (()->Void)?){
_repetition(view, anim.data["animation"] as! UIAnimation, anim.data["repTime"] as! Int, comp)
}
class private func _handleBlock(view : UIView, _ anim : UIAnimation, _ comp: (()->Void)?){
(anim.data["block"] as! BlockWrapper).block();
comp?();
}
class private func _handleWait(view : UIView, _ anim : UIAnimation, _ comp: (()->Void)?){
if let c = comp{
Timer.scheduledTimer(timeInterval: anim.time, target: UIAnimation.PrivateTimer.self, selector: #selector(PrivateTimer.runTimer(timer:)), userInfo: BlockWrapper(c), repeats: false)
}
}
class private func _handleShake(view : UIView, _ anim : UIAnimation, _ comp: (()->Void)?){
let q = anim.data["quant"] as! Int
let f = (anim.data["force"] as! NSValue).cgPointValue
let e = anim.data["eachTime"] as! TimeInterval
var actions = [UIAnimation]()
for _ in 0 ..< q {
let a = CGFloat(arc4random()) / CGFloat(UINT32_MAX) * 2*CGFloat.pi
actions.append(UIAnimation.moveTo(point: CGPoint(x: view.center.x+cos(a)*f.x, y: view.center.y+sin(a)*f.y), duration: e))
}
actions.append(UIAnimation.moveTo(point: view.center, duration: 0))
view.runAnimation(UIAnimation.sequence(animations: actions)) { () -> Void in
comp?()
}
}
class private func _run(_ view : UIView, _ anim : [UIAnimation], _ _i : Int, _ completion : (()->Void)?){
var i = _i
let curr = anim[i]
curr.handler(view,curr,{ () -> Void in
i += 1
if (i)<anim.count{
_run(view, anim, i, completion)
}
else{ completion?() }
})
}
class private func _runPath(_ view : UIView, _ speed : CGFloat, _ points : [NSValue], _ _i : Int, _ completion : (()->Void)?){
var i = _i
let curr = points[i].cgPointValue
view.runAnimation(UIAnimation.moveTo(point: curr, duration: TimeInterval(speed/sqrt(pow(curr.x-view.center.x, 2)+pow(curr.y-view.center.y, 2))))) { () -> Void in
i += 1
if i<points.count{
_runPath(view, speed, points, i, completion)
}
else{ completion?() }
}
}
class private func _repetition(_ view : UIView, _ anim : UIAnimation, _ _rep : Int, _ completion : (()->Void)?){
var rep = _rep
anim.handler(view,anim,{ () -> Void in
rep -= 1
if (rep <= -1 || rep>0){
_repetition(view, anim, rep, completion)
}
else{ completion?() }
})
}
}
| mit | 46e5eb112e5a2c8b029e894230e1569f | 40.567639 | 464 | 0.620764 | 4.287551 | false | false | false | false |
omiz/In-Air | In Air/Source/Core/Objects/Continent.swift | 1 | 502 | //
// Continent.swift
// Clouds
//
// Created by Omar Allaham on 3/16/17.
// Copyright © 2017 Bemaxnet. All rights reserved.
//
import UIKit
class Continent: Group {
var id: Int = -1
var title: String = "North America"
var description: String = ""
init(_ id: Int, title: String, description: String) {
self.id = id
self.title = title
self.description = description
}
convenience init() {
self.init(0, title: "", description: "")
}
}
| apache-2.0 | 475aef7159a7724f5b966e205bcff0b7 | 16.892857 | 57 | 0.588822 | 3.503497 | false | false | false | false |
limamedeiros/SegueManager | src/osx/SegueManager.swift | 1 | 1885 | //
// SegueManager.swift
// Q42
//
// Created by Tom Lokhorst on 2015-03-20.
//
import Cocoa
public class SegueManager {
typealias Handler = NSStoryboardSegue -> Void
private unowned let viewController: NSViewController
private var handlers = [String: Handler]()
private var timers = [String: NSTimer]()
public init(viewController: NSViewController) {
self.viewController = viewController
}
public func performSegue(identifier: String, handler: NSStoryboardSegue -> Void) {
handlers[identifier] = handler
timers[identifier] = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(SegueManager.timeout(_:)), userInfo: identifier, repeats: false)
viewController.performSegueWithIdentifier(identifier, sender: viewController)
}
public func performSegue<T>(identifier: String, handler: T -> Void) {
performSegue(identifier) { segue in
if let vc = segue.destinationController as? T {
handler(vc)
}
else {
print("Performing segue '\(identifier)' however destinationController is of type '\(segue.destinationController.dynamicType)' not of expected type '\(T.self)'.")
}
}
}
public func performSegue(identifier : String) {
self.performSegue(identifier, handler: { _ in })
}
public func prepareForSegue(segue: NSStoryboardSegue) {
if let segueIdentifier = segue.identifier {
timers[segueIdentifier]?.invalidate()
timers.removeValueForKey(segueIdentifier)
if let handler = handlers[segueIdentifier] {
handler(segue)
handlers.removeValueForKey(segueIdentifier)
}
}
}
@objc private func timeout(timer: NSTimer) {
let segueIdentifier = timer.userInfo as? String ?? ""
print("Performed segue `\(segueIdentifier)', but handler not called.")
print("Forgot to call SegueManager.prepareForSegue?")
}
}
| mit | fe890e5e3ec52f23af95bf157fc856c6 | 29.901639 | 169 | 0.703979 | 4.870801 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/number-complement.swift | 2 | 445 | /**
* https://leetcode.com/problems/number-complement/
*
*
*/
// Date: Mon May 4 08:59:44 PDT 2020
class Solution {
func findComplement(_ num: Int) -> Int {
if num == 0 { return 1 }
var ret = 0
var num = num
var bit = 0
while num > 0 {
if num % 2 == 0 {
ret += (1 << bit)
}
num /= 2
bit += 1
}
return ret
}
}
| mit | 238cfaef49358d0b2e62329baf5387cc | 19.227273 | 51 | 0.404494 | 3.739496 | false | false | false | false |
APUtils/APExtensions | APExtensions/Classes/Core/_Extensions/_Foundation/BidirectionalCollection+Utils.swift | 1 | 1245 | //
// BidirectionalCollection+Utils.swift
// APExtensions
//
// Created by Anton Plebanovich on 9.10.21.
// Copyright © 2021 Anton Plebanovich. All rights reserved.
//
import Foundation
public extension BidirectionalCollection {
/// Second index
var secondIndex: Index? {
guard count > 1 else { return nil }
return index(after: startIndex)
}
/// Second element in array
var second: Element? {
guard let secondIndex = secondIndex else { return nil }
return self[secondIndex]
}
/// Third index
var thirdIndex: Index? {
guard count > 2, let secondIndex = secondIndex else { return nil }
return index(after: secondIndex)
}
/// Third element in a collection
var third: Element? {
guard let thirdIndex = thirdIndex else { return nil }
return self[thirdIndex]
}
/// Fourth index
var fourthIndex: Index? {
guard count > 3, let thirdIndex = thirdIndex else { return nil }
return index(after: thirdIndex)
}
/// Fourth element in a collection
var fourth: Element? {
guard let fourthIndex = fourthIndex else { return nil }
return self[fourthIndex]
}
}
| mit | 6bc2792c4a17e689649a81ffaa407b91 | 24.916667 | 74 | 0.619775 | 4.624535 | false | false | false | false |
twtstudio/WePeiYang-iOS | WePeiYang/StudySearch/Model/StudySearchDataManager.swift | 1 | 2199 | //
// StudySearchDataManager.swift
// WePeiYang
//
// Created by Qin Yubo on 16/6/18.
// Copyright © 2016年 Qin Yubo. All rights reserved.
//
import UIKit
import SwiftyJSON
import ObjectMapper
let CLASSROOM_DATA_KEY = "CLASSROOM_DATA_KEY"
class StudySearchDataManager: NSObject {
class func refreshClassroomsList(success: (listDic: [String: String]) -> (), failure: (errorMsg: String) -> ()) {
twtSDK.getClassrooms({ (task, responseObject) in
let jsonData = JSON(responseObject)
if jsonData["error_code"].int == -1 {
let dataArr: [JSON] = jsonData["data", "buildings"].arrayValue
var dataDic: [String: String] = [:]
for tmpJSON in dataArr {
dataDic[tmpJSON["id"].stringValue] = tmpJSON["name"].stringValue
}
wpyCacheManager.saveGroupCacheData(dataDic, withKey: CLASSROOM_DATA_KEY)
success(listDic: dataDic)
}
}, failure: { (task, error) in
if let errorResponse = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? NSData {
let errorJSON = JSON(data: errorResponse)
failure(errorMsg: errorJSON["message"].stringValue)
} else {
failure(errorMsg: error.localizedDescription)
}
})
}
class func getAvaliableClassroomsList(buildingId buildingId: Int, success: () -> (), failure: (errorMsg: String) -> ()) {
twtSDK.getAvaliableClassroomsWithBuildingID(buildingId, success: { (task, responseObj) in
let jsonData = JSON(responseObj)
if jsonData["error_code"].int == -1 {
let data = jsonData["data"]
print("\(data)")
}
}, failure: { (task, error) in
if let errorResponse = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? NSData {
let errorJSON = JSON(data: errorResponse)
failure(errorMsg: errorJSON["message"].stringValue)
} else {
failure(errorMsg: error.localizedDescription)
}
})
}
}
| mit | 5a32c09e38abf62d829a2a46c93015d2 | 38.214286 | 125 | 0.588342 | 4.623158 | false | false | false | false |
zisko/swift | test/Inputs/clang-importer-sdk/swift-modules-without-ns/Foundation.swift | 1 | 4110 | @_exported import ObjectiveC
@_exported import CoreGraphics
@_exported import Foundation
public func == (lhs: NSObject, rhs: NSObject) -> Bool {
return lhs.isEqual(rhs)
}
public let NSUTF8StringEncoding: UInt = 8
extension String : _ObjectiveCBridgeable {
public func _bridgeToObjectiveC() -> NSString {
return NSString()
}
public static func _forceBridgeFromObjectiveC(_ x: NSString,
result: inout String?) {
}
public static func _conditionallyBridgeFromObjectiveC(
_ x: NSString,
result: inout String?
) -> Bool {
return true
}
public static func _unconditionallyBridgeFromObjectiveC(
_ x: NSString?
) -> String {
return String()
}
}
extension Int : _ObjectiveCBridgeable {
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber()
}
public static func _forceBridgeFromObjectiveC(
_ x: NSNumber,
result: inout Int?
) {
}
public static func _conditionallyBridgeFromObjectiveC(
_ x: NSNumber,
result: inout Int?
) -> Bool {
return true
}
public static func _unconditionallyBridgeFromObjectiveC(
_ x: NSNumber?
) -> Int {
return Int()
}
}
extension Array : _ObjectiveCBridgeable {
public func _bridgeToObjectiveC() -> NSArray {
return NSArray()
}
public static func _forceBridgeFromObjectiveC(
_ x: NSArray,
result: inout Array?
) {
}
public static func _conditionallyBridgeFromObjectiveC(
_ x: NSArray,
result: inout Array?
) -> Bool {
return true
}
public static func _unconditionallyBridgeFromObjectiveC(
_ x: NSArray?
) -> Array {
return Array()
}
}
extension Dictionary : _ObjectiveCBridgeable {
public func _bridgeToObjectiveC() -> NSDictionary {
return NSDictionary()
}
public static func _forceBridgeFromObjectiveC(
_ x: NSDictionary,
result: inout Dictionary?
) {
}
public static func _conditionallyBridgeFromObjectiveC(
_ x: NSDictionary,
result: inout Dictionary?
) -> Bool {
return true
}
public static func _unconditionallyBridgeFromObjectiveC(
_ x: NSDictionary?
) -> Dictionary {
return Dictionary()
}
}
extension Set : _ObjectiveCBridgeable {
public func _bridgeToObjectiveC() -> NSSet {
return NSSet()
}
public static func _forceBridgeFromObjectiveC(
_ x: NSSet,
result: inout Set?
) {
}
public static func _conditionallyBridgeFromObjectiveC(
_ x: NSSet,
result: inout Set?
) -> Bool {
return true
}
public static func _unconditionallyBridgeFromObjectiveC(
_ x: NSSet?
) -> Set {
return Set()
}
}
extension CGFloat : _ObjectiveCBridgeable {
public func _bridgeToObjectiveC() -> NSNumber {
return NSNumber()
}
public static func _forceBridgeFromObjectiveC(
_ x: NSNumber,
result: inout CGFloat?
) {
}
public static func _conditionallyBridgeFromObjectiveC(
_ x: NSNumber,
result: inout CGFloat?
) -> Bool {
return true
}
public static func _unconditionallyBridgeFromObjectiveC(
_ x: NSNumber?
) -> CGFloat {
return CGFloat()
}
}
extension NSRange : _ObjectiveCBridgeable {
public func _bridgeToObjectiveC() -> NSValue {
return NSValue()
}
public static func _forceBridgeFromObjectiveC(
_ x: NSValue,
result: inout NSRange?
) {
result = x.rangeValue
}
public static func _conditionallyBridgeFromObjectiveC(
_ x: NSValue,
result: inout NSRange?
) -> Bool {
self._forceBridgeFromObjectiveC(x, result: &result)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(
_ x: NSValue?
) -> NSRange {
return NSRange()
}
}
extension NSError : Error {
public var _domain: String { return domain }
public var _code: Int { return code }
}
public enum _GenericObjCError : Error {
case nilError
}
public func _convertNSErrorToError(_ error: NSError?) -> Error {
if let error = error {
return error
}
return _GenericObjCError.nilError
}
public func _convertErrorToNSError(_ error: Error) -> NSError {
return error as NSError
}
| apache-2.0 | 417db14962bc2821f4a66b1e26b36cab | 21.096774 | 72 | 0.666667 | 4.628378 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/RxSwift/RxSwift/Observables/Range.swift | 20 | 2777 | //
// Range.swift
// RxSwift
//
// Created by Krunoslav Zaher on 9/13/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType where Element : RxAbstractInteger {
/**
Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages.
- seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html)
- parameter start: The value of the first integer in the sequence.
- parameter count: The number of sequential integers to generate.
- parameter scheduler: Scheduler to run the generator loop on.
- returns: An observable sequence that contains a range of sequential integral numbers.
*/
public static func range(start: Element, count: Element, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<Element> {
return RangeProducer<Element>(start: start, count: count, scheduler: scheduler)
}
}
final private class RangeProducer<Element: RxAbstractInteger>: Producer<Element> {
fileprivate let _start: Element
fileprivate let _count: Element
fileprivate let _scheduler: ImmediateSchedulerType
init(start: Element, count: Element, scheduler: ImmediateSchedulerType) {
guard count >= 0 else {
rxFatalError("count can't be negative")
}
guard start &+ (count - 1) >= start || count == 0 else {
rxFatalError("overflow of count")
}
self._start = start
self._count = count
self._scheduler = scheduler
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = RangeSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
final private class RangeSink<Observer: ObserverType>: Sink<Observer> where Observer.Element: RxAbstractInteger {
typealias Parent = RangeProducer<Observer.Element>
private let _parent: Parent
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self._parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return self._parent._scheduler.scheduleRecursive(0 as Observer.Element) { i, recurse in
if i < self._parent._count {
self.forwardOn(.next(self._parent._start + i))
recurse(i + 1)
}
else {
self.forwardOn(.completed)
self.dispose()
}
}
}
}
| mit | a7bb6e1e36d4dc00815631372e44a9f4 | 37.027397 | 171 | 0.660303 | 4.844677 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/YPImagePicker/Source/Pages/Photo/YPCameraVC.swift | 2 | 7079 | //
// YPCameraVC.swift
// YPImgePicker
//
// Created by Sacha Durand Saint Omer on 25/10/16.
// Copyright © 2016 Yummypets. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
public class YPCameraVC: UIViewController, UIGestureRecognizerDelegate, YPPermissionCheckable {
public var didCapturePhoto: ((UIImage) -> Void)?
let photoCapture = newPhotoCapture()
let v: YPCameraView!
var isInited = false
var videoZoomFactor: CGFloat = 1.0
override public func loadView() { view = v }
public required init() {
self.v = YPCameraView(overlayView: YPConfig.overlayView)
super.init(nibName: nil, bundle: nil)
title = YPConfig.wordings.cameraTitle
YPDeviceOrientationHelper.shared.startDeviceOrientationNotifier { _ in }
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
YPDeviceOrientationHelper.shared.stopDeviceOrientationNotifier()
}
override public func viewDidLoad() {
super.viewDidLoad()
v.flashButton.isHidden = true
v.flashButton.addTarget(self, action: #selector(flashButtonTapped), for: .touchUpInside)
v.shotButton.addTarget(self, action: #selector(shotButtonTapped), for: .touchUpInside)
v.flipButton.addTarget(self, action: #selector(flipButtonTapped), for: .touchUpInside)
// Focus
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.focusTapped(_:)))
tapRecognizer.delegate = self
v.previewViewContainer.addGestureRecognizer(tapRecognizer)
// Zoom
let pinchRecongizer = UIPinchGestureRecognizer(target: self, action: #selector(self.pinch(_:)))
pinchRecongizer.delegate = self
v.previewViewContainer.addGestureRecognizer(pinchRecongizer)
}
func start() {
doAfterPermissionCheck { [weak self] in
guard let strongSelf = self else {
return
}
self?.photoCapture.start(with: strongSelf.v.previewViewContainer, completion: {
DispatchQueue.main.async {
self?.isInited = true
self?.refreshFlashButton()
}
})
}
}
@objc
func focusTapped(_ recognizer: UITapGestureRecognizer) {
guard isInited else {
return
}
doAfterPermissionCheck { [weak self] in
self?.focus(recognizer: recognizer)
}
}
func focus(recognizer: UITapGestureRecognizer) {
let point = recognizer.location(in: v.previewViewContainer)
// Focus the capture
let viewsize = v.previewViewContainer.bounds.size
let newPoint = CGPoint(x: point.x/viewsize.width, y: point.y/viewsize.height)
photoCapture.focus(on: newPoint)
// Animate focus view
v.focusView.center = point
YPHelper.configureFocusView(v.focusView)
v.addSubview(v.focusView)
YPHelper.animateFocusView(v.focusView)
}
@objc
func pinch(_ recognizer: UIPinchGestureRecognizer) {
guard isInited else {
return
}
doAfterPermissionCheck { [weak self] in
self?.zoom(recognizer: recognizer)
}
}
func zoom(recognizer: UIPinchGestureRecognizer) {
photoCapture.zoom(began: recognizer.state == .began, scale: recognizer.scale)
}
func stopCamera() {
photoCapture.stopCamera()
}
@objc
func flipButtonTapped() {
doAfterPermissionCheck { [weak self] in
self?.photoCapture.flipCamera {
self?.refreshFlashButton()
}
}
}
@objc
func shotButtonTapped() {
doAfterPermissionCheck { [weak self] in
self?.shoot()
}
}
func shoot() {
// Prevent from tapping multiple times in a row
// causing a crash
v.shotButton.isEnabled = false
photoCapture.shoot { imageData in
guard let shotImage = UIImage(data: imageData) else {
return
}
self.photoCapture.stopCamera()
var image = shotImage
// Crop the image if the output needs to be square.
if YPConfig.onlySquareImagesFromCamera {
image = self.cropImageToSquare(image)
}
// Flip image if taken form the front camera.
if let device = self.photoCapture.device, device.position == .front {
image = self.flipImage(image: image)
}
DispatchQueue.main.async {
let noOrietationImage = image.resetOrientation()
self.didCapturePhoto?(noOrietationImage.resizedImageIfNeeded())
}
}
}
func cropImageToSquare(_ image: UIImage) -> UIImage {
let orientation: UIDeviceOrientation = YPDeviceOrientationHelper.shared.currentDeviceOrientation
var imageWidth = image.size.width
var imageHeight = image.size.height
switch orientation {
case .landscapeLeft, .landscapeRight:
// Swap width and height if orientation is landscape
imageWidth = image.size.height
imageHeight = image.size.width
default:
break
}
// The center coordinate along Y axis
let rcy = imageHeight * 0.5
let rect = CGRect(x: rcy - imageWidth * 0.5, y: 0, width: imageWidth, height: imageWidth)
let imageRef = image.cgImage?.cropping(to: rect)
return UIImage(cgImage: imageRef!, scale: 1.0, orientation: image.imageOrientation)
}
// Used when image is taken from the front camera.
func flipImage(image: UIImage!) -> UIImage! {
let imageSize: CGSize = image.size
UIGraphicsBeginImageContextWithOptions(imageSize, true, 1.0)
let ctx = UIGraphicsGetCurrentContext()!
ctx.rotate(by: CGFloat(Double.pi/2.0))
ctx.translateBy(x: 0, y: -imageSize.width)
ctx.scaleBy(x: imageSize.height/imageSize.width, y: imageSize.width/imageSize.height)
ctx.draw(image.cgImage!, in: CGRect(x: 0.0,
y: 0.0,
width: imageSize.width,
height: imageSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
@objc
func flashButtonTapped() {
photoCapture.tryToggleFlash()
refreshFlashButton()
}
func refreshFlashButton() {
let flashImage = photoCapture.currentFlashMode.flashImage()
v.flashButton.setImage(flashImage, for: .normal)
v.flashButton.isHidden = !photoCapture.hasFlash
}
}
| mit | 3d0be6c707aaf0c5604a54dbfccf93a8 | 32.545024 | 105 | 0.600028 | 5.012748 | false | false | false | false |
ktchernov/Flappy-Swift-Pig | Flappy Swift Pig/GameScene.swift | 1 | 4075 | //
// GameScene.swift
// Flappy Swift Pig
//
// Created by Konstantin Tchernov on 12/07/15.
// Copyright (c) 2015 Konstantin Tchernov. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var pig = SKNode()
var pipeUpTexture = SKTexture()
var pipeDownTexture = SKTexture()
var PipesMoveAndRemove = SKAction()
let kPipeGap = 170.0
let kPigCategory = UInt32(1 << 2)
var gameOver = false
override func didMoveToView(view: SKView) {
pig = childNodeWithName("PigNode")!
pig.physicsBody!.categoryBitMask = kPigCategory
self.physicsWorld.gravity = CGVectorMake(0, -7.0)
self.physicsWorld.contactDelegate = self
pipeUpTexture = SKTexture(imageNamed:"PipeUp")
pipeDownTexture = SKTexture(imageNamed:"PipeDown")
// movement of pipes
let distanceToMove = CGFloat(self.frame.size.width + 2.0 * pipeUpTexture.size().width)
let movePipes = SKAction.moveByX(-distanceToMove, y: 0.0, duration: NSTimeInterval(0.01 * distanceToMove))
let removePipes = SKAction.removeFromParent()
PipesMoveAndRemove = SKAction.sequence([movePipes,removePipes])
//Spawn Pipes
let spawn = SKAction.runBlock({() in self.spawnPipes()})
let delay = SKAction.waitForDuration(NSTimeInterval(2.0))
let spawnThenDelay = SKAction.sequence([spawn, delay])
let spawnThenDelayForever = SKAction.repeatActionForever(spawnThenDelay)
self.runAction(spawnThenDelayForever, withKey:"SpawnPipesAction")
}
func spawnPipes() {
let pipePair = SKNode()
pipePair.position = CGPointMake(self.frame.size.width + pipeUpTexture.size().width * 2, 0)
pipePair.zPosition = -10
let height = UInt32(self.frame.size.height / 6)
let y = arc4random() % height + height
let pipeDown = SKSpriteNode(texture: pipeDownTexture)
pipeDown.setScale(2.0)
pipeDown.position = CGPointMake(0.0, CGFloat(y) + pipeDown.size.height + CGFloat(kPipeGap))
pipeDown.physicsBody = SKPhysicsBody(rectangleOfSize:pipeDown.size)
pipeDown.physicsBody!.dynamic = false
pipeDown.physicsBody!.contactTestBitMask = kPigCategory
pipePair.addChild(pipeDown)
let pipeUp = SKSpriteNode(texture: pipeUpTexture)
pipeUp.setScale(2.0)
pipeUp.position = CGPointMake(0.0, CGFloat(y))
pipeUp.physicsBody = SKPhysicsBody(rectangleOfSize: pipeUp.size)
pipeUp.physicsBody!.dynamic = false
pipeUp.physicsBody!.contactTestBitMask = kPigCategory
pipePair.addChild(pipeUp)
pipePair.runAction(PipesMoveAndRemove, withKey:"PipesMoveAction")
self.addChild(pipePair)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if (!gameOver) {
pig.physicsBody!.velocity = CGVectorMake(0, 0)
pig.physicsBody!.applyImpulse(CGVectorMake(0, 50))
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
func didBeginContact(contact: SKPhysicsContact) {
if (!gameOver) {
pig.runAction(
SKAction.playSoundFileNamed("pig.mp3", waitForCompletion: false))
gameOver = true
pig.physicsBody!.collisionBitMask = 0
pig.physicsBody!.applyAngularImpulse(0.1)
pig.physicsBody!.velocity = CGVectorMake(0, -20)
delay(1.5, completion: { self.view?.paused = true })
removeAllActions()
}
}
func delay(seconds:Double, completion:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(seconds * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), completion)
}
}
| gpl-3.0 | bf70cd944f8c0070d7a99335fb047713 | 33.243697 | 114 | 0.620368 | 4.553073 | false | false | false | false |
zyrx/eidolon | Kiosk/Bid Fulfillment/PlaceBidViewController.swift | 5 | 9611 | import UIKit
import Artsy_UILabels
import ReactiveCocoa
import Swift_RAC_Macros
import Artsy_UIButtons
import Artsy_UILabels
import ORStackView
class PlaceBidViewController: UIViewController {
dynamic var bidDollars: Int = 0
var hasAlreadyPlacedABid: Bool = false
@IBOutlet var bidAmountTextField: TextField!
@IBOutlet var cursor: CursorView!
@IBOutlet var keypadContainer: KeypadContainerView!
@IBOutlet var currentBidTitleLabel: UILabel!
@IBOutlet var yourBidTitleLabel: UILabel!
@IBOutlet var currentBidAmountLabel: UILabel!
@IBOutlet var nextBidAmountLabel: UILabel!
@IBOutlet var artworkImageView: UIImageView!
@IBOutlet weak var detailsStackView: ORTagBasedAutoStackView!
@IBOutlet var bidButton: Button!
@IBOutlet weak var conditionsOfSaleButton: UIButton!
@IBOutlet weak var privacyPolictyButton: UIButton!
var showBuyersPremiumCommand = { () -> RACCommand in
appDelegate().showBuyersPremiumCommand()
}
var showPrivacyPolicyCommand = { () -> RACCommand in
appDelegate().showPrivacyPolicyCommand()
}
var showConditionsOfSaleCommand = { () -> RACCommand in
appDelegate().showConditionsOfSaleCommand()
}
lazy var bidDollarsSignal: RACSignal = { self.keypadContainer.intValueSignal }()
var buyersPremium: () -> (BuyersPremium?) = { appDelegate().sale.buyersPremium }
class func instantiateFromStoryboard(storyboard: UIStoryboard) -> PlaceBidViewController {
return storyboard.viewControllerWithID(.PlaceYourBid) as! PlaceBidViewController
}
override func viewDidLoad() {
super.viewDidLoad()
if !hasAlreadyPlacedABid {
self.fulfillmentNav().reset()
}
currentBidTitleLabel.font = UIFont.serifSemiBoldFontWithSize(17)
yourBidTitleLabel.font = UIFont.serifSemiBoldFontWithSize(17)
conditionsOfSaleButton.rac_command = showConditionsOfSaleCommand()
privacyPolictyButton.rac_command = showPrivacyPolicyCommand()
RAC(self, "bidDollars") <~ bidDollarsSignal
RAC(bidAmountTextField, "text") <~ bidDollarsSignal.map(dollarsToCurrencyString)
if let nav = self.navigationController as? FulfillmentNavigationController {
RAC(nav.bidDetails, "bidAmountCents") <~ bidDollarsSignal.map { $0 as! Float * 100 }.takeUntil(viewWillDisappearSignal())
if let saleArtwork = nav.bidDetails.saleArtwork {
let minimumNextBidSignal = RACObserve(saleArtwork, "minimumNextBidCents")
let bidCountSignal = RACObserve(saleArtwork, "bidCount")
let openingBidSignal = RACObserve(saleArtwork, "openingBidCents")
let highestBidSignal = RACObserve(saleArtwork, "highestBidCents")
RAC(currentBidTitleLabel, "text") <~ bidCountSignal.map(toCurrentBidTitleString)
RAC(nextBidAmountLabel, "text") <~ minimumNextBidSignal.map(toNextBidString)
RAC(currentBidAmountLabel, "text") <~ RACSignal.combineLatest([bidCountSignal, highestBidSignal, openingBidSignal]).map {
let tuple = $0 as! RACTuple
let bidCount = tuple.first as? Int ?? 0
return (bidCount > 0 ? tuple.second : tuple.third) ?? 0
}.map(centsToPresentableDollarsString).takeUntil(viewWillDisappearSignal())
RAC(bidButton, "enabled") <~ RACSignal.combineLatest([bidDollarsSignal, minimumNextBidSignal]).map {
let tuple = $0 as! RACTuple
return (tuple.first as? Int ?? 0) * 100 >= (tuple.second as? Int ?? 0)
}
enum LabelTags: Int {
case LotNumber = 1
case ArtistName
case ArtworkTitle
case ArtworkPrice
case BuyersPremium
case Gobbler
}
let lotNumber = nav.bidDetails.saleArtwork?.lotNumber
if let _ = lotNumber {
let lotNumberLabel = smallSansSerifLabel()
lotNumberLabel.tag = LabelTags.LotNumber.rawValue
detailsStackView.addSubview(lotNumberLabel, withTopMargin: "10", sideMargin: "0")
RAC(lotNumberLabel, "text") <~ saleArtwork.viewModel.lotNumberSignal.takeUntil(viewWillDisappearSignal())
}
let artistNameLabel = sansSerifLabel()
artistNameLabel.tag = LabelTags.ArtistName.rawValue
detailsStackView.addSubview(artistNameLabel, withTopMargin: "15", sideMargin: "0")
let artworkTitleLabel = serifLabel()
artworkTitleLabel.tag = LabelTags.ArtworkTitle.rawValue
detailsStackView.addSubview(artworkTitleLabel, withTopMargin: "15", sideMargin: "0")
let artworkPriceLabel = serifLabel()
artworkPriceLabel.tag = LabelTags.ArtworkPrice.rawValue
detailsStackView.addSubview(artworkPriceLabel, withTopMargin: "15", sideMargin: "0")
if let _ = buyersPremium() {
let buyersPremiumView = UIView()
buyersPremiumView.tag = LabelTags.BuyersPremium.rawValue
let buyersPremiumLabel = ARSerifLabel()
buyersPremiumLabel.font = buyersPremiumLabel.font.fontWithSize(16)
buyersPremiumLabel.text = "This work has a "
buyersPremiumLabel.textColor = .artsyHeavyGrey()
let buyersPremiumButton = ARUnderlineButton()
buyersPremiumButton.titleLabel?.font = buyersPremiumLabel.font
buyersPremiumButton.setTitle("buyers premium", forState: .Normal)
buyersPremiumButton.setTitleColor(.artsyHeavyGrey(), forState: .Normal)
buyersPremiumButton.rac_command = showBuyersPremiumCommand()
buyersPremiumView.addSubview(buyersPremiumLabel)
buyersPremiumView.addSubview(buyersPremiumButton)
buyersPremiumLabel.alignTop("0", leading: "0", bottom: "0", trailing: nil, toView: buyersPremiumView)
buyersPremiumLabel.alignBaselineWithView(buyersPremiumButton, predicate: nil)
buyersPremiumButton.alignAttribute(.Left, toAttribute: .Right, ofView: buyersPremiumLabel, predicate: "0")
detailsStackView.addSubview(buyersPremiumView, withTopMargin: "15", sideMargin: "0")
}
let gobbler = WhitespaceGobbler()
gobbler.tag = LabelTags.Gobbler.rawValue
detailsStackView.addSubview(gobbler, withTopMargin: "0")
if let artist = saleArtwork.artwork.artists?.first {
RAC(artistNameLabel, "text") <~ RACObserve(artist, "name")
}
RAC(artworkTitleLabel, "attributedText") <~ RACObserve(saleArtwork.artwork, "titleAndDate").takeUntil(rac_willDeallocSignal())
RAC(artworkPriceLabel, "text") <~ RACObserve(saleArtwork.artwork, "price").takeUntil(viewWillDisappearSignal())
RACObserve(saleArtwork, "artwork").subscribeNext { [weak self] (artwork) -> Void in
if let url = (artwork as? Artwork)?.defaultImage?.thumbnailURL() {
self?.artworkImageView.sd_setImageWithURL(url)
} else {
self?.artworkImageView.image = nil
}
}
}
}
}
@IBAction func bidButtonTapped(sender: AnyObject) {
let identifier = hasAlreadyPlacedABid ? SegueIdentifier.PlaceAnotherBid : SegueIdentifier.ConfirmBid
performSegue(identifier)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue == .PlaceAnotherBid {
let nextViewController = segue.destinationViewController as! LoadingViewController
nextViewController.placingBid = true
}
}
}
private extension PlaceBidViewController {
func smallSansSerifLabel() -> UILabel {
let label = sansSerifLabel()
label.font = label.font.fontWithSize(12)
return label
}
func sansSerifLabel() -> UILabel {
let label = ARSansSerifLabel()
label.numberOfLines = 1
return label
}
func serifLabel() -> UILabel {
let label = ARSerifLabel()
label.numberOfLines = 1
label.font = label.font.fontWithSize(16)
return label
}
}
/// These are for RAC only
private extension PlaceBidViewController {
func dollarsToCurrencyString(input: AnyObject!) -> AnyObject! {
let dollars = input as! Int
if dollars == 0 {
return ""
}
let formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US")
formatter.numberStyle = .DecimalStyle
return formatter.stringFromNumber(dollars)
}
func toCurrentBidTitleString(input: AnyObject!) -> AnyObject! {
if let count = input as? Int {
return count > 0 ? "Current Bid:" : "Opening Bid:"
} else {
return ""
}
}
func toNextBidString(cents: AnyObject!) -> AnyObject! {
if let dollars = NSNumberFormatter.currencyStringForCents(cents as? Int) {
return "Enter \(dollars) or more"
}
return ""
}
}
| mit | 1e15ab3064bfb5d78bd3dfa74c224076 | 40.426724 | 142 | 0.627822 | 5.514056 | false | false | false | false |
garricn/secret | Pods/GGNLocationPicker/GGNLocationPicker/Classes/LocationService.swift | 1 | 1552 | //
// GGNLocationPicker
//
// LocationService.swift
//
// Created by Garric Nahapetian on 8/22/16.
//
//
import CoreLocation
import GGNObservable
class LocationService: NSObject, CLLocationManagerDelegate {
let authorizedOutput = Observable<Bool>()
var enabledAndAuthorized: Bool {
return CLLocationManager.locationServicesEnabled()
&& CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse
}
var authorizationDenied: Bool {
return CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Denied
}
private var authorizationStatus: CLAuthorizationStatus {
return CLLocationManager.authorizationStatus()
}
private var servicesEnabled: Bool {
return CLLocationManager.locationServicesEnabled()
}
private let locationManger = CLLocationManager()
func requestWhenInUse() {
guard !authorizationDenied else {
return authorizedOutput.emit(false)
}
locationManger.delegate = self
locationManger.requestWhenInUseAuthorization()
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
guard CLLocationManager.locationServicesEnabled() else { return }
switch status {
case .NotDetermined:
locationManger.requestWhenInUseAuthorization()
case .Denied, .Restricted:
break
case .AuthorizedAlways, .AuthorizedWhenInUse:
authorizedOutput.emit(true)
}
}
}
| mit | f70042bd14f28b127ea1c0f68b08e7ee | 27.218182 | 114 | 0.698454 | 5.992278 | false | false | false | false |
eoger/firefox-ios | Client/Helpers/UserActivityHandler.swift | 4 | 2423 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import CoreSpotlight
import MobileCoreServices
import WebKit
private let browsingActivityType: String = "org.mozilla.ios.firefox.browsing"
private let searchableIndex = CSSearchableIndex(name: "firefox")
class UserActivityHandler {
private var tabObservers: TabObservers!
init() {
self.tabObservers = registerFor(
.didLoseFocus,
.didGainFocus,
.didChangeURL,
.didLoadPageMetadata,
// .didLoadFavicon, // TODO: Bug 1390294
.didClose,
queue: .main)
}
deinit {
unregister(tabObservers)
}
class func clearSearchIndex(completionHandler: ((Error?) -> Void)? = nil) {
searchableIndex.deleteAllSearchableItems(completionHandler: completionHandler)
}
fileprivate func setUserActivityForTab(_ tab: Tab, url: URL) {
guard !tab.isPrivate, url.isWebPage(includeDataURIs: false), !url.isLocal else {
tab.userActivity?.resignCurrent()
tab.userActivity = nil
return
}
tab.userActivity?.invalidate()
let userActivity = NSUserActivity(activityType: browsingActivityType)
userActivity.webpageURL = url
userActivity.becomeCurrent()
tab.userActivity = userActivity
}
}
extension UserActivityHandler: TabEventHandler {
func tabDidGainFocus(_ tab: Tab) {
tab.userActivity?.becomeCurrent()
}
func tabDidLoseFocus(_ tab: Tab) {
tab.userActivity?.resignCurrent()
}
func tab(_ tab: Tab, didChangeURL url: URL) {
setUserActivityForTab(tab, url: url)
}
func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) {
guard let url = URL(string: metadata.siteURL) else {
return
}
setUserActivityForTab(tab, url: url)
}
func tabDidClose(_ tab: Tab) {
guard let userActivity = tab.userActivity else {
return
}
tab.userActivity = nil
userActivity.invalidate()
}
}
| mpl-2.0 | d0f2ddfff3b44be74dfdaa5db4bad3b0 | 28.192771 | 88 | 0.607099 | 5.058455 | false | false | false | false |
dreamsxin/swift | test/SILOptimizer/definite_init_hang.swift | 41 | 1717 | // RUN: %target-swift-frontend -emit-sil %s -parse-as-library -o /dev/null -verify
var gg: Bool = false
var rg: Int = 0
func f1() { }
func f2() { }
// The old implementation of the LifetimeChecker in DefiniteInitialization had
// an exponential computation complexity in some cases.
// This test should finish in almost no time. With the old implementation it
// took about 8 minutes.
func testit() {
var tp: (a: Int, b: Int, c: Int) // expected-note {{variable defined here}}
tp.a = 1
while gg {
if gg {
rg = tp.a
rg = tp.b // expected-error {{variable 'tp.b' used before being initialized}}
tp.c = 27
}
// Create some control flow.
// With the old implementation each line doubles the computation time.
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
if gg { f1() } else { f2() }
}
}
| apache-2.0 | e2f0a45f03e4e691b5d95e0f756f89ce | 27.616667 | 83 | 0.49272 | 2.769355 | false | false | false | false |
SoCM/iOS-FastTrack-2014-2015 | 04-App Architecture/Swift 4/BMI-withAbout-Start/BMI/ViewController.swift | 7 | 4374 | //
// ViewController.swift
// BMI
//
// Created by Nicholas Outram on 30/12/2014.
// Copyright (c) 2014 Plymouth University. All rights reserved.
//
// 04-11-2015 Updated for Swift 2
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
//
// DATA MODEL
//
//Stored properties
var weight : Double?
var height : Double?
//Computed properties
var bmi : Double? {
get {
if (weight != nil) && (height != nil) {
return weight! / (height! * height!)
} else {
return nil
}
}
}
//Initialised arrays of values to be displayed in the picker
let listOfHeightsInM = Array(140...220).map({Double($0) * 0.01})
let listOfWeightsInKg = Array(80...240).map({Double($0) * 0.5})
//
// OUTLETS
//
@IBOutlet weak var bmiLabel: UILabel!
@IBOutlet weak var heightTextField: UITextField!
@IBOutlet weak var weightTextField: UITextField!
@IBOutlet weak var heightPickerView: UIPickerView!
@IBOutlet weak var weightPickerView: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//This function dismisses the keyboard when return is tapped
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
//Synchronise the user interface when the model is updated
func updateUI() {
if let b = self.bmi {
self.bmiLabel.text = String(format: "%4.1f", b)
}
}
//Called when ever the textField looses focus
func textFieldDidEndEditing(_ textField: UITextField) {
//First we check if textField.text actually contains a (wrapped) String
guard let txt = textField.text else {
//Simply return if not
return
}
//At this point, txt is of type String. Here is a nested function that will be used
//to parse this string, and convert it to a wrapped Double if possible.
let val = NumberFormatter().number(from: txt)?.doubleValue
//Which textField is being edit?
switch (textField) {
case heightTextField:
self.height = val
case weightTextField:
self.weight = val
//default must be here to give complete coverage. A safety precaution.
default:
print("Something bad happened!")
} //end of switch
//Last of all, update the user interface.
updateUI()
}
//Return the numeber of components in the picker (spinning barrels). We only want 1
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
//For a given component, return the number of rows that are displayed / can be selected
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch (pickerView) {
case heightPickerView:
return self.listOfHeightsInM.count
case weightPickerView:
return self.listOfWeightsInKg.count
default:
return 1
}
}
//For this example, the picker is populated with Strings, derived from arrays.
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch (pickerView) {
case heightPickerView:
return String(format: "%4.2f", self.listOfHeightsInM[row])
case weightPickerView:
return String(format: "%4.1f", self.listOfWeightsInKg[row])
default:
return ""
}
}
//When a user picks a value, this method is called.
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch (pickerView) {
case heightPickerView:
self.height = self.listOfHeightsInM[row]
case weightPickerView:
self.weight = self.listOfWeightsInKg[row]
default:
break
}
updateUI()
}
}
| mit | 393cca19b6d66508234310561b1fd678 | 26.683544 | 110 | 0.620027 | 4.718447 | false | false | false | false |
overtake/TelegramSwift | packages/FetchManager/Sources/FetchManager/FetchManager.swift | 1 | 5995 | import Foundation
import Postbox
import TelegramCore
import SwiftSignalKit
public enum FetchManagerCategory: Int32 {
case image
case file
case voice
case animation
}
public enum FetchManagerLocationKey: Comparable, Hashable {
case messageId(MessageId)
case free
public static func <(lhs: FetchManagerLocationKey, rhs: FetchManagerLocationKey) -> Bool {
switch lhs {
case let .messageId(lhsId):
if case let .messageId(rhsId) = rhs {
return lhsId < rhsId
} else {
return true
}
case .free:
if case .free = rhs {
return false
} else {
return false
}
}
}
}
public struct FetchManagerPriorityKey: Comparable {
public let locationKey: FetchManagerLocationKey
public let hasElevatedPriority: Bool
public let userInitiatedPriority: Int32?
public let topReference: FetchManagerPriority?
public init(locationKey: FetchManagerLocationKey, hasElevatedPriority: Bool, userInitiatedPriority: Int32?, topReference: FetchManagerPriority?) {
self.locationKey = locationKey
self.hasElevatedPriority = hasElevatedPriority
self.userInitiatedPriority = userInitiatedPriority
self.topReference = topReference
}
public static func <(lhs: FetchManagerPriorityKey, rhs: FetchManagerPriorityKey) -> Bool {
if let lhsUserInitiatedPriority = lhs.userInitiatedPriority, let rhsUserInitiatedPriority = rhs.userInitiatedPriority {
if lhsUserInitiatedPriority != rhsUserInitiatedPriority {
if lhsUserInitiatedPriority > rhsUserInitiatedPriority {
return false
} else {
return true
}
}
} else if (lhs.userInitiatedPriority != nil) != (rhs.userInitiatedPriority != nil) {
if lhs.userInitiatedPriority != nil {
return true
} else {
return false
}
}
if lhs.hasElevatedPriority != rhs.hasElevatedPriority {
if lhs.hasElevatedPriority {
return true
} else {
return false
}
}
if lhs.topReference != rhs.topReference {
if let lhsTopReference = lhs.topReference, let rhsTopReference = rhs.topReference {
return lhsTopReference < rhsTopReference
} else if lhs.topReference != nil {
return true
} else {
return false
}
}
return lhs.locationKey < rhs.locationKey
}
}
public enum FetchManagerLocation: Hashable {
case chat(PeerId)
}
public enum FetchManagerForegroundDirection {
case toEarlier
case toLater
}
public enum FetchManagerPriority: Comparable {
case userInitiated
case foregroundPrefetch(direction: FetchManagerForegroundDirection, localOrder: MessageIndex)
case backgroundPrefetch(locationOrder: HistoryPreloadIndex, localOrder: MessageIndex)
public static func <(lhs: FetchManagerPriority, rhs: FetchManagerPriority) -> Bool {
switch lhs {
case .userInitiated:
switch rhs {
case .userInitiated:
return false
case .foregroundPrefetch:
return true
case .backgroundPrefetch:
return true
}
case let .foregroundPrefetch(lhsDirection, lhsLocalOrder):
switch rhs {
case .userInitiated:
return false
case let .foregroundPrefetch(rhsDirection, rhsLocalOrder):
if lhsDirection == rhsDirection {
switch lhsDirection {
case .toEarlier:
return lhsLocalOrder > rhsLocalOrder
case .toLater:
return lhsLocalOrder < rhsLocalOrder
}
} else {
if lhsDirection == .toEarlier {
return true
} else {
return false
}
}
case .backgroundPrefetch:
return true
}
case let .backgroundPrefetch(lhsLocationOrder, lhsLocalOrder):
switch rhs {
case .userInitiated:
return false
case .foregroundPrefetch:
return false
case let .backgroundPrefetch(rhsLocationOrder, rhsLocalOrder):
if lhsLocationOrder != rhsLocationOrder {
return lhsLocationOrder < rhsLocationOrder
}
return lhsLocalOrder > rhsLocalOrder
}
}
}
}
public let FetchCompleteRange = IndexSet(integersIn: 0 ..< Int(Int32.max) as Range<Int>)
public protocol FetchManager {
var queue: Queue { get }
func interactivelyFetched(category: FetchManagerCategory, location: FetchManagerLocation, locationKey: FetchManagerLocationKey, mediaReference: AnyMediaReference?, resourceReference: MediaResourceReference, ranges: IndexSet, statsCategory: MediaResourceStatsCategory, elevatedPriority: Bool, userInitiated: Bool, priority: FetchManagerPriority, storeToDownloadsPeerType: MediaAutoDownloadPeerType?) -> Signal<Void, NoError>
func cancelInteractiveFetches(category: FetchManagerCategory, location: FetchManagerLocation, locationKey: FetchManagerLocationKey, resource: MediaResource)
func cancelInteractiveFetches(resourceId: String)
func toggleInteractiveFetchPaused(resourceId: String, isPaused: Bool)
func raisePriority(resourceId: String)
func fetchStatus(category: FetchManagerCategory, location: FetchManagerLocation, locationKey: FetchManagerLocationKey, resource: MediaResource) -> Signal<MediaResourceStatus, NoError>
}
| gpl-2.0 | 2bc1eb00364ce1c6c18a1baafeba3e9d | 35.779141 | 427 | 0.615847 | 5.44505 | false | false | false | false |
oskarpearson/rileylink_ios | MinimedKit/TimestampedGlucoseEvent.swift | 1 | 826 | //
// TimestampedGlucoseEvent.swift
// RileyLink
//
// Created by Timothy Mecklem on 10/19/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct TimestampedGlucoseEvent {
public let glucoseEvent: GlucoseEvent
public let date: Date
public func isMutable(atDate date: Date = Date()) -> Bool {
return false
}
public init(glucoseEvent: GlucoseEvent, date: Date) {
self.glucoseEvent = glucoseEvent
self.date = date
}
}
extension TimestampedGlucoseEvent: DictionaryRepresentable {
public var dictionaryRepresentation: [String: Any] {
var dict = glucoseEvent.dictionaryRepresentation
dict["timestamp"] = DateFormatter.ISO8601DateFormatter().string(from: date)
return dict
}
}
| mit | 8a96e9e140212eba71afa66c520be38c | 23.264706 | 83 | 0.671515 | 4.608939 | false | false | false | false |
xsunsmile/TwitterApp | Twitter/User.swift | 1 | 5799 | //
// User.swift
// Twitter
//
// Created by Hao Sun on 2/21/15.
// Copyright (c) 2015 Hao Sun. All rights reserved.
//
import UIKit
var _currentUser: [User] = []
let currentUserKey = "kCurrentUser"
let userDidLoginNotification = "userDidLoginNotification"
let userDidLogoutNotification = "userDidLogoutNotification"
class User: NSObject, Equatable {
var dictionary: NSDictionary?
init(dictionary: NSDictionary) {
super.init()
self.dictionary = dictionary
}
func id() -> NSInteger {
return getProperty("id") as NSInteger
}
func name() -> NSString {
return getProperty("name") as NSString
}
func screenName() -> NSString {
return getProperty("screen_name") as NSString
}
func followersCount() -> NSInteger {
return getProperty("followers_count") as NSInteger
}
func tweetsCount() -> NSInteger {
return getProperty("statuses_count") as NSInteger
}
func followingCount() -> NSInteger {
return getProperty("following") as NSInteger
}
func getAccessToken() -> BDBOAuth1Credential {
let token = getProperty("accessToken") as NSString
let sec = getProperty("accessSecret") as NSString
println("use accesstoken: \(token)")
println("use accessSec: \(sec)")
return BDBOAuth1Credential(token: token, secret: sec, expiration: nil)
}
func imageUrl() -> NSURL? {
var url: NSURL?
if let urlStr = getProperty("profile_image_url") as? NSString {
url = NSURL(string: urlStr)
}
return url
}
func backgroundImageUrl() -> NSURL? {
var url: NSURL?
if let urlStr = getProperty("profile_background_image_url") as? NSString {
url = NSURL(string: urlStr)
}
return url
}
func largeImageUrl() -> NSURL? {
var url: NSURL?
if let urlStr = getProperty("profile_image_url") as? NSString {
var largeUrlStr = urlStr.stringByReplacingOccurrencesOfString("_normal", withString: "_bigger")
url = NSURL(string: largeUrlStr)
}
return url
}
func profileTextColor() -> UIColor {
let hex = getProperty("profile_text_color") as NSString
return UIColor(rgba: "#\(hex)")
}
func profileBackgroundColor() -> UIColor {
let hex = getProperty("profile_background_color") as NSString
return UIColor(rgba: "#\(hex)")
}
func getProperty(key: NSString) -> AnyObject? {
return dictionary![key]
}
class func logout() {
currentUser = nil
TwitterClient.sharedInstance.requestSerializer.removeAccessToken()
NSNotificationCenter.defaultCenter().postNotificationName(userDidLogoutNotification, object: nil)
}
class func login() {
TwitterClient.sharedInstance.getRequestToken()
}
class func retrieveCurrentUser() {
TwitterClient.sharedInstance.performWithCompletion("1.1/account/verify_credentials.json", params: nil) {
(result, error) -> Void in
if let userDict = result as? NSDictionary {
var newDict = NSMutableDictionary()
newDict.addEntriesFromDictionary(userDict)
newDict["accessToken"] = TwitterClient.sharedInstance.requestSerializer.accessToken.token
newDict["accessSecret"] = TwitterClient.sharedInstance.requestSerializer.accessToken.secret
self.currentUser = User(dictionary: newDict)
println("User did login detected")
NSNotificationCenter.defaultCenter().postNotificationName(userDidLoginNotification, object: nil)
}
}
}
class var currentUser: User? {
get {
if _currentUser.count == 0 {
if let data = NSUserDefaults.standardUserDefaults().objectForKey(currentUserKey) as? NSData {
let users = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as [NSDictionary]
for user in users {
_currentUser.append(User(dictionary: user))
}
}
}
if _currentUser.count == 0 {
return nil
} else {
let u = _currentUser[0]
println("==========")
println("current user: \(u.name())")
println("==========")
return u
}
}
set(user) {
if user != nil {
if let found = find(_currentUser, user!) {
_currentUser.removeAtIndex(found)
}
_currentUser.insert(user!, atIndex: 0)
} else {
if _currentUser.count > 0 {
_currentUser.removeAtIndex(0)
}
}
println("==========")
for user in _currentUser {
println("\(user.name())")
}
println("==========")
if _currentUser.count != 0 {
var rawData: NSMutableArray = []
for user in _currentUser {
rawData.addObject(user.dictionary!)
}
var data = NSJSONSerialization.dataWithJSONObject(rawData, options: nil, error: nil)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: currentUserKey)
} else {
NSUserDefaults.standardUserDefaults().setObject(nil, forKey: currentUserKey)
}
NSUserDefaults.standardUserDefaults().synchronize()
}
}
class func currentUsers() -> [User]? {
return _currentUser
}
}
func ==(a:User, b:User) -> Bool {
return a.id() == b.id()
}
| apache-2.0 | 1525c26885a8909e8d98fc3aab967868 | 31.044199 | 112 | 0.571823 | 5.205566 | false | false | false | false |
coolsamson7/inject | InjectTests/BeanFactoryTest.swift | 1 | 10002 | //
// BeanFactoryTests.swift
// Inject
//
// Created by Andreas Ernst on 18.07.16.
// Copyright © 2016 Andreas Ernst. All rights reserved.
//
import XCTest
import Foundation
@testable import Inject
class BarFactoryBean: NSObject, FactoryBean {
func create() throws -> AnyObject {
let result = BarBean()
result.name = "factory"
result.age = 4711
return result
}
}
class BarBean: NSObject {
var name : String = "andi"
var age : Int = 51
var weight : Int = 87
}
class Data : NSObject, Bean, BeanDescriptorInitializer {
// instance data
var string : String = ""
var int : Int = 0
var float : Float = 0.0
var double : Double = 0.0
var character : Character = Character(" ")
var int8 : Int8 = 0
var foo : FooBase?
var bar : BarBean?
// ClassInitializer
func initializeBeanDescriptor(_ beanDescriptor : BeanDescriptor) {
beanDescriptor["foo"].inject(InjectBean())
}
// Bean
func postConstruct() -> Void {
//print("post construct \(self)");
}
// CustomStringConvertible
override var description : String {
return "data[string: \(string) foo: \(String(describing: foo))]"
}
}
class FooBase : NSObject, Bean {
// Bean
func postConstruct() -> Void {
//print("post construct \(self)");
}
// CustomStringConvertible
override var description : String {
return "foobase[]"
}
}
class FooBean: FooBase {
var name : String?
var age : Int = 0
// Bean
override func postConstruct() -> Void {
//print("post construct \(self)");.auto
}
// CustomStringConvertible
override var description : String {
return "foo[name: \(String(describing: name)) age: \(age)]"
}
}
class BeanFactoryTests: XCTestCase {
override class func setUp() {
Classes.setDefaultBundle(BeanFactoryTests.self)
try! BeanDescriptor.forClass(Data.self) // force creation
// set tracing
Tracer.setTraceLevel("inject", level: .off)
// set logging
LogManager()
.registerLogger("", level : .off, logs: [QueuedLog(name: "async-console", delegate: ConsoleLog(name: "console", synchronize: false))])
}
// tests
func testXML() {
ConfigurationNamespaceHandler(namespace: "configuration")
// load parent xml
let parentData = try! Foundation.Data(contentsOf: Bundle(for: BeanFactoryTests.self).url(forResource: "parent", withExtension: "xml")!)
let childData = try! Foundation.Data(contentsOf: Bundle(for: BeanFactoryTests.self).url(forResource: "application", withExtension: "xml")!)
var environment = try! Environment(name: "parent")
try! environment.loadXML(parentData)
// load child
environment = try! Environment(name: "parent", parent: environment)
try! environment.loadXML(childData)
// check
let bean : Data = try! environment.getBean(Data.self, byId: "b1")
XCTAssert(bean.string == "b1")
let lazy = try! environment.getBean(Data.self, byId: "lazy")
XCTAssert(lazy.string == "lazy")
let proto1 = try! environment.getBean(Data.self, byId: "prototype")
let proto2 = try! environment.getBean(Data.self, byId: "prototype")
XCTAssert(proto1 !== proto2)
let bar = try! environment.getBean(BarBean.self)
XCTAssert(bar.age == 4711)
// Measure
if false {
try! Timer.measure({
var environment = try! Environment(name: "parent")
try! environment.loadXML(parentData)
// load child
environment = try! Environment(name: "child", parent: environment)
try! environment.loadXML(childData)
// force load!
try! environment.getBean(BarBean.self)
return true
}, times: 1000)
}
}
func testFluent() throws {
let parent = try Environment(name: "parent")
try parent.getConfigurationManager().addSource(ProcessInfoConfigurationSource())
try parent.getConfigurationManager().addSource(PlistConfigurationSource(name: "Info", forClass: type(of: self)))
try parent
.define(parent.settings()
.setValue(key: "key", value: "key_value"))
//.define(parent.bean(ProcessInfoConfigurationSource.self)
// .id("x1"))
.define(parent.bean(Data.self, id: "b0")
.property("string", value: "b0")
.property("int", value: 1)
.property("float", value: Float(-1.1))
.property("double", value: -2.2))
.define(parent.bean(FooBean.self, id: "foo")
.property("name", resolve: "${andi=Andreas?}")
.property("age", resolve: "${SIMULATOR_MAINSCREEN_HEIGHT=51}"))
/*.define(parent.bean(Bar.self)
.id("bar")
.abstract()
.property("name", resolve: "${andi=Andreas?}"))
*/
//print(parent.getConfigurationManager().report())
let child = try! Environment(name: "child", parent: parent)
try! child
.define(child.bean(Data.self)
.id("b1")
.dependsOn("b0")
.property("foo", inject: InjectBean(id: "foo"))
.property("string", value: "b1")
.property("int", value: 1)
.property("int8", value: Int8(1))
.property("float", value: Float(1.1))
.property("double", value: 2.2))
.define(child.bean(Data.self)
.id("lazy")
.lazy()
.property("bar", bean: child.bean(BarBean.self)
.property("name", value: "name")
.property("age", value: 0)
)
.property("string", value: "lazy")
.property("int", value: 1)
.property("float", value: Float(1.1))
.property("double", value: 2.2))
.define(child.bean(Data.self)
.id("prototype")
.scope(child.scope("prototype"))
.property("string", value: "b1")
.property("int", value: 1)
.property("float", value: Float(1.1))
.property("double", value: 2.2))
//.define(child.bean(BarFactory.self)
// .target("Bar"))
//print(parent.getConfigurationManager().report())
// check
let bean : Data = try! child.getBean(Data.self, byId: "b1")
XCTAssert(bean.string == "b1")
let lazy = try! child.getBean(Data.self, byId: "lazy")
XCTAssert(lazy.string == "lazy")
let proto1 = try! child.getBean(Data.self, byId: "prototype")
let proto2 = try! child.getBean(Data.self, byId: "prototype")
XCTAssert(proto1 !== proto2)
let bar = try! child.getBean(BarBean.self)
XCTAssert(bar.age == 0)
_ = try! child.getBean(FooBean.self, byId: "foo")
//XCTAssert(bar.age == 4711)
try! Timer.measure({
let parent = try Environment(name: "parent")
try parent.getConfigurationManager().addSource(ProcessInfoConfigurationSource())
try parent
.define(parent.settings()
.setValue(key: "key", value: "key_value"))
//.define(parent.bean(ProcessInfoConfigurationSource.self)
// .id("x1"))
.define(parent.bean(Data.self, id: "b0")
.property("string", value: "b0")
.property("int", value: 1)
.property("float", value: Float(-1.1))
.property("double", value: -2.2))
.define(parent.bean(FooBean.self, id: "foo")
.property("name", resolve: "${andi=Andreas?}")
.property("age", resolve: "${SIMULATOR_MAINSCREEN_HEIGHT=51}")).startup() // TODO?
/*.define(parent.bean(Bar.self)
.id("bar")
.abstract()
.property("name", resolve: "${andi=Andreas?}"))
*/
let child = try! Environment(name: "child", parent: parent)
try! child
.define(child.bean(Data.self)
.id("b1")
.dependsOn("b0")
.property("foo", inject: InjectBean(id: "foo"))
.property("string", value: "b1")
.property("int", value: 1)
.property("int8", value: Int8(1))
.property("float", value: Float(1.1))
.property("double", value: 2.2))
.define(child.bean(Data.self)
.id("lazy")
.lazy()
.property("bar", bean: child.bean(BarBean.self)
.property("name", value: "name")
.property("age", value: 0)
)
.property("string", value: "lazy")
.property("int", value: 1)
.property("float", value: Float(1.1))
.property("double", value: 2.2))
.define(child.bean(Data.self)
.id("prototype")
.scope(child.scope("prototype"))
.property("string", value: "b1")
.property("int", value: 1)
.property("float", value: Float(1.1))
.property("double", value: 2.2)).startup()
return true
}, times: 1000)
}
}
| mit | 389f61a2752cd0d62c8e51a866f86a7d | 29.490854 | 148 | 0.514549 | 4.299656 | false | false | false | false |
forgo/BabySync | bbsync/mobile/iOS/Baby Sync/Baby Sync/Error.swift | 1 | 656 | //
// ErrorAPI.swift
// Baby Sync
//
// Created by Elliott Richerson on 10/13/15.
// Copyright © 2015 Elliott Richerson. All rights reserved.
//
import Foundation
struct ErrorAPI {
var code: Int = 0
var message: String = ""
init() {
self.code = 0
self.message = ""
}
init(code: Int, message: String) {
self.code = code
self.message = message
}
init(error: JSON) {
self.code = error["code"].intValue
self.message = error["message"].stringValue
}
init(error: ErrorAPI) {
self.code = error.code
self.message = error.message
}
}
| mit | 818b2576e83d1d6ae40e22dc123dfe46 | 18.264706 | 60 | 0.555725 | 3.721591 | false | false | false | false |
lovemo/MVVMFramework-Swift | SwiftMVVMKitDemo/SwiftMVVMKitDemo/Classes/Src/thirdExample/ViewModel/ThirdViewModel.swift | 1 | 1124 | //
// ThirdViewModel.swift
// SwiftMVVMKitDemo
//
// Created by Mac on 16/3/7.
// Copyright © 2016年 momo. All rights reserved.
//
import UIKit
import SUIMVVMNetwork
class ThirdViewModel: NSObject, SMKViewModelProtocolDelegate {
lazy var smk_dataArrayList = []
internal func getRandomData() -> NSObject? {
if smk_dataArrayList.count > 0 {
let index = arc4random_uniform(UInt32(self.smk_dataArrayList.count))
return smk_dataArrayList[Int(index)] as? NSObject
}
return nil
}
func smk_viewModelWithGetDataSuccessHandler(successHandler: ((array: [AnyObject]) -> ())?) {
let url = "http://news-at.zhihu.com/api/4/news/latest"
SMKHttp.get(url, params: nil, success: { (json: AnyObject!) -> Void in
let array = json["stories"]
self.smk_dataArrayList = ThirdModel.mj_objectArrayWithKeyValuesArray(array)
if let _ = successHandler {
successHandler!(array: self.smk_dataArrayList as [AnyObject])
}
}) { (_) -> Void in
}
}
}
| mit | 15180776d2286804b2498c0b45dd6bea | 29.297297 | 97 | 0.601249 | 4.017921 | false | false | false | false |
svachmic/ios-url-remote | URLRemote/Classes/Controllers/ActionEntryTableViewCell.swift | 1 | 2045 | //
// ActionEntryTableViewCell.swift
// URLRemote
//
// Created by Michal Švácha on 09/01/17.
// Copyright © 2017 Svacha, Michal. All rights reserved.
//
import UIKit
import Material
import Bond
/// View responsible for displaying the URL that's supposed to be called. Also handles authentication logic (username + password) input.
class ActionEntryTableViewCell: UITableViewCell {
@IBOutlet weak var urlField: TextField!
@IBOutlet weak var checkboxButton: CheckboxButton!
@IBOutlet weak var checkboxLabel: UILabel!
@IBOutlet weak var usernameField: TextField!
@IBOutlet weak var passwordField: TextField!
override func awakeFromNib() {
super.awakeFromNib()
urlField.apply(Stylesheet.EntrySetup.textField)
urlField.placeholder = NSLocalizedString("URL", comment: "")
checkboxButton.tintColor = .gray
checkboxLabel.text = NSLocalizedString("REQUIRES_AUTH", comment: "")
checkboxLabel.font = RobotoFont.bold(with: 13)
checkboxLabel.textColor = .gray
usernameField.apply(Stylesheet.EntrySetup.textField)
usernameField.placeholder = NSLocalizedString("USER", comment: "")
passwordField.apply(Stylesheet.EntrySetup.textField)
passwordField.placeholder = NSLocalizedString("PASSWORD", comment: "")
passwordField.isSecureTextEntry = true
self.selectionStyle = .none
}
/// Binds checkbox's state to visibility of username + password fields.
func bindCheckbox() {
checkboxButton.isChecked
.bind(to: usernameField.reactive.isEnabled)
.dispose(in: bag)
checkboxButton.isChecked
.bind(to: passwordField.reactive.isEnabled)
.dispose(in: bag)
checkboxButton.isChecked.bind(to: self) { me, checked in
let alpha: CGFloat = checked ? 1.0 : 0.5
me.usernameField.alpha = alpha
me.passwordField.alpha = alpha
}.dispose(in: bag)
}
}
| apache-2.0 | 74dadd0dcdc345067263edb6317c0e24 | 34.824561 | 136 | 0.663565 | 4.94431 | false | false | false | false |
vitkuzmenko/Swiftex | Extensions/UIKit/UIImage+Extension.swift | 1 | 1578 | //
// UIImage+Utilites.swift
// WhatToCook
//
// Created by Vitaliy Kuzmenko on 20/09/14.
// Copyright (c) 2014 KuzmenkoFamily. All rights reserved.
//
#if os(iOS) || os(watchOS) || os(tvOS)
import UIKit
extension UIImage {
public func resize(newSize: CGSize) -> UIImage {
let newRect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height).integral
var newImage: UIImage!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(newRect.size, false, 0.0);
newImage = UIImage(cgImage: self.cgImage!, scale: scale, orientation: self.imageOrientation)
newImage.draw(in: newRect)
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
let data = newImage.jpegData(compressionQuality: 0.9)
let newI = UIImage(data: data!, scale: UIScreen.main.scale)
return newI!
}
public func image(tintColor: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, false, scale)
draw(in: rect)
let ctx = UIGraphicsGetCurrentContext()
ctx!.setBlendMode(CGBlendMode.sourceIn)
ctx!.setFillColor(tintColor.cgColor)
ctx!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return image!;
}
}
#endif
| apache-2.0 | 7fa85c6dc7b3457ae37b75f4d993eceb | 26.684211 | 100 | 0.615336 | 4.781818 | false | false | false | false |
bumpersfm/handy | Handy/UIViewAnimationOptions.swift | 1 | 768 | //
// Created by Dani Postigo on 11/27/16.
//
import Foundation
import UIKit
public struct AnimationOptions {
let duration: NSTimeInterval
let delay: NSTimeInterval
let options: UIViewAnimationOptions
public init(duration: NSTimeInterval = 0.4, delay: NSTimeInterval = 0, options: UIViewAnimationOptions = UIViewAnimationOptions(rawValue: 0)) {
self.duration = duration
self.delay = delay
self.options = options
}
}
extension UIView {
public class func animateWithOptions(options: AnimationOptions, animations: () -> Void, completion: ((Bool) -> Void)? = nil) {
self.animateWithDuration(options.duration, delay: options.delay, options: options.options, animations: animations, completion: completion)
}
} | mit | ed91864a35aca524d9d85925b50f1992 | 31.041667 | 147 | 0.716146 | 4.654545 | false | false | false | false |
daaavid/TIY-Assignments | 19--Forecaster/Forecaster/Forecaster/DarkSkyAPIController.swift | 1 | 1753 | //
// DarkSkyAPIController.swift
// Forecaster
//
// Created by david on 10/29/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import Foundation
class DarkSkyAPIController
{
var darkSkyAPI: DarkSkyAPIControllerProtocol
var task: NSURLSessionDataTask!
init(delegate: DarkSkyAPIControllerProtocol)
{
self.darkSkyAPI = delegate
}
func search(location: Location)
{
let lat = location.lat ; let lng = location.lng
let url = NSURL(string: "https://api.forecast.io/forecast/20e7ef512551da7f8d7ab6d2c9b4128c/\(lat),%20\(lng)")
let session = NSURLSession.sharedSession()
task = session.dataTaskWithURL(url!, completionHandler: {data, reponse, error -> Void in
if error != nil
{
print(error!.localizedDescription)
}
else
{
if let dictionary = self.parseJSON(data!)
{
// if let currently = dictionary["currently"] as? NSDictionary
// {
self.darkSkyAPI.darkSkySearchWasCompleted(dictionary, location: location)
// }
}
}
})
task.resume()
}
func parseJSON(data: NSData) -> NSDictionary?
{
do
{
let dictionary: NSDictionary! = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary
print("parsed darksky JSON")
return dictionary
}
catch let error as NSError
{
print(error)
return nil
}
}
func cancelSearch()
{
task.cancel()
}
} | cc0-1.0 | 6d1cb381d1232d124d0fdfe14eb6813f | 25.560606 | 122 | 0.539384 | 4.735135 | false | false | false | false |
apple/swift-nio-http2 | Sources/NIOHTTP2/HTTP2PingData.swift | 1 | 4994 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
/// The opaque data contained in a HTTP/2 `PING` frame.
///
/// A HTTP/2 ping frame must contain 8 bytes of opaque data that is controlled entirely by the sender.
/// This data type encapsulates those 8 bytes while providing a friendly interface for them.
public struct HTTP2PingData: Sendable {
/// The underlying bytes to be sent to the wire. These are in network byte order.
public var bytes: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)
/// Exposes the ``HTTP2PingData`` as an unsigned 64-bit integer. This property will perform any
/// endianness transition that is required, meaning that there is no need to byte swap the result
/// or before setting this property.
public var integer: UInt64 {
// Note: this is the safest way to do this, because it automatically does the right thing
// from a byte order perspective. It's not necessarily the fastest though, and it's definitely
// not the prettiest.
get {
var rval = UInt64(bytes.0) << 56
rval += UInt64(bytes.1) << 48
rval += UInt64(bytes.2) << 40
rval += UInt64(bytes.3) << 32
rval += UInt64(bytes.4) << 24
rval += UInt64(bytes.5) << 16
rval += UInt64(bytes.6) << 8
rval += UInt64(bytes.7)
return rval
}
set {
self.bytes = (
UInt8(newValue >> 56), UInt8(truncatingIfNeeded: newValue >> 48),
UInt8(truncatingIfNeeded: newValue >> 40), UInt8(truncatingIfNeeded: newValue >> 32),
UInt8(truncatingIfNeeded: newValue >> 24), UInt8(truncatingIfNeeded: newValue >> 16),
UInt8(truncatingIfNeeded: newValue >> 8), UInt8(truncatingIfNeeded: newValue)
)
}
}
/// Create a new, blank, ``HTTP2PingData``.
public init() {
self.bytes = (0, 0, 0, 0, 0, 0, 0, 0)
}
/// Create a ``HTTP2PingData`` containing the 64-bit integer provided in network byte order.
public init(withInteger integer: UInt64) {
self.init()
self.integer = integer
}
/// Create a ``HTTP2PingData`` from a tuple of bytes.
public init(withTuple tuple: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)) {
self.bytes = tuple
}
}
extension HTTP2PingData: RandomAccessCollection, MutableCollection {
public typealias Index = Int
public typealias Element = UInt8
public var startIndex: Index {
return 0
}
public var endIndex: Index {
return 7
}
public subscript(_ index: Index) -> Element {
get {
switch index {
case 0:
return self.bytes.0
case 1:
return self.bytes.1
case 2:
return self.bytes.2
case 3:
return self.bytes.3
case 4:
return self.bytes.4
case 5:
return self.bytes.5
case 6:
return self.bytes.6
case 7:
return self.bytes.7
default:
preconditionFailure("Invalid index into HTTP2PingData: \(index)")
}
}
set {
switch index {
case 0:
self.bytes.0 = newValue
case 1:
self.bytes.1 = newValue
case 2:
self.bytes.2 = newValue
case 3:
self.bytes.3 = newValue
case 4:
self.bytes.4 = newValue
case 5:
self.bytes.5 = newValue
case 6:
self.bytes.6 = newValue
case 7:
self.bytes.7 = newValue
default:
preconditionFailure("Invalid index into HTTP2PingData: \(index)")
}
}
}
}
extension HTTP2PingData: Equatable {
public static func ==(lhs: HTTP2PingData, rhs: HTTP2PingData) -> Bool {
return lhs.bytes.0 == rhs.bytes.0 &&
lhs.bytes.1 == rhs.bytes.1 &&
lhs.bytes.2 == rhs.bytes.2 &&
lhs.bytes.3 == rhs.bytes.3 &&
lhs.bytes.4 == rhs.bytes.4 &&
lhs.bytes.5 == rhs.bytes.5 &&
lhs.bytes.6 == rhs.bytes.6 &&
lhs.bytes.7 == rhs.bytes.7
}
}
extension HTTP2PingData: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(self.integer)
}
}
| apache-2.0 | 2c4c6127726db4cd1257cd9d2ad4fdf2 | 32.972789 | 102 | 0.539848 | 4.435169 | false | false | false | false |
hons82/THLicense | THLicense/THLicense.swift | 1 | 1510 | //
// THLicense.swift
// THLicense
//
// Created by Hannes Tribus on 11/06/15.
// Copyright (c) 2015 3Bus. All rights reserved.
//
import Foundation
public class THLicense: NSObject {
public var debugMode:Bool = false
private lazy var licenseKey = String()
private lazy var salt = String()
// Singleton
public static let sharedLicense : THLicense = THLicense()
private override init() {
println(__FUNCTION__)
super.init()
}
public func setLicenseKey(licenseKey : String) {
self.licenseKey = licenseKey
}
public func setSalt(salt : String) {
self.salt = salt
}
public func isLicenseValid() -> Bool {
if (debugMode) {
println("Licensekey \(licenseKey)")
}
if let bundleId = NSBundle(forClass: self.dynamicType).bundleIdentifier {
if (hashKey(bundleId) == licenseKey) {
return true
}
var bundleIdArray = split(bundleId) {$0 == "."}
if (bundleIdArray.count > 2) {
if (hashKey("\(bundleIdArray[0]).\(bundleIdArray[1])") == licenseKey) {
return true
}
}
}
return false
}
private func hashKey(key : String) -> String {
let validkey = String("\(key)_\(salt)").SHA1
if (debugMode) {
println("Valid key for \(key) would be \(validkey)")
}
return validkey
}
} | mit | 38d98722617673481e6da384473b6e92 | 24.610169 | 87 | 0.540397 | 4.428152 | false | false | false | false |
quran/quran-ios | Sources/BatchDownloader/Observers/DownloadingObserverCollection.swift | 1 | 3676 | //
// DownloadingObserverCollection.swift
// Quran
//
// Created by Afifi, Mohamed on 11/21/20.
// Copyright © 2020 Quran.com. All rights reserved.
//
import Locking
import VLogging
public class DownloadingObserverCollection<Item: Hashable> {
private var cancelling: Protected<Set<Item>> = Protected([])
private var downloadingObservers: [Item: DownloadingObserver<Item>] = [:]
public private(set) var items: [Item] = []
public private(set) var responses: [Item: DownloadBatchResponse] = [:] {
didSet {
for (item, response) in responses {
downloadingObservers[item] = DownloadingObserver(item: item, response: response, actions: observerActions)
}
itemsUpdated?(items)
}
}
public var downloadProgress: ((Item, Int, Float) -> Void)?
public var downloadCompleted: ((Item, Int) -> Void)?
public var downloadFailed: ((Item, Int, Error) -> Void)?
public var itemsUpdated: (([Item]) -> Void)?
public init() {
}
private lazy var observerActions: DownloadingObserverActions<Item> = DownloadingObserverActions(
onDownloadProgressUpdated: { [weak self] progress, item in
self?.onDownloadProgressUpdated(progress: progress, for: item)
},
onDownloadFailed: { [weak self] error, item in
self?.onDownloadFailed(withError: error, for: item)
},
onDownloadCompleted: { [weak self] item in
self?.onDownloadCompleted(for: item)
}
)
public func removeAll() {
downloadingObservers.forEach { $1.stop() }
items.removeAll()
responses.removeAll()
}
public func observe(_ items: [Item], responses: [Item: DownloadBatchResponse]) {
self.items = items
self.responses = responses
}
public func startDownloading(item: Item, response: DownloadBatchResponse) {
guard !cancelling.value.contains(item) else {
logger.warning("Not starting download, but canceling it for \(item)")
response.cancel()
return
}
// update the item to be downloading
responses[item] = response
}
public func stopDownloading(_ item: Item) {
_ = cancelling.sync { $0.insert(item) }
// remove old observer
let observer = downloadingObservers.removeValue(forKey: item)
observer?.cancel()
// update the item to be not downloading
responses[item] = nil
}
public func preparingDownloading(_ item: Item) {
_ = cancelling.sync { $0.remove(item) }
}
}
extension DownloadingObserverCollection {
func onDownloadProgressUpdated(progress: Float, for item: Item) {
guard let index = items.firstIndex(of: item) else {
logger.warning("Cannot update progress for \(item). Item not found in local storage.")
return
}
downloadProgress?(items[index], index, progress)
}
func onDownloadCompleted(for item: Item) {
// remove old observer
stopDownloading(item)
guard let index = items.firstIndex(of: item) else {
logger.warning("Cannot complete download for \(item). Item not found in local storage.")
return
}
downloadCompleted?(items[index], index)
}
func onDownloadFailed(withError error: Error, for item: Item) {
stopDownloading(item)
guard let index = items.firstIndex(of: item) else {
logger.warning("Cannot update failure for \(item). Item not found in local storage.")
return
}
downloadFailed?(items[index], index, error)
}
}
| apache-2.0 | 939847c5b9696c003b9db25cf9f390c9 | 31.522124 | 122 | 0.626395 | 4.59375 | false | false | false | false |
njdehoog/Spelt | Sources/Spelt/Document.swift | 1 | 457 | // Any file which contains front matter and is not a blog post is considered a document
public final class Document: FileWithMetadata {
public let path: String
public var destinationPath: String?
public var contents: String
public var metadata: Metadata
public init(path: String, contents: String = "", metadata: Metadata = .none) {
self.path = path
self.contents = contents
self.metadata = metadata
}
}
| mit | 619b8fe08b542eaa42092d25344dc5e0 | 34.153846 | 87 | 0.682713 | 4.810526 | false | false | false | false |
IngmarStein/swift | test/decl/func/vararg.swift | 4 | 1089 | // RUN: %target-parse-verify-swift
var t1a: (Int...) = (1) // expected-error{{cannot create a variadic tuple}}
var t2d: (Double = 0.0) = 1 // expected-error {{default argument not permitted in a tuple type}} {{18-23=}}
func f1(_ a: Int...) { for _ in a {} }
f1()
f1(1)
f1(1,2)
func f2(_ a: Int, _ b: Int...) { for _ in b {} }
f2(1)
f2(1,2)
f2(1,2,3)
func f3(_ a: (String) -> Void) { }
f3({ print($0) })
func f4(_ a: Int..., b: Int) { }
// rdar://16008564
func inoutVariadic(_ i: inout Int...) { // expected-error {{'inout' may not be used on variadic parameters}}
}
// rdar://19722429
func invalidVariadic(_ e: NonExistentType) { // expected-error {{use of undeclared type 'NonExistentType'}}
{ (e: ExtraCrispy...) in }() // expected-error {{use of undeclared type 'ExtraCrispy'}}
}
func twoVariadics(_ a: Int..., b: Int...) { } // expected-error{{only a single variadic parameter '...' is permitted}} {{38-41=}}
// rdar://22056861
func f5(_ list: Any..., end: String = "") {}
f5(String())
// rdar://18083599
enum E1 {
case On, Off
}
func doEV(_ state: E1...) {}
doEV(.On)
| apache-2.0 | 5a6e2fddf559c68555bac33a02a9a7e1 | 24.928571 | 129 | 0.596878 | 2.756962 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Array/14_Longest Common Prefix.swift | 1 | 2002 | //
// 14. Longest Common Prefix.swift
// https://leetcode.com/problems/longest-common-prefix/
//
// Created by Honghao Zhang on 2016-11-03.
// Copyright © 2016 Honghaoz. All rights reserved.
//
//Write a function to find the longest common prefix string amongst an array of strings.
import Foundation
class Num14_LongestCommonPrefix: Solution {
// TODO: https://leetcode.com/problems/longest-common-prefix/solution/
// 抽空实现这个solution中不同的解决方法
/// Use the first string as a reference
/// loop the rest strings to check if the rest strings shares the common prefix
func longestCommonPrefix(_ strs: [String]) -> String {
var res = ""
guard strs.count > 0 else { return res }
if strs.count == 1 {
return strs[0]
}
let first = Array(strs[0])
for (i, char) in first.enumerated() {
for j in 1..<strs.count {
let chars = Array(strs[j])
if i >= chars.count {
return res
}
else if char != chars[chars.index(chars.startIndex, offsetBy: i)] {
return res
}
}
res.append(char)
}
return res
}
func longestCommonPrefix1(_ strs: [String]) -> String {
if strs.count == 0 {
return ""
}
if strs.count == 1 {
return strs[0]
}
let stringsMaxLength = strs.map { Int($0.count) }.max()!
let stringsMaxIndex = strs.count
var commonPrefix = ""
for checkingIndex in 0 ..< stringsMaxLength {
var lastChar = ""
for stringIndex in 0 ..< stringsMaxIndex {
let string = strs[stringIndex]
if checkingIndex >= string.count {
return commonPrefix
}
let char = String(string[string.index(string.startIndex, offsetBy: checkingIndex)])
if lastChar == "" {
lastChar = char
continue
} else if lastChar == char {
if stringIndex == stringsMaxIndex - 1 {
commonPrefix += char
} else {
continue
}
} else {
return commonPrefix
}
}
}
return commonPrefix
}
func test() {
}
}
| mit | a243a8992e3de540f6992469a8354c1b | 20.681319 | 88 | 0.62443 | 3.492035 | false | false | false | false |
BurlApps/latch | Framework/LTStorage.swift | 2 | 1848 | //
// LTStorage.swift
// Latch
//
// Created by Brian Vallelunga on 10/25/14.
// Copyright (c) 2014 Brian Vallelunga. All rights reserved.
//
import Foundation
class LTStorage {
// MARK: Private Instance Variables
private var data: NSMutableArray!
private var path: String!
// MARK: Initializer Method
init() {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths.objectAtIndex(0)as NSString
self.path = documentsDirectory.stringByAppendingPathComponent("Latch.plist")
let fileManager = NSFileManager.defaultManager()
// Check if file exists
if !fileManager.fileExistsAtPath(path) {
// If it doesn't, copy it from the default file in the Resources folder
let bundle = NSBundle.mainBundle().pathForResource("Info", ofType: "plist")
fileManager.copyItemAtPath(bundle!, toPath: self.path, error:nil)
}
self.data = NSMutableArray(contentsOfFile: path)
if self.data == nil {
self.data = NSMutableArray()
}
}
// MARK: Instance Methods
func readPasscode() -> String! {
if self.data.count > 0 {
return self.data.objectAtIndex(0) as? String
} else {
return nil
}
}
func removePasscode() {
self.data.removeAllObjects()
self.data.writeToFile(self.path, atomically: true)
}
func savePasscode(passcode: String) {
if self.data.count > 0 {
self.data.replaceObjectAtIndex(0, withObject: passcode)
} else {
self.data.insertObject(passcode, atIndex: 0)
}
self.data.writeToFile(self.path, atomically: true)
}
} | gpl-2.0 | 2a0c01f84ce448217ef05b73e84967fc | 28.822581 | 109 | 0.608225 | 4.738462 | false | false | false | false |
sbennett912/SwiftGL | SwiftGL/Vec4.swift | 1 | 34035 | //
// Vec4.swift
// SwiftGL
//
// Created by Scott Bennett on 2014-06-08.
// Copyright (c) 2014 Scott Bennett. All rights reserved.
//
import Darwin
public struct Vec4 {
public var x, y, z, w: Float
public init() {
self.x = 0
self.y = 0
self.z = 0
self.w = 0
}
// Explicit Initializers
public init(s: Float) {
self.x = s
self.y = s
self.z = s
self.w = s
}
public init(x: Float) {
self.x = x
self.y = 0
self.z = 0
self.w = 1
}
public init(x: Float, y: Float) {
self.x = x
self.y = y
self.z = 0
self.w = 1
}
public init(x: Float, y: Float, z: Float) {
self.x = x
self.y = y
self.z = z
self.w = 1
}
public init(x: Float, y: Float, z: Float, w: Float) {
self.x = x
self.y = y
self.z = z
self.w = w
}
public init(xy: Vec2, z: Float, w: Float) {
self.x = xy.x
self.y = xy.y
self.z = z
self.w = w
}
public init(x: Float, yz: Vec2, w: Float) {
self.x = x
self.y = yz.x
self.z = yz.y
self.w = w
}
public init(x: Float, y: Float, zw: Vec2) {
self.x = x
self.y = y
self.z = zw.x
self.w = zw.y
}
public init(xy: Vec2, zw: Vec2) {
self.x = xy.x
self.y = xy.y
self.z = zw.x
self.w = zw.y
}
public init(xyz: Vec3, w: Float) {
self.x = xyz.x
self.y = xyz.y
self.z = xyz.z
self.w = w
}
public init(x: Float, yzw: Vec3) {
self.x = x
self.y = yzw.x
self.z = yzw.y
self.w = yzw.z
}
// Implicit Initializers
public init(_ x: Float) {
self.x = x
self.y = 0
self.z = 0
self.w = 1
}
public init(_ x: Float, _ y: Float) {
self.x = x
self.y = y
self.z = 0
self.w = 1
}
public init(_ x: Float, _ y: Float, _ z: Float) {
self.x = x
self.y = y
self.z = z
self.w = 1
}
public init(_ x: Float, _ y: Float, _ z: Float, _ w: Float) {
self.x = x
self.y = y
self.z = z
self.w = w
}
public init(_ xy: Vec2, _ z: Float, _ w: Float) {
self.x = xy.x
self.y = xy.y
self.z = z
self.w = w
}
public init(_ x: Float, _ yz: Vec2, _ w: Float) {
self.x = x
self.y = yz.x
self.z = yz.y
self.w = w
}
public init(_ x: Float, _ y: Float, _ zw: Vec2) {
self.x = x
self.y = y
self.z = zw.x
self.w = zw.y
}
public init(_ xy: Vec2, _ zw: Vec2) {
self.x = xy.x
self.y = xy.y
self.z = zw.x
self.w = zw.y
}
public init(_ xyz: Vec3, _ w: Float) {
self.x = xyz.x
self.y = xyz.y
self.z = xyz.z
self.w = w
}
public init(_ x: Float, _ yzw: Vec3) {
self.x = x
self.y = yzw.x
self.z = yzw.y
self.w = yzw.z
}
public var length2: Float {
get {
return x * x + y * y + z * z + w * w
}
}
public var length: Float {
get {
return sqrt(self.length2)
}
set {
self = length * normalize(self)
}
}
public var ptr: UnsafePointer<Float> {
mutating get {
return withUnsafePointer(to: &self) {
return UnsafeRawPointer($0).assumingMemoryBound(to: Float.self)
}
}
}
// Swizzle (Vec2) Properties
public var xx: Vec2 { get { return Vec2(x: x, y: x) } }
public var yx: Vec2 { get { return Vec2(x: y, y: x) } set(v) { self.y = v.x; self.x = v.y } }
public var zx: Vec2 { get { return Vec2(x: z, y: x) } set(v) { self.z = v.x; self.x = v.y } }
public var wx: Vec2 { get { return Vec2(x: w, y: x) } set(v) { self.w = v.x; self.x = v.y } }
public var xy: Vec2 { get { return Vec2(x: x, y: y) } set(v) { self.x = v.x; self.y = v.y } }
public var yy: Vec2 { get { return Vec2(x: y, y: y) } }
public var zy: Vec2 { get { return Vec2(x: z, y: y) } set(v) { self.z = v.x; self.y = v.y } }
public var wy: Vec2 { get { return Vec2(x: w, y: y) } set(v) { self.w = v.x; self.y = v.y } }
public var xz: Vec2 { get { return Vec2(x: x, y: z) } set(v) { self.x = v.x; self.z = v.y } }
public var yz: Vec2 { get { return Vec2(x: y, y: z) } set(v) { self.y = v.x; self.z = v.y } }
public var zz: Vec2 { get { return Vec2(x: z, y: z) } }
public var wz: Vec2 { get { return Vec2(x: w, y: z) } set(v) { self.w = v.x; self.z = v.y } }
public var xw: Vec2 { get { return Vec2(x: x, y: w) } set(v) { self.x = v.x; self.w = v.y } }
public var yw: Vec2 { get { return Vec2(x: y, y: w) } set(v) { self.y = v.x; self.w = v.y } }
public var zw: Vec2 { get { return Vec2(x: z, y: w) } set(v) { self.z = v.x; self.w = v.y } }
public var ww: Vec2 { get { return Vec2(x: w, y: w) } }
// Swizzle (Vec3) Properties
public var xxx: Vec3 { get { return Vec3(x: x, y: x, z: x) } }
public var yxx: Vec3 { get { return Vec3(x: y, y: x, z: x) } }
public var zxx: Vec3 { get { return Vec3(x: z, y: x, z: x) } }
public var wxx: Vec3 { get { return Vec3(x: w, y: x, z: x) } }
public var xyx: Vec3 { get { return Vec3(x: x, y: y, z: x) } }
public var yyx: Vec3 { get { return Vec3(x: y, y: y, z: x) } }
public var zyx: Vec3 { get { return Vec3(x: z, y: y, z: x) } set(v) { self.z = v.x; self.y = v.y; self.x = v.z } }
public var wyx: Vec3 { get { return Vec3(x: w, y: y, z: x) } set(v) { self.w = v.x; self.y = v.y; self.x = v.z } }
public var xzx: Vec3 { get { return Vec3(x: x, y: z, z: x) } }
public var yzx: Vec3 { get { return Vec3(x: y, y: z, z: x) } set(v) { self.y = v.x; self.z = v.y; self.x = v.z } }
public var zzx: Vec3 { get { return Vec3(x: z, y: z, z: x) } }
public var wzx: Vec3 { get { return Vec3(x: w, y: z, z: x) } set(v) { self.w = v.x; self.z = v.y; self.x = v.z } }
public var xwx: Vec3 { get { return Vec3(x: x, y: w, z: x) } }
public var ywx: Vec3 { get { return Vec3(x: y, y: w, z: x) } set(v) { self.y = v.x; self.w = v.y; self.x = v.z } }
public var zwx: Vec3 { get { return Vec3(x: z, y: w, z: x) } set(v) { self.z = v.x; self.w = v.y; self.x = v.z } }
public var wwx: Vec3 { get { return Vec3(x: w, y: w, z: x) } }
public var xxy: Vec3 { get { return Vec3(x: x, y: x, z: y) } }
public var yxy: Vec3 { get { return Vec3(x: y, y: x, z: y) } }
public var zxy: Vec3 { get { return Vec3(x: z, y: x, z: y) } set(v) { self.z = v.x; self.x = v.y; self.y = v.z } }
public var wxy: Vec3 { get { return Vec3(x: w, y: x, z: y) } set(v) { self.w = v.x; self.x = v.y; self.y = v.z } }
public var xyy: Vec3 { get { return Vec3(x: x, y: y, z: y) } }
public var yyy: Vec3 { get { return Vec3(x: y, y: y, z: y) } }
public var zyy: Vec3 { get { return Vec3(x: z, y: y, z: y) } }
public var wyy: Vec3 { get { return Vec3(x: w, y: y, z: y) } }
public var xzy: Vec3 { get { return Vec3(x: x, y: z, z: y) } set(v) { self.x = v.x; self.z = v.y; self.y = v.z } }
public var yzy: Vec3 { get { return Vec3(x: y, y: z, z: y) } }
public var zzy: Vec3 { get { return Vec3(x: z, y: z, z: y) } }
public var wzy: Vec3 { get { return Vec3(x: w, y: z, z: y) } set(v) { self.w = v.x; self.z = v.y; self.y = v.z } }
public var xwy: Vec3 { get { return Vec3(x: x, y: w, z: y) } set(v) { self.x = v.x; self.w = v.y; self.y = v.z } }
public var ywy: Vec3 { get { return Vec3(x: y, y: w, z: y) } }
public var zwy: Vec3 { get { return Vec3(x: z, y: w, z: y) } set(v) { self.z = v.x; self.w = v.y; self.y = v.z } }
public var wwy: Vec3 { get { return Vec3(x: w, y: w, z: y) } }
public var xxz: Vec3 { get { return Vec3(x: x, y: x, z: z) } }
public var yxz: Vec3 { get { return Vec3(x: y, y: x, z: z) } set(v) { self.y = v.x; self.x = v.y; self.z = v.z } }
public var zxz: Vec3 { get { return Vec3(x: z, y: x, z: z) } }
public var wxz: Vec3 { get { return Vec3(x: w, y: x, z: z) } set(v) { self.w = v.x; self.x = v.y; self.z = v.z } }
public var xyz: Vec3 { get { return Vec3(x: x, y: y, z: z) } set(v) { self.x = v.x; self.y = v.y; self.z = v.z } }
public var yyz: Vec3 { get { return Vec3(x: y, y: y, z: z) } }
public var zyz: Vec3 { get { return Vec3(x: z, y: y, z: z) } }
public var wyz: Vec3 { get { return Vec3(x: w, y: y, z: z) } set(v) { self.w = v.x; self.y = v.y; self.z = v.z } }
public var xzz: Vec3 { get { return Vec3(x: x, y: z, z: z) } }
public var yzz: Vec3 { get { return Vec3(x: y, y: z, z: z) } }
public var zzz: Vec3 { get { return Vec3(x: z, y: z, z: z) } }
public var wzz: Vec3 { get { return Vec3(x: w, y: z, z: z) } }
public var xwz: Vec3 { get { return Vec3(x: x, y: w, z: z) } set(v) { self.x = v.x; self.w = v.y; self.z = v.z } }
public var ywz: Vec3 { get { return Vec3(x: y, y: w, z: z) } set(v) { self.y = v.x; self.w = v.y; self.z = v.z } }
public var zwz: Vec3 { get { return Vec3(x: z, y: w, z: z) } }
public var wwz: Vec3 { get { return Vec3(x: w, y: w, z: z) } }
public var xxw: Vec3 { get { return Vec3(x: x, y: x, z: w) } }
public var yxw: Vec3 { get { return Vec3(x: y, y: x, z: w) } set(v) { self.y = v.x; self.x = v.y; self.w = v.z } }
public var zxw: Vec3 { get { return Vec3(x: z, y: x, z: w) } set(v) { self.z = v.x; self.x = v.y; self.w = v.z } }
public var wxw: Vec3 { get { return Vec3(x: w, y: x, z: w) } }
public var xyw: Vec3 { get { return Vec3(x: x, y: y, z: w) } set(v) { self.x = v.x; self.y = v.y; self.w = v.z } }
public var yyw: Vec3 { get { return Vec3(x: y, y: y, z: w) } }
public var zyw: Vec3 { get { return Vec3(x: z, y: y, z: w) } set(v) { self.z = v.x; self.y = v.y; self.w = v.z } }
public var wyw: Vec3 { get { return Vec3(x: w, y: y, z: w) } }
public var xzw: Vec3 { get { return Vec3(x: x, y: z, z: w) } set(v) { self.x = v.x; self.z = v.y; self.w = v.z } }
public var yzw: Vec3 { get { return Vec3(x: y, y: z, z: w) } set(v) { self.y = v.x; self.z = v.y; self.w = v.z } }
public var zzw: Vec3 { get { return Vec3(x: z, y: z, z: w) } }
public var wzw: Vec3 { get { return Vec3(x: w, y: z, z: w) } }
public var xww: Vec3 { get { return Vec3(x: x, y: w, z: w) } }
public var yww: Vec3 { get { return Vec3(x: y, y: w, z: w) } }
public var zww: Vec3 { get { return Vec3(x: z, y: w, z: w) } }
public var www: Vec3 { get { return Vec3(x: w, y: w, z: w) } }
// Swizzle (Vec4) Properties
public var xxxx: Vec4 { get { return Vec4(x: x, y: x, z: x, w: x) } }
public var yxxx: Vec4 { get { return Vec4(x: y, y: x, z: x, w: x) } }
public var zxxx: Vec4 { get { return Vec4(x: z, y: x, z: x, w: x) } }
public var wxxx: Vec4 { get { return Vec4(x: w, y: x, z: x, w: x) } }
public var xyxx: Vec4 { get { return Vec4(x: x, y: y, z: x, w: x) } }
public var yyxx: Vec4 { get { return Vec4(x: y, y: y, z: x, w: x) } }
public var zyxx: Vec4 { get { return Vec4(x: z, y: y, z: x, w: x) } }
public var wyxx: Vec4 { get { return Vec4(x: w, y: y, z: x, w: x) } }
public var xzxx: Vec4 { get { return Vec4(x: x, y: z, z: x, w: x) } }
public var yzxx: Vec4 { get { return Vec4(x: y, y: z, z: x, w: x) } }
public var zzxx: Vec4 { get { return Vec4(x: z, y: z, z: x, w: x) } }
public var wzxx: Vec4 { get { return Vec4(x: w, y: z, z: x, w: x) } }
public var xwxx: Vec4 { get { return Vec4(x: x, y: w, z: x, w: x) } }
public var ywxx: Vec4 { get { return Vec4(x: y, y: w, z: x, w: x) } }
public var zwxx: Vec4 { get { return Vec4(x: z, y: w, z: x, w: x) } }
public var wwxx: Vec4 { get { return Vec4(x: w, y: w, z: x, w: x) } }
public var xxyx: Vec4 { get { return Vec4(x: x, y: x, z: y, w: x) } }
public var yxyx: Vec4 { get { return Vec4(x: y, y: x, z: y, w: x) } }
public var zxyx: Vec4 { get { return Vec4(x: z, y: x, z: y, w: x) } }
public var wxyx: Vec4 { get { return Vec4(x: w, y: x, z: y, w: x) } }
public var xyyx: Vec4 { get { return Vec4(x: x, y: y, z: y, w: x) } }
public var yyyx: Vec4 { get { return Vec4(x: y, y: y, z: y, w: x) } }
public var zyyx: Vec4 { get { return Vec4(x: z, y: y, z: y, w: x) } }
public var wyyx: Vec4 { get { return Vec4(x: w, y: y, z: y, w: x) } }
public var xzyx: Vec4 { get { return Vec4(x: x, y: z, z: y, w: x) } }
public var yzyx: Vec4 { get { return Vec4(x: y, y: z, z: y, w: x) } }
public var zzyx: Vec4 { get { return Vec4(x: z, y: z, z: y, w: x) } }
public var wzyx: Vec4 { get { return Vec4(x: w, y: z, z: y, w: x) } set(v) { self.w = v.x; self.z = v.y; self.y = v.z; self.x = v.w } }
public var xwyx: Vec4 { get { return Vec4(x: x, y: w, z: y, w: x) } }
public var ywyx: Vec4 { get { return Vec4(x: y, y: w, z: y, w: x) } }
public var zwyx: Vec4 { get { return Vec4(x: z, y: w, z: y, w: x) } set(v) { self.z = v.x; self.w = v.y; self.y = v.z; self.x = v.w } }
public var wwyx: Vec4 { get { return Vec4(x: w, y: w, z: y, w: x) } }
public var xxzx: Vec4 { get { return Vec4(x: x, y: x, z: z, w: x) } }
public var yxzx: Vec4 { get { return Vec4(x: y, y: x, z: z, w: x) } }
public var zxzx: Vec4 { get { return Vec4(x: z, y: x, z: z, w: x) } }
public var wxzx: Vec4 { get { return Vec4(x: w, y: x, z: z, w: x) } }
public var xyzx: Vec4 { get { return Vec4(x: x, y: y, z: z, w: x) } }
public var yyzx: Vec4 { get { return Vec4(x: y, y: y, z: z, w: x) } }
public var zyzx: Vec4 { get { return Vec4(x: z, y: y, z: z, w: x) } }
public var wyzx: Vec4 { get { return Vec4(x: w, y: y, z: z, w: x) } set(v) { self.w = v.x; self.y = v.y; self.z = v.z; self.x = v.w } }
public var xzzx: Vec4 { get { return Vec4(x: x, y: z, z: z, w: x) } }
public var yzzx: Vec4 { get { return Vec4(x: y, y: z, z: z, w: x) } }
public var zzzx: Vec4 { get { return Vec4(x: z, y: z, z: z, w: x) } }
public var wzzx: Vec4 { get { return Vec4(x: w, y: z, z: z, w: x) } }
public var xwzx: Vec4 { get { return Vec4(x: x, y: w, z: z, w: x) } }
public var ywzx: Vec4 { get { return Vec4(x: y, y: w, z: z, w: x) } set(v) { self.y = v.x; self.w = v.y; self.z = v.z; self.x = v.w } }
public var zwzx: Vec4 { get { return Vec4(x: z, y: w, z: z, w: x) } }
public var wwzx: Vec4 { get { return Vec4(x: w, y: w, z: z, w: x) } }
public var xxwx: Vec4 { get { return Vec4(x: x, y: x, z: w, w: x) } }
public var yxwx: Vec4 { get { return Vec4(x: y, y: x, z: w, w: x) } }
public var zxwx: Vec4 { get { return Vec4(x: z, y: x, z: w, w: x) } }
public var wxwx: Vec4 { get { return Vec4(x: w, y: x, z: w, w: x) } }
public var xywx: Vec4 { get { return Vec4(x: x, y: y, z: w, w: x) } }
public var yywx: Vec4 { get { return Vec4(x: y, y: y, z: w, w: x) } }
public var zywx: Vec4 { get { return Vec4(x: z, y: y, z: w, w: x) } set(v) { self.z = v.x; self.y = v.y; self.w = v.z; self.x = v.w } }
public var wywx: Vec4 { get { return Vec4(x: w, y: y, z: w, w: x) } }
public var xzwx: Vec4 { get { return Vec4(x: x, y: z, z: w, w: x) } }
public var yzwx: Vec4 { get { return Vec4(x: y, y: z, z: w, w: x) } set(v) { self.y = v.x; self.z = v.y; self.w = v.z; self.x = v.w } }
public var zzwx: Vec4 { get { return Vec4(x: z, y: z, z: w, w: x) } }
public var wzwx: Vec4 { get { return Vec4(x: w, y: z, z: w, w: x) } }
public var xwwx: Vec4 { get { return Vec4(x: x, y: w, z: w, w: x) } }
public var ywwx: Vec4 { get { return Vec4(x: y, y: w, z: w, w: x) } }
public var zwwx: Vec4 { get { return Vec4(x: z, y: w, z: w, w: x) } }
public var wwwx: Vec4 { get { return Vec4(x: w, y: w, z: w, w: x) } }
public var xxxy: Vec4 { get { return Vec4(x: x, y: x, z: x, w: y) } }
public var yxxy: Vec4 { get { return Vec4(x: y, y: x, z: x, w: y) } }
public var zxxy: Vec4 { get { return Vec4(x: z, y: x, z: x, w: y) } }
public var wxxy: Vec4 { get { return Vec4(x: w, y: x, z: x, w: y) } }
public var xyxy: Vec4 { get { return Vec4(x: x, y: y, z: x, w: y) } }
public var yyxy: Vec4 { get { return Vec4(x: y, y: y, z: x, w: y) } }
public var zyxy: Vec4 { get { return Vec4(x: z, y: y, z: x, w: y) } }
public var wyxy: Vec4 { get { return Vec4(x: w, y: y, z: x, w: y) } }
public var xzxy: Vec4 { get { return Vec4(x: x, y: z, z: x, w: y) } }
public var yzxy: Vec4 { get { return Vec4(x: y, y: z, z: x, w: y) } }
public var zzxy: Vec4 { get { return Vec4(x: z, y: z, z: x, w: y) } }
public var wzxy: Vec4 { get { return Vec4(x: w, y: z, z: x, w: y) } set(v) { self.w = v.x; self.z = v.y; self.x = v.z; self.y = v.w } }
public var xwxy: Vec4 { get { return Vec4(x: x, y: w, z: x, w: y) } }
public var ywxy: Vec4 { get { return Vec4(x: y, y: w, z: x, w: y) } }
public var zwxy: Vec4 { get { return Vec4(x: z, y: w, z: x, w: y) } set(v) { self.z = v.x; self.w = v.y; self.x = v.z; self.y = v.w } }
public var wwxy: Vec4 { get { return Vec4(x: w, y: w, z: x, w: y) } }
public var xxyy: Vec4 { get { return Vec4(x: x, y: x, z: y, w: y) } }
public var yxyy: Vec4 { get { return Vec4(x: y, y: x, z: y, w: y) } }
public var zxyy: Vec4 { get { return Vec4(x: z, y: x, z: y, w: y) } }
public var wxyy: Vec4 { get { return Vec4(x: w, y: x, z: y, w: y) } }
public var xyyy: Vec4 { get { return Vec4(x: x, y: y, z: y, w: y) } }
public var yyyy: Vec4 { get { return Vec4(x: y, y: y, z: y, w: y) } }
public var zyyy: Vec4 { get { return Vec4(x: z, y: y, z: y, w: y) } }
public var wyyy: Vec4 { get { return Vec4(x: w, y: y, z: y, w: y) } }
public var xzyy: Vec4 { get { return Vec4(x: x, y: z, z: y, w: y) } }
public var yzyy: Vec4 { get { return Vec4(x: y, y: z, z: y, w: y) } }
public var zzyy: Vec4 { get { return Vec4(x: z, y: z, z: y, w: y) } }
public var wzyy: Vec4 { get { return Vec4(x: w, y: z, z: y, w: y) } }
public var xwyy: Vec4 { get { return Vec4(x: x, y: w, z: y, w: y) } }
public var ywyy: Vec4 { get { return Vec4(x: y, y: w, z: y, w: y) } }
public var zwyy: Vec4 { get { return Vec4(x: z, y: w, z: y, w: y) } }
public var wwyy: Vec4 { get { return Vec4(x: w, y: w, z: y, w: y) } }
public var xxzy: Vec4 { get { return Vec4(x: x, y: x, z: z, w: y) } }
public var yxzy: Vec4 { get { return Vec4(x: y, y: x, z: z, w: y) } }
public var zxzy: Vec4 { get { return Vec4(x: z, y: x, z: z, w: y) } }
public var wxzy: Vec4 { get { return Vec4(x: w, y: x, z: z, w: y) } set(v) { self.w = v.x; self.x = v.y; self.z = v.z; self.y = v.w } }
public var xyzy: Vec4 { get { return Vec4(x: x, y: y, z: z, w: y) } }
public var yyzy: Vec4 { get { return Vec4(x: y, y: y, z: z, w: y) } }
public var zyzy: Vec4 { get { return Vec4(x: z, y: y, z: z, w: y) } }
public var wyzy: Vec4 { get { return Vec4(x: w, y: y, z: z, w: y) } }
public var xzzy: Vec4 { get { return Vec4(x: x, y: z, z: z, w: y) } }
public var yzzy: Vec4 { get { return Vec4(x: y, y: z, z: z, w: y) } }
public var zzzy: Vec4 { get { return Vec4(x: z, y: z, z: z, w: y) } }
public var wzzy: Vec4 { get { return Vec4(x: w, y: z, z: z, w: y) } }
public var xwzy: Vec4 { get { return Vec4(x: x, y: w, z: z, w: y) } set(v) { self.x = v.x; self.w = v.y; self.z = v.z; self.y = v.w } }
public var ywzy: Vec4 { get { return Vec4(x: y, y: w, z: z, w: y) } }
public var zwzy: Vec4 { get { return Vec4(x: z, y: w, z: z, w: y) } }
public var wwzy: Vec4 { get { return Vec4(x: w, y: w, z: z, w: y) } }
public var xxwy: Vec4 { get { return Vec4(x: x, y: x, z: w, w: y) } }
public var yxwy: Vec4 { get { return Vec4(x: y, y: x, z: w, w: y) } }
public var zxwy: Vec4 { get { return Vec4(x: z, y: x, z: w, w: y) } set(v) { self.z = v.x; self.x = v.y; self.w = v.z; self.y = v.w } }
public var wxwy: Vec4 { get { return Vec4(x: w, y: x, z: w, w: y) } }
public var xywy: Vec4 { get { return Vec4(x: x, y: y, z: w, w: y) } }
public var yywy: Vec4 { get { return Vec4(x: y, y: y, z: w, w: y) } }
public var zywy: Vec4 { get { return Vec4(x: z, y: y, z: w, w: y) } }
public var wywy: Vec4 { get { return Vec4(x: w, y: y, z: w, w: y) } }
public var xzwy: Vec4 { get { return Vec4(x: x, y: z, z: w, w: y) } set(v) { self.x = v.x; self.z = v.y; self.w = v.z; self.y = v.w } }
public var yzwy: Vec4 { get { return Vec4(x: y, y: z, z: w, w: y) } }
public var zzwy: Vec4 { get { return Vec4(x: z, y: z, z: w, w: y) } }
public var wzwy: Vec4 { get { return Vec4(x: w, y: z, z: w, w: y) } }
public var xwwy: Vec4 { get { return Vec4(x: x, y: w, z: w, w: y) } }
public var ywwy: Vec4 { get { return Vec4(x: y, y: w, z: w, w: y) } }
public var zwwy: Vec4 { get { return Vec4(x: z, y: w, z: w, w: y) } }
public var wwwy: Vec4 { get { return Vec4(x: w, y: w, z: w, w: y) } }
public var xxxz: Vec4 { get { return Vec4(x: x, y: x, z: x, w: z) } }
public var yxxz: Vec4 { get { return Vec4(x: y, y: x, z: x, w: z) } }
public var zxxz: Vec4 { get { return Vec4(x: z, y: x, z: x, w: z) } }
public var wxxz: Vec4 { get { return Vec4(x: w, y: x, z: x, w: z) } }
public var xyxz: Vec4 { get { return Vec4(x: x, y: y, z: x, w: z) } }
public var yyxz: Vec4 { get { return Vec4(x: y, y: y, z: x, w: z) } }
public var zyxz: Vec4 { get { return Vec4(x: z, y: y, z: x, w: z) } }
public var wyxz: Vec4 { get { return Vec4(x: w, y: y, z: x, w: z) } set(v) { self.w = v.x; self.y = v.y; self.x = v.z; self.z = v.w } }
public var xzxz: Vec4 { get { return Vec4(x: x, y: z, z: x, w: z) } }
public var yzxz: Vec4 { get { return Vec4(x: y, y: z, z: x, w: z) } }
public var zzxz: Vec4 { get { return Vec4(x: z, y: z, z: x, w: z) } }
public var wzxz: Vec4 { get { return Vec4(x: w, y: z, z: x, w: z) } }
public var xwxz: Vec4 { get { return Vec4(x: x, y: w, z: x, w: z) } }
public var ywxz: Vec4 { get { return Vec4(x: y, y: w, z: x, w: z) } set(v) { self.y = v.x; self.w = v.y; self.x = v.z; self.z = v.w } }
public var zwxz: Vec4 { get { return Vec4(x: z, y: w, z: x, w: z) } }
public var wwxz: Vec4 { get { return Vec4(x: w, y: w, z: x, w: z) } }
public var xxyz: Vec4 { get { return Vec4(x: x, y: x, z: y, w: z) } }
public var yxyz: Vec4 { get { return Vec4(x: y, y: x, z: y, w: z) } }
public var zxyz: Vec4 { get { return Vec4(x: z, y: x, z: y, w: z) } }
public var wxyz: Vec4 { get { return Vec4(x: w, y: x, z: y, w: z) } set(v) { self.w = v.x; self.x = v.y; self.y = v.z; self.z = v.w } }
public var xyyz: Vec4 { get { return Vec4(x: x, y: y, z: y, w: z) } }
public var yyyz: Vec4 { get { return Vec4(x: y, y: y, z: y, w: z) } }
public var zyyz: Vec4 { get { return Vec4(x: z, y: y, z: y, w: z) } }
public var wyyz: Vec4 { get { return Vec4(x: w, y: y, z: y, w: z) } }
public var xzyz: Vec4 { get { return Vec4(x: x, y: z, z: y, w: z) } }
public var yzyz: Vec4 { get { return Vec4(x: y, y: z, z: y, w: z) } }
public var zzyz: Vec4 { get { return Vec4(x: z, y: z, z: y, w: z) } }
public var wzyz: Vec4 { get { return Vec4(x: w, y: z, z: y, w: z) } }
public var xwyz: Vec4 { get { return Vec4(x: x, y: w, z: y, w: z) } set(v) { self.x = v.x; self.w = v.y; self.y = v.z; self.z = v.w } }
public var ywyz: Vec4 { get { return Vec4(x: y, y: w, z: y, w: z) } }
public var zwyz: Vec4 { get { return Vec4(x: z, y: w, z: y, w: z) } }
public var wwyz: Vec4 { get { return Vec4(x: w, y: w, z: y, w: z) } }
public var xxzz: Vec4 { get { return Vec4(x: x, y: x, z: z, w: z) } }
public var yxzz: Vec4 { get { return Vec4(x: y, y: x, z: z, w: z) } }
public var zxzz: Vec4 { get { return Vec4(x: z, y: x, z: z, w: z) } }
public var wxzz: Vec4 { get { return Vec4(x: w, y: x, z: z, w: z) } }
public var xyzz: Vec4 { get { return Vec4(x: x, y: y, z: z, w: z) } }
public var yyzz: Vec4 { get { return Vec4(x: y, y: y, z: z, w: z) } }
public var zyzz: Vec4 { get { return Vec4(x: z, y: y, z: z, w: z) } }
public var wyzz: Vec4 { get { return Vec4(x: w, y: y, z: z, w: z) } }
public var xzzz: Vec4 { get { return Vec4(x: x, y: z, z: z, w: z) } }
public var yzzz: Vec4 { get { return Vec4(x: y, y: z, z: z, w: z) } }
public var zzzz: Vec4 { get { return Vec4(x: z, y: z, z: z, w: z) } }
public var wzzz: Vec4 { get { return Vec4(x: w, y: z, z: z, w: z) } }
public var xwzz: Vec4 { get { return Vec4(x: x, y: w, z: z, w: z) } }
public var ywzz: Vec4 { get { return Vec4(x: y, y: w, z: z, w: z) } }
public var zwzz: Vec4 { get { return Vec4(x: z, y: w, z: z, w: z) } }
public var wwzz: Vec4 { get { return Vec4(x: w, y: w, z: z, w: z) } }
public var xxwz: Vec4 { get { return Vec4(x: x, y: x, z: w, w: z) } }
public var yxwz: Vec4 { get { return Vec4(x: y, y: x, z: w, w: z) } set(v) { self.y = v.x; self.x = v.y; self.w = v.z; self.z = v.w } }
public var zxwz: Vec4 { get { return Vec4(x: z, y: x, z: w, w: z) } }
public var wxwz: Vec4 { get { return Vec4(x: w, y: x, z: w, w: z) } }
public var xywz: Vec4 { get { return Vec4(x: x, y: y, z: w, w: z) } set(v) { self.x = v.x; self.y = v.y; self.w = v.z; self.z = v.w } }
public var yywz: Vec4 { get { return Vec4(x: y, y: y, z: w, w: z) } }
public var zywz: Vec4 { get { return Vec4(x: z, y: y, z: w, w: z) } }
public var wywz: Vec4 { get { return Vec4(x: w, y: y, z: w, w: z) } }
public var xzwz: Vec4 { get { return Vec4(x: x, y: z, z: w, w: z) } }
public var yzwz: Vec4 { get { return Vec4(x: y, y: z, z: w, w: z) } }
public var zzwz: Vec4 { get { return Vec4(x: z, y: z, z: w, w: z) } }
public var wzwz: Vec4 { get { return Vec4(x: w, y: z, z: w, w: z) } }
public var xwwz: Vec4 { get { return Vec4(x: x, y: w, z: w, w: z) } }
public var ywwz: Vec4 { get { return Vec4(x: y, y: w, z: w, w: z) } }
public var zwwz: Vec4 { get { return Vec4(x: z, y: w, z: w, w: z) } }
public var wwwz: Vec4 { get { return Vec4(x: w, y: w, z: w, w: z) } }
public var xxxw: Vec4 { get { return Vec4(x: x, y: x, z: x, w: w) } }
public var yxxw: Vec4 { get { return Vec4(x: y, y: x, z: x, w: w) } }
public var zxxw: Vec4 { get { return Vec4(x: z, y: x, z: x, w: w) } }
public var wxxw: Vec4 { get { return Vec4(x: w, y: x, z: x, w: w) } }
public var xyxw: Vec4 { get { return Vec4(x: x, y: y, z: x, w: w) } }
public var yyxw: Vec4 { get { return Vec4(x: y, y: y, z: x, w: w) } }
public var zyxw: Vec4 { get { return Vec4(x: z, y: y, z: x, w: w) } set(v) { self.z = v.x; self.y = v.y; self.x = v.z; self.w = v.w } }
public var wyxw: Vec4 { get { return Vec4(x: w, y: y, z: x, w: w) } }
public var xzxw: Vec4 { get { return Vec4(x: x, y: z, z: x, w: w) } }
public var yzxw: Vec4 { get { return Vec4(x: y, y: z, z: x, w: w) } set(v) { self.y = v.x; self.z = v.y; self.x = v.z; self.w = v.w } }
public var zzxw: Vec4 { get { return Vec4(x: z, y: z, z: x, w: w) } }
public var wzxw: Vec4 { get { return Vec4(x: w, y: z, z: x, w: w) } }
public var xwxw: Vec4 { get { return Vec4(x: x, y: w, z: x, w: w) } }
public var ywxw: Vec4 { get { return Vec4(x: y, y: w, z: x, w: w) } }
public var zwxw: Vec4 { get { return Vec4(x: z, y: w, z: x, w: w) } }
public var wwxw: Vec4 { get { return Vec4(x: w, y: w, z: x, w: w) } }
public var xxyw: Vec4 { get { return Vec4(x: x, y: x, z: y, w: w) } }
public var yxyw: Vec4 { get { return Vec4(x: y, y: x, z: y, w: w) } }
public var zxyw: Vec4 { get { return Vec4(x: z, y: x, z: y, w: w) } set(v) { self.z = v.x; self.x = v.y; self.y = v.z; self.w = v.w } }
public var wxyw: Vec4 { get { return Vec4(x: w, y: x, z: y, w: w) } }
public var xyyw: Vec4 { get { return Vec4(x: x, y: y, z: y, w: w) } }
public var yyyw: Vec4 { get { return Vec4(x: y, y: y, z: y, w: w) } }
public var zyyw: Vec4 { get { return Vec4(x: z, y: y, z: y, w: w) } }
public var wyyw: Vec4 { get { return Vec4(x: w, y: y, z: y, w: w) } }
public var xzyw: Vec4 { get { return Vec4(x: x, y: z, z: y, w: w) } set(v) { self.x = v.x; self.z = v.y; self.y = v.z; self.w = v.w } }
public var yzyw: Vec4 { get { return Vec4(x: y, y: z, z: y, w: w) } }
public var zzyw: Vec4 { get { return Vec4(x: z, y: z, z: y, w: w) } }
public var wzyw: Vec4 { get { return Vec4(x: w, y: z, z: y, w: w) } }
public var xwyw: Vec4 { get { return Vec4(x: x, y: w, z: y, w: w) } }
public var ywyw: Vec4 { get { return Vec4(x: y, y: w, z: y, w: w) } }
public var zwyw: Vec4 { get { return Vec4(x: z, y: w, z: y, w: w) } }
public var wwyw: Vec4 { get { return Vec4(x: w, y: w, z: y, w: w) } }
public var xxzw: Vec4 { get { return Vec4(x: x, y: x, z: z, w: w) } }
public var yxzw: Vec4 { get { return Vec4(x: y, y: x, z: z, w: w) } set(v) { self.y = v.x; self.x = v.y; self.z = v.z; self.w = v.w } }
public var zxzw: Vec4 { get { return Vec4(x: z, y: x, z: z, w: w) } }
public var wxzw: Vec4 { get { return Vec4(x: w, y: x, z: z, w: w) } }
public var xyzw: Vec4 { get { return Vec4(x: x, y: y, z: z, w: w) } set(v) { self.x = v.x; self.y = v.y; self.z = v.z; self.w = v.w } }
public var yyzw: Vec4 { get { return Vec4(x: y, y: y, z: z, w: w) } }
public var zyzw: Vec4 { get { return Vec4(x: z, y: y, z: z, w: w) } }
public var wyzw: Vec4 { get { return Vec4(x: w, y: y, z: z, w: w) } }
public var xzzw: Vec4 { get { return Vec4(x: x, y: z, z: z, w: w) } }
public var yzzw: Vec4 { get { return Vec4(x: y, y: z, z: z, w: w) } }
public var zzzw: Vec4 { get { return Vec4(x: z, y: z, z: z, w: w) } }
public var wzzw: Vec4 { get { return Vec4(x: w, y: z, z: z, w: w) } }
public var xwzw: Vec4 { get { return Vec4(x: x, y: w, z: z, w: w) } }
public var ywzw: Vec4 { get { return Vec4(x: y, y: w, z: z, w: w) } }
public var zwzw: Vec4 { get { return Vec4(x: z, y: w, z: z, w: w) } }
public var wwzw: Vec4 { get { return Vec4(x: w, y: w, z: z, w: w) } }
public var xxww: Vec4 { get { return Vec4(x: x, y: x, z: w, w: w) } }
public var yxww: Vec4 { get { return Vec4(x: y, y: x, z: w, w: w) } }
public var zxww: Vec4 { get { return Vec4(x: z, y: x, z: w, w: w) } }
public var wxww: Vec4 { get { return Vec4(x: w, y: x, z: w, w: w) } }
public var xyww: Vec4 { get { return Vec4(x: x, y: y, z: w, w: w) } }
public var yyww: Vec4 { get { return Vec4(x: y, y: y, z: w, w: w) } }
public var zyww: Vec4 { get { return Vec4(x: z, y: y, z: w, w: w) } }
public var wyww: Vec4 { get { return Vec4(x: w, y: y, z: w, w: w) } }
public var xzww: Vec4 { get { return Vec4(x: x, y: z, z: w, w: w) } }
public var yzww: Vec4 { get { return Vec4(x: y, y: z, z: w, w: w) } }
public var zzww: Vec4 { get { return Vec4(x: z, y: z, z: w, w: w) } }
public var wzww: Vec4 { get { return Vec4(x: w, y: z, z: w, w: w) } }
public var xwww: Vec4 { get { return Vec4(x: x, y: w, z: w, w: w) } }
public var ywww: Vec4 { get { return Vec4(x: y, y: w, z: w, w: w) } }
public var zwww: Vec4 { get { return Vec4(x: z, y: w, z: w, w: w) } }
public var wwww: Vec4 { get { return Vec4(x: w, y: w, z: w, w: w) } }
}
// Make it easier to interpret Vec4 as a string
extension Vec4: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String { get { return "(\(x), \(y), \(z), \(w))" } }
public var debugDescription: String { get { return "Vec4(x: \(x), y: \(y), z: \(z), w: \(w))" } }
}
// Vec2 Prefix Operators
public prefix func - (v: Vec4) -> Vec4 { return Vec4(x: -v.x, y: -v.y, z: -v.z, w: -v.w) }
// Vec2 Infix Operators
public func + (a: Vec4, b: Vec4) -> Vec4 { return Vec4(x: a.x + b.x, y: a.y + b.y, z: a.z + b.z, w: a.w + b.w) }
public func - (a: Vec4, b: Vec4) -> Vec4 { return Vec4(x: a.x - b.x, y: a.y - b.y, z: a.z - b.z, w: a.w - b.w) }
public func * (a: Vec4, b: Vec4) -> Vec4 { return Vec4(x: a.x * b.x, y: a.y * b.y, z: a.z * b.z, w: a.w * b.w) }
public func / (a: Vec4, b: Vec4) -> Vec4 { return Vec4(x: a.x / b.x, y: a.y / b.y, z: a.z / b.z, w: a.w / b.w) }
// Vec2 Scalar Operators
public func * (s: Float, v: Vec4) -> Vec4 { return Vec4(x: s * v.x, y: s * v.y, z: s * v.z, w: s * v.w) }
public func * (v: Vec4, s: Float) -> Vec4 { return Vec4(x: v.x * s, y: v.y * s, z: v.z * s, w: v.w * s) }
public func / (v: Vec4, s: Float) -> Vec4 { return Vec4(x: v.x / s, y: v.y / s, z: v.z / s, w: v.w / s) }
// Vec4 Assignment Operators
public func += (a: inout Vec4, b: Vec4) { a = a + b }
public func -= (a: inout Vec4, b: Vec4) { a = a - b }
public func *= (a: inout Vec4, b: Vec4) { a = a * b }
public func /= (a: inout Vec4, b: Vec4) { a = a / b }
public func *= (a: inout Vec4, b: Float) { a = a * b }
public func /= (a: inout Vec4, b: Float) { a = a / b }
// Functions which operate on Vec2
public func length(_ v: Vec4) -> Float { return v.length }
public func length2(_ v: Vec4) -> Float { return v.length2 }
public func normalize(_ v: Vec4) -> Vec4 { return v / v.length }
public func dot(_ a: Vec4, _ b: Vec4) -> Float { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w }
public func clamp(_ value: Vec4, min: Float, max: Float) -> Vec4 { return Vec4(clamp(value.x, min: min, max: max), clamp(value.y, min: min, max: max), clamp(value.z, min: min, max: max), clamp(value.w, min: min, max: max)) }
public func mix(_ a: Vec4, b: Vec4, t: Float) -> Vec4 { return a + (b - a) * t }
public func smoothstep(_ a: Vec4, b: Vec4, t: Float) -> Vec4 { return mix(a, b: b, t: t * t * (3 - 2 * t)) }
public func clamp(_ value: Vec4, min: Vec4, max: Vec4) -> Vec4 { return Vec4(clamp(value.x, min: min.x, max: max.x), clamp(value.y, min: min.y, max: max.y), clamp(value.z, min: min.z, max: max.z), clamp(value.w, min: min.w, max: max.w)) }
public func mix(_ a: Vec4, b: Vec4, t: Vec4) -> Vec4 { return a + (b - a) * t }
public func smoothstep(_ a: Vec4, b: Vec4, t: Vec4) -> Vec4 { return mix(a, b: b, t: t * t * (Vec4(s: 3) - 2 * t)) }
| mit | d8fa59beaf48481ac6b95aa160d0610e | 57.782383 | 238 | 0.506126 | 2.275067 | false | false | false | false |
groupme/LibGroupMe | LibGroupMeTests/BackupStrategyTest.swift | 2 | 3034 | import LibGroupMe
import Quick
import Nimble
import OHHTTPStubs
class BackoffStrategySpec: QuickSpec {
override func spec() {
describe("a linear backoff") {
it("should return the same interval each time, until hitting the max") {
let back = BackoffStrategy(backoffStatusCode: 202, finishedStatusCode: 200, maxNumberOfTries: 4, multiplier: 1)
expect(back.nextDelayInterval()).to(equal(1))
expect(back.nextDelayInterval()).to(equal(1))
expect(back.nextDelayInterval()).to(equal(1))
expect(back.nextDelayInterval()).to(equal(1))
expect(back.nextDelayInterval()).to(equal(-1))
expect(back.nextDelayInterval()).to(equal(-1))
let backTwo = BackoffStrategy(backoffStatusCode: 202, finishedStatusCode: 200, maxNumberOfTries: 2, multiplier: 1)
backTwo.delay = 2
expect(backTwo.nextDelayInterval()).to(equal(2))
expect(backTwo.nextDelayInterval()).to(equal(2))
expect(backTwo.nextDelayInterval()).to(equal(-1))
}
}
describe("an exponential backoff") {
it("should return the an increasing interval each time, until hitting the max") {
let back = BackoffStrategy(backoffStatusCode: 202, finishedStatusCode: 200, maxNumberOfTries: 10, multiplier: 1.5)
expect(back.nextDelayInterval()).to(equal(1))
expect(back.nextDelayInterval()).to(beCloseTo(1.5))
expect(back.nextDelayInterval()).to(beCloseTo(2.25))
expect(back.nextDelayInterval()).to(beCloseTo(3.375))
expect(back.nextDelayInterval()).to(beCloseTo(5.0625))
expect(back.nextDelayInterval()).to(beCloseTo(7.5938))
expect(back.nextDelayInterval()).to(beCloseTo(11.3906))
expect(back.nextDelayInterval()).to(beCloseTo(17.0859))
expect(back.nextDelayInterval()).to(beCloseTo(25.6289))
expect(back.nextDelayInterval()).to(beCloseTo(38.4434))
expect(back.nextDelayInterval()).to(beCloseTo(-1))
expect(back.nextDelayInterval()).to(beCloseTo(-1))
expect(back.nextDelayInterval()).to(beCloseTo(-1))
let backFive = BackoffStrategy(backoffStatusCode: 202, finishedStatusCode: 200, maxNumberOfTries: 4, multiplier: 3.2)
backFive.delay = 2.1
// floating points, how do they work?
expect(backFive.nextDelayInterval()).to(beCloseTo(2.1))
expect(backFive.nextDelayInterval()).to(beCloseTo(6.720))
expect(backFive.nextDelayInterval()).to(beCloseTo(21.504))
expect(backFive.nextDelayInterval()).to(beCloseTo(68.8128))
expect(backFive.nextDelayInterval()).to(equal(-1))
expect(backFive.nextDelayInterval()).to(equal(-1))
}
}
}
}
| mit | 2988d9eae07593f2b51f64aee5bd8d13 | 55.185185 | 133 | 0.601846 | 4.403483 | false | false | false | false |
DrGo/LearningSwift | PLAYGROUNDS/LSB_D006_Composability.playground/section-2.swift | 2 | 3006 | import UIKit
/*
// Composability
//
// Based on: Brandon Willams' talk on Functional Programming in a Playground
// at the Functional Swift Conference, Dec. 6th, 2014, Brooklyn, NY
// http://2014.funswiftconf.com/speakers/brandon.html
/==========================================*/
/*----------------------------------------/
// Methods don't compose well
/----------------------------------------*/
extension Int {
func square () -> Int {
return self * self
}
func incr () -> Int {
return self + 1
}
}
// Methods provide limited composition
3.square().incr()
// Yields a function
Int.square(3)
Int.square(3)()
// What if I want to map this function on an array?
let xs = Array(1...100)
// This doesn't work
map(xs, Int.square)
/*----------------------------------------/
// Go "full free function"
/----------------------------------------*/
func square (x: Int) -> Int {
return x * x
}
func incr (x: Int) -> Int {
return x + 1
}
// Now we can map our xs with square
map(xs, square)
/*------------------------------------------------------/
// Swift allows us to promote non-native composition
/------------------------------------------------------*/
// the compiler can do the work for us
infix operator |> {associativity left}
func |> <A, B> (x: A, f: A -> B) -> B {
return f(x)
}
func |> <A, B, C> (f: A -> B, g: B -> C) -> (A -> C) {
return { a in
return g(f(a))
}
}
// Composition!
3 |> square |> incr
// Pipe 3 into the composed function
// (one less iteration)
3 |> (square |> incr)
/*------------------------------------------------------/
// The standard `map` signature has flipped args
// i.e. we really want the function first to
// promote composability
/------------------------------------------------------*/
//map(<#source: C#>, <#transform: (C.Generator.Element) -> T##(C.Generator.Element) -> T#>)
func map <A, B> (f: A -> B) -> [A] -> [B] {
return { xs in
return map(xs, f)
}
}
// now `map` lifts a func from operating on values to lists
xs |> map(square) |> map(incr)
// now `map` the lifted composition
// (one less iteration)
xs |> map(square |> incr)
/*------------------------------------------------------/
// Same for filter...
/------------------------------------------------------*/
//filter(<#source: S#>, <#includeElement: (S.Generator.Element) -> Bool##(S.Generator.Element) -> Bool#>)
// "lift a predicate into the world of arrays"
func filter <A> (p: A -> Bool) -> [A] -> [A] {
return { xs in
return filter(xs, p)
}
}
// as an example...
func isPrime (p: Int) -> Bool {
if p <= 1 { return false }
if p <= 3 { return true }
for i in 2...Int(sqrtf(Float(p))) {
if p % i == 0 { return false }
}
return true
}
// all where n-squared + 1 are prime
xs |> map(square) |> map(incr) |> filter(isPrime)
// reduce iteration once time
xs |> map(square |> incr) |> filter(isPrime)
// can't reduce iteration further without losing composability...
// unless...
| gpl-3.0 | 08abdefabacc4966698e1afdfcf2352c | 20.312057 | 105 | 0.492349 | 3.544811 | false | false | false | false |
SwiftAndroid/swift | stdlib/public/core/Misc.swift | 1 | 5373 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Extern C functions
//===----------------------------------------------------------------------===//
// FIXME: Once we have an FFI interface, make these have proper function bodies
@_transparent
@warn_unused_result
public // @testable
func _countLeadingZeros(_ value: Int64) -> Int64 {
return Int64(Builtin.int_ctlz_Int64(value._value, false._value))
}
/// Returns if `x` is a power of 2.
@_transparent
@warn_unused_result
public // @testable
func _isPowerOf2(_ x: UInt) -> Bool {
if x == 0 {
return false
}
// Note: use unchecked subtraction because we have checked that `x` is not
// zero.
return x & (x &- 1) == 0
}
/// Returns if `x` is a power of 2.
@_transparent
@warn_unused_result
public // @testable
func _isPowerOf2(_ x: Int) -> Bool {
if x <= 0 {
return false
}
// Note: use unchecked subtraction because we have checked that `x` is not
// `Int.min`.
return x & (x &- 1) == 0
}
#if _runtime(_ObjC)
@_transparent
public func _autorelease(_ x: AnyObject) {
Builtin.retain(x)
Builtin.autorelease(x)
}
#endif
/// Invoke `body` with an allocated, but uninitialized memory suitable for a
/// `String` value.
///
/// This function is primarily useful to call various runtime functions
/// written in C++.
func _withUninitializedString<R>(
_ body: (UnsafeMutablePointer<String>) -> R
) -> (R, String) {
let stringPtr = UnsafeMutablePointer<String>(allocatingCapacity: 1)
let bodyResult = body(stringPtr)
let stringResult = stringPtr.move()
stringPtr.deallocateCapacity(1)
return (bodyResult, stringResult)
}
// FIXME(ABI): this API should allow controlling different kinds of
// qualification separately: qualification with module names and qualification
// with type names that we are nested in.
@_silgen_name("swift_getTypeName")
public func _getTypeName(_ type: Any.Type, qualified: Bool)
-> (UnsafePointer<UInt8>, Int)
/// Returns the demangled qualified name of a metatype.
@warn_unused_result
public // @testable
func _typeName(_ type: Any.Type, qualified: Bool = true) -> String {
let (stringPtr, count) = _getTypeName(type, qualified: qualified)
return ._fromWellFormedCodeUnitSequence(UTF8.self,
input: UnsafeBufferPointer(start: stringPtr, count: count))
}
@_silgen_name("swift_getTypeByMangledName")
func _getTypeByMangledName(
_ name: UnsafePointer<UInt8>,
_ nameLength: UInt)
-> Any.Type?
/// Lookup a class given a name. Until the demangled encoding of type
/// names is stabilized, this is limited to top-level class names (Foo.bar).
@warn_unused_result
public // SPI(Foundation)
func _typeByName(_ name: String) -> Any.Type? {
let components = name.characters.split{$0 == "."}.map(String.init)
guard components.count == 2 else {
return nil
}
// Note: explicitly build a class name to match on, rather than matching
// on the result of _typeName(), to ensure the type we are resolving is
// actually a class.
var name = "C"
if components[0] == "Swift" {
name += "s"
} else {
name += String(components[0].characters.count) + components[0]
}
name += String(components[1].characters.count) + components[1]
let nameUTF8 = Array(name.utf8)
return nameUTF8.withUnsafeBufferPointer { (nameUTF8) in
let type = _getTypeByMangledName(nameUTF8.baseAddress!,
UInt(nameUTF8.endIndex))
return type
}
}
@warn_unused_result
@_silgen_name("swift_stdlib_demangleName")
func _stdlib_demangleNameImpl(
_ mangledName: UnsafePointer<UInt8>,
_ mangledNameLength: UInt,
_ demangledName: UnsafeMutablePointer<String>)
// NB: This function is not used directly in the Swift codebase, but is
// exported for Xcode support. Please coordinate before changing.
@warn_unused_result
public // @testable
func _stdlib_demangleName(_ mangledName: String) -> String {
let mangledNameUTF8 = Array(mangledName.utf8)
return mangledNameUTF8.withUnsafeBufferPointer {
(mangledNameUTF8) in
let (_, demangledName) = _withUninitializedString {
_stdlib_demangleNameImpl(
mangledNameUTF8.baseAddress!, UInt(mangledNameUTF8.endIndex),
$0)
}
return demangledName
}
}
/// Returns `floor(log(x))`. This equals to the position of the most
/// significant non-zero bit, or 63 - number-of-zeros before it.
///
/// The function is only defined for positive values of `x`.
///
/// Examples:
///
/// floorLog2(1) == 0
/// floorLog2(2) == floorLog2(3) == 1
/// floorLog2(9) == floorLog2(15) == 3
///
/// TODO: Implement version working on Int instead of Int64.
@warn_unused_result
@_transparent
public // @testable
func _floorLog2(_ x: Int64) -> Int {
_sanityCheck(x > 0, "_floorLog2 operates only on non-negative integers")
// Note: use unchecked subtraction because we this expression cannot
// overflow.
return 63 &- Int(_countLeadingZeros(x))
}
| apache-2.0 | 6a6ff428bd97279abe90be29673d1376 | 30.792899 | 80 | 0.664433 | 3.997768 | false | false | false | false |
Somnibyte/MLKit | Example/Pods/Upsurge/Source/Operations/Hyperbolic.swift | 1 | 6019 | // Copyright (c) 2014–2015 Mattt Thompson (http://mattt.me)
//
// 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 Accelerate
// MARK: - Double
/// Hyperbolic Sine
public func sinh<C: LinearType>(_ x: C) -> ValueArray<Double> where C.Element == Double {
precondition(x.step == 1, "sinh doesn't support step values other than 1")
let results = ValueArray<Double>(count: x.count)
withPointer(x) { xp in
vvsinh(results.mutablePointer + results.startIndex, xp + x.startIndex, [Int32(x.count)])
}
return results
}
/// Hyperbolic Cosine
public func cosh<C: LinearType>(_ x: C) -> ValueArray<Double> where C.Element == Double {
precondition(x.step == 1, "cosh doesn't support step values other than 1")
let results = ValueArray<Double>(count: x.count)
withPointer(x) { xp in
vvcosh(results.mutablePointer + results.startIndex, xp + x.startIndex, [Int32(x.count)])
}
return results
}
/// Hyperbolic Tangent
public func tanh<C: LinearType>(_ x: C) -> ValueArray<Double> where C.Element == Double {
precondition(x.step == 1, "tanh doesn't support step values other than 1")
let results = ValueArray<Double>(count: x.count)
withPointer(x) { xp in
vvtanh(results.mutablePointer + results.startIndex, xp + x.startIndex, [Int32(x.count)])
}
return results
}
/// Inverse Hyperbolic Sine
public func asinh<C: LinearType>(_ x: C) -> ValueArray<Double> where C.Element == Double {
precondition(x.step == 1, "asinh doesn't support step values other than 1")
let results = ValueArray<Double>(count: x.count)
withPointer(x) { xp in
vvasinh(results.mutablePointer + results.startIndex, xp + x.startIndex, [Int32(x.count)])
}
return results
}
/// Inverse Hyperbolic Cosine
public func acosh<C: LinearType>(_ x: C) -> ValueArray<Double> where C.Element == Double {
precondition(x.step == 1, "acosh doesn't support step values other than 1")
let results = ValueArray<Double>(count: x.count)
withPointer(x) { xp in
vvacosh(results.mutablePointer + results.startIndex, xp + x.startIndex, [Int32(x.count)])
}
return results
}
/// Inverse Hyperbolic Tangent
public func atanh<C: LinearType>(_ x: C) -> ValueArray<Double> where C.Element == Double {
precondition(x.step == 1, "atanh doesn't support step values other than 1")
let results = ValueArray<Double>(count: x.count)
withPointer(x) { xp in
vvatanh(results.mutablePointer + results.startIndex, xp + x.startIndex, [Int32(x.count)])
}
return results
}
// MARK: - Float
/// Hyperbolic Sine
public func sinh<C: LinearType>(_ x: C) -> ValueArray<Float> where C.Element == Float {
precondition(x.step == 1, "sinh doesn't support step values other than 1")
let results = ValueArray<Float>(count: x.count)
withPointer(x) { xp in
vvsinhf(results.mutablePointer + results.startIndex, xp + x.startIndex, [Int32(x.count)])
}
return results
}
/// Hyperbolic Cosine
public func cosh<C: LinearType>(_ x: C) -> ValueArray<Float> where C.Element == Float {
precondition(x.step == 1, "cosh doesn't support step values other than 1")
let results = ValueArray<Float>(count: x.count)
withPointer(x) { xp in
vvcoshf(results.mutablePointer + results.startIndex, xp + x.startIndex, [Int32(x.count)])
}
return results
}
/// Hyperbolic Tangent
public func tanh<C: LinearType>(_ x: C) -> ValueArray<Float> where C.Element == Float {
precondition(x.step == 1, "tanh doesn't support step values other than 1")
let results = ValueArray<Float>(count: x.count)
withPointer(x) { xp in
vvtanhf(results.mutablePointer + results.startIndex, xp + x.startIndex, [Int32(x.count)])
}
return results
}
/// Inverse Hyperbolic Sine
public func asinh<C: LinearType>(_ x: C) -> ValueArray<Float> where C.Element == Float {
precondition(x.step == 1, "asinh doesn't support step values other than 1")
let results = ValueArray<Float>(count: x.count)
withPointer(x) { xp in
vvasinhf(results.mutablePointer + results.startIndex, xp + x.startIndex, [Int32(x.count)])
}
return results
}
/// Inverse Hyperbolic Cosine
public func acosh<C: LinearType>(_ x: C) -> ValueArray<Float> where C.Element == Float {
precondition(x.step == 1, "acosh doesn't support step values other than 1")
let results = ValueArray<Float>(count: x.count)
withPointer(x) { xp in
vvacoshf(results.mutablePointer + results.startIndex, xp + x.startIndex, [Int32(x.count)])
}
return results
}
/// Inverse Hyperbolic Tangent
public func atanh<C: LinearType>(_ x: C) -> ValueArray<Float> where C.Element == Float {
precondition(x.step == 1, "atanh doesn't support step values other than 1")
let results = ValueArray<Float>(count: x.count)
withPointer(x) { xp in
vvatanhf(results.mutablePointer + results.startIndex, xp + x.startIndex, [Int32(x.count)])
}
return results
}
| mit | ad23b3933a5cd053eabc1a9cc6243153 | 34.60355 | 98 | 0.689879 | 3.734947 | false | false | false | false |
vinayaks101/Psychologist-iOSApp | Psychologist/Psychologist/FaceView.swift | 2 | 3750 | //
// FaceView.swift
// Happiness
//
// Created by Vinayak Srivastava on 30/06/15.
// Copyright (c) 2015 Vinayak Srivastava. All rights reserved.
//
import UIKit
protocol FaceViewDataSource {
func smilenessForFace(face: FaceView) -> Double?
}
@IBDesignable
class FaceView: UIView {
@IBInspectable
var lineWidth: CGFloat = 3 { didSet { setNeedsDisplay() } }
@IBInspectable
var color: UIColor = UIColor.blueColor() { didSet { setNeedsDisplay() } }
@IBInspectable
var scale: CGFloat = 0.90 { didSet { setNeedsDisplay() } }
var faceCenter: CGPoint {
return convertPoint(center, fromView: superview)
}
var faceRadius: CGFloat {
return min(bounds.size.width, bounds.size.height) / 2 * scale
}
var dataSource: FaceViewDataSource?
private struct Scaling {
static let FaceRadiusToEyeRadiusRatio: CGFloat = 10
static let FaceRadiusToEyeOffsetRatio: CGFloat = 3
static let FaceRadiusToEyeSeparationRatio: CGFloat = 1.5
static let FaceRadiusToMouthWidthRatio: CGFloat = 1
static let FaceRadiusToMouthHeightRatio: CGFloat = 3
static let FaceRadiusToMouthOffsetRatio: CGFloat = 3
}
private enum Eye { case Left, Right }
private func bezierPathForEye(whichEye: Eye) -> UIBezierPath {
let eyeRadius = faceRadius / Scaling.FaceRadiusToEyeRadiusRatio
let eyeVerticalOffset = faceRadius / Scaling.FaceRadiusToEyeOffsetRatio
let eyeHorizontalSeparation = faceRadius / Scaling.FaceRadiusToEyeSeparationRatio
var eyeCenter = faceCenter
eyeCenter.y -= eyeVerticalOffset
switch whichEye {
case .Left:
eyeCenter.x -= eyeHorizontalSeparation / 2
case .Right:
eyeCenter.x += eyeHorizontalSeparation / 2
}
let path = UIBezierPath (arcCenter: eyeCenter, radius: eyeRadius, startAngle: 0, endAngle: CGFloat(2 * M_PI), clockwise: true)
path.lineWidth = lineWidth
return path
}
private func bezierPathForSmile(fractionOfMaxSmile: Double) -> UIBezierPath {
let mouthWidth = faceRadius / Scaling.FaceRadiusToMouthWidthRatio
let mouthHeight = faceRadius / Scaling.FaceRadiusToMouthHeightRatio
let mouthVerticalOffset = faceRadius / Scaling.FaceRadiusToMouthOffsetRatio
let smileHeight = CGFloat(max(min(fractionOfMaxSmile, 1), -1)) * mouthHeight
let start = CGPoint(x: faceCenter.x - mouthWidth / 2, y: faceCenter.y + mouthVerticalOffset)
let end = CGPoint(x: start.x + mouthWidth, y: start.y)
let cp1 = CGPoint(x: start.x + mouthWidth / 3, y: start.y + smileHeight)
let cp2 = CGPoint(x: end.x - mouthWidth / 3, y: cp1.y)
let path = UIBezierPath()
path.moveToPoint(start)
path.addCurveToPoint(end, controlPoint1: cp1, controlPoint2: cp2)
path.lineWidth = lineWidth
return path
}
override func drawRect(rect: CGRect) {
let facePath = UIBezierPath(arcCenter: faceCenter, radius: faceRadius, startAngle: 0, endAngle: CGFloat(2 * M_PI), clockwise: true)
facePath.lineWidth = lineWidth
color.set()
facePath.stroke()
bezierPathForEye(.Left).stroke()
bezierPathForEye(.Right).stroke()
let smileness = dataSource?.smilenessForFace(self) ?? 0.0
let smilePath = bezierPathForSmile(smileness)
smilePath.stroke()
}
func scaleGesture(gesture: UIPinchGestureRecognizer) {
if (gesture.state == .Changed) {
scale *= gesture.scale
gesture.scale = 1
}
}
}
| apache-2.0 | c278e0c5afd268c8f90c97b592dfa71a | 33.40367 | 139 | 0.645067 | 4.863813 | false | false | false | false |
yangligeryang/codepath | labs/FacebookDemo/FacebookDemo/PhotoZoomTransition.swift | 1 | 3360 | //
// PhotoZoomTransition.swift
// FacebookDemo
//
// Created by Yang Yang on 11/15/16.
// Copyright © 2016 Yang Yang. All rights reserved.
//
import UIKit
class PhotoZoomTransition: BaseTransition {
var aspectRatio: CGFloat!
var largeFrame: CGRect!
var feedViewFrame: CGRect!
var feedImageViewFrame: CGRect!
override func presentTransition(containerView: UIView, fromViewController: UIViewController, toViewController: UIViewController) {
toViewController.view.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0)
let photoViewController = toViewController as! PhotoViewController
let photoContainer = photoViewController.photoContainer
let photo = photoViewController.photo as UIImageView
let photoImage = photoViewController.photoImage
aspectRatio = CGFloat((photoImage?.size.height)! / (photoImage?.size.width)!)
largeFrame = CGRect(x: 0, y: 0, width: 375, height: 375 * aspectRatio)
if self.largeFrame.height < photoViewController.scrollView.frame.size.height {
photoViewController.scrollView.frame.size.height = self.largeFrame.height
photoViewController.scrollView.clipsToBounds = false
}
let tabViewController = fromViewController as! UITabBarController
let navigationController = tabViewController.selectedViewController as! UINavigationController
let feedViewController = navigationController.topViewController as! FeedViewController
let feedImageView = feedViewController.selectedPhoto as UIImageView
let feedViewIndex = Int(feedViewController.photoImages.index(of: feedImageView)!)
feedViewFrame = feedViewController.photoViews[feedViewIndex].frame
feedImageViewFrame = feedImageView.frame
print(feedViewFrame)
photoContainer?.frame = (photoContainer?.convert(feedViewFrame, to: containerView))!
photo.frame = feedImageViewFrame
UIView.animate(withDuration: duration, animations: {
toViewController.view.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
photoContainer?.frame = self.largeFrame
photo.frame = self.largeFrame
photoViewController.scrollView.center = photoViewController.view.center
}) { (finished: Bool) -> Void in
self.finish()
}
}
override func dismissTransition(containerView: UIView, fromViewController: UIViewController, toViewController: UIViewController) {
fromViewController.view.alpha = 1
fromViewController.view.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
let photoViewController = fromViewController as! PhotoViewController
let photoContainer = photoViewController.photoContainer
let photo = photoViewController.photo
UIView.animate(withDuration: duration, animations: {
fromViewController.view.alpha = 0
fromViewController.view.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0)
photoContainer?.frame = self.feedViewFrame
photo?.frame = self.feedImageViewFrame
}) { (finished: Bool) -> Void in
self.finish()
}
}
}
| apache-2.0 | 22b75c69063283c877d87e9f5ecd7359 | 42.623377 | 134 | 0.687109 | 5.409018 | false | false | false | false |
hyp/NUIGExam | NUIGExam/MasterViewController.swift | 1 | 6916 | import UIKit
import CoreData
// A TableViewCell that displays the Exam details.
class ExamCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var seatLabel: UILabel!
}
// Displays the exam timetable.
class MasterViewController: UITableViewController {
var exams: [[Exam]] = []
var dateFormatter = NSDateFormatter()
let timeFormatter = NSDateFormatter()
lazy var managedObjectContext : NSManagedObjectContext? = {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
if let managedObjectContext = appDelegate.managedObjectContext {
return managedObjectContext
}
else {
return nil
}
}()
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let prefs = NSUserDefaults.standardUserDefaults()
if !prefs.boolForKey("isLoggedIn") {
self.performSegueWithIdentifier("showLogin", sender: self)
} else {
if let examSession = prefs.stringForKey("examSession") {
self.navigationItem.title = examSession + " Exams"
}
fetchExams()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.hidesBackButton = true
timeFormatter.dateStyle = NSDateFormatterStyle.NoStyle
timeFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
timeFormatter.locale = NSLocale(localeIdentifier: "en-IE")
dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
dateFormatter.doesRelativeDateFormatting = true
let infoButton = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as UIButton
navigationItem.rightBarButtonItem = UIBarButtonItem(image: infoButton.currentImage, style: UIBarButtonItemStyle.Plain, target: self, action: "showInfo")
// Scroll to show the next exam.
/*
dispatch_async(dispatch_get_main_queue()) {
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1), atScrollPosition: UITableViewScrollPosition.Top, animated: false)
}*/
}
func showInfo() {
performSegueWithIdentifier("showInfo", sender: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Return true if two dates are on the same day.
func areDatesOnSameDay(x: NSDate, _ y: NSDate) -> Bool {
let calendar = NSCalendar.currentCalendar()
return calendar.component(NSCalendarUnit.CalendarUnitYear, fromDate: x) == calendar.component(NSCalendarUnit.CalendarUnitYear, fromDate: y) && calendar.component(NSCalendarUnit.CalendarUnitMonth, fromDate: x) == calendar.component(NSCalendarUnit.CalendarUnitMonth, fromDate: y) && calendar.component(NSCalendarUnit.CalendarUnitDay, fromDate: x) == calendar.component(NSCalendarUnit.CalendarUnitDay, fromDate: y)
}
// Load the exams from CoreData storage.
func fetchExams() {
let fetchRequest = NSFetchRequest(entityName: "Exam")
let sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
if let result = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [Exam] {
exams.removeAll(keepCapacity: true)
for exam in result {
let date = exam.date
var i = 0
for ; i < exams.count; i++ {
if areDatesOnSameDay(date, exams[i][0].date) {
break
}
}
if i >= exams.count {
exams.append([])
}
exams[i].append(exam)
}
}
self.tableView.reloadData()
}
// MARK: - Table View
func selectedExam() -> Exam? {
if let selection = tableView.indexPathForSelectedRow() {
return exams[selection.section][selection.row]
}
return nil
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if !exams.isEmpty {
self.tableView.backgroundView = nil
return exams.count
}
// No exams - show message to the user.
let message = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height))
message.text = "No exams in this session"
message.textColor = UIColor.blackColor()
message.numberOfLines = 0
message.textAlignment = NSTextAlignment.Center
message.font = UIFont.italicSystemFontOfSize(20)
message.sizeToFit()
self.tableView.backgroundView = message
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return exams[section].count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return dateFormatter.stringFromDate(exams[section].first!.date)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let exam = exams[indexPath.section][indexPath.row]
if exam.isFinished {
return 44
}
return 64
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as ExamCell
let exam = exams[indexPath.section][indexPath.row]
cell.nameLabel.text = exam.name
if exam.isFinished {
cell.nameLabel.enabled = false
cell.descriptionLabel.hidden = true
return cell
}
let date = timeFormatter.stringFromDate(exam.date)
if exam.seatNumber.boolValue {
cell.descriptionLabel.text = "\(date) · Seat \(exam.seatNumber) · \(exam.venue)"
} else {
cell.descriptionLabel.text = "\(date) · \(exam.venue)"
}
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return false
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showExam" {
(segue.destinationViewController as ExamViewController).exam = selectedExam()
}
}
}
| mit | 0f66866ee31a16d13083d9d01b7d7558 | 36.166667 | 419 | 0.636771 | 5.338224 | false | false | false | false |
codwam/NPB | Demos/NPBDemo/NPBDemo/TabBarController.swift | 1 | 1080 | //
// TabBarController.swift
// NPBDemo
//
// Created by 李辉 on 2017/4/8.
// Copyright © 2017年 codwam. All rights reserved.
//
import UIKit
/*
Storyboard References cannot be the destinations of relationship segues prior to iOS 9.0
所以写了个类
*/
class TabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
initView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Init View
func initView() {
let npbViewContoller = UIStoryboard(name: "NPB", bundle: nil).instantiateInitialViewController()!
npbViewContoller.tabBarItem.title = "NPB Test"
let jzViewContoller = UIStoryboard(name: "JZ", bundle: nil).instantiateInitialViewController()!
jzViewContoller.tabBarItem.title = "JZ Test"
self.viewControllers = [npbViewContoller, jzViewContoller]
}
}
| mit | ae9480db24f17d2f2fd5e008148770df | 24.261905 | 105 | 0.666352 | 4.514894 | false | false | false | false |
benlangmuir/swift | test/Concurrency/default_actor_definit.swift | 12 | 2106 | // RUN: %target-swift-frontend -emit-sil %s -disable-availability-checking | %FileCheck %s
// REQUIRES: concurrency
actor A {
var x: String = "Hello"
var y: String = "World"
}
// CHECK-LABEL: sil hidden @$s21default_actor_definit1ACACycfc
// CHECK: builtin "initializeDefaultActor"(%0 : $A) : $()
// CHECK-LABEL: end sil function '$s21default_actor_definit1ACACycfc'
actor B {
var x: String
var y: String
init() {
x = "Hello"
y = "World"
}
}
// CHECK-LABEL: sil hidden @$s21default_actor_definit1BCACycfc
// CHECK: builtin "initializeDefaultActor"(%0 : $B) : $()
// CHECK-LABEL: end sil function '$s21default_actor_definit1BCACycfc'
actor C {
var x: String
var y: Int
init?(y: Int) {
self.x = "Hello"
guard y >= 0 else { return nil }
self.y = y
}
convenience init?(yy: Int) {
guard yy <= 100 else { return nil }
self.init(y: yy)
}
}
// CHECK-LABEL: sil hidden @$s21default_actor_definit1CC1yACSgSi_tcfc
// CHECK: builtin "initializeDefaultActor"(%1 : $C)
// CHECK: [[X:%.*]] = ref_element_addr %1 : $C, #C.x
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[X]] : $*String
// CHECK-NEXT: store {{.*}} to [[ACCESS]] : $*String
// CHECK-NEXT: end_access [[ACCESS]] : $*String
// CHECK: cond_br {{%.*}}, bb1, bb2
// CHECK: bb1:
// CHECK: ref_element_addr %1 : $C, #C.y
// CHECK: br bb3
// CHECK: bb2:
// CHECK: [[X:%.*]] = ref_element_addr %1 : $C, #C.x
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [deinit] [static] [[X]] : $*String
// CHECK-NEXT: destroy_addr [[ACCESS]] : $*String
// CHECK-NEXT: end_access [[ACCESS]] : $*String
// CHECK: builtin "destroyDefaultActor"(%1 : $C)
// CHECK: br bb3
// CHECK-LABEL: end sil function '$s21default_actor_definit1CC1yACSgSi_tcfc'
// CHECK-LABEL: sil hidden @$s21default_actor_definit1CC2yyACSgSi_tcfC
// CHECK-NOT: builtin "initializeDefaultActor"
// CHECK-NOT: builtin "destroyDefaultActor"
// CHECK-LABEL: end sil function '$s21default_actor_definit1CC2yyACSgSi_tcfC'
| apache-2.0 | dc49e150542a5e81ae41d2b6ddcc9df4 | 32.967742 | 91 | 0.606838 | 3.065502 | false | false | false | false |
gregomni/swift | stdlib/public/core/ArrayShared.swift | 2 | 13407 | //===--- ArrayShared.swift ------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
/// This type is used as a result of the `_checkSubscript` call to associate the
/// call with the array access call it guards.
///
/// In order for the optimizer see that a call to `_checkSubscript` is semantically
/// associated with an array access, a value of this type is returned and later passed
/// to the accessing function. For example, a typical call to `_getElement` looks like
/// let token = _checkSubscript(index, ...)
/// return _getElement(index, ... , matchingSubscriptCheck: token)
@frozen
public struct _DependenceToken {
@inlinable
public init() {
}
}
/// Returns an Array of `_count` uninitialized elements using the
/// given `storage`, and a pointer to uninitialized memory for the
/// first element.
///
/// This function is referenced by the compiler to allocate array literals.
///
/// - Precondition: `storage` is `_ContiguousArrayStorage`.
@inlinable // FIXME(inline-always)
@inline(__always)
@_semantics("array.uninitialized_intrinsic")
public // COMPILER_INTRINSIC
func _allocateUninitializedArray<Element>(_ builtinCount: Builtin.Word)
-> (Array<Element>, Builtin.RawPointer) {
let count = Int(builtinCount)
if count > 0 {
// Doing the actual buffer allocation outside of the array.uninitialized
// semantics function enables stack propagation of the buffer.
let bufferObject = Builtin.allocWithTailElems_1(
getContiguousArrayStorageType(for: Element.self),
builtinCount, Element.self)
let (array, ptr) = Array<Element>._adoptStorage(bufferObject, count: count)
return (array, ptr._rawValue)
}
// For an empty array no buffer allocation is needed.
let (array, ptr) = Array<Element>._allocateUninitialized(count)
return (array, ptr._rawValue)
}
// Referenced by the compiler to deallocate array literals on the
// error path.
@inlinable
@_semantics("array.dealloc_uninitialized")
public // COMPILER_INTRINSIC
func _deallocateUninitializedArray<Element>(
_ array: __owned Array<Element>
) {
var array = array
array._deallocateUninitialized()
}
#if !INTERNAL_CHECKS_ENABLED
@_alwaysEmitIntoClient
@_semantics("array.finalize_intrinsic")
@_effects(readnone)
public // COMPILER_INTRINSIC
func _finalizeUninitializedArray<Element>(
_ array: __owned Array<Element>
) -> Array<Element> {
var mutableArray = array
mutableArray._endMutation()
return mutableArray
}
#else
// When asserts are enabled, _endCOWMutation writes to _native.isImmutable
// So we cannot have @_effects(readnone)
@_alwaysEmitIntoClient
@_semantics("array.finalize_intrinsic")
public // COMPILER_INTRINSIC
func _finalizeUninitializedArray<Element>(
_ array: __owned Array<Element>
) -> Array<Element> {
var mutableArray = array
mutableArray._endMutation()
return mutableArray
}
#endif
extension Collection {
// Utility method for collections that wish to implement
// CustomStringConvertible and CustomDebugStringConvertible using a bracketed
// list of elements, like an array.
internal func _makeCollectionDescription(
withTypeName type: String? = nil
) -> String {
#if !SWIFT_STDLIB_STATIC_PRINT
var result = ""
if let type = type {
result += "\(type)(["
} else {
result += "["
}
var first = true
for item in self {
if first {
first = false
} else {
result += ", "
}
debugPrint(item, terminator: "", to: &result)
}
result += type != nil ? "])" : "]"
return result
#else
return "(collection printing not available)"
#endif
}
}
extension _ArrayBufferProtocol {
@inlinable // FIXME @useableFromInline https://bugs.swift.org/browse/SR-7588
@inline(never)
internal mutating func _arrayOutOfPlaceReplace<C: Collection>(
_ bounds: Range<Int>,
with newValues: __owned C,
count insertCount: Int
) where C.Element == Element {
let growth = insertCount - bounds.count
let newCount = self.count + growth
var newBuffer = _forceCreateUniqueMutableBuffer(
newCount: newCount, requiredCapacity: newCount)
_arrayOutOfPlaceUpdate(
&newBuffer, bounds.lowerBound - startIndex, insertCount,
{ rawMemory, count in
var p = rawMemory
var q = newValues.startIndex
for _ in 0..<count {
p.initialize(to: newValues[q])
newValues.formIndex(after: &q)
p += 1
}
_expectEnd(of: newValues, is: q)
}
)
}
}
/// A _debugPrecondition check that `i` has exactly reached the end of
/// `s`. This test is never used to ensure memory safety; that is
/// always guaranteed by measuring `s` once and re-using that value.
@inlinable
internal func _expectEnd<C: Collection>(of s: C, is i: C.Index) {
_debugPrecondition(
i == s.endIndex,
"invalid Collection: count differed in successive traversals")
}
@inlinable
internal func _growArrayCapacity(_ capacity: Int) -> Int {
return capacity * 2
}
@_alwaysEmitIntoClient
internal func _growArrayCapacity(
oldCapacity: Int, minimumCapacity: Int, growForAppend: Bool
) -> Int {
if growForAppend {
if oldCapacity < minimumCapacity {
// When appending to an array, grow exponentially.
return Swift.max(minimumCapacity, _growArrayCapacity(oldCapacity))
}
return oldCapacity
}
// If not for append, just use the specified capacity, ignoring oldCapacity.
// This means that we "shrink" the buffer in case minimumCapacity is less
// than oldCapacity.
return minimumCapacity
}
//===--- generic helpers --------------------------------------------------===//
extension _ArrayBufferProtocol {
/// Create a unique mutable buffer that has enough capacity to hold 'newCount'
/// elements and at least 'requiredCapacity' elements. Set the count of the new
/// buffer to 'newCount'. The content of the buffer is uninitialized.
/// The formula used to compute the new buffers capacity is:
/// max(requiredCapacity, source.capacity) if newCount <= source.capacity
/// max(requiredCapacity, _growArrayCapacity(source.capacity)) otherwise
@inline(never)
@inlinable // @specializable
internal func _forceCreateUniqueMutableBuffer(
newCount: Int, requiredCapacity: Int
) -> _ContiguousArrayBuffer<Element> {
return _forceCreateUniqueMutableBufferImpl(
countForBuffer: newCount, minNewCapacity: newCount,
requiredCapacity: requiredCapacity)
}
/// Create a unique mutable buffer that has enough capacity to hold
/// 'minNewCapacity' elements and set the count of the new buffer to
/// 'countForNewBuffer'. The content of the buffer uninitialized.
/// The formula used to compute the new buffers capacity is:
/// max(minNewCapacity, source.capacity) if minNewCapacity <= source.capacity
/// max(minNewCapacity, _growArrayCapacity(source.capacity)) otherwise
@inline(never)
@inlinable // @specializable
internal func _forceCreateUniqueMutableBuffer(
countForNewBuffer: Int, minNewCapacity: Int
) -> _ContiguousArrayBuffer<Element> {
return _forceCreateUniqueMutableBufferImpl(
countForBuffer: countForNewBuffer, minNewCapacity: minNewCapacity,
requiredCapacity: minNewCapacity)
}
/// Create a unique mutable buffer that has enough capacity to hold
/// 'minNewCapacity' elements and at least 'requiredCapacity' elements and set
/// the count of the new buffer to 'countForBuffer'. The content of the buffer
/// uninitialized.
/// The formula used to compute the new capacity is:
/// max(requiredCapacity, source.capacity) if minNewCapacity <= source.capacity
/// max(requiredCapacity, _growArrayCapacity(source.capacity)) otherwise
@inlinable
internal func _forceCreateUniqueMutableBufferImpl(
countForBuffer: Int, minNewCapacity: Int,
requiredCapacity: Int
) -> _ContiguousArrayBuffer<Element> {
_internalInvariant(countForBuffer >= 0)
_internalInvariant(requiredCapacity >= countForBuffer)
_internalInvariant(minNewCapacity >= countForBuffer)
let minimumCapacity = Swift.max(requiredCapacity,
minNewCapacity > capacity
? _growArrayCapacity(capacity) : capacity)
return _ContiguousArrayBuffer(
_uninitializedCount: countForBuffer, minimumCapacity: minimumCapacity)
}
}
extension _ArrayBufferProtocol {
/// Initialize the elements of dest by copying the first headCount
/// items from source, calling initializeNewElements on the next
/// uninitialized element, and finally by copying the last N items
/// from source into the N remaining uninitialized elements of dest.
///
/// As an optimization, may move elements out of source rather than
/// copying when it isUniquelyReferenced.
@inline(never)
@inlinable // @specializable
internal mutating func _arrayOutOfPlaceUpdate(
_ dest: inout _ContiguousArrayBuffer<Element>,
_ headCount: Int, // Count of initial source elements to copy/move
_ newCount: Int, // Number of new elements to insert
_ initializeNewElements:
((UnsafeMutablePointer<Element>, _ count: Int) -> ()) = { ptr, count in
_internalInvariant(count == 0)
}
) {
_internalInvariant(headCount >= 0)
_internalInvariant(newCount >= 0)
// Count of trailing source elements to copy/move
let sourceCount = self.count
let tailCount = dest.count - headCount - newCount
_internalInvariant(headCount + tailCount <= sourceCount)
let oldCount = sourceCount - headCount - tailCount
let destStart = dest.firstElementAddress
let newStart = destStart + headCount
let newEnd = newStart + newCount
// Check to see if we have storage we can move from
if let backing = requestUniqueMutableBackingBuffer(
minimumCapacity: sourceCount) {
let sourceStart = firstElementAddress
let oldStart = sourceStart + headCount
// Destroy any items that may be lurking in a _SliceBuffer before
// its real first element
let backingStart = backing.firstElementAddress
let sourceOffset = sourceStart - backingStart
backingStart.deinitialize(count: sourceOffset)
// Move the head items
destStart.moveInitialize(from: sourceStart, count: headCount)
// Destroy unused source items
oldStart.deinitialize(count: oldCount)
initializeNewElements(newStart, newCount)
// Move the tail items
newEnd.moveInitialize(from: oldStart + oldCount, count: tailCount)
// Destroy any items that may be lurking in a _SliceBuffer after
// its real last element
let backingEnd = backingStart + backing.count
let sourceEnd = sourceStart + sourceCount
sourceEnd.deinitialize(count: backingEnd - sourceEnd)
backing.count = 0
}
else {
let headStart = startIndex
let headEnd = headStart + headCount
let newStart = _copyContents(
subRange: headStart..<headEnd,
initializing: destStart)
initializeNewElements(newStart, newCount)
let tailStart = headEnd + oldCount
let tailEnd = endIndex
_copyContents(subRange: tailStart..<tailEnd, initializing: newEnd)
}
self = Self(_buffer: dest, shiftedToStartIndex: startIndex)
}
}
extension _ArrayBufferProtocol {
@inline(never)
@usableFromInline
internal mutating func _outlinedMakeUniqueBuffer(bufferCount: Int) {
if _fastPath(
requestUniqueMutableBackingBuffer(minimumCapacity: bufferCount) != nil) {
return
}
var newBuffer = _forceCreateUniqueMutableBuffer(
newCount: bufferCount, requiredCapacity: bufferCount)
_arrayOutOfPlaceUpdate(&newBuffer, bufferCount, 0)
}
/// Append items from `newItems` to a buffer.
@inlinable
internal mutating func _arrayAppendSequence<S: Sequence>(
_ newItems: __owned S
) where S.Element == Element {
// this function is only ever called from append(contentsOf:)
// which should always have exhausted its capacity before calling
_internalInvariant(count == capacity)
var newCount = self.count
// there might not be any elements to append remaining,
// so check for nil element first, then increase capacity,
// then inner-loop to fill that capacity with elements
var stream = newItems.makeIterator()
var nextItem = stream.next()
while nextItem != nil {
// grow capacity, first time around and when filled
var newBuffer = _forceCreateUniqueMutableBuffer(
countForNewBuffer: newCount,
// minNewCapacity handles the exponential growth, just
// need to request 1 more than current count/capacity
minNewCapacity: newCount + 1)
_arrayOutOfPlaceUpdate(&newBuffer, newCount, 0)
let currentCapacity = self.capacity
let base = self.firstElementAddress
// fill while there is another item and spare capacity
while let next = nextItem, newCount < currentCapacity {
(base + newCount).initialize(to: next)
newCount += 1
nextItem = stream.next()
}
self.count = newCount
}
}
}
| apache-2.0 | 6891e4e142d06c2edddc061df7f8c979 | 34.096859 | 87 | 0.701798 | 4.852334 | false | false | false | false |
tinrobots/Mechanica | Sources/Foundation/FoundationUtils.swift | 1 | 2894 | #if canImport(Foundation)
import Foundation
/// **Mechanica**
///
/// Returns the type name as `String`.
public func typeName(of some: Any) -> String {
let value = (some is Any.Type) ? "\(some)" : "\(type(of: some))"
if !value.starts(with: "(") { return value }
// match a word inside "(" and " in" https://regex101.com/r/eO6eB7/17
let pattern = "(?<=\\()[^()]{1,}(?=\\sin)"
// if let result = value.range(of: pattern, options: .regularExpression) { return value[result] }
if let result = value.firstRange(matching: pattern) {
return String(value[result])
}
return value
}
// MARK: - Objective-C Associated Objects
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
/// **Mechanica**
///
/// Sets an associated value for a given object using a given key and association policy.
///
/// - Parameters:
/// - value: The value to associate with the key key for object. Pass nil to clear an existing association.
/// - object: The source object for the association.
/// - key: The key for the association.
/// - policy: The policy for the association.
internal func setAssociatedValue<T>(_ value: T?,
forObject object: Any,
usingKey key: UnsafeRawPointer,
andPolicy policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN_NONATOMIC) {
Foundation.objc_setAssociatedObject(object, key, value, policy)
}
/// **Mechanica**
///
/// Returns the value associated with a given object for a given key.
///
/// - Parameters:
/// - object: The source object for the association.
/// - key: The key for the association.
/// - Returns: The value associated with the key for object.
internal func getAssociatedValue<T>(forObject object: Any, usingKey key: UnsafeRawPointer) -> T? {
return Foundation.objc_getAssociatedObject(object, key) as? T
}
/// **Mechanica**
///
/// Removes an associated value for a given object using a given key and association policy.
///
/// - Parameters:
/// - object: The source object for the association.
/// - key: The key for the association.
/// - policy: The policy for the association.
internal func removeAssociatedValue(forObject object: Any,
usingKey key: UnsafeRawPointer,
andPolicy policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN_NONATOMIC) {
Foundation.objc_setAssociatedObject(object, key, nil, policy)
}
/// **Mechanica**
///
/// Removes all the associated value for a given object using a given key and association policy.
///
/// - Parameters:
/// - object: The source object for the association.
/// - key: The key for the association.
/// - policy: The policy for the association.
internal func removeAllAssociatedValues(forObject object: Any) {
Foundation.objc_removeAssociatedObjects(object)
}
#endif
#endif
| mit | 8f8801856ecd7e17bab4c08518073c25 | 35.175 | 116 | 0.653766 | 4.110795 | false | false | false | false |
AlexLombry/SwiftMastery-iOS10 | PlayGround/ControlFlow.playground/Contents.swift | 1 | 888 | //: Playground - noun: a place where people can play
import UIKit
for num in 1...12 {
print("\(num) times 12 is \(num * 12)")
}
let base = 2
let power = 10
var answer = 1
for _ in 1...10 {
answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
// array iterating
let dogNames = ["Fido", "Rex", "Spot", "jack"]
for dogName in dogNames {
print("Hello \(dogName)!")
}
let products = ["iPhone": 499, "iPad": 899.00, "iMac": 2099.00]
for (name, price) in products {
print("Apple's \(name) cost $\(price)")
}
// While style
var myString = "Hello Swift"
var counter = 0
while counter < 5 {
print("\(counter) - \(myString)")
counter += 1
}
var repeatCounter = 0
repeat {
print("The repeat while loop will always execute its code at least once")
repeatCounter += 1
} while repeatCounter < 12
// Do while style (for php users)
| apache-2.0 | 03820145616b687594a4b8b98037c5ba | 14.857143 | 77 | 0.613739 | 3.288889 | false | false | false | false |
toggl/superday | teferi/Services/Implementations/Persistency/DefaultTimeSlotService.swift | 1 | 7881 | import CoreData
import RxSwift
import Foundation
class DefaultTimeSlotService : TimeSlotService
{
// MARK: Private Properties
private let timeService : TimeService
private let loggingService : LoggingService
private let locationService : LocationService
private let persistencyService : BasePersistencyService<TimeSlot>
private let timeSlotCreatedSubject = PublishSubject<TimeSlot>()
private let timeSlotsUpdatedSubject = PublishSubject<[TimeSlot]>()
// MARK: Initializer
init(timeService: TimeService,
loggingService: LoggingService,
locationService: LocationService,
persistencyService: BasePersistencyService<TimeSlot>)
{
self.timeService = timeService
self.loggingService = loggingService
self.locationService = locationService
self.persistencyService = persistencyService
}
// MARK: Public Methods
@discardableResult func addTimeSlot(withStartTime startTime: Date, category: Category, categoryWasSetByUser: Bool, tryUsingLatestLocation: Bool) -> TimeSlot?
{
let location : Location? = tryUsingLatestLocation ? locationService.getLastKnownLocation() : nil
return addTimeSlot(withStartTime: startTime,
category: category,
categoryWasSetByUser: categoryWasSetByUser,
location: location)
}
@discardableResult func addTimeSlot(withStartTime startTime: Date, category: Category, categoryWasSetByUser: Bool, location: Location?) -> TimeSlot?
{
let timeSlot = TimeSlot(startTime: startTime,
category: category,
categoryWasSetByUser: categoryWasSetByUser,
categoryWasSmartGuessed: false,
location: location)
return tryAdd(timeSlot: timeSlot)
}
@discardableResult func addTimeSlot(withStartTime startTime: Date, category: Category, location: Location?) -> TimeSlot?
{
let timeSlot = TimeSlot(startTime: startTime,
category: category,
location: location)
return tryAdd(timeSlot: timeSlot)
}
@discardableResult func addTimeSlot(fromTemporaryTimeslot temporaryTimeSlot: TemporaryTimeSlot) -> TimeSlot?
{
let timeSlot = TimeSlot(startTime: temporaryTimeSlot.start,
endTime: temporaryTimeSlot.end,
category: temporaryTimeSlot.category,
location: temporaryTimeSlot.location,
categoryWasSetByUser: false,
categoryWasSmartGuessed: temporaryTimeSlot.isSmartGuessed,
activity: temporaryTimeSlot.activity)
return tryAdd(timeSlot: timeSlot)
}
func getTimeSlots(forDay day: Date) -> [TimeSlot]
{
return getTimeSlots(forDay: day, category: nil)
}
func getTimeSlots(forDay day: Date, category: Category?) -> [TimeSlot]
{
let startTime = day.ignoreTimeComponents() as NSDate
let endTime = day.tomorrow.ignoreTimeComponents().addingTimeInterval(-1) as NSDate
var timeSlots = [TimeSlot]()
if let category = category
{
let predicates = [Predicate(parameter: "startTime", rangesFromDate: startTime, toDate: endTime),
Predicate(parameter: "category", equals: category.rawValue as AnyObject)]
timeSlots = persistencyService.get(withANDPredicates: predicates)
}
else
{
let predicate = Predicate(parameter: "startTime", rangesFromDate: startTime, toDate: endTime)
timeSlots = persistencyService.get(withPredicate: predicate)
}
return timeSlots
}
func getTimeSlots(sinceDaysAgo days: Int) -> [TimeSlot]
{
let today = timeService.now.ignoreTimeComponents()
let startTime = today.add(days: -days).ignoreTimeComponents() as NSDate
let endTime = today.tomorrow.ignoreTimeComponents() as NSDate
let predicate = Predicate(parameter: "startTime", rangesFromDate: startTime, toDate: endTime)
let timeSlots = persistencyService.get(withPredicate: predicate)
return timeSlots
}
func getTimeSlots(betweenDate firstDate: Date, andDate secondDate: Date) -> [TimeSlot]
{
let date1 = firstDate.ignoreTimeComponents() as NSDate
let date2 = secondDate.add(days: 1).ignoreTimeComponents() as NSDate
let predicate = Predicate(parameter: "startTime", rangesFromDate: date1, toDate: date2)
let timeSlots = persistencyService.get(withPredicate: predicate)
return timeSlots
}
func getLast() -> TimeSlot?
{
return persistencyService.getLast()
}
func calculateDuration(ofTimeSlot timeSlot: TimeSlot) -> TimeInterval
{
let endTime = getEndTime(ofTimeSlot: timeSlot)
return endTime.timeIntervalSince(timeSlot.startTime)
}
// MARK: Private Methods
private func tryAdd(timeSlot: TimeSlot) -> TimeSlot?
{
//The previous TimeSlot needs to be finished before a new one can start
guard endPreviousTimeSlot(atDate: timeSlot.startTime) && persistencyService.create(timeSlot) else
{
loggingService.log(withLogLevel: .warning, message: "Failed to create new TimeSlot")
return nil
}
loggingService.log(withLogLevel: .info, message: "New TimeSlot with category \"\(timeSlot.category)\" created")
NotificationCenter.default.post(OnTimeSlotCreated(startTime: timeSlot.startTime))
timeSlotCreatedSubject.on(.next(timeSlot))
return timeSlot
}
private func getEndTime(ofTimeSlot timeSlot: TimeSlot) -> Date
{
if let endTime = timeSlot.endTime { return endTime}
let date = timeService.now
let timeEntryLimit = timeSlot.startTime.tomorrow.ignoreTimeComponents()
let timeEntryLastedOverOneDay = date > timeEntryLimit
//TimeSlots can't go past midnight
let endTime = timeEntryLastedOverOneDay ? timeEntryLimit : date
return endTime
}
private func endPreviousTimeSlot(atDate date: Date) -> Bool
{
guard let timeSlot = persistencyService.getLast() else { return true }
let startDate = timeSlot.startTime
var endDate = date
guard endDate > startDate else
{
loggingService.log(withLogLevel: .warning, message: "Trying to create a negative duration TimeSlot")
return false
}
//TimeSlot is going for over one day, we should end it at midnight
if startDate.ignoreTimeComponents() != endDate.ignoreTimeComponents()
{
loggingService.log(withLogLevel: .info, message: "Early ending TimeSlot at midnight")
endDate = startDate.tomorrow.ignoreTimeComponents()
}
let predicate = Predicate(parameter: "startTime", equals: timeSlot.startTime as AnyObject)
let editFunction = { (timeSlot: TimeSlot) -> TimeSlot in
return timeSlot.withEndDate(endDate)
}
guard let _ = persistencyService.singleUpdate(withPredicate: predicate, updateFunction: editFunction) else
{
loggingService.log(withLogLevel: .warning, message: "Failed to end TimeSlot started at \(timeSlot.startTime) with category \(timeSlot.category)")
return false
}
return true
}
}
| bsd-3-clause | a6badb335cba3cf5c107f5fc539e7d05 | 38.80303 | 161 | 0.631011 | 5.542194 | false | false | false | false |
awkward/Tatsi | Tatsi/Views/TatsiPickerViewController.swift | 1 | 2840 | //
// TatsiPickerViewController.swift
// Tatsi
//
// Created by Rens Verhoeven on 06/07/2017.
// Copyright © 2017 Awkward BV. All rights reserved.
//
import UIKit
import Photos
final public class TatsiPickerViewController: UINavigationController {
// MARK: - Public properties
public let config: TatsiConfig
public weak var pickerDelegate: TatsiPickerViewControllerDelegate?
override public var preferredStatusBarStyle: UIStatusBarStyle {
return self.config.preferredStatusBarStyle
}
// MARK: - Initializers
public init(config: TatsiConfig = TatsiConfig.default) {
self.config = config
super.init(nibName: nil, bundle: nil)
navigationBar.barTintColor = config.colors.background
navigationBar.tintColor = config.colors.link
self.setIntialViewController()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Helpers
internal func setIntialViewController() {
switch PHPhotoLibrary.authorizationStatus() {
case .authorized, .limited:
//Authorized, show the album view or the album detail view.
var album: PHAssetCollection?
let userLibrary = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil).firstObject
switch self.config.firstView {
case .userLibrary:
album = userLibrary
case .album(let collection):
album = collection
default:
break
}
if let initialAlbum = album ?? userLibrary, self.config.singleViewMode {
self.viewControllers = [AssetsGridViewController(album: initialAlbum)]
} else {
self.showAlbumViewController(with: album)
}
case .denied, .notDetermined, .restricted:
// Not authorized, show the view to give access
self.viewControllers = [AuthorizationViewController()]
@unknown default:
assertionFailure("Unknown authorization status detected.")
}
}
private func showAlbumViewController(with collection: PHAssetCollection?) {
if let collection = collection {
self.viewControllers = [AlbumsViewController(), AssetsGridViewController(album: collection)]
} else {
self.viewControllers = [AlbumsViewController()]
}
}
internal func customCancelButtonItem() -> UIBarButtonItem? {
return self.pickerDelegate?.cancelBarButtonItem(for: self)
}
internal func customDoneButtonItem() -> UIBarButtonItem? {
return self.pickerDelegate?.doneBarButtonItem(for: self)
}
}
| mit | 5ad62b751199ea33fa0d9fd033620b2f | 32.011628 | 147 | 0.643184 | 5.356604 | false | true | false | false |
gsheld/mountie | Mountie/Mountie/MountieViewController.swift | 1 | 954 | //
// MountieViewController.swift
// Mountie
//
// Created by Grant Sheldon on 11/10/16.
// Copyright © 2016 GBY Games. All rights reserved.
//
import UIKit
import SpriteKit
class MountieViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'MountieScene.sks'
if let scene = SKScene(fileNamed: "MountieScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portraitUpsideDown
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| apache-2.0 | e4b12aa60d95d48c1ab29b6174e84b8f | 20.659091 | 75 | 0.674711 | 4.516588 | false | false | false | false |
LonelyHusky/SCWeibo | SCWeibo/Classes/ViewModel/SCStatusViewModel.swift | 1 | 2577 | //
// SCStatusViewModel.swift
// SCWeibo
//
// Created by 云卷云舒丶 on 16/7/24.
//
//对应StatusCell
import UIKit
class SCStatusViewModel: NSObject {
//当前视图模型里面保存的模型
var status : SCStatus?{
didSet{
dealMemberImage()
dealSourceText()
// 设置转发微博的内容
if let s = status?.retweeted_status {
// @昵称:内容
if let name = s.user?.name ,content = s.text {
retweetText = "@\(name):\(content)"
}
}
retweetPictureViewSize = calcPictureViewSize(status?.retweeted_status?.pic_urls)
originalPictureViewSize = calcPictureViewSize(status?.pic_urls)
}
}
// 当前微博用户的会员图标
var memberIamge :UIImage?
// 转发微博的内容
var retweetText : String?
// 来源字符串
var sourcrText : String?
// 转发微博的配图视图大小
var retweetPictureViewSize :CGSize = CGSizeZero
var originalPictureViewSize:CGSize = CGSizeZero
private func calcPictureViewSize(pic_urls:[SCStatusPhontoInfo]?) -> CGSize{
// 获取图片数量
let count = pic_urls?.count ?? 0
if count == 0 {
return CGSizeZero
}
// 根据count计算大小
// 求出几行几列
let col = count == 4 ? 2 : (count > 3 ? 3 : count)
let row = ((count - 1) / 3) + 1
// 计算图片大小
let margin : CGFloat = 5
let itemWH = (SCReenW - 2 * SCStatusCellMargin - 2 * margin) / 3
// 通过每张图片大小和列数求出宽度,行数求出高度
let w = CGFloat(col) * itemWH + CGFloat(col - 1) * margin
let h = CGFloat(row) * itemWH + CGFloat(row - 1) * margin
return CGSize(width: w, height: h)
}
private func dealSourceText(){
guard let s = status?.source else{
return
}
// 开始截取位置
if let startIndex = s.rangeOfString("\">")?.endIndex, endIndex = s.rangeOfString("</")?.startIndex {
let result = s.substringWithRange(startIndex..<endIndex)
sourcrText = "来着\(result)"
}
}
private func dealMemberImage(){
// 会员等级是1——6
if let rank = status?.user?.mbrank where (rank > 0 && rank < 7){
memberIamge = UIImage(named: "common_icon_membership_level\(rank)")
}
}
}
| mit | b0a35a2c43886be08c3d0ccc2e75d540 | 25.05618 | 108 | 0.532557 | 3.930508 | false | false | false | false |
thefuntasty/Gutenberg | Pod/Classes/Gutenberg.swift | 2 | 5355 | //
// Gutenberg.swift
// Pods
//
// Created by Aleš Kocur on 10/12/15.
//
//
public struct Emoji {
public let code: String
public let image: UIImage
public let largeImage: UIImage?
public init(code: String, image: UIImage, largeImage: UIImage? = nil) {
self.code = code
self.image = image
self.largeImage = largeImage
}
}
public enum TranformTextOption {
case None
case LastOccurenceOnly
}
struct EmojiAttachment {
let emoji: Emoji
let textualRepresentation: NSAttributedString
}
typealias Occurence = (range: NSRange, replacement: NSAttributedString)
public class Gutenberg {
static let sharedInstance = Gutenberg()
private var emojis: [EmojiAttachment] = []
private var yOffset: CGFloat = 0
private var defaultHeight: CGFloat?
// MARK: - Public API
public class func transformTextWithEmojiCodes(text: String, option: TranformTextOption = .None) -> NSAttributedString {
return self.sharedInstance._transformTextWithEmojiCodes(text)
}
public class func registerEmoji(emoji: Emoji) {
self.sharedInstance._registerEmoji(emoji)
}
public class func registerEmoji(emoji: Emoji...) {
emoji.forEach(registerEmoji)
}
public class func setDefaultYOffset(offset: CGFloat) {
self.sharedInstance.yOffset = offset
}
public class func setDefaultHeight(height: CGFloat?) {
self.sharedInstance.defaultHeight = height
}
// MARK: - Private methods
/**
Transforms text with emoji codes into attrributed string with images
Example: hello *sad* -> hello 😔
@returns NSAttributedString with emoji if occurence found, otherwise nil
*/
private func _transformTextWithEmojiCodes(text: String, option: TranformTextOption = .None) -> NSAttributedString {
if text.characters.count == 0 {
return NSAttributedString(string: "")
}
let occurences = Gutenberg._occurencesWithOption(option)(text, self.emojis)
if occurences.count == 0 {
return NSAttributedString(string: text)
}
// Sort the occurences from the last to the first
let sortedRanges = occurences.sort { (occ1, occ2) -> Bool in
return occ1.range.location > occ2.range.location
}
let attr = NSMutableAttributedString(string: text)
sortedRanges.forEach { occ in
attr.replaceCharactersInRange(occ.range, withAttributedString: occ.replacement)
}
return attr
}
private class func _occurencesWithOption(option: TranformTextOption = .None) -> (NSString, [EmojiAttachment]) -> [Occurence] {
switch option {
case .None:
return Gutenberg._findAllOccurencesInText
case .LastOccurenceOnly:
return Gutenberg._findLastOccurenceInText
}
}
// Find all occurences in given text
private class func _findAllOccurencesInText(text: NSString, emojis: [EmojiAttachment]) -> [Occurence] {
var occurences: [Occurence] = []
for emojiAttch in emojis {
var nextRange: NSRange? = text.rangeOfString(text as String)
repeat {
let range = text.rangeOfString(emojiAttch.emoji.code, options: NSStringCompareOptions(), range: nextRange!)
if range.location != NSNotFound {
occurences.append((range, emojiAttch.textualRepresentation))
let startLocation = range.location + range.length
let len = text.length - startLocation
nextRange = NSMakeRange(startLocation, len)
} else {
nextRange = nil
}
} while nextRange != nil
}
return occurences
}
// Find only last occurence in string
private class func _findLastOccurenceInText(text: NSString, emojis: [EmojiAttachment]) -> [Occurence] {
for emojiAttch in emojis {
let range = text.rangeOfString(emojiAttch.emoji.code, options: NSStringCompareOptions.BackwardsSearch)
if range.location != NSNotFound {
return [(range, emojiAttch.textualRepresentation)]
}
}
return []
}
/**
Registers emoji so it can be recognized in text
*/
private func _registerEmoji(emoji: Emoji) {
let attachment = NSTextAttachment()
attachment.image = emoji.image
attachment.bounds = {
// scale image if needed
let height = self.defaultHeight ?? emoji.image.size.height
let scale = height / emoji.image.size.height
return CGRectMake(0, yOffset, emoji.image.size.width * scale, height)
}()
let attr = NSAttributedString(attachment: attachment)
self.emojis.append(EmojiAttachment(emoji: emoji, textualRepresentation: attr))
}
}
public extension UILabel {
func gtb_text(text: String) {
self.attributedText = Gutenberg.transformTextWithEmojiCodes(text)
}
}
| mit | 09da1a3ce7d90e420185652ea8f466f0 | 29.747126 | 130 | 0.605794 | 5.066288 | false | false | false | false |
aatalyk/swift-algorithm-club | Treap/TreapMergeSplit.swift | 3 | 3672 | //
// TreapMergeSplit.swift
// TreapExample
//
// Created by Robert Thompson on 7/27/15.
// Copyright © 2016 Robert Thompson
/* Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
import Foundation
public extension Treap {
internal func split(_ key: Key) -> (left: Treap, right: Treap) {
var current = self
let val: Element
if let newVal = self.get(key) {
// swiftlint:disable force_try
current = try! current.delete(key: key)
// swiftlint:enable force_try
val = newVal
} else if case let .node(_, newVal, _, _, _) = self {
val = newVal
} else {
fatalError("No values in treap")
}
switch self {
case .node:
if case let .node(_, _, _, left, right) = current.set(key: key, val: val, p: -1) {
return (left: left, right: right)
} else {
return (left: .empty, right: .empty)
}
default:
return (left: .empty, right: .empty)
}
}
internal var leastKey: Key? {
switch self {
case .empty:
return nil
case let .node(key, _, _, .empty, _):
return key
case let .node(_, _, _, left, _):
return left.leastKey
}
}
internal var mostKey: Key? {
switch self {
case .empty:
return nil
case let .node(key, _, _, _, .empty):
return key
case let .node(_, _, _, _, right):
return right.mostKey
}
}
}
internal func merge<Key: Comparable, Element>(_ left: Treap<Key, Element>, right: Treap<Key, Element>) -> Treap<Key, Element> {
switch (left, right) {
case (.empty, _):
return right
case (_, .empty):
return left
case let (.node(leftKey, leftVal, leftP, leftLeft, leftRight), .node(rightKey, rightVal, rightP, rightLeft, rightRight)):
if leftP < rightP {
return .node(key: leftKey, val: leftVal, p: leftP, left: leftLeft, right: merge(leftRight, right: right))
} else {
return .node(key: rightKey, val: rightVal, p: rightP, left: merge(rightLeft, right: left), right: rightRight)
}
default:
break
}
return .empty
}
extension Treap: CustomStringConvertible {
public var description: String {
get {
return Treap.descHelper(self, indent: 0)
}
}
fileprivate static func descHelper(_ treap: Treap<Key, Element>, indent: Int) -> String {
if case let .node(key, value, priority, left, right) = treap {
var result = ""
let tabs = String(repeating: "\t", count: indent)
result += descHelper(left, indent: indent + 1)
result += "\n" + tabs + "\(key), \(value), \(priority)\n"
result += descHelper(right, indent: indent + 1)
return result
} else {
return ""
}
}
}
| mit | a428fbd8d1167ab00a33b22bc94460ea | 30.646552 | 127 | 0.643966 | 3.909478 | false | false | false | false |
iain8/faderbar | FaderBar/VolumeControl.swift | 1 | 2662 | //
// VolumeControl.swift
// FaderBar
//
// Created by iain on 04/12/16.
// Copyright © 2016 iain. All rights reserved.
//
import Foundation
/// Default fade length in seconds
struct Defaults {
static let fadeLength = 1800.0
}
class VolumeControl {
/// Timer used for scheduling
var timer: Timer
/// Initial volume when schedule started
var initialVolume: Double
/// Amount to change volume;
var delta: Double
/// Length of fade (in seconds)
var fadeLength: Double
/**
Initialises a volume control with default parameters
- Returns: A new volume control
*/
init() {
self.timer = Timer()
self.initialVolume = 0.0
self.delta = 0.0
self.fadeLength = Defaults.fadeLength
}
/**
Set the volume based on the delta from the current volume.
*/
@objc func changeVolume() {
let currentVolume = Double(NSSound.systemVolume())
let newVolume = Float(currentVolume - delta)
print("volume change:", currentVolume, newVolume)
if newVolume > 0 {
NSSound.setSystemVolume(newVolume)
} else {
NSSound.setSystemVolume(0.0)
self.showNotification(message: "Sound muted")
self.timer.invalidate()
}
}
/**
Show a notification
- Parameter message: The notification contents
*/
func showNotification(message: String) -> Void {
let notification = NSUserNotification()
notification.title = "Message from faderbar"
notification.informativeText = message
notification.soundName = nil
NSUserNotificationCenter.default.deliver(notification)
}
/**
Start the volume reduction schedule
*/
func startShrinkage() -> Void {
self.timer.invalidate()
self.initialVolume = Double(NSSound.systemVolume())
let interval = self.fadeLength / 60.0
// calculate change per interval from number of times timer is called
self.delta = self.initialVolume / (self.fadeLength / interval)
self.timer = Timer.scheduledTimer(
timeInterval: interval,
target: self,
selector: #selector(self.changeVolume),
userInfo: nil,
repeats: true
)
self.showNotification(message: "Fade out of \(UInt(self.fadeLength)) minutes started")
}
/**
Cancel the volume scheduling and return to originally set volume
*/
func cancelShrinkage() -> Void {
self.timer.invalidate()
NSSound.setSystemVolume(Float(initialVolume))
}
}
| mit | ee94d2631ac441ec1d9e66c100326e09 | 21.550847 | 94 | 0.614055 | 4.693122 | false | false | false | false |
ericyanush/Plex-TVOS | Pods/Swifter/Common/HttpServer.swift | 1 | 5800 | //
// HttpServer.swift
// Swifter
// Copyright (c) 2014 Damian Kołakowski. All rights reserved.
//
import Foundation
public class HttpServer
{
static let VERSION = "1.0.2";
public typealias Handler = HttpRequest -> HttpResponse
var handlers: [(expression: NSRegularExpression, handler: Handler)] = []
var clientSockets: Set<CInt> = []
let clientSocketsLock = 0
var acceptSocket: CInt = -1
let matchingOptions = NSMatchingOptions(rawValue: 0)
let expressionOptions = NSRegularExpressionOptions(rawValue: 0)
public init() { }
public subscript (path: String) -> Handler? {
get {
return nil
}
set ( newValue ) {
do {
let regex = try NSRegularExpression(pattern: path, options: expressionOptions)
if let newHandler = newValue {
handlers.append(expression: regex, handler: newHandler)
}
} catch {
}
}
}
public func routes() -> [String] { return handlers.map { $0.0.pattern } }
public func start(listenPort: in_port_t = 8080, error: NSErrorPointer = nil) -> Bool {
stop()
if let socket = Socket.tcpForListen(listenPort, error: error) {
self.acceptSocket = socket
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
while let socket = Socket.acceptClientSocket(self.acceptSocket) {
HttpServer.lock(self.clientSocketsLock) {
self.clientSockets.insert(socket)
}
if self.acceptSocket == -1 { return }
let socketAddress = Socket.peername(socket)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
let parser = HttpParser()
while let request = parser.nextHttpRequest(socket) {
let keepAlive = parser.supportsKeepAlive(request.headers)
if let (expression, handler) = self.findHandler(request.url) {
let capturedUrlsGroups = self.captureExpressionGroups(expression, value: request.url)
let updatedRequest = HttpRequest(url: request.url, urlParams: request.urlParams, method: request.method, headers: request.headers, body: request.body, capturedUrlGroups: capturedUrlsGroups, address: socketAddress)
HttpServer.respond(socket, response: handler(updatedRequest), keepAlive: keepAlive)
} else {
HttpServer.respond(socket, response: HttpResponse.NotFound, keepAlive: keepAlive)
}
if !keepAlive { break }
}
Socket.release(socket)
HttpServer.lock(self.clientSocketsLock) {
self.clientSockets.remove(socket)
}
})
}
self.stop()
})
return true
}
return false
}
func findHandler(url:String) -> (NSRegularExpression, Handler)? {
let u = NSURL(string: url)!
let path = u.path!
for handler in self.handlers {
let regex = handler.0
let matches = regex.numberOfMatchesInString(path, options: self.matchingOptions, range: HttpServer.asciiRange(path)) > 0
if matches {
return handler;
}
}
return nil
}
func captureExpressionGroups(expression: NSRegularExpression, value: String) -> [String] {
let u = NSURL(string: value)!
let path = u.path!
var capturedGroups = [String]()
if let result = expression.firstMatchInString(path, options: matchingOptions, range: HttpServer.asciiRange(path)) {
let nsValue: NSString = path
for var i = 1 ; i < result.numberOfRanges ; ++i {
if let group = nsValue.substringWithRange(result.rangeAtIndex(i)).stringByRemovingPercentEncoding {
capturedGroups.append(group)
}
}
}
return capturedGroups
}
public func stop() {
Socket.release(acceptSocket)
acceptSocket = -1
HttpServer.lock(self.clientSocketsLock) {
for clientSocket in self.clientSockets {
Socket.release(clientSocket)
}
self.clientSockets.removeAll(keepCapacity: true)
}
}
public class func asciiRange(value: String) -> NSRange {
return NSMakeRange(0, value.lengthOfBytesUsingEncoding(NSASCIIStringEncoding))
}
public class func lock(handle: AnyObject, closure: () -> ()) {
objc_sync_enter(handle)
closure()
objc_sync_exit(handle)
}
public class func respond(socket: CInt, response: HttpResponse, keepAlive: Bool) {
Socket.writeUTF8(socket, string: "HTTP/1.1 \(response.statusCode()) \(response.reasonPhrase())\r\n")
if let body = response.body() {
Socket.writeASCII(socket, string: "Content-Length: \(body.length)\r\n")
} else {
Socket.writeASCII(socket, string: "Content-Length: 0\r\n")
}
if keepAlive {
Socket.writeASCII(socket, string: "Connection: keep-alive\r\n")
}
for (name, value) in response.headers() {
Socket.writeASCII(socket, string: "\(name): \(value)\r\n")
}
Socket.writeASCII(socket, string: "\r\n")
if let body = response.body() {
Socket.writeData(socket, data: body)
}
}
}
| mit | 2594d379bc3508dce0f73b6812aa551a | 38.182432 | 245 | 0.564753 | 4.828476 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Core/MPSDKError.swift | 1 | 4426 | import UIKit
class MPSDKError {
open var message: String = ""
open var errorDetail: String = ""
open var apiException: ApiException?
open var requestOrigin: String = ""
open var retry: Bool?
init () {
}
init(message: String, errorDetail: String, retry: Bool, requestOrigin: String?=nil) {
self.message = message
self.errorDetail = errorDetail
self.retry = retry
if let reqOrigin = requestOrigin {
self.requestOrigin = reqOrigin
}
}
class func convertFrom(_ error: Error, requestOrigin: String) -> MPSDKError {
let mpError = MPSDKError()
let currentError = error as NSError
if currentError.userInfo.count > 0 {
let errorMessage = currentError.userInfo[NSLocalizedDescriptionKey] as? String ?? ""
mpError.message = errorMessage.localized
mpError.apiException = ApiException.fromJSON(currentError.userInfo as NSDictionary)
if let apiException = mpError.apiException {
if apiException.error == nil {
let pxError = currentError as? PXError
mpError.apiException = MPSDKError.pxApiExceptionToApiException(pxApiException: pxError?.apiException)
}
}
}
mpError.requestOrigin = requestOrigin
mpError.retry = (currentError.code == -2 || currentError.code == NSURLErrorCannotDecodeContentData || currentError.code == NSURLErrorNotConnectedToInternet || currentError.code == NSURLErrorTimedOut)
return mpError
}
func toJSON() -> [String: Any] {
let obj: [String: Any] = [
"message": self.message,
"error_detail": self.errorDetail,
"recoverable": self.retry ?? true
]
return obj
}
func toJSONString() -> String {
return JSONHandler.jsonCoding(self.toJSON())
}
class func pxApiExceptionToApiException(pxApiException: PXApiException?) -> ApiException {
let apiException = ApiException()
guard let pxApiException = pxApiException else {
return apiException
}
if !Array.isNullOrEmpty(pxApiException.cause) {
for pxCause in pxApiException.cause! {
let cause = pxCauseToCause(pxCause: pxCause)
if cause != nil {
apiException.cause = Array.safeAppend(apiException.cause, cause!)
}
}
}
apiException.error = pxApiException.error
apiException.message = pxApiException.message
apiException.status = pxApiException.status ?? 0
return apiException
}
class func pxCauseToCause(pxCause: PXCause?) -> Cause? {
guard let pxCause = pxCause else {
return nil
}
let cause = Cause()
cause.causeDescription = pxCause._description
cause.code = pxCause.code
return cause
}
class func getApiException(_ error: Error) -> ApiException? {
let mpError = MPSDKError()
let currentError = error as NSError
if !currentError.userInfo.isEmpty {
let errorMessage = currentError.userInfo[NSLocalizedDescriptionKey] as? String ?? ""
mpError.message = errorMessage.localized
mpError.apiException = ApiException.fromJSON(currentError.userInfo as NSDictionary)
if let apiException = mpError.apiException {
if apiException.error == nil {
let pxError = currentError as? PXError
mpError.apiException = MPSDKError.pxApiExceptionToApiException(pxApiException: pxError?.apiException)
}
}
}
return mpError.apiException
}
}
// MARK: Tracking
extension MPSDKError {
func getErrorForTracking() -> [String: Any] {
var errorDic: [String: Any] = [:]
errorDic["url"] = requestOrigin
errorDic["retry_available"] = retry ?? false
errorDic["status"] = apiException?.status
if let causes = apiException?.cause {
var causesDic: [String: Any] = [:]
for cause in causes where !String.isNullOrEmpty(cause.code) {
causesDic["code"] = cause.code
causesDic["description"] = cause.causeDescription
}
errorDic["causes"] = causesDic
}
return errorDic
}
}
| mit | d7f573582531f31f474314c71c885d15 | 36.193277 | 207 | 0.60732 | 4.703507 | false | false | false | false |
zhangkeqinga/ios-charts | Charts/Classes/Renderers/CandleStickChartRenderer.swift | 33 | 11853 | //
// CandleStickChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
@objc
public protocol CandleStickChartRendererDelegate
{
func candleStickChartRendererCandleData(renderer: CandleStickChartRenderer) -> CandleChartData!
func candleStickChartRenderer(renderer: CandleStickChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer!
func candleStickChartDefaultRendererValueFormatter(renderer: CandleStickChartRenderer) -> NSNumberFormatter!
func candleStickChartRendererChartYMax(renderer: CandleStickChartRenderer) -> Double
func candleStickChartRendererChartYMin(renderer: CandleStickChartRenderer) -> Double
func candleStickChartRendererChartXMax(renderer: CandleStickChartRenderer) -> Double
func candleStickChartRendererChartXMin(renderer: CandleStickChartRenderer) -> Double
func candleStickChartRendererMaxVisibleValueCount(renderer: CandleStickChartRenderer) -> Int
}
public class CandleStickChartRenderer: LineScatterCandleRadarChartRenderer
{
public weak var delegate: CandleStickChartRendererDelegate?
public init(delegate: CandleStickChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.delegate = delegate
}
public override func drawData(#context: CGContext)
{
var candleData = delegate!.candleStickChartRendererCandleData(self)
for set in candleData.dataSets as! [CandleChartDataSet]
{
if (set.isVisible)
{
drawDataSet(context: context, dataSet: set)
}
}
}
private var _shadowPoints = [CGPoint](count: 2, repeatedValue: CGPoint())
private var _bodyRect = CGRect()
private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint())
internal func drawDataSet(#context: CGContext, dataSet: CandleChartDataSet)
{
var trans = delegate!.candleStickChartRenderer(self, transformerForAxis: dataSet.axisDependency)
var phaseX = _animator.phaseX
var phaseY = _animator.phaseY
var bodySpace = dataSet.bodySpace
var entries = dataSet.yVals as! [CandleChartDataEntry]
var entryFrom = dataSet.entryForXIndex(_minX)
var entryTo = dataSet.entryForXIndex(_maxX)
var minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0)
var maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count)
CGContextSaveGState(context)
CGContextSetLineWidth(context, dataSet.shadowWidth)
for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++)
{
// get the entry
var e = entries[j]
if (e.xIndex < _minX || e.xIndex > _maxX)
{
continue
}
// calculate the shadow
_shadowPoints[0].x = CGFloat(e.xIndex)
_shadowPoints[0].y = CGFloat(e.high) * phaseY
_shadowPoints[1].x = CGFloat(e.xIndex)
_shadowPoints[1].y = CGFloat(e.low) * phaseY
trans.pointValuesToPixel(&_shadowPoints)
// draw the shadow
var shadowColor: UIColor! = nil
if (dataSet.shadowColorSameAsCandle)
{
if (e.open > e.close)
{
shadowColor = dataSet.decreasingColor ?? dataSet.colorAt(j)
}
else if (e.open < e.close)
{
shadowColor = dataSet.increasingColor ?? dataSet.colorAt(j)
}
}
if (shadowColor === nil)
{
shadowColor = dataSet.shadowColor ?? dataSet.colorAt(j);
}
CGContextSetStrokeColorWithColor(context, shadowColor.CGColor)
CGContextStrokeLineSegments(context, _shadowPoints, 2)
// calculate the body
_bodyRect.origin.x = CGFloat(e.xIndex) - 0.5 + bodySpace
_bodyRect.origin.y = CGFloat(e.close) * phaseY
_bodyRect.size.width = (CGFloat(e.xIndex) + 0.5 - bodySpace) - _bodyRect.origin.x
_bodyRect.size.height = (CGFloat(e.open) * phaseY) - _bodyRect.origin.y
trans.rectValueToPixel(&_bodyRect)
// draw body differently for increasing and decreasing entry
if (e.open > e.close)
{
var color = dataSet.decreasingColor ?? dataSet.colorAt(j)
if (dataSet.isDecreasingFilled)
{
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, _bodyRect)
}
else
{
CGContextSetStrokeColorWithColor(context, color.CGColor)
CGContextStrokeRect(context, _bodyRect)
}
}
else if (e.open < e.close)
{
var color = dataSet.increasingColor ?? dataSet.colorAt(j)
if (dataSet.isIncreasingFilled)
{
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, _bodyRect)
}
else
{
CGContextSetStrokeColorWithColor(context, color.CGColor)
CGContextStrokeRect(context, _bodyRect)
}
}
else
{
CGContextSetStrokeColorWithColor(context, shadowColor.CGColor)
CGContextStrokeRect(context, _bodyRect)
}
}
CGContextRestoreGState(context)
}
public override func drawValues(#context: CGContext)
{
var candleData = delegate!.candleStickChartRendererCandleData(self)
if (candleData === nil)
{
return
}
var defaultValueFormatter = delegate!.candleStickChartDefaultRendererValueFormatter(self)
// if values are drawn
if (candleData.yValCount < Int(ceil(CGFloat(delegate!.candleStickChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX)))
{
var dataSets = candleData.dataSets
for (var i = 0; i < dataSets.count; i++)
{
var dataSet = dataSets[i]
if (!dataSet.isDrawValuesEnabled)
{
continue
}
var valueFont = dataSet.valueFont
var valueTextColor = dataSet.valueTextColor
var formatter = dataSet.valueFormatter
if (formatter === nil)
{
formatter = defaultValueFormatter
}
var trans = delegate!.candleStickChartRenderer(self, transformerForAxis: dataSet.axisDependency)
var entries = dataSet.yVals as! [CandleChartDataEntry]
var entryFrom = dataSet.entryForXIndex(_minX)
var entryTo = dataSet.entryForXIndex(_maxX)
var minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0)
var maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count)
var positions = trans.generateTransformedValuesCandle(entries, phaseY: _animator.phaseY)
var lineHeight = valueFont.lineHeight
var yOffset: CGFloat = lineHeight + 5.0
for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * _animator.phaseX + CGFloat(minx))); j < count; j++)
{
var x = positions[j].x
var y = positions[j].y
if (!viewPortHandler.isInBoundsRight(x))
{
break
}
if (!viewPortHandler.isInBoundsLeft(x) || !viewPortHandler.isInBoundsY(y))
{
continue
}
var val = entries[j].high
ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(val)!, point: CGPoint(x: x, y: y - yOffset), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor])
}
}
}
}
public override func drawExtras(#context: CGContext)
{
}
private var _highlightPtsBuffer = [CGPoint](count: 4, repeatedValue: CGPoint())
public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight])
{
var candleData = delegate!.candleStickChartRendererCandleData(self)
if (candleData === nil)
{
return
}
for (var i = 0; i < indices.count; i++)
{
var xIndex = indices[i].xIndex; // get the x-position
var set = candleData.getDataSetByIndex(indices[i].dataSetIndex) as! CandleChartDataSet!
if (set === nil || !set.isHighlightEnabled)
{
continue
}
var e = set.entryForXIndex(xIndex) as! CandleChartDataEntry!
if (e === nil || e.xIndex != xIndex)
{
continue
}
var trans = delegate!.candleStickChartRenderer(self, transformerForAxis: set.axisDependency)
CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor)
CGContextSetLineWidth(context, set.highlightLineWidth)
if (set.highlightLineDashLengths != nil)
{
CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
var low = CGFloat(e.low) * _animator.phaseY
var high = CGFloat(e.high) * _animator.phaseY
var y = (low + high) / 2.0
_highlightPtsBuffer[0] = CGPoint(x: CGFloat(xIndex), y: CGFloat(delegate!.candleStickChartRendererChartYMax(self)))
_highlightPtsBuffer[1] = CGPoint(x: CGFloat(xIndex), y: CGFloat(delegate!.candleStickChartRendererChartYMin(self)))
_highlightPtsBuffer[2] = CGPoint(x: CGFloat(delegate!.candleStickChartRendererChartXMin(self)), y: y)
_highlightPtsBuffer[3] = CGPoint(x: CGFloat(delegate!.candleStickChartRendererChartXMax(self)), y: y)
trans.pointValuesToPixel(&_highlightPtsBuffer)
// draw the lines
drawHighlightLines(context: context, points: _highlightPtsBuffer,
horizontal: set.isHorizontalHighlightIndicatorEnabled, vertical: set.isVerticalHighlightIndicatorEnabled)
}
}
} | apache-2.0 | 7004b8a8fad74df1dbf3dc23fef2edfc | 37.865574 | 246 | 0.560364 | 5.85912 | false | false | false | false |
vgorloff/AUHost | Vendor/mc/mcxUIExtensions/Sources/AppKit/NSToolbar.swift | 1 | 2079 | //
// NSToolbar.swift
// MCA-OSS-AUH
//
// Created by Vlad Gorlov on 06.06.2020.
// Copyright © 2020 Vlad Gorlov. All rights reserved.
//
#if canImport(AppKit)
import Cocoa
extension NSToolbar {
public class GenericDelegate: NSObject, NSToolbarDelegate {
public var selectableItemIdentifiers: [NSToolbarItem.Identifier] = []
public var defaultItemIdentifiers: [NSToolbarItem.Identifier] = []
public var allowedItemIdentifiers: [NSToolbarItem.Identifier] = []
var eventHandler: ((Event) -> Void)?
public var makeItemCallback: ((_ itemIdentifier: NSToolbarItem.Identifier, _ willBeInserted: Bool) -> NSToolbarItem?)?
}
}
extension NSToolbar.GenericDelegate {
enum Event {
case willAddItem(item: NSToolbarItem, index: Int)
case didRemoveItem(item: NSToolbarItem)
}
}
extension NSToolbar.GenericDelegate {
public func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier,
willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem?
{
return makeItemCallback?(itemIdentifier, flag)
}
public func toolbarDefaultItemIdentifiers(_: NSToolbar) -> [NSToolbarItem.Identifier] {
return defaultItemIdentifiers
}
public func toolbarAllowedItemIdentifiers(_: NSToolbar) -> [NSToolbarItem.Identifier] {
return allowedItemIdentifiers
}
public func toolbarSelectableItemIdentifiers(_: NSToolbar) -> [NSToolbarItem.Identifier] {
return selectableItemIdentifiers
}
// MARK: Notifications
public func toolbarWillAddItem(_ notification: Notification) {
if let toolbarItem = notification.userInfo?["item"] as? NSToolbarItem,
let index = notification.userInfo?["newIndex"] as? Int
{
eventHandler?(.willAddItem(item: toolbarItem, index: index))
}
}
public func toolbarDidRemoveItem(_ notification: Notification) {
if let toolbarItem = notification.userInfo?["item"] as? NSToolbarItem {
eventHandler?(.didRemoveItem(item: toolbarItem))
}
}
}
#endif
| mit | 277cb3766898e56464ecac44571c3c06 | 29.115942 | 124 | 0.705967 | 4.777011 | false | false | false | false |
Drakken-Engine/GameEngine | DrakkenEngine/dMaterialManager.swift | 1 | 1183 | //
// dMaterialManager.swift
// DrakkenEngine
//
// Created by Allison Lindner on 23/08/16.
// Copyright © 2016 Drakken Studio. All rights reserved.
//
internal class dMaterialTexture {
internal var texture: dTexture
internal var index: Int
internal init(texture: dTexture, index: Int) {
self.texture = texture
self.index = index
}
}
internal class dMaterialData {
internal var shader: dShader
internal var buffers: [dBufferable] = []
internal var textures: [dMaterialTexture] = []
internal init(shader: dShader) {
self.shader = shader
}
}
internal class dMaterialManager {
private var _materials: [String : dMaterialData] = [:]
internal func create(name: String,
shader: String,
buffers: [dBufferable],
textures: [dMaterialTexture]) {
let instancedShader = dCore.instance.shManager.get(shader: shader)
let materialData = dMaterialData(shader: instancedShader)
materialData.buffers = buffers
materialData.textures = textures
self._materials[name] = materialData
}
internal func get(material name: String) -> dMaterialData? {
return self._materials[name]
}
}
| gpl-3.0 | e511be7e931360ee672acc35dc7051ab | 22.64 | 68 | 0.684433 | 3.581818 | false | false | false | false |
ahoppen/swift | test/attr/attr_dynamic_member_lookup.swift | 3 | 24096 | // RUN: %target-typecheck-verify-swift
var global = 42
@dynamicMemberLookup
struct Gettable {
subscript(dynamicMember member: StaticString) -> Int {
return 42
}
}
@dynamicMemberLookup
struct Settable {
subscript(dynamicMember member: StaticString) -> Int {
get {return 42}
set {}
}
}
@dynamicMemberLookup
struct MutGettable {
subscript(dynamicMember member: StaticString) -> Int {
mutating get {
return 42
}
}
}
@dynamicMemberLookup
struct NonMutSettable {
subscript(dynamicMember member: StaticString) -> Int {
get { return 42 }
nonmutating set {}
}
}
func test(a: Gettable, b: Settable, c: MutGettable, d: NonMutSettable) {
global = a.wyverns
a.flavor = global // expected-error {{cannot assign through dynamic lookup property: 'a' is a 'let' constant}}
global = b.flavor
b.universal = global // expected-error {{cannot assign through dynamic lookup property: 'b' is a 'let' constant}}
b.thing += 1 // expected-error {{left side of mutating operator isn't mutable: 'b' is a 'let' constant}}
var bm = b
global = bm.flavor
bm.universal = global
bm.thing += 1
var cm = c
global = c.dragons // expected-error {{cannot use mutating getter on immutable value: 'c' is a 'let' constant}}
global = c[dynamicMember: "dragons"] // expected-error {{cannot use mutating getter on immutable value: 'c' is a 'let' constant}}
global = cm.dragons
c.woof = global // expected-error {{cannot use mutating getter on immutable value: 'c' is a 'let' constant}}
var dm = d
global = d.dragons // ok
global = dm.dragons // ok
d.woof = global // ok
dm.woof = global // ok
}
func testIUO(a: Gettable!, b: Settable!) {
global = a.wyverns
a.flavor = global // expected-error {{cannot assign through dynamic lookup property: 'a' is a 'let' constant}}
global = b.flavor
b.universal = global // expected-error {{cannot assign through dynamic lookup property: 'b' is a 'let' constant}}
var bm: Settable! = b
global = bm.flavor
bm.universal = global
}
//===----------------------------------------------------------------------===//
// Returning a function
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
struct FnTest {
subscript(dynamicMember member: StaticString) -> (Int) -> () {
return { x in () }
}
}
func testFunction(x: FnTest) {
x.phunky(12)
}
func testFunctionIUO(x: FnTest!) {
x.flavor(12)
}
//===----------------------------------------------------------------------===//
// Explicitly declared members take precedence
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
struct Dog {
public var name = "Kaylee"
subscript(dynamicMember member: String) -> String {
return "Zoey"
}
}
func testDog(person: Dog) -> String {
return person.name + person.otherName
}
//===----------------------------------------------------------------------===//
// Returning an IUO
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
struct IUOResult {
subscript(dynamicMember member: StaticString) -> Int! {
get { return 42 }
nonmutating set {}
}
}
func testIUOResult(x: IUOResult) {
x.foo?.negate() // Test mutating writeback.
let _: Int = x.bar // Test implicitly forced optional
let b = x.bar
// expected-note@-1{{short-circuit}}
// expected-note@-2{{coalesce}}
// expected-note@-3{{force-unwrap}}
let _: Int = b // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}}
// expected-note@-1{{coalesce}}
// expected-note@-2{{force-unwrap}}
}
//===----------------------------------------------------------------------===//
// Error cases
//===----------------------------------------------------------------------===//
// Subscript index must be ExpressibleByStringLiteral.
@dynamicMemberLookup
struct Invalid1 {
// expected-error @+1 {{@dynamicMemberLookup attribute requires 'Invalid1' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a key path}}
subscript(dynamicMember member: Int) -> Int {
return 42
}
}
// Subscript may not be variadic.
@dynamicMemberLookup
struct Invalid2 {
// expected-error @+1 {{@dynamicMemberLookup attribute requires 'Invalid2' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a key path}}
subscript(dynamicMember member: String...) -> Int {
return 42
}
}
// References to overloads are resolved just like normal subscript lookup:
// they are either contextually disambiguated or are invalid.
@dynamicMemberLookup
struct Ambiguity {
subscript(dynamicMember member: String) -> Int {
return 42
}
subscript(dynamicMember member: String) -> Float {
return 42
}
}
func testAmbiguity(a: Ambiguity) {
let _: Int = a.flexibility
let _: Float = a.dynamism
_ = a.dynamism // expected-error {{ambiguous use of 'subscript(dynamicMember:)'}}
}
// expected-error @+1 {{'@dynamicMemberLookup' attribute cannot be applied to this declaration}}
@dynamicMemberLookup
extension Int {
subscript(dynamicMember member: String) -> Int {
fatalError()
}
}
// expected-error @+1 {{'@dynamicMemberLookup' attribute cannot be applied to this declaration}}
@dynamicMemberLookup
func NotAllowedOnFunc() {}
// @dynamicMemberLookup cannot be declared on a base class and fulfilled with a
// derived class.
// expected-error @+1 {{@dynamicMemberLookup attribute requires 'InvalidBase' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a key path}}
@dynamicMemberLookup
class InvalidBase {}
class InvalidDerived : InvalidBase { subscript(dynamicMember: String) -> Int { get {}} }
// expected-error @+1 {{value of type 'InvalidDerived' has no member 'dynamicallyLookedUp'}}
_ = InvalidDerived().dynamicallyLookedUp
//===----------------------------------------------------------------------===//
// Existentials
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
protocol DynamicProtocol {
subscript(dynamicMember member: StaticString) -> DynamicProtocol {
get nonmutating set
}
}
struct MyDynamicStruct : DynamicProtocol {
subscript(dynamicMember member: StaticString) -> DynamicProtocol {
get { fatalError() }
nonmutating set {}
}
}
func testMutableExistential(a: DynamicProtocol,
b: MyDynamicStruct) -> DynamicProtocol {
a.x.y = b
b.x.y = b
return a.foo.bar.baz
}
// Verify protocol compositions and protocol refinements work.
protocol SubDynamicProtocol : DynamicProtocol {}
typealias ProtocolComp = AnyObject & DynamicProtocol
func testMutableExistential2(a: AnyObject & DynamicProtocol,
b: SubDynamicProtocol,
c: ProtocolComp & AnyObject) {
a.x.y = b
b.x.y = b
c.x.y = b
}
@dynamicMemberLookup
protocol ProtoExt {}
extension ProtoExt {
subscript(dynamicMember member: String) -> String {
get {}
}
}
extension String: ProtoExt {}
func testProtoExt() -> String {
let str = "test"
return str.sdfsdfsdf
}
//===----------------------------------------------------------------------===//
// JSON example
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
enum JSON {
case IntValue(Int)
case StringValue(String)
case ArrayValue(Array<JSON>)
case DictionaryValue(Dictionary<String, JSON>)
var stringValue: String? {
if case .StringValue(let str) = self {
return str
}
return nil
}
subscript(index: Int) -> JSON? {
if case .ArrayValue(let arr) = self {
return index < arr.count ? arr[index] : nil
}
return nil
}
subscript(key: String) -> JSON? {
if case .DictionaryValue(let dict) = self {
return dict[key]
}
return nil
}
subscript(dynamicMember member: String) -> JSON? {
if case .DictionaryValue(let dict) = self {
return dict[member]
}
return nil
}
}
func testJsonExample(x: JSON) -> String? {
_ = x.name?.first
return x.name?.first?.stringValue
}
//===----------------------------------------------------------------------===//
// Class inheritance tests
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
class BaseClass {
subscript(dynamicMember member: String) -> Int {
return 42
}
}
class DerivedClass : BaseClass {}
func testDerivedClass(x: BaseClass, y: DerivedClass) -> Int {
return x.life - y.the + x.universe - y.and + x.everything
}
// Test that derived classes can add a setter.
class DerivedClassWithSetter : BaseClass {
override subscript(dynamicMember member: String) -> Int {
get { return super[dynamicMember: member] }
set {}
}
}
func testOverrideSubscript(a: BaseClass, b: DerivedClassWithSetter) {
let x = a.frotz + b.garbalaz
b.baranozo = x
a.balboza = 12 // expected-error {{cannot assign through dynamic lookup property: 'a' is a 'let' constant}}
}
//===----------------------------------------------------------------------===//
// Generics
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
struct SettableGeneric1<T> {
subscript(dynamicMember member: StaticString) -> T? {
get {}
nonmutating set {}
}
}
func testGenericType<T>(a: SettableGeneric1<T>, b: T) -> T? {
a.dfasdf = b
return a.dfsdffff
}
func testConcreteGenericType(a: SettableGeneric1<Int>) -> Int? {
a.dfasdf = 42
return a.dfsdffff
}
@dynamicMemberLookup
struct SettableGeneric2<T> {
subscript<U: ExpressibleByStringLiteral>(dynamicMember member: U) -> T {
get {}
nonmutating set {}
}
}
func testGenericType2<T>(a: SettableGeneric2<T>, b: T) -> T? {
a[dynamicMember: "fasdf"] = b
a.dfasdf = b
return a.dfsdffff
}
func testConcreteGenericType2(a: SettableGeneric2<Int>) -> Int? {
a.dfasdf = 42
return a.dfsdffff
}
// SR-8077 test case.
// `subscript(dynamicMember:)` works as a `@dynamicMemberLookup` protocol
// requirement.
@dynamicMemberLookup
protocol GenericProtocol {
associatedtype S: ExpressibleByStringLiteral
associatedtype T
subscript(dynamicMember member: S) -> T { get }
}
@dynamicMemberLookup
class GenericClass<S: ExpressibleByStringLiteral, T> {
let t: T
init(_ t: T) { self.t = t }
subscript(dynamicMember member: S) -> T { return t }
}
func testGenerics<S, T, P: GenericProtocol>(
a: P,
b: AnyObject & GenericClass<S, T>
) where P.S == S, P.T == T {
let _: T = a.wew
let _: T = b.lad
}
//===----------------------------------------------------------------------===//
// Keypaths
//===----------------------------------------------------------------------===//
@dynamicMemberLookup
class KP {
subscript(dynamicMember member: String) -> Int { return 7 }
}
_ = \KP.[dynamicMember: "hi"]
_ = \KP.testLookup
/* KeyPath based dynamic lookup */
struct Point {
var x: Int
let y: Int // expected-note 2 {{change 'let' to 'var' to make it mutable}}
private let z: Int = 0 // expected-note 10 {{declared here}}
}
struct Rectangle {
var topLeft, bottomRight: Point
}
@dynamicMemberLookup
struct Lens<T> {
var obj: T
init(_ obj: T) {
self.obj = obj
}
subscript<U>(dynamicMember member: KeyPath<T, U>) -> Lens<U> {
get { return Lens<U>(obj[keyPath: member]) }
}
subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> Lens<U> {
get { return Lens<U>(obj[keyPath: member]) }
set { obj[keyPath: member] = newValue.obj }
}
}
var topLeft = Point(x: 0, y: 0)
var bottomRight = Point(x: 10, y: 10)
var lens = Lens(Rectangle(topLeft: topLeft,
bottomRight: bottomRight))
_ = lens.topLeft
_ = lens.topLeft.x
_ = lens.topLeft.y
_ = lens.topLeft.z // expected-error {{'z' is inaccessible due to 'private' protection level}}
_ = lens.bottomRight
_ = lens.bottomRight.x
_ = lens.bottomRight.y
_ = lens.bottomRight.z // expected-error {{'z' is inaccessible due to 'private' protection level}}
_ = \Lens<Point>.x
_ = \Lens<Point>.y
_ = \Lens<Point>.z // expected-error {{'z' is inaccessible due to 'private' protection level}}
_ = \Lens<Rectangle>.topLeft.x
_ = \Lens<Rectangle>.topLeft.y
_ = \Lens<Rectangle>.topLeft.z // expected-error {{'z' is inaccessible due to 'private' protection level}}
_ = \Lens<[Int]>.count
_ = \Lens<[Int]>.[0]
_ = \Lens<[[Int]]>.[0].count
lens.topLeft = Lens(Point(x: 1, y: 2)) // Ok
lens.bottomRight.x = Lens(11) // Ok
lens.bottomRight.y = Lens(12) // expected-error {{cannot assign to property: 'y' is a 'let' constant}}
lens.bottomRight.z = Lens(13) // expected-error {{'z' is inaccessible due to 'private' protection level}}
func acceptKeyPathDynamicLookup(_: Lens<Int>) {}
acceptKeyPathDynamicLookup(lens.topLeft.x)
acceptKeyPathDynamicLookup(lens.topLeft.y)
acceptKeyPathDynamicLookup(lens.topLeft.z) // expected-error {{'z' is inaccessible due to 'private' protection level}}
var tupleLens = Lens<(String, Int)>(("ultimate question", 42))
_ = tupleLens.0.count
_ = tupleLens.1
var namedTupleLens = Lens<(question: String, answer: Int)>((question: "ultimate question", answer: 42))
_ = namedTupleLens.question.count
_ = namedTupleLens.answer
@dynamicMemberLookup
class A<T> {
var value: T
init(_ v: T) {
self.value = v
}
subscript<U>(dynamicMember member: KeyPath<T, U>) -> U {
get { return value[keyPath: member] }
}
}
// Let's make sure that keypath dynamic member lookup
// works with inheritance
class B<T> : A<T> {}
func bar(_ b: B<Point>) {
let _: Int = b.x
let _ = b.y
let _: Float = b.y // expected-error {{cannot convert value of type 'Int' to specified type 'Float'}}
let _ = b.z // expected-error {{'z' is inaccessible due to 'private' protection level}}
}
// Existentials and IUOs
@dynamicMemberLookup
protocol KeyPathLookup {
associatedtype T
var value: T { get }
subscript(dynamicMember member: KeyPath<T, Int>) -> Int! { get }
}
extension KeyPathLookup {
subscript(dynamicMember member: KeyPath<T, Int>) -> Int! {
get { return value[keyPath: member] }
}
}
class C<T> : KeyPathLookup {
var value: T
init(_ v: T) {
self.value = v
}
}
func baz(_ c: C<Point>) {
let _: Int = c.x
let _ = c.y
let _: Float = c.y // expected-error {{cannot convert value of type 'Int?' to specified type 'Float'}}
let _ = c.z // expected-error {{'z' is inaccessible due to 'private' protection level}}
}
@dynamicMemberLookup
class D<T> {
var value: T
init(_ v: T) {
self.value = v
}
subscript<U: Numeric>(dynamicMember member: KeyPath<T, U>) -> (U) -> U {
get { return { offset in self.value[keyPath: member] + offset } }
}
}
func faz(_ d: D<Point>) {
let _: Int = d.x(42)
let _ = d.y(1 + 0)
let _: Float = d.y(1 + 0) // expected-error {{cannot convert value of type 'Int' to specified type 'Float'}}
let _ = d.z(1 + 0) // expected-error {{'z' is inaccessible due to 'private' protection level}}
}
@dynamicMemberLookup
struct SubscriptLens<T> {
var value: T
var counter: Int = 0
subscript(foo: String) -> Int {
get { return 42 }
}
subscript(offset: Int) -> Int {
get { return counter }
set { counter = counter + newValue }
}
subscript<U>(dynamicMember member: KeyPath<T, U>) -> U! {
get { return value[keyPath: member] }
}
subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> U {
get { return value[keyPath: member] }
set { value[keyPath: member] = newValue }
}
}
func keypath_with_subscripts(_ arr: SubscriptLens<[Int]>,
_ dict: inout SubscriptLens<[String: Int]>) {
_ = arr[0..<3]
for idx in 0..<arr.count {
let _ = arr[idx]
print(arr[idx])
}
_ = arr["hello"] // Ok
_ = dict["hello"] // Ok
_ = arr["hello"] = 42 // expected-error {{cannot assign through subscript: subscript is get-only}}
_ = dict["hello"] = 0 // Ok
_ = arr[0] = 42 // expected-error {{cannot assign through subscript: 'arr' is a 'let' constant}}
_ = dict[0] = 1 // Ok
if let index = dict.value.firstIndex(where: { $0.value == 42 }) {
let _ = dict[index]
}
dict["ultimate question"] = 42
}
func keypath_with_incorrect_return_type(_ arr: Lens<Array<Int>>) {
for idx in 0..<arr.count {
// expected-error@-1 {{cannot convert value of type 'Lens<Int>' to expected argument type 'Int'}}
let _ = arr[idx]
}
}
struct WithTrailingClosure {
subscript(fn: () -> Int) -> Int {
get { return fn() }
nonmutating set { _ = fn() + newValue }
}
subscript(offset: Int, _ fn: () -> Int) -> Int {
get { return offset + fn() }
}
}
func keypath_with_trailing_closure_subscript(_ ty: inout SubscriptLens<WithTrailingClosure>) {
_ = ty[0] { 42 } // expected-error {{subscript index of type '() -> Int' in a key path must be Hashable}}
_ = ty[0] { 42 } = 0 // expected-error {{cannot assign through subscript: subscript is get-only}}
// expected-error@-1 {{subscript index of type '() -> Int' in a key path must be Hashable}}
_ = ty[] { 42 } // expected-error {{subscript index of type '() -> Int' in a key path must be Hashable}}
_ = ty[] { 42 } = 0 // expected-error {{subscript index of type '() -> Int' in a key path must be Hashable}}
}
func keypath_to_subscript_to_property(_ lens: inout Lens<Array<Rectangle>>) {
_ = lens[0].topLeft.x
_ = lens[0].topLeft.y
_ = lens[0].topLeft.x = Lens(0)
_ = lens[0].topLeft.y = Lens(1)
// expected-error@-1 {{cannot assign to property: 'y' is a 'let' constant}}
}
@dynamicMemberLookup
struct SingleChoiceLens<T> {
var obj: T
init(_ obj: T) {
self.obj = obj
}
subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> U {
get { return obj[keyPath: member] }
set { obj[keyPath: member] = newValue }
}
}
// Make sure that disjunction filtering optimization doesn't
// impede keypath dynamic member lookup by eagerly trying to
// simplify disjunctions with a single viable choice.
func test_lens_with_a_single_choice(a: inout SingleChoiceLens<[Int]>) {
a[0] = 1 // Ok
}
func test_chain_of_recursive_lookups(_ lens: Lens<Lens<Lens<Point>>>) {
_ = lens.x
_ = lens.y
_ = lens.z // expected-error {{'z' is inaccessible due to 'private' protection level}}
// Make sure that 'obj' field could be retrieved at any level
_ = lens.obj
_ = lens.obj.obj
_ = lens.obj.x
_ = lens.obj.obj.x
_ = \Lens<Lens<Point>>.x
_ = \Lens<Lens<Point>>.obj.x
}
// KeyPath Dynamic Member Lookup can't refer to methods, mutating setters and static members
// because of the KeyPath limitations
func invalid_refs_through_dynamic_lookup() {
struct S {
static var foo: Int = 42
func bar() -> Q { return Q() }
static func baz(_: String) -> Int { return 0 }
}
struct Q {
var faz: Int = 0
}
func test(_ lens: A<S>) {
_ = lens.foo // expected-error {{dynamic key path member lookup cannot refer to static member 'foo'}}
_ = lens.bar() // expected-error {{dynamic key path member lookup cannot refer to instance method 'bar()'}}
_ = lens.bar().faz + 1 // expected-error {{dynamic key path member lookup cannot refer to instance method 'bar()'}}
_ = lens.baz("hello") // expected-error {{dynamic key path member lookup cannot refer to static method 'baz'}}
}
}
// SR-10597
final class SR10597 {
}
@dynamicMemberLookup
struct SR10597_W<T> {
var obj: T
init(_ obj: T) { self.obj = obj }
subscript<U>(dynamicMember member: KeyPath<T, U>) -> U {
return obj[keyPath: member]
}
var wooo: SR10597 { SR10597() } // expected-note {{declared here}}
}
_ = SR10597_W<SR10597>(SR10597()).wooooo // expected-error {{value of type 'SR10597_W<SR10597>' has no dynamic member 'wooooo' using key path from root type 'SR10597'; did you mean 'wooo'?}}
_ = SR10597_W<SR10597>(SR10597()).bla // expected-error {{value of type 'SR10597_W<SR10597>' has no dynamic member 'bla' using key path from root type 'SR10597'}}
final class SR10597_1 {
var woo: Int? // expected-note 2 {{'woo' declared here}}
}
@dynamicMemberLookup
struct SR10597_1_W<T> {
var obj: T
init(_ obj: T) { self.obj = obj }
subscript<U>(dynamicMember member: KeyPath<T, U>) -> U {
return obj[keyPath: member]
}
}
_ = SR10597_1_W<SR10597_1>(SR10597_1()).wooo // expected-error {{value of type 'SR10597_1_W<SR10597_1>' has no dynamic member 'wooo' using key path from root type 'SR10597_1'; did you mean 'woo'?}}
_ = SR10597_1_W<SR10597_1>(SR10597_1()).bla // expected-error {{value of type 'SR10597_1_W<SR10597_1>' has no dynamic member 'bla' using key path from root type 'SR10597_1'}}
// SR-10557
@dynamicMemberLookup
struct SR_10557_S {
subscript(dynamicMember: String) -> String { // expected-error {{@dynamicMemberLookup attribute requires 'SR_10557_S' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a key path}}
// expected-note@-1 {{add an explicit argument label to this subscript to satisfy the @dynamicMemberLookup requirement}}{{13-13=dynamicMember }}
fatalError()
}
}
@dynamicMemberLookup
struct SR_10557_S1 {
subscript(foo bar: String) -> String { // expected-error {{@dynamicMemberLookup attribute requires 'SR_10557_S1' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a key path}}
fatalError()
}
subscript(foo: String) -> String { // expected-error {{@dynamicMemberLookup attribute requires 'SR_10557_S1' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a key path}}
// expected-note@-1 {{add an explicit argument label to this subscript to satisfy the @dynamicMemberLookup requirement}} {{13-13=dynamicMember }}
fatalError()
}
}
@dynamicMemberLookup
struct SR11877 {
subscript(dynamicMember member: Substring) -> Int { 0 }
}
_ = \SR11877.okay
func test_infinite_self_recursion() {
@dynamicMemberLookup
struct Recurse<T> {
subscript<U>(dynamicMember member: KeyPath<Recurse<T>, U>) -> Int {
return 1
}
}
_ = Recurse<Int>().foo
// expected-error@-1 {{value of type 'Recurse<Int>' has no dynamic member 'foo' using key path from root type 'Recurse<Int>'}}
}
// rdar://problem/60225883 - crash during solution application (ExprRewriter::buildKeyPathDynamicMemberIndexExpr)
func test_combination_of_keypath_and_string_lookups() {
@dynamicMemberLookup
struct Outer {
subscript(dynamicMember member: String) -> Outer {
Outer()
}
subscript(dynamicMember member: KeyPath<Inner, Inner>) -> Outer {
Outer()
}
}
@dynamicMemberLookup
struct Inner {
subscript(dynamicMember member: String) -> Inner {
Inner()
}
}
func test(outer: Outer) {
_ = outer.hello.world // Ok
}
}
// SR-12626
@dynamicMemberLookup
struct SR12626 {
var i: Int
subscript(dynamicMember member: KeyPath<SR12626, Int>) -> Int {
get { self[keyPath: member] }
set { self[keyPath: member] = newValue } // expected-error {{cannot assign through subscript: 'member' is a read-only key path}}
}
}
// SR-12245
public struct SR12425_S {}
@dynamicMemberLookup
public struct SR12425_R {}
internal var rightStructInstance: SR12425_R = SR12425_R()
public extension SR12425_R {
subscript<T>(dynamicMember member: WritableKeyPath<SR12425_S, T>) -> T {
get { rightStructInstance[keyPath: member] } // expected-error {{key path with root type 'SR12425_S' cannot be applied to a base of type 'SR12425_R'}}
set { rightStructInstance[keyPath: member] = newValue } // expected-error {{key path with root type 'SR12425_S' cannot be applied to a base of type 'SR12425_R'}}
}
}
@dynamicMemberLookup
public struct SR12425_R1 {}
public extension SR12425_R1 {
subscript<T>(dynamicMember member: KeyPath<SR12425_R1, T>) -> T {
get { rightStructInstance[keyPath: member] } // expected-error {{key path with root type 'SR12425_R1' cannot be applied to a base of type 'SR12425_R'}}
}
}
| apache-2.0 | 5fe9dcc3b5668be9623da29a8b423179 | 28.242718 | 229 | 0.629109 | 3.805433 | false | false | false | false |
xglofter/PicturePicker | PicturePicker/PhotoToolbar.swift | 1 | 3453 | //
// PhotoToolbar.swift
//
// Created by Richard on 2017/4/21.
// Copyright © 2017年 Richard. All rights reserved.
//
import UIKit
public protocol PhotoToolbarDelegate: NSObjectProtocol {
func touchPreviewAction()
func touchFinishAction()
}
open class PhotoToolbar: UIView {
fileprivate(set) var topLineView: UIView!
fileprivate(set) var previewButton: UIButton!
fileprivate(set) var finishButton: UIButton!
fileprivate(set) var contentLabel: UILabel!
fileprivate let barHeight: CGFloat = PickerConfig.pickerToolbarHeight
weak var delegate: PhotoToolbarDelegate!
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setCurrentNumber(number: Int, maxNumber: Int) {
let title = "已选择:\(number)/\(maxNumber)"
contentLabel.text = title
updateContentLabelFrame()
}
override open func layoutSubviews() {
super.layoutSubviews()
updateFrame()
}
}
private extension PhotoToolbar {
func setup() {
self.backgroundColor = PickerConfig.pickerToolbarColor
topLineView = UIView()
topLineView.backgroundColor = UIColor.lightGray
self.addSubview(topLineView)
previewButton = UIButton()
previewButton.backgroundColor = PickerConfig.pickerThemeColor
previewButton.setTitleColor(UIColor.white, for: .normal)
previewButton.setTitle("预览", for: .normal)
previewButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
previewButton.addTarget(self, action: #selector(onPreviewAction), for: .touchUpInside)
previewButton.layer.cornerRadius = 4
self.addSubview(previewButton)
finishButton = UIButton()
finishButton.backgroundColor = PickerConfig.pickerThemeColor
finishButton.setTitleColor(UIColor.white, for: .normal)
finishButton.setTitle("完成", for: .normal)
finishButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
finishButton.addTarget(self, action: #selector(onFinishAction), for: .touchUpInside)
finishButton.layer.cornerRadius = 4
self.addSubview(finishButton)
contentLabel = UILabel()
contentLabel.textAlignment = .center
contentLabel.font = UIFont.boldSystemFont(ofSize: 14)
contentLabel.textColor = PickerConfig.pickerToolbarLabelColor
self.addSubview(contentLabel)
}
func updateFrame() {
topLineView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: 0.5)
previewButton.frame.origin = CGPoint(x: 20, y: (bounds.height - 30)/2)
previewButton.frame.size = CGSize(width: 80, height: 30)
finishButton.frame.origin = CGPoint(x: bounds.width - 20 - 80, y: (bounds.height - 30)/2)
finishButton.frame.size = CGSize(width: 80, height: 30)
updateContentLabelFrame()
}
func updateContentLabelFrame() {
contentLabel.center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
contentLabel.frame.size = CGSize(width: 150, height: 30)
}
@objc func onPreviewAction() {
self.delegate?.touchPreviewAction()
}
@objc func onFinishAction() {
self.delegate?.touchFinishAction()
}
}
| mit | 6805c15b57e42104a2a9f5bd59b331a6 | 31.396226 | 97 | 0.656669 | 4.64682 | false | false | false | false |
yangalex/WeMeet | WeMeet/Models/Timeslot.swift | 1 | 2794 | //
// TimeSlot.swift
// WeMeet
//
// Created by Alexandre Yang on 7/26/15.
// Copyright (c) 2015 Alex Yang. All rights reserved.
//
import Foundation
import Parse
class Timeslot : PFObject, Comparable {
// date variables
@NSManaged var timeDate: TimeDate
@NSManaged var hour: Int
@NSManaged var isHalf: Bool
@NSManaged var weekday: String
@NSManaged var group: Group
@NSManaged var user: PFUser
init(hour: Int, isHalf: Bool) {
super.init()
if hour > 23 || hour < 0 {
self.hour = 0
} else {
self.hour = hour
}
self.isHalf = isHalf
}
override init() {
super.init()
}
func stringDescription() -> String {
if isHalf == true {
if hour > 9 {
return "\(String(hour)):30"
} else {
return "0\(String(hour)):30"
}
} else {
if hour > 9 {
return "\(String(hour)):00"
} else {
return "0\(String(hour)):00"
}
}
}
static func fromString(timeString: String) -> Timeslot {
let timeArray = timeString.componentsSeparatedByString(":")
let hour = timeArray[0]
let minute = timeArray[1]
if minute == "30" {
return Timeslot(hour: hour.toInt()!, isHalf: true)
} else {
return Timeslot(hour: hour.toInt()!, isHalf: false)
}
}
func equalTo(otherTimeslot: Timeslot) -> Bool {
if self.hour == otherTimeslot.hour && self.isHalf == otherTimeslot.isHalf {
return true
} else {
return false
}
}
override class func query() -> PFQuery? {
let query = PFQuery(className: "Timeslot")
query.includeKey("user")
query.includeKey("group")
query.includeKey("timeDate")
query.orderByAscending("hour")
return query
}
}
extension Timeslot : PFSubclassing {
static func parseClassName() -> String {
return "Timeslot"
}
override class func initialize() {
var onceToken: dispatch_once_t = 0
dispatch_once(&onceToken) {
self.registerSubclass()
}
}
}
func <(lhs: Timeslot, rhs: Timeslot) -> Bool {
if lhs.hour == rhs.hour {
if !lhs.isHalf && rhs.isHalf {
return true
} else {
return false
}
} else if lhs.hour < rhs.hour {
return true
} else {
return false
}
}
func ==(lhs: Timeslot, rhs: Timeslot) -> Bool {
if lhs.hour == rhs.hour && lhs.isHalf == rhs.isHalf {
return true
} else {
return false
}
}
| mit | f64a0597cec81b5229047666e02e6517 | 21.901639 | 83 | 0.510737 | 4.259146 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/01310-getselftypeforcontainer.swift | 1 | 862 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func c<g {
q c {
p _ = : h {
}
class h<f : q, g : q o f.g == g> {
}
protocol q {
}
}
class f<o : h, o : h c o.o> : p {
protocol p {
f q: h -> h = {
}(k, q)
protocol h : f { func f
struct c<d : Sequence> {
var b: [c<d>] {
}
protocol a {
}
class b: a {
}
func f<T : Boolean>(b: T) {
}
func e() {
}
}
protocol c : b { func b
otocol A {
}
struct }
}
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
}
struct e<c : where e.f ==b {
>(f: B<{ }
})
}
typealias
h
| apache-2.0 | 526360804db6d19de49e1de9c079bb25 | 16.591837 | 79 | 0.604408 | 2.60423 | false | false | false | false |
MaxHasADHD/TraktKit | Common/Wrapper/URLSessionProtocol.swift | 1 | 2423 | //
// URLSessionProtocol.swift
// TraktKit
//
// Created by Maximilian Litteral on 3/11/18.
// Copyright © 2018 Maximilian Litteral. All rights reserved.
//
import Foundation
public protocol URLSessionProtocol {
typealias DataTaskResult = (Data?, URLResponse?, Error?) -> Void
func _dataTask(with request: URLRequest, completion: @escaping DataTaskResult) -> URLSessionDataTaskProtocol
func data(for request: URLRequest) async throws -> (Data, URLResponse)
}
public protocol URLSessionDataTaskProtocol {
func resume()
func cancel()
}
// MARK: Conform to protocols
extension URLSession: URLSessionProtocol {
public func _dataTask(with request: URLRequest, completion: @escaping DataTaskResult) -> URLSessionDataTaskProtocol {
dataTask(with: request, completionHandler: completion) as URLSessionDataTaskProtocol
}
public func data(for request: URLRequest) async throws -> (Data, URLResponse) {
try await data(for: request, delegate: nil)
}
}
extension URLSessionDataTask: URLSessionDataTaskProtocol {}
// MARK: MOCK
class MockURLSession: URLSessionProtocol {
var nextDataTask = MockURLSessionDataTask()
var nextData: Data?
var nextStatusCode: Int = StatusCodes.Success
var nextError: Error?
private (set) var lastURL: URL?
func successHttpURLResponse(request: URLRequest) -> URLResponse {
return HTTPURLResponse(url: request.url!, statusCode: nextStatusCode, httpVersion: "HTTP/1.1", headerFields: nil)!
}
public func _dataTask(with request: URLRequest, completion: @escaping DataTaskResult) -> URLSessionDataTaskProtocol {
lastURL = request.url
completion(nextData, successHttpURLResponse(request: request), nextError)
return nextDataTask
}
public func data(for request: URLRequest) async throws -> (Data, URLResponse) {
lastURL = request.url
if let nextData = nextData {
return (nextData, successHttpURLResponse(request: request))
} else if let nextError = nextError {
throw nextError
} else {
fatalError("No error or data")
}
}
}
class MockURLSessionDataTask: URLSessionDataTaskProtocol {
private(set) var resumeWasCalled = false
private(set) var cancelWasCalled = false
func resume() {
resumeWasCalled = true
}
func cancel() {
cancelWasCalled = true
}
}
| mit | e09b17013522043ed2bb6e0ee3eba988 | 28.901235 | 122 | 0.700248 | 4.863454 | false | false | false | false |
dtop/SwiftValidate | validate/Validators/ValidatorEmpty.swift | 1 | 1520 | //
// ValidatorEmpty.swift
// validator
//
// Created by Danilo Topalovic on 19.12.15.
// Copyright © 2015 Danilo Topalovic. All rights reserved.
//
import Foundation
/**
* Validates on emptynes
*/
public class ValidatorEmpty: BaseValidator, ValidatorProtocol {
/// can the value be nil?
public var allowNil: Bool = false
/// this error message
public var errorMessage: String = NSLocalizedString("Value was Empty", comment: "ValidatorEmpty - Error String")
/**
inits
- parameter initializer: the initializer callback
- returns: the instance
*/
required public init( _ initializer: (ValidatorEmpty) -> () = { _ in }) {
super.init()
initializer(self)
}
/**
Validates
- parameter value: the value
- parameter context: the context
- throws: validation erorrs
- returns: true on correctness
*/
override public func validate<T: Any>(_ value: T?, context: [String: Any?]?) throws -> Bool {
// reset errors
self.emptyErrors()
if self.allowNil && nil == value {
return true
}
if let val: String = value as? String {
if val.isEmpty {
return self.returnError(error: self.errorMessage)
}
return true
}
return self.returnError(error: self.errorMessage)
}
}
| mit | 8872f92e891f661ee105e329ae4a4c32 | 22.015152 | 116 | 0.547729 | 4.83758 | false | false | false | false |
texuf/outandabout | outandabout/outandabout/RSBarcodes/RSITFGenerator.swift | 4 | 1713 | //
// RSITFGenerator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/11/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
// http://www.barcodeisland.com/int2of5.phtml
public class RSITFGenerator: RSAbstractCodeGenerator {
let ITF_CHARACTER_ENCODINGS = [
"00110",
"10001",
"01001",
"11000",
"00101",
"10100",
"01100",
"00011",
"10010",
"01010",
]
override public func isValid(contents: String) -> Bool {
return super.isValid(contents) && contents.length() % 2 == 0
}
override public func initiator() -> String {
return "1010"
}
override public func terminator() -> String {
return "1101"
}
override public func barcode(contents: String) -> String {
var barcode = ""
for i in 0..<contents.length() / 2 {
let pair = contents.substring(i * 2, length: 2)
let bars = ITF_CHARACTER_ENCODINGS[pair[0].toInt()!]
let spaces = ITF_CHARACTER_ENCODINGS[pair[1].toInt()!]
for j in 0..<10 {
if j % 2 == 0 {
let bar = bars[j / 2].toInt()
if bar == 1 {
barcode += "11"
} else {
barcode += "1"
}
} else {
let space = spaces[j / 2].toInt()
if space == 1 {
barcode += "00"
} else {
barcode += "0"
}
}
}
}
return barcode
}
}
| mit | 30ac597451810dc2425055b4cb6758c5 | 25.353846 | 68 | 0.435493 | 4.381074 | false | false | false | false |
megabitsenmzq/PomoNow-iOS | Old-1.0/PomoNow/PomoNow/AnimationToList.swift | 1 | 3051 | //
// MagicMoveTransion.swift
// PomoNow
//
// Created by Megabits on 15/7/13.
// Copyright © 2015年 ScrewBox. All rights reserved.
//
import UIKit
class AnimationToList: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.5
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
//获取动画的源控制器和目标控制器
let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! PomodoroViewController
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! PomoListViewController
let container = transitionContext.containerView()
let snap = fromVC.TimerView.snapshotViewAfterScreenUpdates(false)
snap.frame = container!.convertRect(fromVC.TimerView.frame, fromView: fromVC.TimerViewContainer)
let snapRound = fromVC.round.snapshotViewAfterScreenUpdates(false)
snapRound.frame = container!.convertRect(fromVC.round.frame, fromView: fromVC.view)
fromVC.TimerView.hidden = true
toVC.view.frame = transitionContext.finalFrameForViewController(toVC)
toVC.view.alpha = 0
snapRound.alpha = 0
//代理管理以下view
container!.addSubview(snap)
container!.addSubview(snapRound)
container!.addSubview(toVC.view)
UIView.animateWithDuration(0.1, delay:0,options:UIViewAnimationOptions.TransitionNone, animations: { () -> Void in
fromVC.taskLabel.alpha = 0
fromVC.readme.alpha = 0
}) { (finish: Bool) -> Void in
fromVC.round.hidden = true
snapRound.alpha = 1
}
UIView.animateWithDuration(0.25, delay:0.1,options:UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
toVC.view.layoutIfNeeded()
toVC.view.setNeedsDisplay()
snapRound.frame = toVC.round.frame
snap.frame = toVC.TimerView.frame
}) { (finish: Bool) -> Void in
}
UIView.animateWithDuration(0.25, delay:0.8,options:UIViewAnimationOptions.TransitionNone, animations: { () -> Void in
snap.alpha = 0
}) { (finish: Bool) -> Void in
}
UIView.animateWithDuration(0.15, delay:0.35,options:UIViewAnimationOptions.TransitionNone, animations: { () -> Void in
snapRound.alpha = 0
toVC.view.alpha = 1
}) { (finish: Bool) -> Void in
//让系统管理 navigation
fromVC.TimerView.hidden = false
fromVC.round.hidden = false
fromVC.taskLabel.alpha = 1
fromVC.readme.alpha = 1
snap.removeFromSuperview()
snapRound.removeFromSuperview()
transitionContext.completeTransition(true)
}
}
} | mit | 021ca04d4fa350d93c87fc7e3e2316af | 38.96 | 128 | 0.64219 | 5.077966 | false | false | false | false |
tkremenek/swift | stdlib/public/Differentiation/ArrayDifferentiation.swift | 4 | 14310 | //===--- ArrayDifferentiation.swift ---------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
//===----------------------------------------------------------------------===//
// Protocol conformances
//===----------------------------------------------------------------------===//
// TODO(TF-938): Add `Element: Differentiable` requirement.
extension Array {
/// The view of an array as the differentiable product manifold of `Element`
/// multiplied with itself `count` times.
@frozen
public struct DifferentiableView {
var _base: [Element]
}
}
extension Array.DifferentiableView: Differentiable
where Element: Differentiable {
/// The viewed array.
public var base: [Element] {
get { _base }
_modify { yield &_base }
}
@usableFromInline
@derivative(of: base)
func _vjpBase() -> (
value: [Element], pullback: (Array<Element>.TangentVector) -> TangentVector
) {
return (base, { $0 })
}
@usableFromInline
@derivative(of: base)
func _jvpBase() -> (
value: [Element], differential: (Array<Element>.TangentVector) -> TangentVector
) {
return (base, { $0 })
}
/// Creates a differentiable view of the given array.
public init(_ base: [Element]) { self._base = base }
@usableFromInline
@derivative(of: init(_:))
static func _vjpInit(_ base: [Element]) -> (
value: Array.DifferentiableView, pullback: (TangentVector) -> TangentVector
) {
return (Array.DifferentiableView(base), { $0 })
}
@usableFromInline
@derivative(of: init(_:))
static func _jvpInit(_ base: [Element]) -> (
value: Array.DifferentiableView, differential: (TangentVector) -> TangentVector
) {
return (Array.DifferentiableView(base), { $0 })
}
public typealias TangentVector =
Array<Element.TangentVector>.DifferentiableView
public mutating func move(by offset: TangentVector) {
if offset.base.isEmpty {
return
}
precondition(
base.count == offset.base.count, """
Count mismatch: \(base.count) ('self') and \(offset.base.count) \
('direction')
""")
for i in offset.base.indices {
base[i].move(by: offset.base[i])
}
}
}
extension Array.DifferentiableView: Equatable
where Element: Differentiable & Equatable {
public static func == (
lhs: Array.DifferentiableView,
rhs: Array.DifferentiableView
) -> Bool {
return lhs.base == rhs.base
}
}
extension Array.DifferentiableView: ExpressibleByArrayLiteral
where Element: Differentiable {
public init(arrayLiteral elements: Element...) {
self.init(elements)
}
}
extension Array.DifferentiableView: CustomStringConvertible
where Element: Differentiable {
public var description: String {
return base.description
}
}
/// Makes `Array.DifferentiableView` additive as the product space.
///
/// Note that `Array.DifferentiableView([])` is the zero in the product spaces
/// of all counts.
extension Array.DifferentiableView: AdditiveArithmetic
where Element: AdditiveArithmetic & Differentiable {
public static var zero: Array.DifferentiableView {
return Array.DifferentiableView([])
}
public static func + (
lhs: Array.DifferentiableView,
rhs: Array.DifferentiableView
) -> Array.DifferentiableView {
if lhs.base.count == 0 {
return rhs
}
if rhs.base.count == 0 {
return lhs
}
precondition(
lhs.base.count == rhs.base.count,
"Count mismatch: \(lhs.base.count) and \(rhs.base.count)")
return Array.DifferentiableView(zip(lhs.base, rhs.base).map(+))
}
public static func - (
lhs: Array.DifferentiableView,
rhs: Array.DifferentiableView
) -> Array.DifferentiableView {
if lhs.base.count == 0 {
return rhs
}
if rhs.base.count == 0 {
return lhs
}
precondition(
lhs.base.count == rhs.base.count,
"Count mismatch: \(lhs.base.count) and \(rhs.base.count)")
return Array.DifferentiableView(zip(lhs.base, rhs.base).map(-))
}
@inlinable
public subscript(_ index: Int) -> Element {
if index < base.count {
return base[index]
} else {
return Element.zero
}
}
}
/// Makes `Array` differentiable as the product manifold of `Element`
/// multiplied with itself `count` times.
extension Array: Differentiable where Element: Differentiable {
// In an ideal world, `TangentVector` would be `[Element.TangentVector]`.
// Unfortunately, we cannot conform `Array` to `AdditiveArithmetic` for
// `TangentVector` because `Array` already has a static `+` method with
// different semantics from `AdditiveArithmetic.+`. So we use
// `Array.DifferentiableView` for all these associated types.
public typealias TangentVector =
Array<Element.TangentVector>.DifferentiableView
public mutating func move(by offset: TangentVector) {
var view = DifferentiableView(self)
view.move(by: offset)
self = view.base
}
}
//===----------------------------------------------------------------------===//
// Derivatives
//===----------------------------------------------------------------------===//
extension Array where Element: Differentiable {
@usableFromInline
@derivative(of: subscript)
func _vjpSubscript(index: Int) -> (
value: Element, pullback: (Element.TangentVector) -> TangentVector
) {
func pullback(_ v: Element.TangentVector) -> TangentVector {
var dSelf = [Element.TangentVector](
repeating: .zero,
count: count)
dSelf[index] = v
return TangentVector(dSelf)
}
return (self[index], pullback)
}
@usableFromInline
@derivative(of: subscript)
func _jvpSubscript(index: Int) -> (
value: Element, differential: (TangentVector) -> Element.TangentVector
) {
func differential(_ v: TangentVector) -> Element.TangentVector {
return v[index]
}
return (self[index], differential)
}
@usableFromInline
@derivative(of: +)
static func _vjpConcatenate(_ lhs: Self, _ rhs: Self) -> (
value: Self,
pullback: (TangentVector) -> (TangentVector, TangentVector)
) {
func pullback(_ v: TangentVector) -> (TangentVector, TangentVector) {
if v.base.isEmpty {
return (.zero, .zero)
}
precondition(
v.base.count == lhs.count + rhs.count, """
Tangent vector with invalid count \(v.base.count); expected to \
equal the sum of operand counts \(lhs.count) and \(rhs.count)
""")
return (
TangentVector([Element.TangentVector](v.base[0..<lhs.count])),
TangentVector([Element.TangentVector](v.base[lhs.count...]))
)
}
return (lhs + rhs, pullback)
}
@usableFromInline
@derivative(of: +)
static func _jvpConcatenate(_ lhs: Self, _ rhs: Self) -> (
value: Self,
differential: (TangentVector, TangentVector) -> TangentVector
) {
func differential(_ l: TangentVector, _ r: TangentVector) -> TangentVector {
precondition(
l.base.count == lhs.count && r.base.count == rhs.count, """
Tangent vectors with invalid count; expected to equal the \
operand counts \(lhs.count) and \(rhs.count)
""")
return .init(l.base + r.base)
}
return (lhs + rhs, differential)
}
}
extension Array where Element: Differentiable {
@usableFromInline
@derivative(of: append)
mutating func _vjpAppend(_ element: Element) -> (
value: Void, pullback: (inout TangentVector) -> Element.TangentVector
) {
let appendedElementIndex = count
append(element)
return ((), { v in
defer { v.base.removeLast() }
return v.base[appendedElementIndex]
})
}
@usableFromInline
@derivative(of: append)
mutating func _jvpAppend(_ element: Element) -> (
value: Void,
differential: (inout TangentVector, Element.TangentVector) -> Void
) {
append(element)
return ((), { $0.base.append($1) })
}
}
extension Array where Element: Differentiable {
@usableFromInline
@derivative(of: +=)
static func _vjpAppend(_ lhs: inout Self, _ rhs: Self) -> (
value: Void, pullback: (inout TangentVector) -> TangentVector
) {
let lhsCount = lhs.count
lhs += rhs
return ((), { v in
let drhs =
TangentVector(.init(v.base.dropFirst(lhsCount)))
let rhsCount = drhs.base.count
v.base.removeLast(rhsCount)
return drhs
})
}
@usableFromInline
@derivative(of: +=)
static func _jvpAppend(_ lhs: inout Self, _ rhs: Self) -> (
value: Void, differential: (inout TangentVector, TangentVector) -> Void
) {
lhs += rhs
return ((), { $0.base += $1.base })
}
}
extension Array where Element: Differentiable {
@usableFromInline
@derivative(of: init(repeating:count:))
static func _vjpInit(repeating repeatedValue: Element, count: Int) -> (
value: Self, pullback: (TangentVector) -> Element.TangentVector
) {
(
value: Self(repeating: repeatedValue, count: count),
pullback: { v in
v.base.reduce(.zero, +)
}
)
}
@usableFromInline
@derivative(of: init(repeating:count:))
static func _jvpInit(repeating repeatedValue: Element, count: Int) -> (
value: Self, differential: (Element.TangentVector) -> TangentVector
) {
(
value: Self(repeating: repeatedValue, count: count),
differential: { v in TangentVector(.init(repeating: v, count: count)) }
)
}
}
//===----------------------------------------------------------------------===//
// Differentiable higher order functions for collections
//===----------------------------------------------------------------------===//
extension Array where Element: Differentiable {
@inlinable
@differentiable(reverse, wrt: self)
public func differentiableMap<Result: Differentiable>(
_ body: @differentiable(reverse) (Element) -> Result
) -> [Result] {
map(body)
}
@inlinable
@derivative(of: differentiableMap)
internal func _vjpDifferentiableMap<Result: Differentiable>(
_ body: @differentiable(reverse) (Element) -> Result
) -> (
value: [Result],
pullback: (Array<Result>.TangentVector) -> Array.TangentVector
) {
var values: [Result] = []
var pullbacks: [(Result.TangentVector) -> Element.TangentVector] = []
for x in self {
let (y, pb) = valueWithPullback(at: x, of: body)
values.append(y)
pullbacks.append(pb)
}
func pullback(_ tans: Array<Result>.TangentVector) -> Array.TangentVector {
.init(zip(tans.base, pullbacks).map { tan, pb in pb(tan) })
}
return (value: values, pullback: pullback)
}
@inlinable
@derivative(of: differentiableMap)
internal func _jvpDifferentiableMap<Result: Differentiable>(
_ body: @differentiable(reverse) (Element) -> Result
) -> (
value: [Result],
differential: (Array.TangentVector) -> Array<Result>.TangentVector
) {
var values: [Result] = []
var differentials: [(Element.TangentVector) -> Result.TangentVector] = []
for x in self {
let (y, df) = valueWithDifferential(at: x, of: body)
values.append(y)
differentials.append(df)
}
func differential(_ tans: Array.TangentVector) -> Array<Result>.TangentVector {
.init(zip(tans.base, differentials).map { tan, df in df(tan) })
}
return (value: values, differential: differential)
}
}
extension Array where Element: Differentiable {
@inlinable
@differentiable(reverse, wrt: (self, initialResult))
public func differentiableReduce<Result: Differentiable>(
_ initialResult: Result,
_ nextPartialResult: @differentiable(reverse) (Result, Element) -> Result
) -> Result {
reduce(initialResult, nextPartialResult)
}
@inlinable
@derivative(of: differentiableReduce)
internal func _vjpDifferentiableReduce<Result: Differentiable>(
_ initialResult: Result,
_ nextPartialResult: @differentiable(reverse) (Result, Element) -> Result
) -> (
value: Result,
pullback: (Result.TangentVector)
-> (Array.TangentVector, Result.TangentVector)
) {
var pullbacks:
[(Result.TangentVector) -> (Result.TangentVector, Element.TangentVector)] =
[]
let count = self.count
pullbacks.reserveCapacity(count)
var result = initialResult
for element in self {
let (y, pb) =
valueWithPullback(at: result, element, of: nextPartialResult)
result = y
pullbacks.append(pb)
}
return (
value: result,
pullback: { tangent in
var resultTangent = tangent
var elementTangents = TangentVector([])
elementTangents.base.reserveCapacity(count)
for pullback in pullbacks.reversed() {
let (newResultTangent, elementTangent) = pullback(resultTangent)
resultTangent = newResultTangent
elementTangents.base.append(elementTangent)
}
return (TangentVector(elementTangents.base.reversed()), resultTangent)
}
)
}
@inlinable
@derivative(of: differentiableReduce, wrt: (self, initialResult))
func _jvpDifferentiableReduce<Result: Differentiable>(
_ initialResult: Result,
_ nextPartialResult: @differentiable(reverse) (Result, Element) -> Result
) -> (value: Result,
differential: (Array.TangentVector, Result.TangentVector)
-> Result.TangentVector) {
var differentials:
[(Result.TangentVector, Element.TangentVector) -> Result.TangentVector]
= []
let count = self.count
differentials.reserveCapacity(count)
var result = initialResult
for element in self {
let (y, df) =
valueWithDifferential(at: result, element, of: nextPartialResult)
result = y
differentials.append(df)
}
return (value: result, differential: { dSelf, dInitial in
var dResult = dInitial
for (dElement, df) in zip(dSelf.base, differentials) {
dResult = df(dResult, dElement)
}
return dResult
})
}
}
| apache-2.0 | 75c188af99d3c6a70a75aa4d4a2f818e | 29.576923 | 83 | 0.632355 | 4.35219 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/Kafka/Kafka_Error.swift | 1 | 3043 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for Kafka
public struct KafkaErrorType: AWSErrorType {
enum Code: String {
case badRequestException = "BadRequestException"
case conflictException = "ConflictException"
case forbiddenException = "ForbiddenException"
case internalServerErrorException = "InternalServerErrorException"
case notFoundException = "NotFoundException"
case serviceUnavailableException = "ServiceUnavailableException"
case tooManyRequestsException = "TooManyRequestsException"
case unauthorizedException = "UnauthorizedException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize Kafka
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// Returns information about an error.
public static var badRequestException: Self { .init(.badRequestException) }
/// Returns information about an error.
public static var conflictException: Self { .init(.conflictException) }
/// Returns information about an error.
public static var forbiddenException: Self { .init(.forbiddenException) }
/// Returns information about an error.
public static var internalServerErrorException: Self { .init(.internalServerErrorException) }
/// Returns information about an error.
public static var notFoundException: Self { .init(.notFoundException) }
/// Returns information about an error.
public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) }
/// Returns information about an error.
public static var tooManyRequestsException: Self { .init(.tooManyRequestsException) }
/// Returns information about an error.
public static var unauthorizedException: Self { .init(.unauthorizedException) }
}
extension KafkaErrorType: Equatable {
public static func == (lhs: KafkaErrorType, rhs: KafkaErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension KafkaErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| apache-2.0 | 425172d1153e450cd4f044cfe659211d | 38.012821 | 117 | 0.675978 | 5.237522 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/LakeFormation/LakeFormation_Paginator.swift | 1 | 9346 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension LakeFormation {
/// Returns the Lake Formation permissions for a specified table or database resource located at a path in Amazon S3. GetEffectivePermissionsForPath will not return databases and tables if the catalog is encrypted.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func getEffectivePermissionsForPathPaginator<Result>(
_ input: GetEffectivePermissionsForPathRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, GetEffectivePermissionsForPathResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: getEffectivePermissionsForPath,
tokenKey: \GetEffectivePermissionsForPathResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func getEffectivePermissionsForPathPaginator(
_ input: GetEffectivePermissionsForPathRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (GetEffectivePermissionsForPathResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: getEffectivePermissionsForPath,
tokenKey: \GetEffectivePermissionsForPathResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of the principal permissions on the resource, filtered by the permissions of the caller. For example, if you are granted an ALTER permission, you are able to see only the principal permissions for ALTER. This operation returns only those permissions that have been explicitly granted. For information about permissions, see Security and Access Control to Metadata and Data.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listPermissionsPaginator<Result>(
_ input: ListPermissionsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListPermissionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listPermissions,
tokenKey: \ListPermissionsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listPermissionsPaginator(
_ input: ListPermissionsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListPermissionsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listPermissions,
tokenKey: \ListPermissionsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the resources registered to be managed by the Data Catalog.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listResourcesPaginator<Result>(
_ input: ListResourcesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListResourcesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listResources,
tokenKey: \ListResourcesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listResourcesPaginator(
_ input: ListResourcesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListResourcesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listResources,
tokenKey: \ListResourcesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension LakeFormation.GetEffectivePermissionsForPathRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> LakeFormation.GetEffectivePermissionsForPathRequest {
return .init(
catalogId: self.catalogId,
maxResults: self.maxResults,
nextToken: token,
resourceArn: self.resourceArn
)
}
}
extension LakeFormation.ListPermissionsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> LakeFormation.ListPermissionsRequest {
return .init(
catalogId: self.catalogId,
maxResults: self.maxResults,
nextToken: token,
principal: self.principal,
resource: self.resource,
resourceType: self.resourceType
)
}
}
extension LakeFormation.ListResourcesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> LakeFormation.ListResourcesRequest {
return .init(
filterConditionList: self.filterConditionList,
maxResults: self.maxResults,
nextToken: token
)
}
}
| apache-2.0 | 13fc54fe5800475d093cd4854648a639 | 43.932692 | 397 | 0.653007 | 5.18071 | false | false | false | false |
hooliooo/Astral | Sources/OAuth/Client+OAuth.swift | 1 | 2980 | //
// Astral
// Copyright (c) Julio Miguel Alorro
// Licensed under the MIT license. See LICENSE file
//
import class Foundation.FileManager
import class Foundation.JSONEncoder
import class Foundation.JSONDecoder
import class Foundation.URLResponse
import struct Astral.Client
import struct Astral.RequestBuilder
import struct Foundation.Data
import struct Foundation.URLQueryItem
public extension Client {
/**
Queries the given OAuth2.0 token url as a POST request with the necessary payload given the data
from the ResourceOwnerPasswordCredentialsGrant and ClientCredentials instances
- parameters:
- url: The URL of the OAuth2.0 token endpoint
- credentialGrant: The ResourceOwnerPasswordCredentialsGrant instance containing data necessary for the http POST request
- clientCredentials: The ClientCredentials instance containing data necessary for the http POST request
*/
func passwordCredentials(
url: String,
credentialGrant: ResourceOwnerPasswordCredentialsGrant,
clientCredentials: ClientCredentials
) throws -> RequestBuilder {
let items: [URLQueryItem] = [
("password", \ResourceOwnerPasswordCredentialsGrant.password),
("username", \ResourceOwnerPasswordCredentialsGrant.username),
("grant_type", \ResourceOwnerPasswordCredentialsGrant.grantType),
("scope", \ResourceOwnerPasswordCredentialsGrant.scope)
].compactMap { (name: String, keyPath: PartialKeyPath<ResourceOwnerPasswordCredentialsGrant>) -> URLQueryItem? in
URLQueryItem(name: name, value: credentialGrant[keyPath: keyPath] as? String)
}
return try self.post(url: url)
.form(items: items)
.basicAuthentication(username: clientCredentials.clientId, password: clientCredentials.clientSecret)
}
// func authenticate(
// url: String,
// credentialGrant: ResourceOwnerPasswordCredentialsGrant,
// clientCredentials: ClientCredentials
// ) async throws -> Client {
// let decoder: JSONDecoder = JSONDecoder()
// decoder.keyDecodingStrategy = JSONDecoder.KeyDecodingStrategy.convertFromSnakeCase
// let (token, response): (OAuth2Token, URLResponse) = try await self
// .passwordCredentials(url: url, credentialGrant: credentialGrant, clientCredentials: clientCredentials)
// .send(decoder: decoder)
//
// // Save OAuth2 in memory
// await OAuth2TokenStore.shared.store(token: token)
//
// // Save OAuth2 to document directory
// let fileManager: FileManager = self.fileManager
// Task.detached(priority: TaskPriority.background) { () -> Void in
// let encoder: JSONEncoder = JSONEncoder()
// let data: Data = try encoder.encode(token)
// let url = fileManager.ast.documentDirectory.appendingPathComponent("token.json")
// // Check if it exists
// if fileManager.fileExists(atPath: url.path) {
// try fileManager.removeItem(at: url)
// }
//
// try data.write(to: url)
// }
//
// return self
// }
}
| mit | b4ced78484fa6853ef0b3a47227e2331 | 38.210526 | 129 | 0.733221 | 4.535769 | false | false | false | false |
GabrielGhe/SwiftProjects | App5/App5/myTableViewController.swift | 1 | 3514 | //
// myTableViewController.swift
// App5
//
// Created by Gabriel on 2014-06-23.
// Copyright (c) 2014 Gabriel. All rights reserved.
//
import UIKit
class myTableViewController: UITableViewController {
var myData: Array<AnyObject> = []
override func viewDidLoad() {
super.viewDidLoad()
myData = ["Apples", "Bananas", "Peaches", "Plums"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return myData.count
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
let cellId:String = "cell"
var cell:UITableViewCell = tableView?.dequeueReusableCellWithIdentifier(cellId) as UITableViewCell
if let ip = indexPath {
cell.textLabel.text = myData[ip.row] as String
}
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView?, canEditRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
override func tableView(tableView: UITableView?, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath?) {
if editingStyle == .Delete {
// Delete the row from the data source
if let tv = tableView {
myData.removeAtIndex(indexPath!.row)
tv.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
}
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
if let index = indexPath {
println("The index is \(myData[indexPath.row])")
}
}
/*
// 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 NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// #pragma 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.
}
*/
}
| mit | 61a837bdc6de6ecf3f04dff92fad0ab0 | 32.466667 | 159 | 0.658509 | 5.42284 | false | false | false | false |
calebkleveter/UIWebKit | Sources/UIWebKit/Components/UILists.swift | 1 | 5097 | // The MIT License (MIT)
//
// Copyright (c) 2017 Caleb Kleveter
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// MARK: - UIUnorderedList
/// A wrapper class that represents an HTML `ul` element.
open class UIUnorderedList {
/// The base `ul` element of the `UIUnorderedList` object.
public let ul = UIElement(element: .ul)
/// The list items used in the unordered list.
public private(set) var listItems: [UIListItem] = []
/// Creates a `UIUnorderedList` object with text in the list items.
///
/// - Parameter text: The strings for the `UIListItems`.
public init(text: [String]) {
self.listItems = text.map { UIListItem(text: $0) }
_ = listItems.map { ul.add($0) }
}
/// Creates a `UIUnorderedList` object with children in the list items.
///
/// - Parameter elements: The elements that will be used in the `li` elements.
public init(elements: [ElementRenderable]) {
self.listItems = elements.map { UIListItem(children: [$0]) }
_ = listItems.map { ul.add($0) }
}
/// Creates a `UIUnorderedList` object with custom `UIListItems`.
///
/// - Parameter listElements: The `UIListItems` for the `UIUnorderedList` ul.
public init(with listElements: [UIListItem]) {
self.listItems = listElements
_ = listItems.map { ul.add($0) }
}
}
extension UIUnorderedList: ElementRenderable {
/// The top level `ul` element.
public var topLevelElement: UIElement {
return self.ul
}
}
// MARK: - UIOrderedList
/// A wrapper class around an `ol` (odered list) element.
open class UIOrderedList {
/// The `ol` element that is represented by this class.
public let ol = UIElement(element: .ol)
/// The list items used in the ordered list.
public private(set) var listItems: [UIListItem] = []
/// Creates a `UIOrderedList` with text in the list items.
///
/// - Parameter text: The strings for the `UIListItems`.
public init(text: [String]) {
self.listItems = text.map { UIListItem(text: $0) }
_ = listItems.map { ol.add($0) }
}
/// Creates a `UIOrderedList` with children in the list items.
///
/// - Parameter elements: The elements that will be used in the `li` elements.
public init(elements: [ElementRenderable]) {
self.listItems = elements.map { UIListItem(children: [$0]) }
_ = listItems.map { ol.add($0) }
}
/// Creates a `UIOrderedList` with custom `UIListItems`.
///
/// - Parameter listElements: The `UIListItems` for the `UIOrderedList` ol.
public init(with listElements: [UIListItem]) {
self.listItems = listElements
_ = listItems.map { ol.add($0) }
}
}
extension UIOrderedList: ElementRenderable {
/// The top level `ol` element of the object.
public var topLevelElement: UIElement {
return self.ol
}
}
// MARK: - UIListItem
/// A wrapper class for li (list) elements.
open class UIListItem {
/// The base list element of the class
public let li = UIElement(element: .li)
/// The child elements of the li.
public var children: [ElementRenderable] = []
/// The text for the list element.
public let text: String?
/// Creates a `UIListItem` with the text passed in.
///
/// - Parameter text: The text for instances `li` property.
public init(text: String? = nil) {
self.text = text
if let text = text { li.add(text) }
}
/// Creates a `UIListItem` with children and no text.
///
/// - Parameter children: The elements that are to be the children of the `li` element.
public init(children: [ElementRenderable]) {
self.text = nil
self.children = children
for child in children { li.add(child) }
}
}
extension UIListItem: ElementRenderable {
/// The `li` property of the instance of `UIListItem`.
public var topLevelElement: UIElement {
return self.li
}
}
| mit | 1e34db201f093a0c252f71068f585023 | 33.208054 | 91 | 0.64744 | 4.08741 | false | false | false | false |
ptangen/equityStatus | EquityStatus/BuyView.swift | 1 | 12621 | //
// BuyView.swift
// EquityStatus
//
// Created by Paul Tangen on 12/19/16.
// Copyright © 2016 Paul Tangen. All rights reserved.
//
import UIKit
import Charts
protocol BuyViewDelegate: class {
func openCompanyDetail(company: Company)
}
class BuyView: UIView, ChartViewDelegate {
let store = DataStore.sharedInstance
weak var delegate: BuyViewDelegate?
let barChartView = HorizontalBarChartView()
let countLabel = UILabel()
let companiesLabel = UILabel()
let pageDescLabel = UILabel()
var companiesExpectedROI = [Double]()
var companiesPreviousROI = [Double]()
var companiesTickers = [String]()
var companiesNames = [String]()
let activityIndicator = UIView()
var chartHeight = CGFloat()
let barHeight:Int = 60
override init(frame:CGRect){
super.init(frame: frame)
self.barChartView.delegate = self
self.accessibilityLabel = "buyView"
self.barChartView.accessibilityLabel = "barChartView"
self.pageLayoutLabels()
self.updateCompanyData(selectedTab: .buy) // must init chart even though there is no data yet
// if data is available, update the display
if self.store.companies.count > 0 {
self.setHeadingLabels()
self.pageLayoutWithData()
}
}
func setHeadingLabels() {
self.companiesExpectedROI.count == 1 ? (self.pageDescLabel.text = "This company has passed all 14 assessments and therefore, it's stock is considered a buy. The expected return for the equity is displayed below.") : (self.pageDescLabel.text = "These companies have passed all 14 assessments and therefore, their stock are considered buys. The expected returns for the equities are displayed below.")
self.countLabel.text = "\(self.companiesExpectedROI.count)"
self.companiesExpectedROI.count == 1 ? (self.companiesLabel.text = "company") : (self.companiesLabel.text = "companies")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func pageLayoutLabels() {
self.addSubview(self.countLabel)
self.countLabel.translatesAutoresizingMaskIntoConstraints = false
self.countLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 110).isActive = true
self.countLabel.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true
self.countLabel.rightAnchor.constraint(equalTo: self.centerXAnchor, constant: -45).isActive = true
self.countLabel.font = UIFont(name: Constants.appFont.regular.rawValue, size: Constants.fontSize.xxlarge.rawValue)
self.countLabel.textAlignment = .right
self.addSubview(self.companiesLabel)
self.companiesLabel.translatesAutoresizingMaskIntoConstraints = false
self.companiesLabel.topAnchor.constraint(equalTo: self.countLabel.bottomAnchor, constant: 0).isActive = true
self.companiesLabel.leftAnchor.constraint(equalTo: self.countLabel.leftAnchor, constant: 0).isActive = true
self.companiesLabel.rightAnchor.constraint(equalTo: self.countLabel.rightAnchor, constant: 0).isActive = true
self.companiesLabel.font = UIFont(name: Constants.appFont.bold.rawValue, size: Constants.fontSize.small.rawValue)
self.companiesLabel.textAlignment = .right
self.addSubview(self.pageDescLabel)
self.pageDescLabel.translatesAutoresizingMaskIntoConstraints = false
self.pageDescLabel.leftAnchor.constraint(equalTo: self.centerXAnchor, constant: -30).isActive = true
self.pageDescLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10).isActive = true
self.pageDescLabel.bottomAnchor.constraint(equalTo: self.companiesLabel.bottomAnchor, constant: 0).isActive = true
self.pageDescLabel.font = UIFont(name: Constants.appFont.regular.rawValue, size: Constants.fontSize.xsmall.rawValue)
self.pageDescLabel.numberOfLines = 0
}
func pageLayoutNoData() {
self.addSubview(self.activityIndicator)
self.activityIndicator.translatesAutoresizingMaskIntoConstraints = false
self.activityIndicator.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
self.activityIndicator.heightAnchor.constraint(equalToConstant: 80).isActive = true
self.activityIndicator.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
self.activityIndicator.widthAnchor.constraint(equalToConstant: 80).isActive = true
}
func pageLayoutWithData() {
self.addSubview(self.barChartView)
self.barChartView.translatesAutoresizingMaskIntoConstraints = false
self.barChartView.topAnchor.constraint(equalTo: self.pageDescLabel.bottomAnchor, constant: 24).isActive = true
self.barChartView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true
self.barChartView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
self.barChartView.heightAnchor.constraint(equalToConstant: self.chartHeight).isActive = true
}
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
let companyClickedArr = self.store.companies.filter({$0.ticker == self.companiesTickers[Int(entry.x)]})
if let companyClicked = companyClickedArr.first {
self.delegate?.openCompanyDetail(company: companyClicked)
}
}
// create array for view, same function in own and buy views
func updateCompanyData(selectedTab: Constants.EquityTabValue) {
self.companiesExpectedROI.removeAll()
self.companiesNames.removeAll()
self.companiesTickers.removeAll()
let companies = self.store.companies.filter({$0.tab == selectedTab})
for company in companies {
if let expected_roi = company.expected_roi, let previous_roi = company.previous_roi {
self.companiesExpectedROI.append(Double(expected_roi))
self.companiesPreviousROI.append(Double(previous_roi))
if companies.count == 1 {
self.companiesExpectedROI.append(Double(expected_roi))
self.companiesPreviousROI.append(Double(previous_roi))
}
} else {
self.companiesExpectedROI.append(0.0)
self.companiesPreviousROI.append(0.0)
if companies.count == 1 {
self.companiesExpectedROI.append(0.0)
self.companiesPreviousROI.append(0.0)
}
}
self.companiesNames.append(String(company.name.prefix(18)))
self.companiesTickers.append(company.ticker)
// there is a bug in the chart engine where if there is only one company
// the chart breaks, so if there is one company add it to the array twice
if companies.count == 1 {
self.companiesNames.append(String(company.name.prefix(18)))
self.companiesTickers.append(company.ticker)
}
}
self.companiesExpectedROI.reverse()
self.companiesPreviousROI.reverse()
self.companiesNames.reverse()
self.companiesTickers.reverse()
self.chartHeight = CGFloat(self.companiesNames.count * self.barHeight)
let maxChartHeight: CGFloat = UIScreen.main.bounds.height - 260 // subtract for heading and tabs at bottom
if self.chartHeight > maxChartHeight {
self.chartHeight = maxChartHeight
}
self.updateChartWithData()
}
// create array for view, same function in own and buy views
func updateChartWithData() {
let stringFormatter = ChartStringFormatter() // allow labels to be shown for bars
let percentFormatter = PercentValueFormatter() // allow labels to be shown for bars
// data and names of the bars
var dataEntries: [BarChartDataEntry] = []
var dataEntries1: [BarChartDataEntry] = []
for (index, expectedROI) in self.companiesExpectedROI.enumerated() {
let dataEntry = BarChartDataEntry(x: Double(index) , y: expectedROI)
dataEntries.append(dataEntry)
let dataEntry1 = BarChartDataEntry(x: Double(index) , y: self.companiesPreviousROI[index])
dataEntries1.append(dataEntry1)
}
stringFormatter.nameValues = self.companiesNames // labels for the y axis
// formatting, the horizontal bar chart is rotated so the axis labels are odd
barChartView.xAxis.avoidFirstLastClippingEnabled = true
barChartView.xAxis.valueFormatter = stringFormatter // allow labels to be shown for bars
barChartView.xAxis.drawGridLinesEnabled = false // hide horizontal grid lines
barChartView.xAxis.drawAxisLineEnabled = false // hide right axis
barChartView.xAxis.labelFont = UIFont(name: Constants.appFont.regular.rawValue, size: Constants.fontSize.small.rawValue)!
barChartView.xAxis.setLabelCount(stringFormatter.nameValues.count, force: false)
barChartView.xAxis.labelPosition = XAxis.LabelPosition.bottom
barChartView.rightAxis.enabled = false // hide values on bottom axis
barChartView.leftAxis.enabled = false // hide values on top axis
barChartView.animate(xAxisDuration: 0.0, yAxisDuration: 0.6)
barChartView.legend.enabled = false
if let chartDescription = barChartView.chartDescription {
chartDescription.enabled = false
}
barChartView.drawValueAboveBarEnabled = false // places values inside the bars
barChartView.leftAxis.axisMinimum = 0.0 // required to show values on the horz bars, its a bug
// format bars
let chartDataSetExpectedRIO = BarChartDataSet(values: dataEntries, label: "")
chartDataSetExpectedRIO.valueFormatter = percentFormatter // formats the values into a %
chartDataSetExpectedRIO.colors = [UIColor(red: 61/255, green: 182/255, blue: 111/255, alpha: 0.6)]
// rgb values from status green with alpha value changed
chartDataSetExpectedRIO.valueTextColor = UIColor.white
chartDataSetExpectedRIO.valueFont = UIFont(name: Constants.appFont.regular.rawValue, size: Constants.fontSize.small.rawValue)!
let chartDataSetPreviousROI = BarChartDataSet(values: dataEntries1, label: "")
chartDataSetPreviousROI.valueFormatter = percentFormatter // formats the values into a %
chartDataSetPreviousROI.colors = [UIColor(named: .statusGreen)]
chartDataSetPreviousROI.valueTextColor = UIColor.white
chartDataSetPreviousROI.valueFont = UIFont(name: Constants.appFont.regular.rawValue, size: Constants.fontSize.small.rawValue)!
let dataSets: [BarChartDataSet] = [chartDataSetExpectedRIO,chartDataSetPreviousROI]
let chartData = BarChartData(dataSets: dataSets)
let groupCount = self.companiesExpectedROI.count
let paddingBottom = 0.5
barChartView.xAxis.axisMinimum = Double(paddingBottom)
let groupSpace = 0.14
let barSpace = 0.05
let barWidth = 0.33
// (groupSpace + barSpace) * 2 + barWidth = 0.8 -> interval per "group"
chartData.barWidth = barWidth;
let groupWidth = chartData.groupWidth(groupSpace: groupSpace, barSpace: barSpace)
//print("groupWidth: \(groupWidth)") // must equal 0.9
barChartView.xAxis.axisMaximum = Double(paddingBottom) + groupWidth * Double(groupCount)
chartData.groupBars(fromX: Double(paddingBottom), groupSpace: groupSpace, barSpace: barSpace)
barChartView.notifyDataSetChanged()
if(stringFormatter.nameValues.count > 0){
self.barChartView.data = chartData
}
}
func showActivityIndicator(uiView: UIView) {
self.activityIndicator.backgroundColor = UIColor(named: .blue)
self.activityIndicator.layer.cornerRadius = 10
self.activityIndicator.clipsToBounds = true
let actInd: UIActivityIndicatorView = UIActivityIndicatorView()
actInd.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
actInd.style = UIActivityIndicatorView.Style.large
actInd.center = CGPoint(x: 40, y: 40)
self.activityIndicator.addSubview(actInd)
actInd.startAnimating()
}
}
| apache-2.0 | d2056d240de66630ce08701be07d0c9e | 49.48 | 407 | 0.684865 | 4.853846 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/SharedViews/PledgeCTAContainerView.swift | 1 | 9038 | import KsApi
import Library
import Prelude
import UIKit
protocol PledgeCTAContainerViewDelegate: AnyObject {
func pledgeCTAButtonTapped(with state: PledgeStateCTAType)
}
private enum Layout {
enum Button {
static let minHeight: CGFloat = 48.0
static let minWidth: CGFloat = 98.0
}
enum RetryButton {
static let minWidth: CGFloat = 120.0
}
enum ActivityIndicator {
static let height: CGFloat = 30
}
}
final class PledgeCTAContainerView: UIView {
// MARK: - Properties
private lazy var activityIndicator: UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
indicator.startAnimating()
return indicator
}()
private lazy var activityIndicatorContainerView: UIView = {
UIView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private(set) lazy var pledgeCTAButton: UIButton = {
UIButton(type: .custom)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private(set) lazy var retryButton: UIButton = {
UIButton(type: .custom)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var retryDescriptionLabel: UILabel = { UILabel(frame: .zero) }()
private lazy var retryStackView: UIStackView = { UIStackView(frame: .zero) }()
private lazy var rootStackView: UIStackView = {
UIStackView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var spacer: UIView = {
UIView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var subtitleLabel: UILabel = { UILabel(frame: .zero) }()
private lazy var titleAndSubtitleStackView: UIStackView = {
UIStackView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var titleLabel: UILabel = { UILabel(frame: .zero) }()
weak var delegate: PledgeCTAContainerViewDelegate?
private let viewModel: PledgeCTAContainerViewViewModelType = PledgeCTAContainerViewViewModel()
// MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
self.configureSubviews()
self.setupConstraints()
self.bindViewModel()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Styles
override func bindStyles() {
super.bindStyles()
_ = self
|> \.layoutMargins .~ .init(all: Styles.grid(3))
_ = self.layer
|> checkoutLayerCardRoundedStyle
|> \.backgroundColor .~ UIColor.ksr_white.cgColor
|> \.shadowColor .~ UIColor.ksr_black.cgColor
|> \.shadowOpacity .~ 0.12
|> \.shadowOffset .~ CGSize(width: 0, height: -1.0)
|> \.shadowRadius .~ CGFloat(1.0)
|> \.maskedCorners .~ [
CACornerMask.layerMaxXMinYCorner,
CACornerMask.layerMinXMinYCorner
]
let isAccessibilityCategory = self.traitCollection.preferredContentSizeCategory.isAccessibilityCategory
_ = self.retryButton
|> greyButtonStyle
|> UIButton.lens.title(for: .normal) %~ { _ in Strings.Retry() }
_ = self.retryStackView
|> retryStackViewStyle
_ = self.retryDescriptionLabel
|> retryDescriptionLabelStyle
_ = self.titleAndSubtitleStackView
|> titleAndSubtitleStackViewStyle
_ = self.rootStackView
|> adaptableStackViewStyle(isAccessibilityCategory)
_ = self.titleLabel
|> titleLabelStyle
_ = self.subtitleLabel
|> subtitleLabelStyle
_ = self.activityIndicator
|> activityIndicatorStyle
}
// MARK: - View Model
override func bindViewModel() {
super.bindViewModel()
self.viewModel.outputs.notifyDelegateCTATapped
.observeForUI()
.observeValues { [weak self] state in
self?.delegate?.pledgeCTAButtonTapped(with: state)
}
self.viewModel.outputs.buttonStyleType
.observeForUI()
.observeValues { [weak self] buttonStyleType in
_ = self?.pledgeCTAButton
?|> buttonStyleType.style
}
self.viewModel.outputs.pledgeCTAButtonIsHidden
.observeForUI()
.observeValues { [weak self] isHidden in
self?.animateView(self?.pledgeCTAButton, isHidden: isHidden)
}
self.activityIndicatorContainerView.rac.hidden = self.viewModel.outputs.activityIndicatorIsHidden
self.pledgeCTAButton.rac.hidden = self.viewModel.outputs.pledgeCTAButtonIsHidden
self.pledgeCTAButton.rac.title = self.viewModel.outputs.buttonTitleText
self.retryStackView.rac.hidden = self.viewModel.outputs.retryStackViewIsHidden
self.spacer.rac.hidden = self.viewModel.outputs.spacerIsHidden
self.subtitleLabel.rac.text = self.viewModel.outputs.subtitleText
self.titleAndSubtitleStackView.rac.hidden = self.viewModel.outputs.stackViewIsHidden
self.titleLabel.rac.text = self.viewModel.outputs.titleText
}
// MARK: - Configuration
func configureWith(value: PledgeCTAContainerViewData) {
self.viewModel.inputs.configureWith(value: value)
}
// MARK: Functions
private func configureSubviews() {
_ = (self.rootStackView, self)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToEdgesInParent()
_ = (self.activityIndicator, self.activityIndicatorContainerView)
|> ksr_addSubviewToParent()
_ = ([self.titleLabel, self.subtitleLabel], self.titleAndSubtitleStackView)
|> ksr_addArrangedSubviewsToStackView()
_ = ([self.retryDescriptionLabel, self.retryButton], self.retryStackView)
|> ksr_addArrangedSubviewsToStackView()
self.retryButton.setContentHuggingPriority(.required, for: .horizontal)
_ = (
[
self.retryStackView,
self.titleAndSubtitleStackView,
self.spacer,
self.pledgeCTAButton,
self.activityIndicatorContainerView
],
self.rootStackView
)
|> ksr_addArrangedSubviewsToStackView()
self.pledgeCTAButton.addTarget(
self, action: #selector(self.pledgeCTAButtonTapped), for: .touchUpInside
)
}
private func setupConstraints() {
NSLayoutConstraint.activate([
self.activityIndicator.centerXAnchor.constraint(equalTo: self.layoutMarginsGuide.centerXAnchor),
self.activityIndicator.centerYAnchor.constraint(equalTo: self.layoutMarginsGuide.centerYAnchor),
self.activityIndicatorContainerView.heightAnchor.constraint(equalToConstant: Layout.Button.minHeight),
self.pledgeCTAButton.heightAnchor.constraint(greaterThanOrEqualToConstant: Layout.Button.minHeight),
self.pledgeCTAButton.widthAnchor.constraint(greaterThanOrEqualToConstant: Layout.Button.minWidth),
self.retryButton.heightAnchor.constraint(greaterThanOrEqualToConstant: Layout.Button.minHeight),
self.retryButton.widthAnchor.constraint(greaterThanOrEqualToConstant: Layout.RetryButton.minWidth)
])
}
fileprivate func animateView(_ view: UIView?, isHidden: Bool) {
let duration = isHidden ? 0.0 : 0.18
let alpha: CGFloat = isHidden ? 0.0 : 1.0
UIView.animate(withDuration: duration, animations: {
_ = view
?|> \.alpha .~ alpha
})
}
@objc func pledgeCTAButtonTapped() {
self.viewModel.inputs.pledgeCTAButtonTapped()
}
}
// MARK: - Styles
private let activityIndicatorStyle: ActivityIndicatorStyle = { activityIndicator in
activityIndicator
|> \.color .~ UIColor.ksr_support_400
|> \.hidesWhenStopped .~ true
}
private func adaptableStackViewStyle(_ isAccessibilityCategory: Bool) -> (StackViewStyle) {
return { (stackView: UIStackView) in
let spacing: CGFloat = (isAccessibilityCategory ? Styles.grid(1) : 0)
return stackView
|> \.alignment .~ .center
|> \.axis .~ NSLayoutConstraint.Axis.horizontal
|> \.isLayoutMarginsRelativeArrangement .~ true
|> \.layoutMargins .~ UIEdgeInsets.init(topBottom: Styles.grid(3), leftRight: Styles.grid(3))
|> \.spacing .~ spacing
}
}
private let subtitleLabelStyle: LabelStyle = { label in
label
|> \.font .~ UIFont.ksr_caption1().bolded
|> \.textColor .~ UIColor.ksr_support_400
|> \.numberOfLines .~ 0
}
private let titleAndSubtitleStackViewStyle: StackViewStyle = { stackView in
stackView
|> \.axis .~ NSLayoutConstraint.Axis.vertical
|> \.isLayoutMarginsRelativeArrangement .~ true
|> \.spacing .~ Styles.gridHalf(1)
}
private let titleLabelStyle: LabelStyle = { label in
label
|> \.font .~ UIFont.ksr_callout().bolded
|> \.numberOfLines .~ 0
}
private let retryStackViewStyle: StackViewStyle = { stackView in
stackView
|> \.axis .~ .horizontal
|> \.alignment .~ .center
|> \.spacing .~ Styles.grid(3)
|> \.isLayoutMarginsRelativeArrangement .~ true
}
private let retryDescriptionLabelStyle: LabelStyle = { label in
label
|> \.textAlignment .~ .left
|> \.font .~ .ksr_headline()
|> \.lineBreakMode .~ .byWordWrapping
|> \.numberOfLines .~ 0
|> \.text %~ { _ in Strings.Content_isnt_loading_right_now() }
}
| apache-2.0 | 9c35a7e4b169b02e25521fa36642dc9f | 29.637288 | 108 | 0.701483 | 4.784542 | false | false | false | false |
ewhitley/CDAKit | CDAKit/health-data-standards/lib/models/person.swift | 1 | 2526 | //
// person.swift
// CDAKit
//
// Created by Eric Whitley on 11/30/15.
// Copyright © 2015 Eric Whitley. All rights reserved.
//
import Foundation
import Mustache
/**
Person. Generic person container. Should not use for a provider.
*/
public class CDAKPerson: CDAKPersonable, CDAKJSONInstantiable {
// MARK: CDA properties
///Prefix (Mrs., MD., etc.) (was Title)
public var prefix: String?
///First / given name
public var given_name: String?
///Family / last name
public var family_name: String?
///Suffix
public var suffix: String?
///addresses
public var addresses: [CDAKAddress] = [CDAKAddress]()
///telecoms
public var telecoms: [CDAKTelecom] = [CDAKTelecom]()
// MARK: - Initializers
public init(prefix: String? = nil, given_name: String? = nil, family_name: String? = nil, suffix: String? = nil, addresses: [CDAKAddress] = [], telecoms: [CDAKTelecom] = []){
self.prefix = prefix
self.given_name = given_name
self.family_name = family_name
self.suffix = suffix
self.addresses = addresses
self.telecoms = telecoms
}
// MARK: - Deprecated - Do not use
///Do not use - will be removed. Was used in HDS Ruby.
required public init(event: [String:Any?]) {
initFromEventList(event)
}
}
extension CDAKPerson: MustacheBoxable {
// MARK: - Mustache marshalling
var boxedValues: [String:MustacheBox] {
var vals: [String:MustacheBox] = [:]
vals = [
"prefix" : Box(prefix),
"given_name" : Box(given_name),
"family_name" : Box(family_name),
"suffix" : Box(suffix)
]
if addresses.count > 0 {
vals["addresses"] = Box(addresses)
}
if telecoms.count > 0 {
vals["telecoms"] = Box(telecoms)
}
return vals
}
public var mustacheBox: MustacheBox {
return Box(boxedValues)
}
}
extension CDAKPerson: CDAKJSONExportable {
// MARK: - JSON Generation
///Dictionary for JSON data
public var jsonDict: [String: AnyObject] {
var dict: [String: AnyObject] = [:]
if let prefix = prefix {
dict["prefix"] = prefix
}
if let given_name = given_name {
dict["given"] = given_name
}
if let family_name = family_name {
dict["family_name"] = family_name
}
if let suffix = suffix {
dict["suffix"] = suffix
}
if telecoms.count > 0 {
dict["telecoms"] = telecoms.map({$0.jsonDict})
}
if addresses.count > 0 {
dict["addresses"] = addresses.map({$0.jsonDict})
}
return dict
}
} | mit | bce026198e76ee7a3aed4d07ee06f3dc | 24.009901 | 176 | 0.623762 | 3.686131 | false | false | false | false |
timd/ProiOSTableCollectionViews | Ch17/Bounce/Scratch/BounceTests/LayoutTests.swift | 4 | 3902 | //
// LayoutTests.swift
// Bounce
//
// Created by Tim Duckett on 03/11/15.
// Copyright © 2015 Tim Duckett. All rights reserved.
//
import XCTest
@testable import Bounce
class LayoutTests: XCTestCase {
var layout: BounceLayout!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
layout = BounceLayout()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func test_WhenCalculatingRadiusForSquareCases_CalculatesCorrectly() {
// Assume:
// CV w:500, h:500
// item w:50, h:50
let cv = UICollectionView(frame: CGRectMake(0, 0, 500, 500), collectionViewLayout: layout)
layout.itemSize = CGSizeMake(50, 50)
layout.numberOfItems = 1
cv.collectionViewLayout.prepareLayout()
XCTAssertEqual(layout.radius, 475)
}
func test_WhenCalculatingRadiusForHighCases_CalculatesCorrectly() {
// Assume:
// CV w:500, h:500
// item w:50, h:50
let cv = UICollectionView(frame: CGRectMake(0, 0, 200, 500), collectionViewLayout: layout)
layout.itemSize = CGSizeMake(50, 50)
layout.numberOfItems = 1
cv.collectionViewLayout.prepareLayout()
XCTAssertEqual(layout.radius, 175)
}
func test_WhenCalculatingRadiusForWideCases_CalculatesCorrectly() {
// Assume:
// CV w:500, h:500
// item w:50, h:50
let cv = UICollectionView(frame: CGRectMake(0, 0, 500, 100), collectionViewLayout: layout)
layout.itemSize = CGSizeMake(50, 50)
layout.numberOfItems = 1
cv.collectionViewLayout.prepareLayout()
XCTAssertEqual(layout.radius, 75)
}
func test_WhenCalculatingRadiusOffset_CalculatesCorrectly() {
// Assume:
// CV w:500, h:500
// item w:50, h:50
let cv = UICollectionView(frame: CGRectMake(0, 0, 200, 500), collectionViewLayout: layout)
layout.itemSize = CGSizeMake(50, 50)
layout.numberOfItems = 2
cv.collectionViewLayout.prepareLayout()
XCTAssertEqual(layout.radiusOffset, M_PI)
layout.numberOfItems = 4
cv.collectionViewLayout.prepareLayout()
XCTAssertEqual(layout.radiusOffset, M_PI_2)
layout.numberOfItems = 3
cv.collectionViewLayout.prepareLayout()
XCTAssertEqual(layout.radiusOffset, (2 * M_PI) / 3)
}
func test_WhenCalculatingFinalCenterPoint_CalculatesCorrectly() {
let cv = UICollectionView(frame: CGRectMake(0, 0, 400, 400), collectionViewLayout: layout)
layout.itemSize = CGSizeMake(50, 50)
layout.numberOfItems = 4
let indexPath1 = NSIndexPath(forItem: 0, inSection: 0)
let indexPath2 = NSIndexPath(forItem: 1, inSection: 0)
let indexPath3 = NSIndexPath(forItem: 2, inSection: 0)
let indexPath4 = NSIndexPath(forItem: 3, inSection: 0)
let attr1 = layout.layoutAttributesForItemAtIndexPath(indexPath1)
let attr2 = layout.layoutAttributesForItemAtIndexPath(indexPath2)
let attr3 = layout.layoutAttributesForItemAtIndexPath(indexPath3)
let attr4 = layout.layoutAttributesForItemAtIndexPath(indexPath4)
XCTAssertEqual(attr1?.center, CGPointMake(200, 200))
XCTAssertEqual(attr2?.center, CGPointMake(400, 200))
XCTAssertEqual(attr3?.center, CGPointMake(200, 400))
XCTAssertEqual(attr4?.center, CGPointMake(0, 200))
}
}
| mit | d9947e1c1de716b52856ce13ab86d8a2 | 28.778626 | 111 | 0.616252 | 4.774786 | false | true | false | false |
Judy-u/Reflect | Reflect/Archiver3.swift | 4 | 789 | //
// Archiver3.swift
// Reflect
//
// Created by 成林 on 15/8/23.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import Foundation
/** 主要测试数组的归档 */
class Book3: Reflect{
var name: String!
var price: NSNumber!
class func action(){
let b1 = Book3()
b1.name = "name1"
b1.price = 18.0
let b2 = Book3()
b2.name = "name2"
b2.price = 25.5
let b3 = Book3()
b3.name = "name3"
b3.price = 17.9
let bookArr = [b1,b2,b3]
let path = Book3.save(obj: bookArr, name: "book3")
println(path)
let arr = Book3.read(name: "book3")
}
} | mit | cad774b460c2d2ea767b266cef9a66fb | 14.833333 | 59 | 0.44664 | 3.358407 | false | false | false | false |
Sadmansamee/quran-ios | Quran/DownloadNetworkRequest.swift | 1 | 832 | //
// DownloadNetworkRequest.swift
// Quran
//
// Created by Mohamed Afifi on 5/14/16.
// Copyright © 2016 Quran.com. All rights reserved.
//
import Foundation
class DownloadNetworkRequest: Request {
let task: URLSessionDownloadTask
let destination: String
let resumeDestination: String
let progress: Foundation.Progress
var onCompletion: ((Result<()>) -> Void)? = nil
init(task: URLSessionDownloadTask, destination: String, resumeDestination: String, progress: Foundation.Progress) {
self.task = task
self.destination = destination
self.resumeDestination = resumeDestination
self.progress = progress
}
func resume() {
task.resume()
}
func suspend() {
task.suspend()
}
func cancel() {
task.cancel { _ in }
}
}
| mit | 00c1cfbf88c309f92de3137e8ba005a6 | 20.307692 | 119 | 0.645006 | 4.516304 | false | false | false | false |
saagarjha/iina | iina/AppDelegate.swift | 1 | 36186 | //
// AppDelegate.swift
// iina
//
// Created by lhc on 8/7/16.
// Copyright © 2016 lhc. All rights reserved.
//
import Cocoa
import MediaPlayer
import Sparkle
let IINA_ENABLE_PLUGIN_SYSTEM = Preference.bool(for: .iinaEnablePluginSystem)
/** Max time interval for repeated `application(_:openFile:)` calls. */
fileprivate let OpenFileRepeatTime = TimeInterval(0.2)
/** Tags for "Open File/URL" menu item when "Always open file in new windows" is off. Vice versa. */
fileprivate let NormalMenuItemTag = 0
/** Tags for "Open File/URL in New Window" when "Always open URL" when "Open file in new windows" is off. Vice versa. */
fileprivate let AlternativeMenuItemTag = 1
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, SPUUpdaterDelegate {
/** Whether performed some basic initialization, like bind menu items. */
var isReady = false
/**
Becomes true once `application(_:openFile:)` or `droppedText()` is called.
Mainly used to distinguish normal launches from others triggered by drag-and-dropping files.
*/
var openFileCalled = false
var shouldIgnoreOpenFile = false
/** Cached URL when launching from URL scheme. */
var pendingURL: String?
/** Cached file paths received in `application(_:openFile:)`. */
private var pendingFilesForOpenFile: [String] = []
/** The timer for `OpenFileRepeatTime` and `application(_:openFile:)`. */
private var openFileTimer: Timer?
private var commandLineStatus = CommandLineStatus()
private var isTerminating = false
// Windows
lazy var openURLWindow: OpenURLWindowController = OpenURLWindowController()
lazy var aboutWindow: AboutWindowController = AboutWindowController()
lazy var fontPicker: FontPickerWindowController = FontPickerWindowController()
lazy var inspector: InspectorWindowController = InspectorWindowController()
lazy var historyWindow: HistoryWindowController = HistoryWindowController()
lazy var guideWindow: GuideWindowController = GuideWindowController()
lazy var vfWindow: FilterWindowController = {
let w = FilterWindowController()
w.filterType = MPVProperty.vf
return w
}()
lazy var afWindow: FilterWindowController = {
let w = FilterWindowController()
w.filterType = MPVProperty.af
return w
}()
lazy var preferenceWindowController: NSWindowController = {
var list: [NSViewController & PreferenceWindowEmbeddable] = [
PrefGeneralViewController(),
PrefUIViewController(),
PrefCodecViewController(),
PrefSubViewController(),
PrefNetworkViewController(),
PrefControlViewController(),
PrefKeyBindingViewController(),
PrefAdvancedViewController(),
// PrefPluginViewController(),
PrefUtilsViewController(),
]
if IINA_ENABLE_PLUGIN_SYSTEM {
list.insert(PrefPluginViewController(), at: 8)
}
return PreferenceWindowController(viewControllers: list)
}()
@IBOutlet weak var menuController: MenuController!
@IBOutlet weak var dockMenu: NSMenu!
private func getReady() {
menuController.bindMenuItems()
PlayerCore.loadKeyBindings()
isReady = true
}
// MARK: - SPUUpdaterDelegate
func feedURLString(for updater: SPUUpdater) -> String? {
return Preference.bool(for: .receiveBetaUpdate) ? AppData.appcastBetaLink : AppData.appcastLink
}
// MARK: - App Delegate
/// Log details about when and from what sources IINA was built.
///
/// For developers that take a development build to other machines for testing it is useful to log information that can be used to
/// distinguish between development builds.
///
/// In support of this the build populated `Info.plist` with keys giving:
/// - The build date
/// - The git branch
/// - The git commit
private func logBuildDetails() {
// Xcode refused to allow the build date in the Info.plist to use Date as the type because the
// value specified in the Info.plist is an identifier that is replaced at build time using the
// C preprocessor. So we need to convert from the ISO formatted string to a Date object.
let fromString = ISO8601DateFormatter()
// As recommended by Apple IINA's custom Info.plist keys start with the bundle identifier.
guard let infoDic = Bundle.main.infoDictionary,
let bundleIdentifier = infoDic["CFBundleIdentifier"] as? String else { return }
let keyPrefix = bundleIdentifier + ".build"
guard let branch = infoDic["\(keyPrefix).branch"] as? String,
let commit = infoDic["\(keyPrefix).commit"] as? String,
let date = infoDic["\(keyPrefix).date"] as? String,
let dateObj = fromString.date(from: date) else { return }
// Use a localized date in the log message.
let toString = DateFormatter()
toString.dateStyle = .medium
toString.timeStyle = .medium
Logger.log("Built \(toString.string(from: dateObj)) from branch \(branch), commit \(commit)")
}
func applicationWillFinishLaunching(_ notification: Notification) {
// Must setup preferences before logging so log level is set correctly.
registerUserDefaultValues()
// Start the log file by logging the version of IINA producing the log file.
let (version, build) = Utility.iinaVersion()
Logger.log("IINA \(version) Build \(build)")
// The copyright is used in the Finder "Get Info" window which is a narrow window so the
// copyright consists of multiple lines.
let copyright = Utility.iinaCopyright()
copyright.enumerateLines { line, _ in
Logger.log(line)
}
// Useful to know the versions of significant dependencies that are being used so log that
// information as well when it can be obtained.
// The version of mpv is not logged at this point because mpv does not provide a static
// method that returns the version. To obtain version related information you must
// construct a mpv object, which has side effects. So the mpv version is logged in
// applicationDidFinishLaunching to preserve the existing order of initialization.
Logger.log("FFmpeg \(String(cString: av_version_info()))")
// FFmpeg libraries and their versions in alphabetical order.
let libraries: [(name: String, version: UInt32)] = [("libavcodec", avcodec_version()), ("libavformat", avformat_version()), ("libavutil", avutil_version()), ("libswscale", swscale_version())]
for library in libraries {
// The version of FFmpeg libraries is encoded into an unsigned integer in a proprietary
// format which needs to be decoded into a string for display.
Logger.log(" \(library.name) \(AppDelegate.versionAsString(library.version))")
}
logBuildDetails()
Logger.log("App will launch")
// register for url event
NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(self.handleURLEvent(event:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
// guide window
if FirstRunManager.isFirstRun(for: .init("firstLaunchAfter\(version)")) {
guideWindow.show(pages: [.highlights])
}
// Hide Window > "Enter Full Screen" menu item, because this is already present in the Video menu
UserDefaults.standard.set(false, forKey: "NSFullScreenMenuItemEverywhere")
// handle arguments
let arguments = ProcessInfo.processInfo.arguments.dropFirst()
guard arguments.count > 0 else { return }
var iinaArgs: [String] = []
var iinaArgFilenames: [String] = []
var dropNextArg = false
Logger.log("Got arguments \(arguments)")
for arg in arguments {
if dropNextArg {
dropNextArg = false
continue
}
if arg.first == "-" {
let indexAfterDash = arg.index(after: arg.startIndex)
if indexAfterDash == arg.endIndex {
// single '-'
commandLineStatus.isStdin = true
} else if arg[indexAfterDash] == "-" {
// args starting with --
iinaArgs.append(arg)
} else {
// args starting with -
dropNextArg = true
}
} else {
// assume args starting with nothing is a filename
iinaArgFilenames.append(arg)
}
}
Logger.log("IINA arguments: \(iinaArgs)")
Logger.log("Filenames from arguments: \(iinaArgFilenames)")
commandLineStatus.parseArguments(iinaArgs)
print("IINA \(version) Build \(build)")
guard !iinaArgFilenames.isEmpty || commandLineStatus.isStdin else {
print("This binary is not intended for being used as a command line tool. Please use the bundled iina-cli.")
print("Please ignore this message if you are running in a debug environment.")
return
}
shouldIgnoreOpenFile = true
commandLineStatus.isCommandLine = true
commandLineStatus.filenames = iinaArgFilenames
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
Logger.log("App launched")
if !isReady {
getReady()
}
// show alpha in color panels
NSColorPanel.shared.showsAlpha = true
// other initializations at App level
if #available(macOS 10.12.2, *) {
NSApp.isAutomaticCustomizeTouchBarMenuItemEnabled = false
NSWindow.allowsAutomaticWindowTabbing = false
}
JavascriptPlugin.loadGlobalInstances()
let _ = PlayerCore.first
Logger.log("Using \(PlayerCore.active.mpv.mpvVersion!)")
if #available(macOS 10.13, *) {
if RemoteCommandController.useSystemMediaControl {
Logger.log("Setting up MediaPlayer integration")
RemoteCommandController.setup()
NowPlayingInfoManager.updateInfo(state: .unknown)
}
}
// if have pending open request
if let url = pendingURL {
parsePendingURL(url)
}
if !commandLineStatus.isCommandLine {
// check whether showing the welcome window after 0.1s
Timer.scheduledTimer(timeInterval: TimeInterval(0.1), target: self, selector: #selector(self.checkForShowingInitialWindow), userInfo: nil, repeats: false)
} else {
var lastPlayerCore: PlayerCore? = nil
let getNewPlayerCore = { () -> PlayerCore in
let pc = PlayerCore.newPlayerCore
self.commandLineStatus.assignMPVArguments(to: pc)
lastPlayerCore = pc
return pc
}
if commandLineStatus.isStdin {
getNewPlayerCore().openURLString("-")
} else {
let validFileURLs: [URL] = commandLineStatus.filenames.compactMap { filename in
if Regex.url.matches(filename) {
return URL(string: filename.addingPercentEncoding(withAllowedCharacters: .urlAllowed) ?? filename)
} else {
return FileManager.default.fileExists(atPath: filename) ? URL(fileURLWithPath: filename) : nil
}
}
if commandLineStatus.openSeparateWindows {
validFileURLs.forEach { url in
getNewPlayerCore().openURL(url)
}
} else {
getNewPlayerCore().openURLs(validFileURLs)
}
}
// enter PIP
if #available(macOS 10.12, *), let pc = lastPlayerCore, commandLineStatus.enterPIP {
pc.mainWindow.enterPIP()
}
}
NSRunningApplication.current.activate(options: [.activateIgnoringOtherApps, .activateAllWindows])
NSApplication.shared.servicesProvider = self
(NSApp.delegate as? AppDelegate)?.menuController?.updatePluginMenu()
}
/** Show welcome window if `application(_:openFile:)` wasn't called, i.e. launched normally. */
@objc
func checkForShowingInitialWindow() {
if !openFileCalled {
showWelcomeWindow()
}
}
private func showWelcomeWindow(checkingForUpdatedData: Bool = false) {
let actionRawValue = Preference.integer(for: .actionAfterLaunch)
let action: Preference.ActionAfterLaunch = Preference.ActionAfterLaunch(rawValue: actionRawValue) ?? .welcomeWindow
switch action {
case .welcomeWindow:
let window = PlayerCore.first.initialWindow!
window.showWindow(nil)
if checkingForUpdatedData {
window.loadLastPlaybackInfo()
window.reloadData()
}
case .openPanel:
openFile(self)
default:
break
}
}
func applicationShouldAutomaticallyLocalizeKeyEquivalents(_ application: NSApplication) -> Bool {
// Do not re-map keyboard shortcuts based on keyboard position in different locales
return false
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
guard PlayerCore.active.mainWindow.loaded || PlayerCore.active.initialWindow.loaded else { return false }
guard !PlayerCore.active.mainWindow.isWindowHidden else { return false }
return Preference.bool(for: .quitWhenNoOpenedWindow)
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
Logger.log("App should terminate")
isTerminating = true
// Normally termination happens fast enough that the user does not have time to initiate
// additional actions, however to be sure shutdown further input from the user.
Logger.log("Disabling all menus")
menuController.disableAllMenus()
// Remove custom menu items added by IINA to the dock menu. AppKit does not allow the dock
// supplied items to be changed by an application so there is no danger of removing them.
// The menu items are being removed because setting the isEnabled property to false had no
// effect under macOS 12.6.
removeAllMenuItems(dockMenu)
// If supported and enabled disable all remote media commands. This also removes IINA from
// the Now Playing widget.
if #available(macOS 10.13, *) {
if RemoteCommandController.useSystemMediaControl {
Logger.log("Disabling remote commands")
RemoteCommandController.disableAllCommands()
}
}
// Close all windows. When a player window is closed it will send a stop command to mpv to stop
// playback and unload the file.
Logger.log("Closing all windows")
for window in NSApp.windows {
window.close()
}
// Check if there are any players that are not shutdown. If all players are already shutdown
// then application termination can proceed immediately. This will happen if there is only one
// player and shutdown was initiated by typing "q" in the player window. That sends a quit
// command directly to mpv causing mpv and the player to shutdown before application
// termination is initiated.
var canTerminateNow = true
for player in PlayerCore.playerCores {
if !player.isShutdown {
canTerminateNow = false
break
}
}
if canTerminateNow {
Logger.log("All players have shutdown; proceeding with application termination")
// Tell Cocoa that it is ok to immediately proceed with termination.
return .terminateNow
}
// Shutdown of player cores involves sending the stop and quit commands to mpv. Even though
// these commands are sent to mpv using the synchronous API mpv executes them asynchronously.
// This requires IINA to wait for mpv to finish executing these commands.
Logger.log("Waiting for players to stop and shutdown")
// To ensure termination completes and the user is not required to force quit IINA, impose an
// arbitrary timeout that forces termination to complete. The expectation is that this timeout
// is never triggered. If a timeout warning is logged during termination then that needs to be
// investigated.
var timedOut = false
let timer = Timer(timeInterval: 10, repeats: false) { _ in
timedOut = true
Logger.log("Timed out waiting for players to stop and shutdown", level: .warning)
// For debugging list players that have not terminated.
for player in PlayerCore.playerCores {
let label = player.label ?? "unlabeled"
if !player.isStopped {
Logger.log("Player \(label) failed to stop", level: .warning)
} else if !player.isShutdown {
Logger.log("Player \(label) failed to shutdown", level: .warning)
}
}
// For debugging purposes we do not remove observers in case players stop or shutdown after
// the timeout has fired as knowing that occurred maybe useful for debugging why the
// termination sequence failed to complete on time.
Logger.log("Not waiting for players to shutdown; proceeding with application termination",
level: .warning)
// Tell Cocoa to proceed with termination.
NSApp.reply(toApplicationShouldTerminate: true)
}
RunLoop.main.add(timer, forMode: .common)
// Establish an observer for a player core stopping.
let center = NotificationCenter.default
var observers: [NSObjectProtocol] = []
var observer = center.addObserver(forName: .iinaPlayerStopped, object: nil, queue: .main) { note in
guard !timedOut else {
// The player has stopped after IINA already timed out, gave up waiting for players to
// shutdown, and told Cocoa to proceed with termination. AppKit will continue to process
// queued tasks during application termination even after AppKit has called
// applicationWillTerminate. So this observer can be called after IINA has told Cocoa to
// proceed with termination. When the termination sequence times out IINA does not remove
// observers as it may be useful for debugging purposes to know that a player stopped after
// the timeout as that indicates the stopping was proceeding as opposed to being permanently
// blocked. Log that this has occurred and take no further action as it is too late to
// proceed with the normal termination sequence. If the log file has already been closed
// then the message will only be printed to the console.
Logger.log("Player stopped after application termination timed out", level: .warning)
return
}
guard let player = note.object as? PlayerCore else { return }
// Now that the player has stopped it is safe to instruct the player to terminate. IINA MUST
// wait for the player to stop before instructing it to terminate because sending the quit
// command to mpv while it is still asynchronously executing the stop command can result in a
// watch later file that is missing information such as the playback position. See issue #3939
// for details.
player.shutdown()
}
observers.append(observer)
// Establish an observer for a player core shutting down.
observer = center.addObserver(forName: .iinaPlayerShutdown, object: nil, queue: .main) { _ in
guard !timedOut else {
// The player has shutdown after IINA already timed out, gave up waiting for players to
// shutdown, and told Cocoa to proceed with termination. AppKit will continue to process
// queued tasks during application termination even after AppKit has called
// applicationWillTerminate. So this observer can be called after IINA has told Cocoa to
// proceed with termination. When the termination sequence times out IINA does not remove
// observers as it may be useful for debugging purposes to know that a player shutdown after
// the timeout as that indicates shutdown was proceeding as opposed to being permanently
// blocked. Log that this has occurred and take no further action as it is too late to
// proceed with the normal termination sequence. If the log file has already been closed
// then the message will only be printed to the console.
Logger.log("Player shutdown after application termination timed out", level: .warning)
return
}
// If any player has not shutdown then continue waiting.
for player in PlayerCore.playerCores {
guard player.isShutdown else { return }
}
// All players have shutdown. Proceed with termination.
Logger.log("All players have shutdown; proceeding with application termination")
// No longer need the timer that forces termination to proceed.
timer.invalidate()
// No longer need the observers for players stopping and shutting down.
ObjcUtils.silenced {
observers.forEach {
NotificationCenter.default.removeObserver($0)
}
}
// Tell Cocoa to proceed with termination.
NSApp.reply(toApplicationShouldTerminate: true)
}
observers.append(observer)
// Instruct any players that are already stopped to start shutting down.
for player in PlayerCore.playerCores {
if player.isStopped && !player.isShutdown {
player.shutdown()
}
}
// Tell Cocoa that it is ok to proceed with termination, but wait for our reply.
return .terminateLater
}
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
// Once termination starts subsystems such as mpv are being shutdown. Accessing mpv
// once it has been instructed to shutdown can trigger a crash. MUST NOT permit
// reopening once termination has started.
guard !isTerminating else { return false }
guard !flag else { return true }
Logger.log("Handle reopen")
showWelcomeWindow(checkingForUpdatedData: true)
return true
}
func applicationWillTerminate(_ notification: Notification) {
Logger.log("App will terminate")
Logger.closeLogFile()
}
/**
When dragging multiple files to App icon, cocoa will simply call this method repeatedly.
Therefore we must cache all possible calls and handle them together.
*/
func application(_ sender: NSApplication, openFile filename: String) -> Bool {
openFileCalled = true
openFileTimer?.invalidate()
pendingFilesForOpenFile.append(filename)
openFileTimer = Timer.scheduledTimer(timeInterval: OpenFileRepeatTime, target: self, selector: #selector(handleOpenFile), userInfo: nil, repeats: false)
return true
}
/** Handle pending file paths if `application(_:openFile:)` not being called again in `OpenFileRepeatTime`. */
@objc
func handleOpenFile() {
if !isReady {
getReady()
}
// if launched from command line, should ignore openFile once
if shouldIgnoreOpenFile {
shouldIgnoreOpenFile = false
return
}
// open pending files
let urls = pendingFilesForOpenFile.map { URL(fileURLWithPath: $0) }
pendingFilesForOpenFile.removeAll()
if PlayerCore.activeOrNew.openURLs(urls) == 0 {
Utility.showAlert("nothing_to_open")
}
}
// MARK: - Accept dropped string and URL
@objc
func droppedText(_ pboard: NSPasteboard, userData:String, error: NSErrorPointer) {
if let url = pboard.string(forType: .string) {
openFileCalled = true
PlayerCore.active.openURLString(url)
}
}
// MARK: - Dock menu
func applicationDockMenu(_ sender: NSApplication) -> NSMenu? {
return dockMenu
}
/// Remove all menu items in the given menu and any submenus.
///
/// This method recursively descends through the entire tree of menu items removing all items.
/// - Parameter menu: Menu to remove items from
private func removeAllMenuItems(_ menu: NSMenu) {
for item in menu.items {
if item.hasSubmenu {
removeAllMenuItems(item.submenu!)
}
menu.removeItem(item)
}
}
// MARK: - URL Scheme
@objc func handleURLEvent(event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
openFileCalled = true
guard let url = event.paramDescriptor(forKeyword: keyDirectObject)?.stringValue else { return }
Logger.log("URL event: \(url)")
if isReady {
parsePendingURL(url)
} else {
pendingURL = url
}
}
/**
Parses the pending iina:// url.
- Parameter url: the pending URL.
- Note:
The iina:// URL scheme currently supports the following actions:
__/open__
- `url`: a url or string to open.
- `new_window`: 0 or 1 (default) to indicate whether open the media in a new window.
- `enqueue`: 0 (default) or 1 to indicate whether to add the media to the current playlist.
- `full_screen`: 0 (default) or 1 to indicate whether open the media and enter fullscreen.
- `pip`: 0 (default) or 1 to indicate whether open the media and enter pip.
- `mpv_*`: additional mpv options to be passed. e.g. `mpv_volume=20`.
Options starting with `no-` are not supported.
*/
private func parsePendingURL(_ url: String) {
Logger.log("Parsing URL \(url)")
guard let parsed = URLComponents(string: url) else {
Logger.log("Cannot parse URL using URLComponents", level: .warning)
return
}
if parsed.scheme != "iina" {
// try to open the URL directly
PlayerCore.activeOrNewForMenuAction(isAlternative: false).openURLString(url)
return
}
// handle url scheme
guard let host = parsed.host else { return }
if host == "open" || host == "weblink" {
// open a file or link
guard let queries = parsed.queryItems else { return }
let queryDict = [String: String](uniqueKeysWithValues: queries.map { ($0.name, $0.value ?? "") })
// url
guard let urlValue = queryDict["url"], !urlValue.isEmpty else {
Logger.log("Cannot find parameter \"url\", stopped")
return
}
// new_window
let player: PlayerCore
if let newWindowValue = queryDict["new_window"], newWindowValue == "1" {
player = PlayerCore.newPlayerCore
} else {
player = PlayerCore.activeOrNewForMenuAction(isAlternative: false)
}
// enqueue
if let enqueueValue = queryDict["enqueue"], enqueueValue == "1", !PlayerCore.lastActive.info.playlist.isEmpty {
PlayerCore.lastActive.addToPlaylist(urlValue)
PlayerCore.lastActive.postNotification(.iinaPlaylistChanged)
PlayerCore.lastActive.sendOSD(.addToPlaylist(1))
} else {
player.openURLString(urlValue)
}
// presentation options
if let fsValue = queryDict["full_screen"], fsValue == "1" {
// full_screeen
player.mpv.setFlag(MPVOption.Window.fullscreen, true)
} else if let pipValue = queryDict["pip"], pipValue == "1" {
// pip
if #available(macOS 10.12, *) {
player.mainWindow.enterPIP()
}
}
// mpv options
for query in queries {
if query.name.hasPrefix("mpv_") {
let mpvOptionName = String(query.name.dropFirst(4))
guard let mpvOptionValue = query.value else { continue }
Logger.log("Setting \(mpvOptionName) to \(mpvOptionValue)")
player.mpv.setString(mpvOptionName, mpvOptionValue)
}
}
Logger.log("Finished URL scheme handling")
}
}
// MARK: - Menu actions
@IBAction func openFile(_ sender: AnyObject) {
Logger.log("Menu - Open file")
let panel = NSOpenPanel()
panel.title = NSLocalizedString("alert.choose_media_file.title", comment: "Choose Media File")
panel.canCreateDirectories = false
panel.canChooseFiles = true
panel.canChooseDirectories = true
panel.allowsMultipleSelection = true
if panel.runModal() == .OK {
if Preference.bool(for: .recordRecentFiles) {
for url in panel.urls {
NSDocumentController.shared.noteNewRecentDocumentURL(url)
}
}
let isAlternative = (sender as? NSMenuItem)?.tag == AlternativeMenuItemTag
let playerCore = PlayerCore.activeOrNewForMenuAction(isAlternative: isAlternative)
if playerCore.openURLs(panel.urls) == 0 {
Utility.showAlert("nothing_to_open")
}
}
}
@IBAction func openURL(_ sender: AnyObject) {
Logger.log("Menu - Open URL")
openURLWindow.isAlternativeAction = sender.tag == AlternativeMenuItemTag
openURLWindow.showWindow(nil)
openURLWindow.resetFields()
}
@IBAction func menuNewWindow(_ sender: Any) {
PlayerCore.newPlayerCore.initialWindow.showWindow(nil)
}
@IBAction func menuOpenScreenshotFolder(_ sender: NSMenuItem) {
let screenshotPath = Preference.string(for: .screenshotFolder)!
let absoluteScreenshotPath = NSString(string: screenshotPath).expandingTildeInPath
let url = URL(fileURLWithPath: absoluteScreenshotPath, isDirectory: true)
NSWorkspace.shared.open(url)
}
@IBAction func menuSelectAudioDevice(_ sender: NSMenuItem) {
if let name = sender.representedObject as? String {
PlayerCore.active.setAudioDevice(name)
}
}
@IBAction func showPreferences(_ sender: AnyObject) {
preferenceWindowController.showWindow(self)
}
@IBAction func showVideoFilterWindow(_ sender: AnyObject) {
vfWindow.showWindow(self)
}
@IBAction func showAudioFilterWindow(_ sender: AnyObject) {
afWindow.showWindow(self)
}
@IBAction func showAboutWindow(_ sender: AnyObject) {
aboutWindow.showWindow(self)
}
@IBAction func showHistoryWindow(_ sender: AnyObject) {
historyWindow.showWindow(self)
}
@IBAction func showHighlights(_ sender: AnyObject) {
guideWindow.show(pages: [.highlights])
}
@IBAction func helpAction(_ sender: AnyObject) {
NSWorkspace.shared.open(URL(string: AppData.wikiLink)!)
}
@IBAction func githubAction(_ sender: AnyObject) {
NSWorkspace.shared.open(URL(string: AppData.githubLink)!)
}
@IBAction func websiteAction(_ sender: AnyObject) {
NSWorkspace.shared.open(URL(string: AppData.websiteLink)!)
}
private func registerUserDefaultValues() {
UserDefaults.standard.register(defaults: [String: Any](uniqueKeysWithValues: Preference.defaultPreference.map { ($0.0.rawValue, $0.1) }))
}
// MARK: - FFmpeg version parsing
/// Extracts the major version number from the given FFmpeg encoded version number.
///
/// This is a Swift implementation of the FFmpeg macro `AV_VERSION_MAJOR`.
/// - Parameter version: Encoded version number in FFmpeg proprietary format.
/// - Returns: The major version number
private static func avVersionMajor(_ version: UInt32) -> UInt32 {
version >> 16
}
/// Extracts the minor version number from the given FFmpeg encoded version number.
///
/// This is a Swift implementation of the FFmpeg macro `AV_VERSION_MINOR`.
/// - Parameter version: Encoded version number in FFmpeg proprietary format.
/// - Returns: The minor version number
private static func avVersionMinor(_ version: UInt32) -> UInt32 {
(version & 0x00FF00) >> 8
}
/// Extracts the micro version number from the given FFmpeg encoded version number.
///
/// This is a Swift implementation of the FFmpeg macro `AV_VERSION_MICRO`.
/// - Parameter version: Encoded version number in FFmpeg proprietary format.
/// - Returns: The micro version number
private static func avVersionMicro(_ version: UInt32) -> UInt32 {
version & 0xFF
}
/// Forms a string representation from the given FFmpeg encoded version number.
///
/// FFmpeg returns the version number of its libraries encoded into an unsigned integer. The FFmpeg source
/// `libavutil/version.h` describes FFmpeg's versioning scheme and provides C macros for operating on encoded
/// version numbers. Since the macros can't be used in Swift code we've had to code equivalent functions in Swift.
/// - Parameter version: Encoded version number in FFmpeg proprietary format.
/// - Returns: A string containing the version number.
private static func versionAsString(_ version: UInt32) -> String {
let major = AppDelegate.avVersionMajor(version)
let minor = AppDelegate.avVersionMinor(version)
let micro = AppDelegate.avVersionMicro(version)
return "\(major).\(minor).\(micro)"
}
}
struct CommandLineStatus {
var isCommandLine = false
var isStdin = false
var openSeparateWindows = false
var enterPIP = false
var mpvArguments: [(String, String)] = []
var iinaArguments: [(String, String)] = []
var filenames: [String] = []
mutating func parseArguments(_ args: [String]) {
mpvArguments.removeAll()
iinaArguments.removeAll()
for arg in args {
let splitted = arg.dropFirst(2).split(separator: "=", maxSplits: 1)
let name = String(splitted[0])
if (name.hasPrefix("mpv-")) {
// mpv args
let strippedName = String(name.dropFirst(4))
if strippedName == "-" {
isStdin = true
} else if splitted.count <= 1 {
mpvArguments.append((strippedName, "yes"))
} else {
mpvArguments.append((strippedName, String(splitted[1])))
}
} else {
// other args
if splitted.count <= 1 {
iinaArguments.append((name, "yes"))
} else {
iinaArguments.append((name, String(splitted[1])))
}
if name == "stdin" {
isStdin = true
}
if name == "separate-windows" {
openSeparateWindows = true
}
if name == "pip" {
enterPIP = true
}
}
}
}
func assignMPVArguments(to playerCore: PlayerCore) {
Logger.log("Setting mpv properties from arguments: \(mpvArguments)")
for arg in mpvArguments {
playerCore.mpv.setString(arg.0, arg.1)
}
}
}
@available(macOS 10.13, *)
class RemoteCommandController {
static let remoteCommand = MPRemoteCommandCenter.shared()
static var useSystemMediaControl: Bool = Preference.bool(for: .useMediaKeys)
static func setup() {
remoteCommand.playCommand.addTarget { _ in
PlayerCore.lastActive.resume()
return .success
}
remoteCommand.pauseCommand.addTarget { _ in
PlayerCore.lastActive.pause()
return .success
}
remoteCommand.togglePlayPauseCommand.addTarget { _ in
PlayerCore.lastActive.togglePause()
return .success
}
remoteCommand.stopCommand.addTarget { _ in
PlayerCore.lastActive.stop()
return .success
}
remoteCommand.nextTrackCommand.addTarget { _ in
PlayerCore.lastActive.navigateInPlaylist(nextMedia: true)
return .success
}
remoteCommand.previousTrackCommand.addTarget { _ in
PlayerCore.lastActive.navigateInPlaylist(nextMedia: false)
return .success
}
remoteCommand.changeRepeatModeCommand.addTarget { _ in
PlayerCore.lastActive.togglePlaylistLoop()
return .success
}
remoteCommand.changeShuffleModeCommand.isEnabled = false
// remoteCommand.changeShuffleModeCommand.addTarget {})
remoteCommand.changePlaybackRateCommand.supportedPlaybackRates = [0.5, 1, 1.5, 2]
remoteCommand.changePlaybackRateCommand.addTarget { event in
PlayerCore.lastActive.setSpeed(Double((event as! MPChangePlaybackRateCommandEvent).playbackRate))
return .success
}
remoteCommand.skipForwardCommand.preferredIntervals = [15]
remoteCommand.skipForwardCommand.addTarget { event in
PlayerCore.lastActive.seek(relativeSecond: (event as! MPSkipIntervalCommandEvent).interval, option: .exact)
return .success
}
remoteCommand.skipBackwardCommand.preferredIntervals = [15]
remoteCommand.skipBackwardCommand.addTarget { event in
PlayerCore.lastActive.seek(relativeSecond: -(event as! MPSkipIntervalCommandEvent).interval, option: .exact)
return .success
}
remoteCommand.changePlaybackPositionCommand.addTarget { event in
PlayerCore.lastActive.seek(absoluteSecond: (event as! MPChangePlaybackPositionCommandEvent).positionTime)
return .success
}
}
static func disableAllCommands() {
remoteCommand.playCommand.removeTarget(nil)
remoteCommand.pauseCommand.removeTarget(nil)
remoteCommand.togglePlayPauseCommand.removeTarget(nil)
remoteCommand.stopCommand.removeTarget(nil)
remoteCommand.nextTrackCommand.removeTarget(nil)
remoteCommand.previousTrackCommand.removeTarget(nil)
remoteCommand.changeRepeatModeCommand.removeTarget(nil)
remoteCommand.changeShuffleModeCommand.removeTarget(nil)
remoteCommand.changePlaybackRateCommand.removeTarget(nil)
remoteCommand.skipForwardCommand.removeTarget(nil)
remoteCommand.skipBackwardCommand.removeTarget(nil)
remoteCommand.changePlaybackPositionCommand.removeTarget(nil)
}
}
| gpl-3.0 | be82e67cb8405599c7abdc31a59a7931 | 37.992457 | 206 | 0.696366 | 4.684749 | false | false | false | false |
jingyu982887078/daily-of-programmer | WeiBo/WeiBo/Classes/View/Home/WBHomeViewController.swift | 1 | 2361 | //
// WBHomeViewController.swift
// WeiBo
//
// Created by wangjingyu on 2017/5/4.
// Copyright © 2017年 wangjingyu. All rights reserved.
//
import UIKit
fileprivate let cellId = "cellId"
class WBHomeViewController: WBBaseViewController {
///懒加载微博数据数组,1.不要考虑解包,2.不需要实例化,3.延迟创建的,这也是Swift中懒加载的好处。
lazy var statusList = [String]()
/// 加载数据
override func loadData() {
print("加载数据")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
for i in 0..<15 {
if self.isPullup {
//讲数据追加到底部
self.statusList.append("上拉 \(i)")
}else {
self.statusList.insert(i.description, at: 0)
}
}
print("刷新表格")
self.refreshControl?.endRefreshing()
//恢复上拉刷新
self.isPullup = false
//刷新表格
self.tableView?.reloadData()
}
}
///
@objc fileprivate func leftBtn() {
let vc = WBDemoViewController()
navigationController?.pushViewController(vc, animated: true)
}
}
// MARK: - 表格数据源
extension WBHomeViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return statusList.count;
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
cell.textLabel?.text = statusList[indexPath.row]
return cell
}
}
// MARK: - ****设置界面相关****
extension WBHomeViewController {
override func setupTableView(){
super.setupTableView()
//设置导航栏按钮
navItem.leftBarButtonItem = UIBarButtonItem(title: "首页", fontSize: 16, target: self, action: #selector(leftBtn))
tableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
}
}
| mit | 40d6515e57b8009d8639301ee9c7ff46 | 23.965517 | 120 | 0.550184 | 5.074766 | false | false | false | false |
GitTennis/SuccessFramework | Templates/_BusinessAppSwift_/_BusinessAppSwift_/Factories/ManagerFactory.swift | 2 | 5001 | //
// ManagerFactory.swift
// _BusinessAppSwift_
//
// Created by Gytenis Mikulenas on 31/10/2016.
// Copyright © 2016 Gytenis Mikulėnas
// https://github.com/GitTennis/SuccessFramework
//
// 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. All rights reserved.
//
import UIKit
class ManagerFactory: ManagerFactoryProtocol {
// MARK: ManagerFactoryProtocol
static func shared() -> ManagerFactoryProtocol {
return _shared
}
var userManager: UserManagerProtocol {
get {
return self._userManager
}
}
var keychainManager: KeychainManagerProtocol {
get {
return self._keychainManager
}
}
var settingsManager: SettingsManagerProtocol {
get {
return self._settingsManager
}
}
var crashManager: CrashManagerProtocol {
get {
return self._crashManager
}
}
var analyticsManager: AnalyticsManagerProtocol {
get {
return self._analyticsManager
}
}
var messageBarManager: MessageBarManagerProtocol {
get {
return self._messageBarManager
}
}
var reachabilityManager: ReachabilityManagerProtocol {
get {
return self._reachabilityManager
}
}
var networkOperationFactory: NetworkOperationFactoryProtocol {
get {
return self._networkOperationFactory
}
set {
self._networkOperationFactory = newValue
}
}
var localizationManager: LocalizationManagerProtocol {
get {
return self._localizationManager
}
}
var logManager: LogManagerProtocol {
get {
return self._logManager
}
}
var pushNotificationManager: PushNotificationManagerProtocol {
get {
return self._pushNotificationManager
}
}
// MARK:
// MARK: Internal
// MARK:
internal static let _shared: ManagerFactoryProtocol = ManagerFactory()
internal lazy var _reachabilityManager: ReachabilityManagerProtocol = ReachabilityManager()
internal lazy var _crashManager: CrashManagerProtocol = CrashManager()
internal lazy var _analyticsManager: AnalyticsManagerProtocol = AnalyticsManager()
internal lazy var _messageBarManager: MessageBarManagerProtocol = MessageBarManager()
internal lazy var _keychainManager: KeychainManagerProtocol = KeychainManager()
internal lazy var _pushNotificationManager: PushNotificationManagerProtocol = PushNotificationManager()
internal lazy var _logManager: LogManagerProtocol = LogManager()
internal lazy var _userManager: UserManagerProtocol = {
self._networkOperationFactory = NetworkOperationFactory.init(appConfig: nil, settingsManager: self._settingsManager)
let userManager: UserManagerProtocol = UserManager.init(settingsManager: self._settingsManager, networkOperationFactory: self._networkOperationFactory!, analyticsManager: self._analyticsManager, keychainManager: self._keychainManager)
self._networkOperationFactory.userManager = userManager
return userManager
}()
internal lazy var _settingsManager: SettingsManagerProtocol = {
let settingsManager = SettingsManager.init(localizationManager: self._localizationManager)
return settingsManager
}()
internal var _networkOperationFactory: NetworkOperationFactoryProtocol!
internal lazy var _localizationManager: LocalizationManagerProtocol = {
return LocalizationManager()
}()
}
| mit | 658a28bbe3376e99c74a2118a41c11fb | 29.668712 | 242 | 0.64893 | 5.772517 | false | false | false | false |
syxc/ZhihuDaily | ZhihuDaily/Classes/Views/HomeTopBannerCell.swift | 1 | 2883 | //
// HomeTopBannerCell.swift
// ZhihuDaily
//
// Copyright (c) 2016年 syxc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class HomeTopBannerCell: UITableViewCell, XRCarouselViewDelegate {
lazy var bannerView: XRCarouselView = {
let bannerView = XRCarouselView()
bannerView.clipsToBounds = true
bannerView.contentMode = .ScaleAspectFill
bannerView.changeMode = .Default
bannerView.backgroundColor = UIColor.flatWhiteColor()
return bannerView
}()
override func awakeFromNib() {
super.awakeFromNib()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
bannerView.frame = self.contentView.bounds
}
deinit {
log.info("HomeTopBannerCell deinit")
bannerView.stopTimer()
bannerView.delegate = nil
}
func setupView() {
bannerView.delegate = self
self.contentView.addSubview(bannerView)
}
/**
初始化轮播图数据
- parameter topStories: 轮播图数据
*/
func setupBannerData(topStories: [TopStory]?) {
guard let topStories = topStories else {
return
}
var imageArray: [AnyObject] = []
var titleArray: [String] = []
// 添加轮播图和标题
for topStory in topStories {
imageArray.append(topStory.image!)
titleArray.append(topStory.title!)
}
bannerView.imageArray = imageArray
bannerView.describeArray = titleArray
}
// MARK: XRCarouselViewDelegate
func carouselView(carouselView: XRCarouselView!, clickImageAtIndex index: Int) {
log.info("clickImageAtIndex=\(index)")
}
}
| mit | 348da4c5c4cb34b11a8cb2ad5c5128ac | 28.572917 | 82 | 0.710461 | 4.492089 | false | false | false | false |
codefellows/sea-b23-iOS | Interstellar/Interstellar/GameScene.swift | 1 | 3146 | //
// GameScene.swift
// Interstellar
//
// Created by Bradley Johnson on 11/6/14.
// Copyright (c) 2014 Code Fellows. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
var spaceShip = SKSpriteNode(imageNamed:"Spaceship")
var currentTime = 0.0
var previousTime = 0.0
var deltaTime = 0.0
var enemySpawnTime = 2.0
var timeSinceLastEnemySpawn = 0.0
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let starPath = NSBundle.mainBundle().pathForResource("SpaceParticle", ofType: "sks")
let starField = NSKeyedUnarchiver.unarchiveObjectWithFile(starPath!) as SKEmitterNode
starField.position = CGPoint(x: self.scene!.frame.size.width * 0.5, y: self.scene!.frame.size.height)
self.addChild(starField)
self.spaceShip.position = CGPoint(x: self.scene!.frame.size.width * 0.5, y: 100)
spaceShip.size = CGSize(width: spaceShip.size.width * 0.3, height: spaceShip.size.height * 0.3)
self.addChild(self.spaceShip)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
// if location.x < self.scene!.size.width * 0.5 {
// self.spaceShip.position = CGPoint(x: self.spaceShip.position.x - 10, y: self.spaceShip.position.y)
// }
//
// let sprite = SKSpriteNode(imageNamed:"Spaceship")
//
// sprite.xScale = 0.5
// sprite.yScale = 0.5
// sprite.position = location
//
// let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1)
//
// sprite.runAction(SKAction.repeatActionForever(action))
//
// self.addChild(sprite)
}
}
func spawnEnemy() {
var widthInt = UInt32(self.scene!.frame.width)
var randomX = arc4random_uniform(widthInt)
var mcconaugheyFeels = SKSpriteNode(imageNamed: "mcconaugheyfeels.jpg")
mcconaugheyFeels.position = CGPoint(x: CGFloat(randomX), y: 800)
mcconaugheyFeels.size = CGSize(width: mcconaugheyFeels.size.width * 0.3, height: mcconaugheyFeels.size.width * 0.4)
self.addChild(mcconaugheyFeels)
var moveAction = SKAction.moveTo(CGPoint(x: CGFloat(randomX), y: -200), duration: 2.0)
mcconaugheyFeels.runAction(moveAction)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
self.currentTime = currentTime
self.deltaTime = self.currentTime - self.previousTime
self.previousTime = self.currentTime
// println(self.deltaTime)
self.timeSinceLastEnemySpawn = self.timeSinceLastEnemySpawn + self.deltaTime
if self.timeSinceLastEnemySpawn > self.enemySpawnTime {
// println("time for an enemy")
self.timeSinceLastEnemySpawn = 0.0
self.spawnEnemy()
}
}
}
| mit | d78cf415355f291525aeeef8253dd4ce | 36.011765 | 123 | 0.620153 | 3.942356 | false | false | false | false |
apple/swift-log | 1 | 918 | // swift-tools-version:5.5
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import PackageDescription
let package = Package(
name: "swift-log",
products: [
.library(name: "Logging", targets: ["Logging"]),
],
targets: [
.target(
name: "Logging",
dependencies: []
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
]
)
| apache-2.0 | 63587de966510e5a8fd2240e17587eaa | 26.818182 | 80 | 0.503268 | 4.882979 | false | true | false | false |
|
eonil/toolbox.swift | EonilToolbox/LayoutBox/Box.swift | 1 | 746 | //
// Box.swift
// Editor3
//
// Created by Hoon H. on 2016/01/01.
// Copyright © 2016 Eonil. All rights reserved.
//
import Foundation
import CoreGraphics
extension CGFloat: BoxScalarType {
}
public struct Box: BoxType {
public typealias Scalar = CGFloat
public typealias Point = (x: Scalar, y: Scalar)
public init(min: Point, max: Point) {
precondition(min.x <= max.x)
precondition(min.y <= max.y)
self.min = min
self.max = max
}
public var min: Point
public var max: Point
}
public extension CGRect {
public func toBox() -> Box {
return Box(center: (midX, midY), size: (width, height))
}
}
| mit | f6ac537b187835b4834cec203a63be72 | 22.28125 | 71 | 0.561074 | 3.983957 | false | false | false | false |
davidbutz/ChristmasFamDuels | iOS/Boat Aware/emailInvitationsViewController.swift | 1 | 4509 | //
// emailInvitationsViewController.swift
// Christmas Fam Duels
//
// Created by Dave Butz on 10/30/16.
// Copyright © 2016 Thrive Engineering. All rights reserved.
//
import UIKit
class emailInvitationsViewController: FormViewController {
@IBOutlet weak var txtemail1: UITextField!
@IBOutlet weak var txtemail2: UITextField!
@IBOutlet weak var txtemail3: UITextField!
@IBOutlet weak var txtemail4: UITextField!
@IBOutlet weak var txtemail5: UITextField!
@IBOutlet weak var onclickSendInvitations: UIButton!
@IBAction func onClickSendInvites(sender: AnyObject) {
LoadingOverlay.shared.showOverlay(self.view);
LoadingOverlay.shared.setCaption("Sending out Invitations...");
let api = APICalls();
let appvar = ApplicationVariables.applicationvariables;
let leaguevar = LeagueVariables.leaguevariables;
let JSONObject: [String : AnyObject] = [
"login_token" : appvar.logintoken ]
//build up the email lists.
var email = "";
if(!(txtemail1.text?.isEmpty)!){
email += txtemail1.text! + ";";
}
if(!(txtemail2.text?.isEmpty)!){
email += txtemail2.text! + ";";
}
if(!(txtemail3.text?.isEmpty)!){
email += txtemail3.text! + ";";
}
if(!(txtemail4.text?.isEmpty)!){
email += txtemail4.text! + ";";
}
if(!(txtemail5.text?.isEmpty)!){
email += txtemail5.text! + ";";
}
///api/setup/league/invite/:userID/:leagueID/:email/:logintoken
api.apicallout("/api/setup/league/invite/" + appvar.userid + "/" + leaguevar.leagueID + "/" + email + "/" + appvar.logintoken , iptype: "localIPAddress", method: "GET", JSONObject: JSONObject, callback: { (response) -> () in
dispatch_async(dispatch_get_main_queue()) {
LoadingOverlay.shared.hideOverlayView();
};
let JSONResponse = response as! JSONDictionary;
if(JSONResponse["success"] as! Bool){
/*let leagueID = JSONResponse["leagueID"] as! String;
let leagueName = JSONResponse["leagueName"] as! String;
let leagueOwnerID = JSONResponse["leagueOwnerID"] as! String;
//store these deep.
let leaguevar = LeagueVariables.leaguevariables;
leaguevar.leagueID = leagueID;
leaguevar.leagueName = leagueName;
leaguevar.leagueOwnerID = leagueOwnerID;
*/
//move them along to game play
dispatch_async(dispatch_get_main_queue()) {
let inviteFriends = self.storyboard?.instantiateViewControllerWithIdentifier("viewLaunch");
self.presentViewController(inviteFriends!, animated: true, completion: nil);
}
}
});
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if (textField == txtemail1) {
txtemail2.becomeFirstResponder()
} else if (textField == txtemail2) {
txtemail3.becomeFirstResponder()
} else if (textField == txtemail3) {
txtemail4.becomeFirstResponder();
} else if (textField == txtemail4) {
txtemail5.becomeFirstResponder();
} else if (textField == txtemail5) {
// TODO Submit/Login
onClickSendInvites(textField);
}
return true
}
override func viewDidLoad() {
super.viewDidLoad()
txtemail1.resignFirstResponder();
txtemail2.resignFirstResponder();
txtemail3.resignFirstResponder();
txtemail4.resignFirstResponder();
txtemail5.resignFirstResponder();
definesPresentationContext = true;
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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.
}
*/
}
| mit | 08d8d594dac814b70cb93bb379df0d1c | 35.064 | 232 | 0.596051 | 4.800852 | false | false | false | false |
gpancio/iOS-Prototypes | VehicleID/VehicleID/Classes/BarcodeScanner.swift | 1 | 3969 | //
// BarcodeScanner.swift
// VehicleID
//
import Foundation
import AVFoundation
protocol BarcodeScannerDelegate: class {
func setupFailed(reason: String)
func didScan(value: String)
}
public class BarcodeScanner: NSObject, AVCaptureMetadataOutputObjectsDelegate {
let captureSession = AVCaptureSession()
var captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var captureLayer: AVCaptureVideoPreviewLayer?
weak var delegate: BarcodeScannerDelegate?
public func toggleLed() {
if captureDevice.hasTorch {
do {
try captureDevice.lockForConfiguration()
if captureDevice.torchMode == .Off && captureDevice.isTorchModeSupported(.On) {
captureDevice.torchMode = .On
} else {
captureDevice.torchMode = .Off
}
} catch {
return
}
}
}
public func setupCaptureSession(previewLayerFrame: CGRect) {
let deviceInput:AVCaptureDeviceInput
do {
deviceInput = try AVCaptureDeviceInput(device: captureDevice)
} catch {
delegate?.setupFailed("Failed to get AVCaptureDeviceInput")
return
}
if (captureSession.canAddInput(deviceInput)) {
// Show live feed
captureSession.addInput(deviceInput)
setupPreviewLayer(previewLayerFrame, completion: {
self.captureSession.startRunning()
self.addMetaDataCaptureOutToSession()
})
} else {
delegate?.setupFailed("Error while setting up input captureSession.")
}
}
func updateVideoOrientation(uiOrientation: UIInterfaceOrientation) {
switch uiOrientation {
case .Portrait:
captureLayer!.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
case .LandscapeLeft:
captureLayer!.connection.videoOrientation = AVCaptureVideoOrientation.LandscapeLeft
case .LandscapeRight:
captureLayer!.connection.videoOrientation = AVCaptureVideoOrientation.LandscapeRight
default:
captureLayer!.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
}
}
/**
* Handles setting up the UI to show the camera feed.
- parameter completion: Completion handler to invoke if setting up the feed was successful.
*/
private func setupPreviewLayer(capLayerFrame: CGRect, completion:() -> ()) {
self.captureLayer = AVCaptureVideoPreviewLayer(session: captureSession)
if let capLayer = self.captureLayer {
capLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
capLayer.frame = capLayerFrame
completion()
} else {
delegate?.setupFailed("An error occured beginning video capture")
}
}
// MARK: Metadata capture
/**
* Handles identifying what kind of data output we want from the session, in our case, metadata and the available types of metadata.
*/
private func addMetaDataCaptureOutToSession() {
let metadata = AVCaptureMetadataOutput()
self.captureSession.addOutput(metadata)
metadata.metadataObjectTypes = metadata.availableMetadataObjectTypes
metadata.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
}
public func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
for metadata in metadataObjects{
if let decodedData:AVMetadataMachineReadableCodeObject = metadata as? AVMetadataMachineReadableCodeObject {
delegate?.didScan(decodedData.stringValue)
self.captureSession.stopRunning()
}
}
}
}
| mit | 312225beb5220c8eacbf716f407f93f0 | 35.75 | 169 | 0.653817 | 6.280063 | false | false | false | false |
practicalswift/swift | test/SILOptimizer/let_properties_opts.swift | 14 | 14562 |
// RUN: %target-swift-frontend -module-name let_properties_opts %s -O -enforce-exclusivity=checked -emit-sil | %FileCheck -check-prefix=CHECK-WMO %s
// RUN: %target-swift-frontend -module-name let_properties_opts -primary-file %s -O -emit-sil | %FileCheck %s
// Test propagation of non-static let properties with compile-time constant values.
// TODO: Once this optimization can remove the propagated fileprivate/internal let properties or
// mark them as ones without a storage, new tests should be added here to check for this
// functionality.
// FIXME: This test is written in Swift instead of SIL, because there are some problems
// with SIL deserialization (rdar://22636911)
// Check that initializers do not contain a code to initialize fileprivate or
// internal (if used with WMO) properties, because their values are propagated into
// their uses and they cannot be accessed from other modules. Therefore the
// initialization code could be removed.
// Specifically, the initialization code for Prop1, Prop2 and Prop3 can be removed.
// CHECK-WMO-LABEL: sil @$s19let_properties_opts3FooC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Int32, @owned Foo) -> @owned Foo
// CHECK-WMO-NOT: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop1
// CHECK-WMO-NOT: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop2
// CHECK-WMO-NOT: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop3
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop0
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop1
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop2
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop3
// CHECK-WMO: return
// CHECK-WMO-LABEL: sil @$s19let_properties_opts3FooC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Int64, @owned Foo) -> @owned Foo
// CHECK-WMO-NOT: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop1
// CHECK-WMO-NOT: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop2
// CHECK-WMO-NOT: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop3
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop0
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop1
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop2
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop3
// CHECK-WMO: return
// Check that initializers do not contain a code to initialize fileprivate properties,
// because their values are propagated into their uses and they cannot be accessed
// from other modules. Therefore the initialization code could be removed.
// Specifically, the initialization code for Prop2 can be removed.
// CHECK-LABEL: sil @$s19let_properties_opts3FooC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Int32, @owned Foo) -> @owned Foo
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop0
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop1
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop2
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop3
// CHECK: return
// CHECK-LABEL: sil @$s19let_properties_opts3FooC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Int64, @owned Foo) -> @owned Foo
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop0
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop1
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop2
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop3
// CHECK: return
public class Foo {
public let Prop0: Int32 = 1
let Prop1: Int32 = 1 + 4/2 + 8
fileprivate let Prop2: Int32 = 3*7
internal let Prop3: Int32 = 4*8
public init(i:Int32) {}
public init(i:Int64) {}
}
public class Foo1 {
let Prop1: Int32
fileprivate let Prop2: Int32 = 3*7
internal let Prop3: Int32 = 4*8
public init(i:Int32) {
Prop1 = 11
}
public init(i:Int64) {
Prop1 = 1111
}
}
public struct Boo {
public let Prop0: Int32 = 1
let Prop1: Int32 = 1 + 4/2 + 8
fileprivate let Prop2: Int32 = 3*7
internal let Prop3: Int32 = 4*8
public init(i:Int32) {}
public init(i:Int64) {}
}
public class Foo2 {
internal let x: Int32
@inline(never)
init(count: Int32) {
if count < 2 {
x = 5
} else {
x = 10
}
}
}
public class C {}
struct Boo3 {
//public
let Prop0: Int32
let Prop1: Int32
fileprivate let Prop2: Int32
internal let Prop3: Int32
@inline(__always)
init(_ f1: C, _ f2: C) {
self.Prop0 = 0
self.Prop1 = 1
self.Prop2 = 2
self.Prop3 = 3
}
init(_ v: C) {
self.Prop0 = 10
self.Prop1 = 11
self.Prop2 = 12
self.Prop3 = 13
}
}
// The initializer of this struct can be defined elsewhere,
// e.g. in an extension of this struct in a different module.
public struct StructWithOnlyPublicLetProperties {
public let Prop0: Int32
public let Prop1: Int32
init(_ v: Int32, _ u: Int32) {
Prop0 = 10
Prop1 = 11
}
}
// The initializer of this struct cannot be defined outside
// of the current module, because it contains an internal stored
// property, which is impossible to initialize outside of this module.
public struct StructWithPublicAndInternalLetProperties {
public let Prop0: Int32
internal let Prop1: Int32
init(_ v: Int32, _ u: Int32) {
Prop0 = 10
Prop1 = 11
}
}
// The initializer of this struct cannot be defined elsewhere,
// because it contains a fileprivate stored property, which is
// impossible to initialize outside of this file.
public struct StructWithPublicAndInternalAndPrivateLetProperties {
public let Prop0: Int32
internal let Prop1: Int32
fileprivate let Prop2: Int32
init(_ v: Int32, _ u: Int32) {
Prop0 = 10
Prop1 = 11
Prop2 = 12
}
}
// Check that Foo1.Prop1 is not constant-folded, because its value is unknown, since it is initialized differently
// by Foo1 initializers.
// CHECK-LABEL: sil @$s19let_properties_opts13testClassLet1ys5Int32VAA4Foo1CF : $@convention(thin) (@guaranteed Foo1) -> Int32
// bb0
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop1
// CHECK-NOT: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop2
// CHECK-NOT: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop3
// CHECK: return
public func testClassLet1(_ f: Foo1) -> Int32 {
return f.Prop1 + f.Prop2 + f.Prop3
}
// Check that Foo1.Prop1 is not constant-folded, because its value is unknown, since it is initialized differently
// by Foo1 initializers.
// CHECK-LABEL: sil @$s19let_properties_opts13testClassLet1ys5Int32VAA4Foo1CzF : $@convention(thin) (@inout Foo1) -> Int32
// bb0
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop1
// CHECK-NOT: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop2
// CHECK-NOT: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop3
// CHECK: return
public func testClassLet1(_ f: inout Foo1) -> Int32 {
return f.Prop1 + f.Prop2 + f.Prop3
}
// Check that return expressions in all subsequent functions can be constant folded, because the values of let properties
// are known to be constants of simple types.
// CHECK: sil @$s19let_properties_opts12testClassLetys5Int32VAA3FooCF : $@convention(thin) (@guaranteed Foo) -> Int32
// CHECK: bb0
// CHECK: integer_literal $Builtin.Int32, 75
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
public func testClassLet(_ f: Foo) -> Int32 {
return f.Prop1 + f.Prop1 + f.Prop2 + f.Prop3
}
// CHECK-LABEL: sil @$s19let_properties_opts12testClassLetys5Int32VAA3FooCzF : $@convention(thin) (@inout Foo) -> Int32
// CHECK: bb0
// CHECK: integer_literal $Builtin.Int32, 75
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
public func testClassLet(_ f: inout Foo) -> Int32 {
return f.Prop1 + f.Prop1 + f.Prop2 + f.Prop3
}
// CHECK-LABEL: sil @$s19let_properties_opts18testClassPublicLetys5Int32VAA3FooCF : $@convention(thin) (@guaranteed Foo) -> Int32
// CHECK: bb0
// CHECK: integer_literal $Builtin.Int32, 1
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
public func testClassPublicLet(_ f: Foo) -> Int32 {
return f.Prop0
}
// CHECK-LABEL: sil @$s19let_properties_opts13testStructLetys5Int32VAA3BooVF : $@convention(thin) (Boo) -> Int32
// CHECK: bb0
// CHECK: integer_literal $Builtin.Int32, 75
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
public func testStructLet(_ b: Boo) -> Int32 {
return b.Prop1 + b.Prop1 + b.Prop2 + b.Prop3
}
// CHECK-LABEL: sil @$s19let_properties_opts13testStructLetys5Int32VAA3BooVzF : $@convention(thin) (@inout Boo) -> Int32
// CHECK: bb0
// CHECK: integer_literal $Builtin.Int32, 75
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
public func testStructLet(_ b: inout Boo) -> Int32 {
return b.Prop1 + b.Prop1 + b.Prop2 + b.Prop3
}
// CHECK-LABEL: sil @$s19let_properties_opts19testStructPublicLetys5Int32VAA3BooVF : $@convention(thin) (Boo) -> Int32
// CHECK: bb0
// CHECK: integer_literal $Builtin.Int32, 1
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
public func testStructPublicLet(_ b: Boo) -> Int32 {
return b.Prop0
}
// Check that f.x is not constant folded, because the initializer of Foo2 has multiple
// assignments to the property x with different values.
// CHECK-LABEL: sil @$s19let_properties_opts13testClassLet2ys5Int32VAA4Foo2CF : $@convention(thin) (@guaranteed Foo2) -> Int32
// bb0
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo2, #Foo2.x
// CHECK-NOT: ref_element_addr %{{[0-9]+}} : $Foo2, #Foo2.x
// CHECK-NOT: ref_element_addr %{{[0-9]+}} : $Foo2, #Foo2.x
// CHECK: return
public func testClassLet2(_ f: Foo2) -> Int32 {
return f.x + f.x
}
// Check that the sum of properties is not folded into a constant.
// CHECK-WMO-LABEL: sil hidden [noinline] @$s19let_properties_opts27testStructWithMultipleInitsys5Int32VAA4Boo3V_AFtF : $@convention(thin) (Boo3, Boo3) -> Int32
// CHECK-WMO: bb0
// No constant folding should have been performed.
// CHECK-WMO-NOT: integer_literal $Builtin.Int32, 92
// CHECK-WMO: struct_extract
// CHECK-WMO: }
@inline(never)
func testStructWithMultipleInits( _ boos1: Boo3, _ boos2: Boo3) -> Int32 {
let count1 = boos1.Prop0 + boos1.Prop1 + boos1.Prop2 + boos1.Prop3
let count2 = boos2.Prop0 + boos2.Prop1 + boos2.Prop2 + boos2.Prop3
return count1 + count2
}
public func testStructWithMultipleInitsAndInlinedInitializer() {
let things = [C()]
// This line results in inlining of the initializer Boo3(C, C) and later
// removal of this initializer by the dead function elimination pass.
// As a result, only one initializer, Boo3(C) is seen by the Let Properties Propagation
// pass. This pass may think that there is only one initializer and take the
// values of let properties assigned there as constants and try to propagate
// those values into uses. But this is wrong! The pass should be clever enough
// to detect all stores to the let properties, including those outside of
// initializers, e.g. inside inlined initializers. And if it detects all such
// stores it should understand that values of let properties in Boo3 are not
// statically known constant initializers with the same value and thus
// cannot be propagated.
let boos1 = things.map { Boo3($0, C()) }
let boos2 = things.map(Boo3.init)
print(testStructWithMultipleInits(boos1[0], boos2[0]))
}
// Since all properties are public, they can be initialized in a
// different module.
// Their values are not known and cannot be propagated.
// CHECK-LABEL: sil @$s19let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0E27WithOnlyPublicLetPropertiesVF
// CHECK: struct_extract %0 : $StructWithOnlyPublicLetProperties, #StructWithOnlyPublicLetProperties.Prop0
// CHECK: return
// CHECK-WMO-LABEL: sil @$s19let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0E27WithOnlyPublicLetPropertiesVF
// CHECK-WMO: struct_extract %0 : $StructWithOnlyPublicLetProperties, #StructWithOnlyPublicLetProperties.Prop0
// CHECK-WMO: return
public func testStructPropertyAccessibility(_ b: StructWithOnlyPublicLetProperties) -> Int32 {
return b.Prop0 + b.Prop1
}
// Properties can be initialized in a different file in the same module.
// Their values are not known and cannot be propagated,
// unless it is a WMO compilation.
// CHECK-LABEL: sil @$s19let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0E34WithPublicAndInternalLetPropertiesVF
// CHECK: struct_extract %0 : $StructWithPublicAndInternalLetProperties, #StructWithPublicAndInternalLetProperties.Prop0
// CHECK-NOT: integer_literal $Builtin.Int32, 21
// CHECK: return
// CHECK-WMO-LABEL: sil @$s19let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0E34WithPublicAndInternalLetPropertiesVF
// CHECK-WMO: integer_literal $Builtin.Int32, 21
// CHECK-WMO-NEXT: struct $Int32
// CHECK-WMO-NEXT: return
public func testStructPropertyAccessibility(_ b: StructWithPublicAndInternalLetProperties) -> Int32 {
return b.Prop0 + b.Prop1
}
// Properties can be initialized only in this file, because one of the
// properties is fileprivate.
// Therefore their values are known and can be propagated.
// CHECK: sil @$s19let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0e21WithPublicAndInternalK20PrivateLetPropertiesVF
// CHECK: integer_literal $Builtin.Int32, 33
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
// CHECK-WMO-LABEL: sil @$s19let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0e21WithPublicAndInternalK20PrivateLetPropertiesVF
// CHECK-WMO: integer_literal $Builtin.Int32, 33
// CHECK-WMO-NEXT: struct $Int32
// CHECK-WMO-NEXT: return
public func testStructPropertyAccessibility(_ b: StructWithPublicAndInternalAndPrivateLetProperties) -> Int32 {
return b.Prop0 + b.Prop1 + b.Prop2
}
// Force use of initializers, otherwise they got removed by the dead-function-elimination pass
// and the values of let properties cannot be determined.
public func useInitializers() -> StructWithOnlyPublicLetProperties {
return StructWithOnlyPublicLetProperties(1, 1)
}
public func useInitializers() -> StructWithPublicAndInternalLetProperties {
return StructWithPublicAndInternalLetProperties(1, 1)
}
public func useInitializers() -> StructWithPublicAndInternalAndPrivateLetProperties {
return StructWithPublicAndInternalAndPrivateLetProperties(1, 1)
}
struct RACStruct {
private let end = 27
var startIndex: Int { return 0 }
// CHECK-LABEL: RACStruct.endIndex.getter
// CHECK-NEXT: sil hidden @{{.*}}endIndexSivg
// CHECK-NEXT: bb0
// CHECK-NEXT: %1 = integer_literal $Builtin.Int{{.*}}, 27
// CHECK-NEXT: %2 = struct $Int (%1 : $Builtin.Int{{.*}})
// CHECK-NEXT: return %2 : $Int
var endIndex: Int { return end }
subscript(_ bitIndex: Int) -> Bool {
get { return false }
set { }
}
}
extension RACStruct : RandomAccessCollection {}
| apache-2.0 | 8da87a1489ee608bbecd77c2e27cddec | 37.52381 | 160 | 0.7089 | 3.275304 | false | true | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformKit/APIs/Fees/CryptoFeeClient.swift | 1 | 972 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import NetworkKit
final class CryptoFeeClient<FeeType: TransactionFee & Decodable> {
// MARK: - Types
private enum Endpoint {
enum Fees {
static var path: [String] {
["mempool", "fees", FeeType.cryptoType.pathComponent]
}
}
}
// MARK: - Private Properties
private let requestBuilder: RequestBuilder
private let networkAdapter: NetworkAdapterAPI
var fees: AnyPublisher<FeeType, NetworkError> {
let request = requestBuilder.get(
path: Endpoint.Fees.path
)!
return networkAdapter.perform(request: request)
}
// MARK: - Init
init(
networkAdapter: NetworkAdapterAPI = resolve(),
requestBuilder: RequestBuilder = resolve()
) {
self.requestBuilder = requestBuilder
self.networkAdapter = networkAdapter
}
}
| lgpl-3.0 | ba4406931a4e857821e7450461fd3250 | 23.275 | 69 | 0.632338 | 5.005155 | false | false | false | false |
admkopec/BetaOS | Kernel/Modules/PIT8254.swift | 1 | 4505 | //
// PIT8254.swift
// Kernel
//
// Created by Adam Kopeć on 11/18/17.
// Copyright © 2017-2018 Adam Kopeć. All rights reserved.
//
import CustomArrays
import Loggable
final class PIT8254: Module {
fileprivate let BaseFrequency = 1193182
fileprivate let CommandPort = 0x43 as UInt32
var Name: String = "PIT8254"
var description: String {
return "Legacy PIT8254 Timer Device Controller"
}
// Raw Value is the I/O port
enum TimerChannel: UInt32 {
case CHANNEL_0 = 0x40
// CHANNEL_1 is not valid
case CHANNEL_2 = 0x42
var channelSelect: ChannelSelect {
switch self {
case .CHANNEL_0: return ChannelSelect.CHANNEL0
case .CHANNEL_2: return ChannelSelect.CHANNEL2
}
}
}
// Mode / Command Register commands
enum ChannelSelect: UInt8 {
static let mask: UInt8 = 0b11000000
case CHANNEL0 = 0b00000000
case CHANNEL1 = 0b01000000
case CHANNEL2 = 0b10000000
case READBACK = 0b11000000
init(channel: UInt8) {
self.init(rawValue: channel & ChannelSelect.mask)!
}
}
enum AccessMode: UInt8 {
static let mask: UInt8 = 0b00110000
case LATCH_COUNT = 0b00000000
case LO_BYTE_ONLY = 0b00010000
case HI_BYTE_ONLY = 0b00100000
case LO_HI_BYTE = 0b00110000
init(mode: UInt8) {
self.init(rawValue: mode & AccessMode.mask)!
}
}
enum OperatingMode: UInt8 {
static let mask: UInt8 = 0b00001110
case MODE_0 = 0b00000000
case MODE_1 = 0b00000010
case MODE_2 = 0b00000100
case MODE_3 = 0b00000110
case MODE_4 = 0b00001000
case MODE_5 = 0b00001010
case MODE_6 = 0b00001100 // Actually mode 2
case MODE_7 = 0b00001110 // Actually mode 3
init(mode: UInt8) {
var value = UInt8(mode & OperatingMode.mask);
if (value == OperatingMode.MODE_6.rawValue) {
value = OperatingMode.MODE_2.rawValue
} else if (value == OperatingMode.MODE_7.rawValue) {
value = OperatingMode.MODE_3.rawValue
}
self.init(rawValue: value)!
}
}
enum NumberMode: UInt8 {
static let mask: UInt8 = 0b00000001
case BINARY = 0b00000000
case BCD = 0b00000001 // This mode is not supported
init(mode: UInt8) {
self.init(rawValue: mode & NumberMode.mask)!
}
}
init() {
setChannel(.CHANNEL_0, mode: .MODE_3, hz: 60)
}
fileprivate func toCommandByte(_ channel: ChannelSelect, _ access: AccessMode,
_ mode: OperatingMode, _ number: NumberMode) -> UInt8 {
return channel.rawValue | access.rawValue | mode.rawValue | number.rawValue
}
fileprivate func fromCommandByte(_ command: UInt8) ->
(ChannelSelect, AccessMode, OperatingMode, NumberMode) {
return (ChannelSelect(channel: command),
AccessMode(mode: command),
OperatingMode(mode: command),
NumberMode(mode: command)
)
}
fileprivate func mapChannelToSelect(_ channel: TimerChannel) -> ChannelSelect {
switch(channel) {
case .CHANNEL_0: return ChannelSelect.CHANNEL0
case .CHANNEL_2: return ChannelSelect.CHANNEL2
}
}
fileprivate func setDivisor(_ channel: TimerChannel, _ value: UInt16) {
let v = ByteArray(value)
outb(channel.rawValue, v[0])
outb(channel.rawValue, v[1])
}
fileprivate func setHz(_ channel: TimerChannel, _ hz: Int) {
let divisor = UInt16(BaseFrequency / hz)
setDivisor(channel, divisor)
}
func setChannel(_ channel: TimerChannel, mode: OperatingMode, hz: Int) {
let command = toCommandByte(mapChannelToSelect(channel), .LO_HI_BYTE, mode, .BINARY)
outb(CommandPort, command)
setHz(channel, hz)
// Enable IRQ
System.sharedInstance.interruptManager.setIrqHandler(0, handler: Handler)
}
// Interrupt Handler
public func Handler(irq: Int) {
// Do some timer specific interrupt stuff, like screen refresh or ticks
System.sharedInstance.Video.refresh()
}
}
| apache-2.0 | da6874e16c37ae353345a2d44104f242 | 29.214765 | 92 | 0.57841 | 4.066847 | false | false | false | false |
makingspace/NetworkingServiceKit | NetworkingServiceKit/Classes/Testing/ServiceStub.swift | 1 | 3890 | //
// Service.swift
// Makespace Inc.
//
// Created by Phillipe Casorla Sagot (@darkzlave) on 2/27/17.
//
//
import Foundation
/// Defines the Behavior of a stub response
///
/// - immediate: the sub returns inmediatly
/// - delayed: the stub returns after a defined number of seconds
public enum ServiceStubBehavior {
/// Return a response immediately.
case immediate
/// Return a response after a delay.
case delayed(seconds: TimeInterval)
}
private let validStatusCodes = (200...299)
/// Used for stubbing responses.
public enum ServiceStubType {
/// Builds a ServiceStubType from a HTTP Code and a local JSON file
///
/// - Parameters:
/// - jsonFile: the name of the bundled json file
/// - code: the http code. Success codes are (200..299)
public init(buildWith jsonFile:String, http code:Int) {
let response = JSONSerialization.JSONObjectWithFileName(fileName: jsonFile)
if validStatusCodes.contains(code) {
self = .success(code: code, response: response)
} else {
self = .failure(code: code, response: response)
}
}
/// The network returned a response, including status code and response.
case success(code:Int, response:[String:Any]?)
/// The network request failed with an error
case failure(code:Int, response:[String:Any]?)
}
/// Defines the scenario case that this request expects
///
/// - authenticated: service is authenticated
/// - unauthenticated: service is unauthenticated
public enum ServiceStubCase {
case authenticated(tokenInfo:[String:Any])
case unauthenticated
}
/// Defines a stub request case
public struct ServiceStubRequest {
/// URL Path to regex against upcoming requests
public let path:String
/// Optional parameters that will get compare as well against requests with the same kinda of parameters
public let parameters:[String:Any]?
public init(path:String, parameters:[String:Any]? = nil) {
self.path = path
self.parameters = parameters
}
}
/// Defines stub response for a matching API path
public struct ServiceStub {
/// A stubbed request
public let request:ServiceStubRequest
/// The type of stubbing we want to do, either a success or a failure
public let stubType:ServiceStubType
/// The behavior for this stub, if we want the request to come back sync or async
public let stubBehavior:ServiceStubBehavior
/// The type of case we want when the request gets executed, either authenticated with a token or unauthenticated
public let stubCase:ServiceStubCase
public init(execute request:ServiceStubRequest,
with type:ServiceStubType,
when stubCase:ServiceStubCase,
react behavior:ServiceStubBehavior)
{
self.request = request
self.stubType = type
self.stubBehavior = behavior
self.stubCase = stubCase
}
}
extension JSONSerialization
{
/// Builds a JSON Dictionary from a bundled json file
///
/// - Parameter fileName: the name of the json file
/// - Returns: returns a JSON dictionary
public class func JSONObjectWithFileName(fileName:String) -> [String:Any]?
{
if let path = Bundle.currentTestBundle?.path(forResource: fileName, ofType: "json"),
let jsonData = NSData(contentsOfFile: path),
let jsonResult = try! JSONSerialization.jsonObject(with: jsonData as Data, options: ReadingOptions.mutableContainers) as? [String:Any]
{
return jsonResult
}
return nil
}
}
extension Bundle {
/// Locates the first bundle with a '.xctest' file extension.
internal static var currentTestBundle: Bundle? {
return allBundles.first { $0.bundlePath.hasSuffix(".xctest") }
}
}
| mit | 0dca590e175ba9e43aa59013e1e32e04 | 30.370968 | 146 | 0.669152 | 4.647551 | false | false | false | false |
vysotsky/WhatsTheWeatherIn | WhatsTheWeatherIn/ForecastTableViewCell.swift | 1 | 1177 | //
// ForecastTableViewCell.swift
// WhatsTheWeatherIn
//
// Created by Marin Bencevic on 17/10/15.
// Copyright © 2015 marinbenc. All rights reserved.
//
import UIKit
class ForecastTableViewCell: UITableViewCell {
var forecast: ForecastEntity? {
didSet {
updateCell()
}
}
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var cityDegreesLabel: UILabel!
@IBOutlet weak var weatherMessageLabel: UILabel!
@IBOutlet weak var weatherImageOutlet: UIImageView!
fileprivate func updateCell() {
if let forecastToShow = forecast {
dateLabel.text = forecastToShow.date!.hoursString
if let temp = forecastToShow.temp {
cityDegreesLabel.text = "\(temp)°C"
}
weatherMessageLabel.text = forecastToShow.description
let imageLoader = AppDelegate.resolve(ImageLoaderType.self)
imageLoader.loadImageTo(weatherImageOutlet, url: URL(string: Constants.baseImageURL + forecastToShow.imageID! + Constants.imageExtension)!)
}
}
override func awakeFromNib() {
super.awakeFromNib()
updateCell()
}
}
| mit | 47066da02a9eb547a5d712f6cee63475 | 28.375 | 151 | 0.657021 | 4.737903 | false | false | false | false |
HarukaMa/iina | iina/Extensions.swift | 1 | 9252 | //
// Extensions.swift
// iina
//
// Created by lhc on 12/8/16.
// Copyright © 2016年 lhc. All rights reserved.
//
import Cocoa
extension NSSlider {
/** Returns the positon of knob center by point */
func knobPointPosition() -> CGFloat {
let sliderOrigin = frame.origin.x + knobThickness / 2
let sliderWidth = frame.width - knobThickness
let knobPos = sliderOrigin + sliderWidth * CGFloat((doubleValue - minValue) / (maxValue - minValue))
return knobPos
}
}
extension NSSegmentedControl {
func selectSegment(withLabel label: String) {
self.selectedSegment = -1
for i in 0..<segmentCount {
if self.label(forSegment: i) == label {
self.selectedSegment = i
}
}
}
}
func - (lhs: NSPoint, rhs: NSPoint) -> NSPoint {
return NSMakePoint(lhs.x - rhs.x, lhs.y - rhs.y)
}
extension NSSize {
var aspect: CGFloat {
get {
return width / height
}
}
/** Resize to no smaller than a min size while keeping same aspect */
func satisfyMinSizeWithSameAspectRatio(_ minSize: NSSize) -> NSSize {
if width >= minSize.width && height >= minSize.height { // no need to resize if larger
return self
} else {
return grow(toSize: minSize)
}
}
/** Resize to no larger than a max size while keeping same aspect */
func satisfyMaxSizeWithSameAspectRatio(_ maxSize: NSSize) -> NSSize {
if width <= maxSize.width && height <= maxSize.height { // no need to resize if smaller
return self
} else {
return shrink(toSize: maxSize)
}
}
func crop(withAspect aspectRect: Aspect) -> NSSize {
let targetAspect = aspectRect.value
if aspect > targetAspect { // self is wider, crop width, use same height
return NSSize(width: height * targetAspect, height: height)
} else {
return NSSize(width: width, height: width / targetAspect)
}
}
func expand(withAspect aspectRect: Aspect) -> NSSize {
let targetAspect = aspectRect.value
if aspect < targetAspect { // self is taller, expand width, use same height
return NSSize(width: height * targetAspect, height: height)
} else {
return NSSize(width: width, height: width / targetAspect)
}
}
func grow(toSize size: NSSize) -> NSSize {
let sizeAspect = size.aspect
if aspect > sizeAspect { // self is wider, grow to meet height
return NSSize(width: size.height * aspect, height: size.height)
} else {
return NSSize(width: size.width, height: size.width / aspect)
}
}
func shrink(toSize size: NSSize) -> NSSize {
let sizeAspect = size.aspect
if aspect < sizeAspect { // self is taller, shrink to meet height
return NSSize(width: size.height * aspect, height: size.height)
} else {
return NSSize(width: size.width, height: size.width / aspect)
}
}
func multiply(_ multiplier: CGFloat) -> NSSize {
return NSSize(width: width * multiplier, height: height * multiplier)
}
func add(_ multiplier: CGFloat) -> NSSize {
return NSSize(width: width + multiplier, height: height + multiplier)
}
}
extension NSRect {
func multiply(_ multiplier: CGFloat) -> NSRect {
return NSRect(x: origin.x, y: origin.y, width: width * multiplier, height: height * multiplier)
}
func centeredResize(to newSize: NSSize) -> NSRect {
return NSRect(x: origin.x - (newSize.width - size.width) / 2,
y: origin.y - (newSize.height - size.height) / 2,
width: newSize.width,
height: newSize.height)
}
func constrain(in biggerRect: NSRect) -> NSRect {
// new size
var newSize = size
if newSize.width > biggerRect.width || newSize.height > biggerRect.height {
newSize = size.shrink(toSize: biggerRect.size)
}
// new origin
var newOrigin = origin
if newOrigin.x < biggerRect.origin.x {
newOrigin.x = biggerRect.origin.x
}
if newOrigin.y < biggerRect.origin.y {
newOrigin.y = biggerRect.origin.y
}
if newOrigin.x + width > biggerRect.origin.x + biggerRect.width {
newOrigin.x = biggerRect.origin.x + biggerRect.width - width
}
if newOrigin.y + height > biggerRect.origin.y + biggerRect.height {
newOrigin.y = biggerRect.origin.y + biggerRect.height - height
}
return NSRect(origin: newOrigin, size: newSize)
}
}
extension NSPoint {
func constrain(in rect: NSRect) -> NSPoint {
let l = rect.origin.x
let r = l + rect.width
let t = rect.origin.y
let b = t + rect.height
return NSMakePoint(x.constrain(min: l, max: r), y.constrain(min: t, max: b))
}
}
extension Array {
func at(_ pos: Int) -> Element? {
if pos < count {
return self[pos]
} else {
return nil
}
}
}
extension NSMenu {
func addItem(withTitle string: String, action selector: Selector? = nil, tag: Int? = nil, obj: Any? = nil, stateOn: Bool = false) {
let menuItem = NSMenuItem(title: string, action: selector, keyEquivalent: "")
menuItem.tag = tag ?? -1
menuItem.representedObject = obj
menuItem.state = stateOn ? NSOnState : NSOffState
self.addItem(menuItem)
}
}
extension Int {
func toStr() -> String {
return "\(self)"
}
func constrain(min: Int, max: Int) -> Int {
var value = self
if self < min { value = min }
if self > max { value = max }
return value
}
}
extension CGFloat {
func constrain(min: CGFloat, max: CGFloat) -> CGFloat {
var value = self
if self < min { value = min }
if self > max { value = max }
return value
}
var unifiedDouble: Double {
get {
return self == 0 ? 0 : (self > 0 ? 1 : -1)
}
}
}
extension Double {
func toStr(format: String? = nil) -> String {
if let f = format {
return String(format: f, self)
} else {
return "\(self)"
}
}
func constrain(min: Double, max: Double) -> Double {
var value = self
if self < min { value = min }
if self > max { value = max }
return value
}
func prettyFormat() -> String {
if truncatingRemainder(dividingBy: 1) == 0 {
return "\(Int(self))"
} else {
return "\(self)"
}
}
}
extension NSColor {
var mpvColorString: String {
get {
return "\(self.redComponent)/\(self.greenComponent)/\(self.blueComponent)/\(self.alphaComponent)"
}
}
convenience init?(mpvColorString: String) {
let splitted = mpvColorString.characters.split(separator: "/").map { (seq) -> Double? in
return Double(String(seq))
}
// check nil
if (!splitted.contains {$0 == nil}) {
if splitted.count == 3 { // if doesn't have alpha value
self.init(red: CGFloat(splitted[0]!), green: CGFloat(splitted[1]!), blue: CGFloat(splitted[2]!), alpha: CGFloat(1))
} else if splitted.count == 4 { // if has alpha value
self.init(red: CGFloat(splitted[0]!), green: CGFloat(splitted[1]!), blue: CGFloat(splitted[2]!), alpha: CGFloat(splitted[3]!))
} else {
return nil
}
} else {
return nil
}
}
}
extension NSMutableAttributedString {
convenience init?(linkTo url: String, text: String, font: NSFont) {
self.init(string: text)
let range = NSRange(location: 0, length: self.length)
let nsurl = NSURL(string: url)!
self.beginEditing()
self.addAttribute(NSLinkAttributeName, value: nsurl, range: range)
self.addAttribute(NSFontAttributeName, value: font, range: range)
self.endEditing()
}
}
extension UserDefaults {
func mpvColor(forKey key: String) -> String? {
guard let data = self.data(forKey: key) else { return nil }
guard let color = NSUnarchiver.unarchiveObject(with: data) as? NSColor else { return nil }
return color.usingColorSpace(.deviceRGB)?.mpvColorString
}
}
extension NSData {
func md5() -> NSString {
let digestLength = Int(CC_MD5_DIGEST_LENGTH)
let md5Buffer = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLength)
CC_MD5(bytes, CC_LONG(length), md5Buffer)
let output = NSMutableString(capacity: Int(CC_MD5_DIGEST_LENGTH * 2))
for i in 0..<digestLength {
output.appendFormat("%02x", md5Buffer[i])
}
return NSString(format: output)
}
}
extension Data {
var md5: String {
get {
return (self as NSData).md5() as String
}
}
var chksum64: UInt64 {
get {
let count64 = self.count / MemoryLayout<UInt64>.size
return self.withUnsafeBytes{ (ptr: UnsafePointer<UInt64>) -> UInt64 in
let bufferPtr = UnsafeBufferPointer(start: ptr, count: count64)
return bufferPtr.reduce(UInt64(0), &+)
}
}
}
func saveToFolder(_ url: URL, filename: String) -> URL? {
let fileUrl = url.appendingPathComponent(filename)
do {
try self.write(to: fileUrl)
} catch {
Utility.showAlert("error_saving_file", arguments: ["data", filename])
return nil
}
return fileUrl
}
}
extension CharacterSet {
static let urlAllowed = CharacterSet.urlHostAllowed
.union(.urlUserAllowed)
.union(.urlPasswordAllowed)
.union(.urlPathAllowed)
.union(.urlQueryAllowed)
.union(.urlFragmentAllowed)
}
extension NSMenuItem {
static let dummy = NSMenuItem(title: "Dummy", action: nil, keyEquivalent: "")
}
| gpl-3.0 | d5f32dadc93f271b28e83556d459819a | 26.445104 | 134 | 0.63715 | 3.863409 | false | false | false | false |
mokagio/CircularButtons | CircularButtons/UIView+Drawing.swift | 1 | 1660 | import UIKit
/*
A `UIView` extension adding some drawing methods
*/
extension UIView {
func drawCircleInRect(rect: CGRect, width: CGFloat, color: UIColor) {
let insetRect = CGRectInset(rect, width / 2, width / 2)
let borderPath = UIBezierPath(ovalInRect: insetRect)
borderPath.lineWidth = width
color.setStroke()
borderPath.stroke()
}
func drawHorizontalLineAtCenterOfRect(rect: CGRect, lineWidth: CGFloat, color: UIColor, ratio: CGFloat) {
let path = UIBezierPath()
let width: CGFloat = min(bounds.width, bounds.height) * ratio
path.lineWidth = lineWidth
path.moveToPoint(CGPoint(x: bounds.width / 2 - width / 2, y: bounds.height / 2))
path.addLineToPoint(CGPoint(x: bounds.width / 2 + width / 2, y: bounds.height / 2))
color.setStroke()
path.stroke()
}
func drawVerticalLineAtCenterOfRect(rect: CGRect, lineWidth: CGFloat, color: UIColor, ratio: CGFloat) {
let path = UIBezierPath()
let height: CGFloat = min(bounds.width, bounds.height) * ratio
path.lineWidth = lineWidth
path.moveToPoint(CGPoint(x: bounds.width / 2, y: bounds.height / 2 - height / 2))
path.addLineToPoint(CGPoint(x: bounds.width / 2, y: bounds.height / 2 + height / 2))
color.setStroke()
path.stroke()
}
func drawPlusAtCenterOfRect(rect: CGRect, lineWidth: CGFloat, color: UIColor, ratio: CGFloat) {
drawHorizontalLineAtCenterOfRect(rect, lineWidth: lineWidth, color: color, ratio: ratio)
drawVerticalLineAtCenterOfRect(rect, lineWidth: lineWidth, color: color, ratio: ratio)
}
}
| mit | b782f7a7937c2ae144ee74ca8aeb1374 | 39.487805 | 109 | 0.662651 | 4.18136 | false | false | false | false |
KinoAndWorld/DailyMood | CustomView/MainBottomView.swift | 1 | 1527 | //
// MainBottomView.swift
// DailyMood
//
// Created by kino on 14-7-11.
// Copyright (c) 2014 kino. All rights reserved.
//
import UIKit
@IBDesignable class MainBottomView: UIView {
@IBOutlet var addButton:UIButton
var backColor:UIColor?
@IBInspectable var borderColor: UIColor = UIColor.clearColor() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
//addButton block
typealias AddButtonBlock = (button:UIButton)->Void
var addButtonAction:AddButtonBlock? = nil
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
backColor = self.backgroundColor
self.backgroundColor = UIColor.grayColor()
}
override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
self.backgroundColor = backColor
var touch:UITouch = event.allTouches().anyObject() as UITouch
var point:CGPoint = touch.locationInView(self)
println("x:\(point.x) y:\(point.y)")
if(point.x >= 0 &&
point.y >= 0 &&
point.x <= addButton.frame.size.width &&
point.y <= addButton.frame.size.height){
println("ok")
addButtonAction?(button: addButton)
}
}
}
| mit | 5b99f84040010c91612ffbe2e0b413d2 | 24.881356 | 76 | 0.605108 | 4.669725 | false | false | false | false |
apptentive/apptentive-ios | Example/iOSExample/AppDelegate.swift | 1 | 1420 | //
// AppDelegate.swift
// ApptentiveExample
//
// Created by Frank Schmitt on 8/6/15.
// Copyright (c) 2015 Apptentive, Inc. All rights reserved.
//
import UIKit
import Apptentive
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UITabBarControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let configuration = ApptentiveConfiguration(apptentiveKey: "<#Your Apptentive Key#>", apptentiveSignature: "<#Your Apptentive Signature#>") {
precondition(configuration.apptentiveKey != "<#Your Apptentive Key#>" && configuration.apptentiveSignature != "<#Your Apptentive Signature#>", "Please set your Apptentive key and signature above")
Apptentive.register(with: configuration)
}
if let tabBarController = self.window?.rootViewController as? UITabBarController {
tabBarController.delegate = self
}
return true
}
// MARK: Tab bar controller delegate
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
if tabBarController.viewControllers?.firstIndex(of: viewController) ?? 0 == 0 {
Apptentive.shared.engage(event: "photos_tab_selected", from: tabBarController)
} else {
Apptentive.shared.engage(event: "favorites_tab_selected", from: tabBarController)
}
}
}
| bsd-3-clause | 91faf23b846a26eddd0a37d0ddc7871a | 33.634146 | 199 | 0.761268 | 4.565916 | false | true | false | false |
nerdyc/Squeal | Tests/StatementSpec.swift | 1 | 12969 | import Quick
import Nimble
import Squeal
class StatementSpec: QuickSpec {
override func spec() {
var database : Database!
var statement : Statement!
beforeEach {
database = Database()
try! database.execute("CREATE TABLE people (personId INTEGER PRIMARY KEY, name TEXT, age REAL, is_adult INTEGER, photo BLOB)")
try! database.execute("INSERT INTO people (name, age, is_adult, photo) VALUES (\"Amelia\", 1.5, 0, NULL),(\"Brian\", 43.375, 1, X''),(\"Cara\", NULL, 1, X'696D616765')")
// 696D616765 is "image" in Hex.
}
afterEach {
statement = nil
database = nil
}
#if arch(x86_64) || arch(arm64)
// this test only works on 64-bit architectures because weak references are cleared immediately on 64-bit runtimes, but
// not on 32-bit. Probably because of tagged pointers?
it("retains the database until the statement has been finalized") {
statement = try! database.prepareStatement("SELECT personId, name, age, photo FROM people")
weak var db = database
// remove the last non-weak external reference to the database; only the statement has retained it.
database = nil
expect(db).notTo(beNil())
// now release the statement, which should release the last hold on the database.
statement = nil
expect(db).to(beNil())
}
#endif
// =============================================================================================================
// MARK:- Columns
describe(".columnCount, .columnNames, etc.") {
beforeEach {
statement = try! database.prepareStatement("SELECT personId, name, age, photo FROM people")
}
it("describe the selected columns") {
expect(statement.columnCount).to(equal(4))
expect(statement.columnNames).to(equal(["personId", "name", "age", "photo"]))
expect(statement.indexOfColumnNamed("personId")).to(equal(0))
expect(statement.indexOfColumnNamed("name")).to(equal(1))
expect(statement.indexOfColumnNamed("age")).to(equal(2))
expect(statement.indexOfColumnNamed("photo")).to(equal(3))
expect(statement.nameOfColumnAtIndex(0)).to(equal("personId"));
expect(statement.nameOfColumnAtIndex(1)).to(equal("name"));
expect(statement.nameOfColumnAtIndex(2)).to(equal("age"));
expect(statement.nameOfColumnAtIndex(3)).to(equal("photo"));
}
}
// =============================================================================================================
// MARK:- Current Row
describe(".dictionaryValue") {
beforeEach {
statement = try! database.prepareStatement("SELECT personId, name, age, photo FROM people")
}
it("returns row values in a dictionary") {
expect(try! statement.next()).to(beTruthy())
// 0: id:1, name:Amelia, age:1.5, photo:NULL
expect(statement.dictionaryValue["personId"] as? Int64).to(equal(1))
expect(statement.dictionaryValue["name"] as? String).to(equal("Amelia"))
expect(statement.dictionaryValue["age"] as? Double).to(equal(1.5))
expect(statement.dictionaryValue["photo"]).to(beNil())
// NULL columns aren't included in resulting dictionary
expect(statement.dictionaryValue.keys.sorted()).to(equal(["age", "name", "personId"]))
}
}
describe(".valueOf()") {
beforeEach {
statement = try! database.prepareStatement("SELECT personId, name, age, photo FROM people")
}
it("returns the value at the index") {
expect(try! statement.next()).to(equal(true))
expect(statement.valueOf("personId") as? Int64).to(equal(1))
expect(statement.valueOf("name") as? String).to(equal("Amelia"))
expect(statement.valueOf("age") as? Double).to(equal(1.5))
expect(statement.valueOf("photo")).to(beNil())
}
}
describe(".[columnName]") {
beforeEach {
statement = try! database.prepareStatement("SELECT personId, name, age, photo FROM people")
}
it("returns the value at the index") {
expect(try! statement.next()).to(equal(true))
expect(statement["personId"] as? Int64).to(equal(1))
expect(statement["name"] as? String).to(equal("Amelia"))
expect(statement["age"] as? Double).to(equal(1.5))
expect(statement["photo"]).to(beNil())
}
}
describe(".values") {
beforeEach {
statement = try! database.prepareStatement("SELECT personId, name, age, photo FROM people")
}
it("returns row values in a dictionary") {
expect(try! statement.next()).to(equal(true))
// 0: id:1, name:Amelia, age:1.5, photo:NULL
expect(statement.values[0] as? Int64).to(equal(1))
expect(statement.values[1] as? String).to(equal("Amelia"))
expect(statement.values[2] as? Double).to(equal(1.5))
expect(statement.values[3]).to(beNil())
}
}
describe(".valueAtIndex(columnIndex:)") {
beforeEach {
statement = try! database.prepareStatement("SELECT personId, name, age, photo FROM people")
}
it("returns the value at the index") {
expect(try! statement.next()).to(equal(true))
expect(statement.valueAtIndex(0) as? Int64).to(equal(1))
expect(statement.valueAtIndex(1) as? String).to(equal("Amelia"))
expect(statement.valueAtIndex(2) as? Double).to(equal(1.5))
expect(statement.valueAtIndex(3)).to(beNil())
}
}
describe(".[columnIndex]") {
beforeEach {
statement = try! database.prepareStatement("SELECT personId, name, age, photo FROM people")
}
it("returns the value at the index") {
expect(try! statement.next()).to(equal(true))
expect(statement[0] as? Int64).to(equal(1))
expect(statement[1] as? String).to(equal("Amelia"))
expect(statement[2] as? Double).to(equal(1.5))
expect(statement[3]).to(beNil())
}
}
// =============================================================================================================
// MARK:- STEPS
describe(".query()") {
beforeEach {
statement = try! database.prepareStatement("SELECT personId, name, age, photo FROM people WHERE personId > ?")
try! statement.bind([1])
}
it("iterates through each row of the statement") {
let ids = try! statement.select { $0.int64ValueAtIndex(0) ?? 0 }
expect(ids).to(equal([2, 3]))
// now prove that it resets the statement
let sameIds = try! statement.select { $0.int64ValueAtIndex(0) ?? 0 }
expect(sameIds).to(equal([2, 3]))
}
}
describe(".query(parameters:)") {
beforeEach {
statement = try! database.prepareStatement("SELECT personId, name, age, photo FROM people WHERE personId > ?")
}
it("clears parameters and iterates through each step of the statement") {
try! statement.bind([3]) // bind another value to prove the value is cleared
let ids = try! statement.select([1]) { $0.int64ValueAtIndex(0) ?? 0 }
expect(ids).to(equal([2, 3]))
}
}
describe("next()") {
beforeEach {
statement = try! database.prepareStatement("SELECT personId, name, age, photo FROM people")
}
it("advances to the next row, returning false when there are no more rows") {
expect(try! statement.next()).to(equal(true))
// 0: id:1, name:Amelia, age:1.5, photo:NULL
expect(statement.intValueAtIndex(0)).to(equal(1))
expect(statement.intValue("personId")).to(equal(1))
expect(statement.stringValueAtIndex(1)).to(equal("Amelia"))
expect(statement.stringValue("name")).to(equal("Amelia"))
expect(statement.realValueAtIndex(2)).to(equal(1.5))
expect(statement.realValue("age")).to(equal(1.5))
expect(statement.blobValueAtIndex(3)).to(beNil())
expect(statement.blobValue("photo")).to(beNil())
// 1: id:2, Brian, age:43.375, photo:''
expect(try! statement.next()).to(equal(true))
expect(statement.intValueAtIndex(0)).to(equal(2))
expect(statement.intValue("personId")).to(equal(2))
expect(statement.stringValueAtIndex(1)).to(equal("Brian"))
expect(statement.stringValue("name")).to(equal("Brian"))
expect(statement.realValueAtIndex(2)).to(equal(43.375))
expect(statement.realValue("age")).to(equal(43.375))
expect(statement.blobValueAtIndex(3)).to(equal(Data()))
expect(statement.blobValue("photo")).to(equal(Data()))
// 2: id:3, name:Cara, age:nil, photo:X'696D616765' ("image")
expect(try! statement.next()).to(equal(true))
expect(statement.intValueAtIndex(0)).to(equal(3))
expect(statement.intValue("personId")).to(equal(3))
expect(statement.stringValueAtIndex(1)).to(equal("Cara"))
expect(statement.stringValue("name")).to(equal("Cara"))
expect(statement.realValueAtIndex(2)).to(beNil())
expect(statement.realValue("age")).to(beNil())
expect(statement.blobValueAtIndex(3)).to(equal("image".data(using: String.Encoding.utf8)))
expect(statement.blobValue("photo")).to(equal("image".data(using: String.Encoding.utf8)))
expect(try! statement.next()).to(equal(false))
}
}
// =============================================================================================================
// MARK:- Parameters
describe("reset()") {
beforeEach {
statement = try! database.prepareStatement("SELECT * FROM people WHERE name IS ?")
try! statement.bind(["Brian"])
expect(try! statement.next()) == true
try! statement.reset()
}
it("resets the statement so it can be executed again") {
expect(try! statement.next()).to(equal(true))
expect(statement.stringValue("name")).to(equal("Brian"))
}
}
describe("parameterCount") {
beforeEach {
statement = try! database.prepareStatement("SELECT * FROM people WHERE name IS ? AND age > ?")
}
it("returns the number of parameters") {
expect(statement.parameterCount).to(equal(2))
}
}
// =============================================================================================================
// MARK:- Named Parameters
describe("indexOfParameterNamed(name:)") {
beforeEach {
statement = try! database.prepareStatement("SELECT * FROM people WHERE name IS $NAME")
}
it("returns the index of the parameter when it exists") {
expect(statement.indexOfParameterNamed("$NAME")).to(equal(1))
}
it("returns nil when it doesn't exist") {
expect(statement.indexOfParameterNamed("$NOPE")).to(beNil())
}
}
}
}
| mit | 97a4a3242a344c6af796352cff8c8996 | 42.814189 | 181 | 0.493793 | 4.934932 | false | false | false | false |
Azure/azure-mobile-apps-quickstarts | client/iOS-Swift/ZUMOAPPNAME/ZUMOAPPNAME/ToDoTableViewController.swift | 1 | 10669 | // ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
import CoreData
class ToDoTableViewController: UITableViewController, NSFetchedResultsControllerDelegate, ToDoItemDelegate {
var table : MSSyncTable?
var store : MSCoreDataStore?
lazy var fetchedResultController: NSFetchedResultsController<NSFetchRequestResult> = {
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "TodoItem")
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext!
// show only non-completed items
fetchRequest.predicate = NSPredicate(format: "complete != true")
// sort by item text
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)]
// Note: if storing a lot of data, you should specify a cache for the last parameter
// for more information, see Apple's documentation: http://go.microsoft.com/fwlink/?LinkId=524591&clcid=0x409
let resultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
resultsController.delegate = self;
return resultsController
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let client = MSClient(applicationURLString: "ZUMOAPPURL")
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext!
self.store = MSCoreDataStore(managedObjectContext: managedObjectContext)
client.syncContext = MSSyncContext(delegate: nil, dataSource: self.store, callback: nil)
self.table = client.syncTable(withName: "TodoItem")
self.refreshControl?.addTarget(self, action: #selector(ToDoTableViewController.onRefresh(_:)), for: UIControlEvents.valueChanged)
var error : NSError? = nil
do {
try self.fetchedResultController.performFetch()
} catch let error1 as NSError {
error = error1
print("Unresolved error \(error), \(error?.userInfo)")
abort()
}
// Refresh data on load
self.refreshControl?.beginRefreshing()
self.onRefresh(self.refreshControl)
}
func onRefresh(_ sender: UIRefreshControl!) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
self.table!.pull(with: self.table?.query(), queryId: "AllRecords") {
(error) -> Void in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if error != nil {
// A real application would handle various errors like network conditions,
// server conflicts, etc via the MSSyncContextDelegate
print("Error: \((error! as NSError).description)")
// We will just discard our changes and keep the servers copy for simplicity
if let opErrors = (error! as NSError).userInfo[MSErrorPushResultKey] as? Array<MSTableOperationError> {
for opError in opErrors {
print("Attempted operation to item \(opError.itemId)")
if (opError.operation == MSTableOperationTypes() || opError.operation == .delete) {
print("Insert/Delete, failed discarding changes")
opError.cancelOperationAndDiscardItem(completion: nil)
} else {
print("Update failed, reverting to server's copy")
opError.cancelOperationAndUpdateItem(opError.serverItem!, completion: nil)
}
}
}
}
self.refreshControl?.endRefreshing()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Table Controls
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool
{
return true
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle
{
return UITableViewCellEditingStyle.delete
}
override func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String?
{
return "Complete"
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
let record = self.fetchedResultController.object(at: indexPath) as! NSManagedObject
var item = self.store!.tableItem(from: record)
item["complete"] = true
UIApplication.shared.isNetworkActivityIndicatorVisible = true
self.table!.update(item) { (error) -> Void in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if error != nil {
print("Error: \((error! as NSError).description)")
return
}
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if let sections = self.fetchedResultController.sections {
return sections[section].numberOfObjects
}
return 0;
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let CellIdentifier = "Cell"
var cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier, for: indexPath)
cell = configureCell(cell, indexPath: indexPath)
return cell
}
func configureCell(_ cell: UITableViewCell, indexPath: IndexPath) -> UITableViewCell {
let item = self.fetchedResultController.object(at: indexPath) as! NSManagedObject
// Set the label on the cell and make sure the label color is black (in case this cell
// has been reused and was previously greyed out
if let text = item.value(forKey: "text") as? String {
cell.textLabel!.text = text
} else {
cell.textLabel!.text = "?"
}
cell.textLabel!.textColor = UIColor.black
return cell
}
// MARK: Navigation
@IBAction func addItem(_ sender : AnyObject) {
self.performSegue(withIdentifier: "addItem", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any!)
{
if segue.identifier == "addItem" {
let todoController = segue.destination as! ToDoItemViewController
todoController.delegate = self
}
}
// MARK: - ToDoItemDelegate
func didSaveItem(_ text: String)
{
if text.isEmpty {
return
}
// We set created at to now, so it will sort as we expect it to post the push/pull
let itemToInsert = ["text": text, "complete": false, "__createdAt": Date()] as [String : Any]
UIApplication.shared.isNetworkActivityIndicatorVisible = true
self.table!.insert(itemToInsert) {
(item, error) in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if error != nil {
print("Error: " + (error! as NSError).description)
}
}
}
// MARK: - NSFetchedResultsDelegate
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
DispatchQueue.main.async(execute: { () -> Void in
self.tableView.beginUpdates()
});
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
DispatchQueue.main.async(execute: { () -> Void in
let indexSectionSet = IndexSet(integer: sectionIndex)
if type == .insert {
self.tableView.insertSections(indexSectionSet, with: .fade)
} else if type == .delete {
self.tableView.deleteSections(indexSectionSet, with: .fade)
}
})
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
DispatchQueue.main.async(execute: { () -> Void in
switch type {
case .insert:
self.tableView.insertRows(at: [newIndexPath!], with: .fade)
case .delete:
self.tableView.deleteRows(at: [indexPath!], with: .fade)
case .move:
self.tableView.deleteRows(at: [indexPath!], with: .fade)
self.tableView.insertRows(at: [newIndexPath!], with: .fade)
case .update:
// note: Apple samples show a call to configureCell here; this is incorrect--it can result in retrieving the
// wrong index when rows are reordered. For more information, see:
// http://go.microsoft.com/fwlink/?LinkID=524590&clcid=0x409
self.tableView.reloadRows(at: [indexPath!], with: .automatic)
}
})
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
DispatchQueue.main.async(execute: { () -> Void in
self.tableView.endUpdates()
});
}
}
| apache-2.0 | 67c294075005846d2d644e86d1f307cc | 40.19305 | 209 | 0.616084 | 5.644974 | false | false | false | false |
brettg/Signal-iOS | Signal/src/call/UserInterface/CallUIAdapter.swift | 1 | 7454 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
import CallKit
import WebRTC
protocol CallUIAdaptee {
var notificationsAdapter: CallNotificationsAdapter { get }
var callService: CallService { get }
var hasManualRinger: Bool { get }
func startOutgoingCall(handle: String) -> SignalCall
func reportIncomingCall(_ call: SignalCall, callerName: String)
func reportMissedCall(_ call: SignalCall, callerName: String)
func answerCall(localId: UUID)
func answerCall(_ call: SignalCall)
func declineCall(localId: UUID)
func declineCall(_ call: SignalCall)
func recipientAcceptedCall(_ call: SignalCall)
func localHangupCall(_ call: SignalCall)
func remoteDidHangupCall(_ call: SignalCall)
func remoteBusy(_ call: SignalCall)
func failCall(_ call: SignalCall, error: CallError)
func setIsMuted(call: SignalCall, isMuted: Bool)
func setHasLocalVideo(call: SignalCall, hasLocalVideo: Bool)
func startAndShowOutgoingCall(recipientId: String)
}
// Shared default implementations
extension CallUIAdaptee {
internal func showCall(_ call: SignalCall) {
AssertIsOnMainThread()
let callNotificationName = CallService.callServiceActiveCallNotificationName()
NotificationCenter.default.post(name: NSNotification.Name(rawValue: callNotificationName), object: call)
}
internal func reportMissedCall(_ call: SignalCall, callerName: String) {
AssertIsOnMainThread()
notificationsAdapter.presentMissedCall(call, callerName: callerName)
}
internal func startAndShowOutgoingCall(recipientId: String) {
AssertIsOnMainThread()
guard self.callService.call == nil else {
Logger.info("unexpectedly found an existing call when trying to start outgoing call: \(recipientId)")
return
}
let call = self.startOutgoingCall(handle: recipientId)
self.showCall(call)
}
}
/**
* Notify the user of call related activities.
* Driven by either a CallKit or System notifications adaptee
*/
@objc class CallUIAdapter: NSObject, CallServiceObserver {
let TAG = "[CallUIAdapter]"
private let adaptee: CallUIAdaptee
private let contactsManager: OWSContactsManager
private let audioService: CallAudioService
required init(callService: CallService, contactsManager: OWSContactsManager, notificationsAdapter: CallNotificationsAdapter) {
AssertIsOnMainThread()
self.contactsManager = contactsManager
if Platform.isSimulator {
// CallKit doesn't seem entirely supported in simulator.
// e.g. you can't receive calls in the call screen.
// So we use the non-CallKit call UI.
Logger.info("\(TAG) choosing non-callkit adaptee for simulator.")
adaptee = NonCallKitCallUIAdaptee(callService: callService, notificationsAdapter: notificationsAdapter)
} else if #available(iOS 10.0, *), Environment.getCurrent().preferences.isCallKitEnabled() {
Logger.info("\(TAG) choosing callkit adaptee for iOS10+")
adaptee = CallKitCallUIAdaptee(callService: callService, notificationsAdapter: notificationsAdapter)
} else {
Logger.info("\(TAG) choosing non-callkit adaptee")
adaptee = NonCallKitCallUIAdaptee(callService: callService, notificationsAdapter: notificationsAdapter)
}
audioService = CallAudioService(handleRinging: adaptee.hasManualRinger)
super.init()
callService.addObserverAndSyncState(observer: self)
}
internal func reportIncomingCall(_ call: SignalCall, thread: TSContactThread) {
AssertIsOnMainThread()
let callerName = self.contactsManager.displayName(forPhoneIdentifier: call.remotePhoneNumber)
adaptee.reportIncomingCall(call, callerName: callerName)
}
internal func reportMissedCall(_ call: SignalCall) {
AssertIsOnMainThread()
let callerName = self.contactsManager.displayName(forPhoneIdentifier: call.remotePhoneNumber)
adaptee.reportMissedCall(call, callerName: callerName)
}
internal func startOutgoingCall(handle: String) -> SignalCall {
AssertIsOnMainThread()
let call = adaptee.startOutgoingCall(handle: handle)
return call
}
internal func answerCall(localId: UUID) {
AssertIsOnMainThread()
adaptee.answerCall(localId: localId)
}
internal func answerCall(_ call: SignalCall) {
AssertIsOnMainThread()
adaptee.answerCall(call)
}
internal func declineCall(localId: UUID) {
AssertIsOnMainThread()
adaptee.declineCall(localId: localId)
}
internal func declineCall(_ call: SignalCall) {
AssertIsOnMainThread()
adaptee.declineCall(call)
}
internal func startAndShowOutgoingCall(recipientId: String) {
AssertIsOnMainThread()
adaptee.startAndShowOutgoingCall(recipientId: recipientId)
}
internal func recipientAcceptedCall(_ call: SignalCall) {
AssertIsOnMainThread()
adaptee.recipientAcceptedCall(call)
}
internal func remoteDidHangupCall(_ call: SignalCall) {
AssertIsOnMainThread()
adaptee.remoteDidHangupCall(call)
}
internal func remoteBusy(_ call: SignalCall) {
AssertIsOnMainThread()
adaptee.remoteBusy(call)
}
internal func localHangupCall(_ call: SignalCall) {
AssertIsOnMainThread()
adaptee.localHangupCall(call)
}
internal func failCall(_ call: SignalCall, error: CallError) {
AssertIsOnMainThread()
adaptee.failCall(call, error: error)
}
internal func showCall(_ call: SignalCall) {
AssertIsOnMainThread()
adaptee.showCall(call)
}
internal func setIsMuted(call: SignalCall, isMuted: Bool) {
AssertIsOnMainThread()
// With CallKit, muting is handled by a CXAction, so it must go through the adaptee
adaptee.setIsMuted(call: call, isMuted: isMuted)
}
internal func setHasLocalVideo(call: SignalCall, hasLocalVideo: Bool) {
AssertIsOnMainThread()
adaptee.setHasLocalVideo(call: call, hasLocalVideo: hasLocalVideo)
}
internal func setIsSpeakerphoneEnabled(call: SignalCall, isEnabled: Bool) {
AssertIsOnMainThread()
// Speakerphone is not handled by CallKit (e.g. there is no CXAction), so we handle it w/o going through the
// adaptee, relying on the AudioService CallObserver to put the system in a state consistent with the call's
// assigned property.
call.isSpeakerphoneEnabled = isEnabled
}
// CallKit handles ringing state on it's own. But for non-call kit we trigger ringing start/stop manually.
internal var hasManualRinger: Bool {
AssertIsOnMainThread()
return adaptee.hasManualRinger
}
// MARK: - CallServiceObserver
internal func didUpdateCall(call: SignalCall?) {
AssertIsOnMainThread()
call?.addObserverAndSyncState(observer: audioService)
}
internal func didUpdateVideoTracks(call: SignalCall?,
localVideoTrack: RTCVideoTrack?,
remoteVideoTrack: RTCVideoTrack?) {
AssertIsOnMainThread()
audioService.didUpdateVideoTracks(call:call)
}
}
| gpl-3.0 | 53307207ebd63e8eb946d8ee3735e388 | 31.837004 | 130 | 0.694124 | 5.165627 | false | false | false | false |
brocktonpoint/CawBoxKit | CawBoxKit/UserData.swift | 1 | 2982 | /*
The MIT License (MIT)
Copyright (c) 2015 CawBox
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
struct UserData <V> {
static func setDefaults (defaults: [String: AnyObject]) {
for (key, value) in defaults {
if UserData<AnyObject>.get (forKey: key) == nil {
UserData<AnyObject>.set (forKey: key, value: value)
}
}
}
static func clear (keys: [String]) {
for key in keys {
set (forKey: key, value: nil)
}
}
static func clearAll () {
sync (values: [:])
}
static func get (forKey: String) -> V? {
return userData[forKey] as? V
}
static func set (forKey: String, value: V?) {
var localUserData = userData
if let object = value.self {
localUserData[forKey] = object as? AnyObject
} else {
localUserData.removeValue (forKey: forKey)
}
sync (values: localUserData)
}
}
extension UserData {
private static var userDataURL: NSURL? {
let URL = try? NSFileManager.default().urlForDirectory (
.cachesDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
return URL?.appendingPathComponent ("userDataDefaults")
}
private static var userData: [String: AnyObject] {
if let url = userDataURL, let data = NSData (contentsOf: url) {
if let json = try? NSJSONSerialization.jsonObject (with: data, options: .mutableContainers),
userData = json as? [String: AnyObject]{
return userData
}
}
return [:]
}
private static func sync (values: [String: AnyObject]) {
if let url = userDataURL, let data = try? NSJSONSerialization.data (withJSONObject: values, options: .prettyPrinted) {
data.write (to: url, atomically: true)
}
}
}
| mit | 84e8b20ae4d55dd405623a43265211a0 | 32.886364 | 126 | 0.638833 | 4.70347 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.