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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cdmx/MiniMancera
|
miniMancera/Controller/Abstract/ControllerGame.swift
|
1
|
4558
|
import SpriteKit
class ControllerGame<T:MGame>:UIViewController, SKSceneDelegate, SKPhysicsContactDelegate
{
let model:T
let playSounds:Bool
private(set) weak var dataOption:DOption?
private var lastUpdateTime:TimeInterval?
private var elapsedTime:TimeInterval
required init(dataOption:DOption)
{
self.dataOption = dataOption
model = T()
if let playSounds:Bool = MSession.sharedInstance.settings?.sounds
{
self.playSounds = playSounds
}
else
{
playSounds = true
}
elapsedTime = 0
super.init(nibName:nil, bundle:nil)
}
required init?(coder:NSCoder)
{
return nil
}
deinit
{
NotificationCenter.default.removeObserver(self)
}
override var preferredStatusBarStyle:UIStatusBarStyle
{
return UIStatusBarStyle.lightContent
}
override var prefersStatusBarHidden:Bool
{
return true
}
override var shouldAutorotate:Bool
{
get
{
return true
}
}
override func loadView()
{
let view:ViewGame = ViewGame(controller:self)
self.view = view
}
override func viewDidLoad()
{
super.viewDidLoad()
edgesForExtendedLayout = UIRectEdge()
extendedLayoutIncludesOpaqueBars = false
automaticallyAdjustsScrollViewInsets = false
NotificationCenter.default.addObserver(
self,
selector:#selector(notifiedEnterBackground(sender:)),
name:Notification.enterBackground,
object:nil)
}
override func viewDidAppear(_ animated:Bool)
{
super.viewDidAppear(animated)
guard
let parent:ControllerParent = self.parent as? ControllerParent,
let view:ViewParent = parent.view as? ViewParent
else
{
return
}
view.panRecognizer.isEnabled = false
}
//MARK: notified
func notifiedEnterBackground(sender notification:Notification)
{
stopTimer()
}
//MARK: public
func exitGame()
{
DispatchQueue.main.async
{ [weak self] in
guard
let parent:ControllerParent = self?.parent as? ControllerParent
else
{
return
}
parent.pop(vertical:ControllerParent.Vertical.bottom)
}
}
func didMove()
{
model.didMove()
}
func postScore()
{
let score:Int = model.score
guard
let dataOption:DOption = self.dataOption
else
{
return
}
dataOption.postScore(score:score)
guard
let gameId:String = dataOption.gameId,
let parent:ControllerParent = UIApplication.shared.keyWindow?.rootViewController as? ControllerParent
else
{
return
}
parent.gameScore(score:score, gameId:gameId)
}
func stopTimer()
{
lastUpdateTime = nil
}
func restartTimer()
{
elapsedTime = 0
lastUpdateTime = nil
}
func game1up()
{
restartTimer()
}
func gamePlayNoMore()
{
exitGame()
}
//MARK: scene delegate
func update(_ currentTime:TimeInterval, for scene:SKScene)
{
if let lastUpdateTime:TimeInterval = self.lastUpdateTime
{
let deltaTime:TimeInterval = currentTime - lastUpdateTime
elapsedTime += deltaTime
guard
let strategy:MGameStrategyMain<T> = model.gameStrategy(modelType:model),
let scene:ViewGameScene<T> = scene as? ViewGameScene<T>
else
{
return
}
self.lastUpdateTime = currentTime
strategy.update(elapsedTime:elapsedTime, scene:scene)
}
else
{
lastUpdateTime = currentTime
}
}
//MARK: contact delegate
func didBegin(_ contact:SKPhysicsContact)
{
}
func didEnd(_ contact:SKPhysicsContact)
{
}
}
|
mit
|
8e3cec90b88719c3c03b897c1586cf93
| 20.399061 | 113 | 0.524572 | 5.76962 | false | false | false | false |
vamsirajendra/firefox-ios
|
Utils/Prefs.swift
|
2
|
5001
|
/* 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
public struct PrefsKeys {
public static let KeyLastRemoteTabSyncTime = "lastRemoteTabSyncTime"
public static let KeyLastSyncFinishTime = "lastSyncFinishTime"
}
public protocol Prefs {
func getBranchPrefix() -> String
func branch(branch: String) -> Prefs
func setTimestamp(value: Timestamp, forKey defaultName: String)
func setLong(value: UInt64, forKey defaultName: String)
func setLong(value: Int64, forKey defaultName: String)
func setInt(value: Int32, forKey defaultName: String)
func setString(value: String, forKey defaultName: String)
func setBool(value: Bool, forKey defaultName: String)
func setObject(value: AnyObject?, forKey defaultName: String)
func stringForKey(defaultName: String) -> String?
func boolForKey(defaultName: String) -> Bool?
func intForKey(defaultName: String) -> Int32?
func timestampForKey(defaultName: String) -> Timestamp?
func longForKey(defaultName: String) -> Int64?
func unsignedLongForKey(defaultName: String) -> UInt64?
func stringArrayForKey(defaultName: String) -> [String]?
func arrayForKey(defaultName: String) -> [AnyObject]?
func dictionaryForKey(defaultName: String) -> [String : AnyObject]?
func removeObjectForKey(defaultName: String)
func clearAll()
}
public class MockProfilePrefs : Prefs {
let prefix: String
public func getBranchPrefix() -> String {
return self.prefix
}
// Public for testing.
public var things: NSMutableDictionary = NSMutableDictionary()
public init(things: NSMutableDictionary, prefix: String) {
self.things = things
self.prefix = prefix
}
public init() {
self.prefix = ""
}
public func branch(branch: String) -> Prefs {
return MockProfilePrefs(things: self.things, prefix: self.prefix + branch + ".")
}
private func name(name: String) -> String {
return self.prefix + name
}
public func setTimestamp(value: Timestamp, forKey defaultName: String) {
self.setLong(value, forKey: defaultName)
}
public func setLong(value: UInt64, forKey defaultName: String) {
setObject(NSNumber(unsignedLongLong: value), forKey: defaultName)
}
public func setLong(value: Int64, forKey defaultName: String) {
setObject(NSNumber(longLong: value), forKey: defaultName)
}
public func setInt(value: Int32, forKey defaultName: String) {
things[name(defaultName)] = NSNumber(int: value)
}
public func setString(value: String, forKey defaultName: String) {
things[name(defaultName)] = value
}
public func setBool(value: Bool, forKey defaultName: String) {
things[name(defaultName)] = value
}
public func setObject(value: AnyObject?, forKey defaultName: String) {
things[name(defaultName)] = value
}
public func stringForKey(defaultName: String) -> String? {
return things[name(defaultName)] as? String
}
public func boolForKey(defaultName: String) -> Bool? {
return things[name(defaultName)] as? Bool
}
public func timestampForKey(defaultName: String) -> Timestamp? {
return unsignedLongForKey(defaultName)
}
public func unsignedLongForKey(defaultName: String) -> UInt64? {
let num = things[name(defaultName)] as? NSNumber
if let num = num {
return num.unsignedLongLongValue
}
return nil
}
public func longForKey(defaultName: String) -> Int64? {
let num = things[name(defaultName)] as? NSNumber
if let num = num {
return num.longLongValue
}
return nil
}
public func intForKey(defaultName: String) -> Int32? {
let num = things[name(defaultName)] as? NSNumber
if let num = num {
return num.intValue
}
return nil
}
public func stringArrayForKey(defaultName: String) -> [String]? {
if let arr = self.arrayForKey(defaultName) {
if let arr = arr as? [String] {
return arr
}
}
return nil
}
public func arrayForKey(defaultName: String) -> [AnyObject]? {
let r: AnyObject? = things.objectForKey(defaultName)
if (r == nil) {
return nil
}
if let arr = r as? [AnyObject] {
return arr
}
return nil
}
public func dictionaryForKey(defaultName: String) -> [String : AnyObject]? {
return things.objectForKey(name(defaultName)) as? [String: AnyObject]
}
public func removeObjectForKey(defaultName: String) {
self.things.removeObjectForKey(name(defaultName))
}
public func clearAll() {
self.things.removeAllObjects()
}
}
|
mpl-2.0
|
1f3eec9f4c7909943ff247d8288b5c1b
| 30.853503 | 88 | 0.65207 | 4.592287 | false | false | false | false |
pixelkind/FUX
|
FUX/FUXEasingCombinators.swift
|
1
|
8564
|
//
// FUXEasingCombinators.swift
// FUX
//
// Created by Garrit Schaap on 06.02.15.
// Copyright (c) 2015 Garrit UG (haftungsbeschränkt). All rights reserved.
//
import UIKit
public func easeInCubic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in time * time * time }
}
public func easeOutCubic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
let t = time - 1.0
return t * t * t + 1
}
}
public func easeInOutCubic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
var t = time * 2
if t < 1 {
return 0.5 * t * t * t
}
t -= 2
return 0.5 * (t * t * t + 2)
}
}
public func easeInCircular(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in -(sqrtf(1 - time * time) - 1) }
}
public func easeOutCircular(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
let t = time - 1.0
return sqrtf(1 - t * t)
}
}
public func easeInOutCircular(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
var t = time * 2
if t < 1 {
return -0.5 * (sqrtf(1 - t * t) - 1)
}
t -= 2
return 0.5 * (sqrtf(1 - t * t) + 1)
}
}
public func easeInSine(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in 1 - cosf(time * Float(M_PI_2)) }
}
public func easeOutSine(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in sinf(time * Float(M_PI_2)) }
}
public func easeInOutSine(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in -0.5 * (cosf(Float(M_PI) * time) - 1) }
}
public func easeInQuadratic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in time * time }
}
public func easeOutQuadratic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in -time * (time - 2) }
}
public func easeInOutQuadratic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
var t = time * 2
if t < 1 {
return 0.5 * t * t
}
return -0.5 * (--t * (t - 2) - 1)
}
}
public func easeInQuartic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in time * time * time * time }
}
public func easeOutQuartic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
let t = time - 1
return -(t * t * t * t - 1)
}
}
public func easeInOutQuartic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
var t = time * 2
if t < 1 {
return 0.5 * t * t * t * t
}
t -= 2
return -0.5 * (t * t * t * t - 2)
}
}
public func easeInQuintic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in time * time * time * time * time }
}
public func easeOutQuintic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
let t = time - 1
return -(t * t * t * t * t - 1)
}
}
public func easeInOutQuintic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
var t = time * 2
if t < 1 {
return 0.5 * t * t * t * t * t
}
t -= 2
return -0.5 * (t * t * t * t * t - 2)
}
}
public func easeInExpo(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in time == 0 ? 0 : powf(2, 10 * (time - 1)) }
}
public func easeOutExpo(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in time == 1 ? 1 : -powf(2, -10 * time) + 1 }
}
public func easeInOutExpo(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
if time == 0 {
return 0
} else if time == 1 {
return 1
}
var t = time * 2
if t < 1 {
return 0.5 * powf(2, 10 * (t - 1))
} else {
return 0.5 * (-powf(2, -10 * --t) + 2)
}
}
}
let easeBackSValue: Float = 1.70158;
public func easeInBack(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in time * time * ((easeBackSValue + 1) * time - easeBackSValue) }
}
public func easeOutBack(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
let t = time - 1
return t * t * ((easeBackSValue + 1) * t + easeBackSValue) + 1
}
}
public func easeInOutBack(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
var t = time * 2
let s = easeBackSValue * 1.525
if t < 1 {
return 0.5 * (t * t * ((s + 1) * t - s))
}
t -= 2
return 0.5 * (t * t * ((s + 1) * t + s) + 2)
}
}
public func easeInBounce(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)) { time in
var t = 1 - time
if t < 1.0 / 2.75 {
return 1 - 7.5625 * t * t
} else if t < 2.0 / 2.75 {
t -= (1.5 / 2.75)
return 1 - Float(7.5625 * t * t + 0.75)
} else if t < 2.5 / 2.75 {
t -= (2.25 / 2.75)
return 1 - Float(7.5625 * t * t + 0.9375)
} else {
t -= (2.625 / 2.75)
return 1 - Float(7.5625 * t * t + 0.984375)
}
}
}
public func easeOutBounce(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)) { time in
var t = time
if t < 1.0 / 2.75 {
return 7.5625 * t * t
} else if t < 2.0 / 2.75 {
t -= (1.5 / 2.75)
return Float(7.5625 * t * t + 0.75)
} else if t < 2.5 / 2.75 {
t -= (2.25 / 2.75)
return Float(7.5625 * t * t + 0.9375)
} else {
t -= (2.625 / 2.75)
return Float(7.5625 * t * t + 0.984375)
}
}
}
public func easeInOutBounce(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)) { time in
var t = time * 2
if t < 1 {
return (1 - easeOutBounceWithTime(1 - t, 1)) * 0.5
} else {
return easeOutBounceWithTime(t - 1, 1) * 0.5 + 0.5
}
}
}
func easeOutBounceWithTime(time: Float, duration: Float) -> Float {
var t = time / duration
if t < 1.0 / 2.75 {
return 7.5625 * t * t
} else if t < 2.0 / 2.75 {
t -= (1.5 / 2.75)
return Float(7.5625 * t * t + 0.75)
} else if t < 2.5 / 2.75 {
t -= (2.25 / 2.75)
return Float(7.5625 * t * t + 0.9375)
} else {
t -= (2.625 / 2.75)
return Float(7.5625 * t * t + 0.984375)
}
}
var easeElasticPValue: Float = 0.3
var easeElasticSValue: Float = 0.3 / 4
var easeElasticAValue : Float = 1
public func setEaseElasticPValue(value: Float) {
easeElasticPValue = value
if easeElasticAValue < 1 {
easeElasticSValue = easeElasticPValue / 4
} else {
easeElasticSValue = easeElasticPValue / (Float(M_PI) * 2) * asinf(1 / easeElasticAValue)
}
}
public func setEaseElasticAValue(value: Float) {
if easeElasticAValue >= 1 {
easeElasticAValue = value
easeElasticSValue = easeElasticPValue / (Float(M_PI) * 2) * asinf(1 / easeElasticAValue)
}
}
public func easeInElastic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)) { time in
if time == 0 {
return 0
} else if time == 1 {
return 1
}
let t = time - 1
return -(powf(2, 10 * t) * sinf((t - easeElasticSValue) * (Float(M_PI) * 2) / easeElasticPValue))
}
}
public func easeOutElastic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)) { time in
if time == 0 {
return 0
} else if time == 1 {
return 1
}
return powf(2, (-10 * time)) * sinf((time - easeElasticSValue) * (Float(M_PI) * 2) / easeElasticPValue) + 1
}
}
public func easeInOutElastic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)) { time in
if time == 0 {
return 0
} else if time == 1 {
return 1
}
var t = time * 2
if t < 1 {
t -= 1
return -0.5 * (powf(2, 10 * t) * sinf((t - easeElasticSValue) * (Float(M_PI) * 2) / easeElasticPValue))
}
t -= 1
return powf(2, -10 * t) * sinf((t - easeElasticSValue) * (Float(M_PI) * 2) / easeElasticPValue) * 0.5 + 1
}
}
|
mit
|
e0f178567075d0868ad0736ac9c9e0a0
| 26.805195 | 115 | 0.536144 | 3.066977 | false | false | false | false |
MartinOSix/DemoKit
|
dSwift/swiftreflect/swiftreflect/BaseInfo.swift
|
1
|
1447
|
//
// BaseInfo.swift
// swiftreflect
//
// Created by runo on 17/3/15.
// Copyright © 2017年 com.runo. All rights reserved.
//
import UIKit
class BaseInfo: NSObject, NSCoding {
var name = ""
override init() {
super.init()
}
convenience required init(coder aDecoder:NSCoder) {
self.init()
forEachChildOfMirror(reflecting: self) { (key) in
setValue(aDecoder.decodeObject(forKey: key), forKey: key)
}
}
func encode(with aCoder: NSCoder) {
forEachChildOfMirror(reflecting: self) { (key) in
aCoder.encode(value(forKey: key), forKey: key)
}
}
func forEachChildOfMirror(reflecting subject: Any, handler:(String)->Void) {
var mirror: Mirror? = Mirror(reflecting: subject);
while mirror != nil {
print("style \(mirror!.displayStyle!)")
print("type \(mirror!.subjectType)")
for child in mirror!.children {
if let key = child.label {
print("property \(key) \(child.value) \(child)")
handler(key)
}
}
mirror = mirror!.superclassMirror
}
}
}
final class TestA: BaseInfo{
var accessKey = ""
var secretKey = ""
}
final class TestB: BaseInfo{
var userName = ""
var password = ""
}
|
apache-2.0
|
436f17508ff33ebb87459c11646bc718
| 21.920635 | 80 | 0.524931 | 4.484472 | false | false | false | false |
jlecomte/iOSRottenTomatoesApp
|
RottenTomatoes/MoviesViewController.swift
|
1
|
5576
|
//
// MoviesViewController.swift
// RottenTomatoes
//
// Created by Julien Lecomte on 9/12/14.
// Copyright (c) 2014 Julien Lecomte. All rights reserved.
//
import UIKit
class MoviesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchDisplayDelegate, UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var refreshControl: UIRefreshControl!
var movies: [NSDictionary] = []
var filteredMovies: [NSDictionary] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh...")
refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
tableView.addSubview(refreshControl)
activityIndicator.center = view.center
activityIndicator.startAnimating()
tableView.hidden = true
fetchMovies(false)
}
func fetchMovies(pullToRefresh: Bool) {
var url = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?apikey=4jvsq52hmsc9vsngu6ewrqku&limit=50&country=us"
var request = NSURLRequest(URL: NSURL(string: url))
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var hasError = false
self.activityIndicator.stopAnimating()
self.refreshControl.endRefreshing()
if error == nil {
var object = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSDictionary
if object["error"] == nil {
self.movies = object["movies"] as [NSDictionary]
self.tableView.reloadData()
} else {
hasError = true
}
} else {
hasError = true
}
if hasError {
var alert = UIAlertController(title: "Error", message: "The Rotten Tomatoes API returned a friggin' error...", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alert, animated: false, completion: nil)
} else {
self.tableView.hidden = false
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func refresh(sender:AnyObject) {
movies = []
tableView.reloadData()
fetchMovies(true)
}
func filterContentForSearchText(searchText: String) {
filteredMovies = movies.filter { (movie: NSDictionary) -> Bool in
let title = movie["title"] as String
let stringMatch = title.rangeOfString(searchText)
return stringMatch != nil
}
}
func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String!) -> Bool {
filterContentForSearchText(searchString)
return true
}
// Needed for iOS < 8...
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 133
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == searchDisplayController!.searchResultsTableView {
return filteredMovies.count
} else {
return movies.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = self.tableView.dequeueReusableCellWithIdentifier("MovieCell") as MovieCell
var movie: NSDictionary
if tableView == searchDisplayController!.searchResultsTableView {
movie = filteredMovies[indexPath.row]
} else {
movie = movies[indexPath.row]
}
cell.titleLabel.text = movie["title"] as? String
cell.synopsisLabel.text = movie["synopsis"] as? String
var posters = movie["posters"] as NSDictionary
var thumbnailUrl = posters["thumbnail"] as String
cell.posterView.setImageWithURL(NSURL(string: thumbnailUrl))
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
var movie: NSDictionary
if tableView == searchDisplayController!.searchResultsTableView {
movie = filteredMovies[indexPath.row]
} else {
movie = movies[indexPath.row]
}
performSegueWithIdentifier("Movie Detail", sender: movie)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
var vc = segue.destinationViewController as MovieDetailViewController
var movie = sender as NSDictionary
vc.movieTitle = movie["title"] as String
vc.synopsis = movie["synopsis"] as String
var posters = movie["posters"] as NSDictionary
var posterUrl = posters["original"] as String
// replace '_tmb.' by '_ori.'
posterUrl = posterUrl.stringByReplacingOccurrencesOfString("_tmb.", withString: "_ori.", options: nil, range: nil)
vc.posterUrl = posterUrl
}
}
|
mit
|
d3f804d67f10d88302ece8b5ec2a553f
| 33.63354 | 172 | 0.651722 | 5.413592 | false | false | false | false |
KevinCoble/AIToolbox
|
Package/ConstraintPropogation.swift
|
2
|
23600
|
//
// ConstraintPropogation.swift
// AIToolbox
//
// Created by Kevin Coble on 3/6/15.
// Copyright (c) 2015 Kevin Coble. All rights reserved.
//
import Foundation
// MARK: ConstraintProblemVariable
/// Class for assignment variable
open class ConstraintProblemVariable {
open let domainSize: Int
var possibleSettings : [Bool]
var remainingPossibilityCount: Int
var assignedValueIndex: Int?
public init(sizeOfDomain: Int) {
// Store the number of settings
self.domainSize = sizeOfDomain
// Allocate an array of the possible settings
possibleSettings = Array(repeating: true, count: sizeOfDomain)
// Set the number of remaining possibilities
remainingPossibilityCount = sizeOfDomain
}
open var hasNoPossibleSettings : Bool {
get {
return (remainingPossibilityCount == 0)
}
}
open var isSingleton : Bool {
get {
return (assignedValueIndex == nil && remainingPossibilityCount == 1)
}
}
open var assignedValue : Int? {
get {
return assignedValueIndex
}
set {
assignedValueIndex = assignedValue
}
}
open var smallestAllowedValue : Int? {
get {
for index in 0..<domainSize {
if (possibleSettings[index]) {return index}
}
return nil
}
}
open var largestAllowedValue : Int? {
get {
for index in 1...domainSize {
if (possibleSettings[domainSize - index]) {return domainSize - index}
}
return nil
}
}
open func reset() {
for index in 0..<domainSize {
possibleSettings[index] = true
remainingPossibilityCount = domainSize
}
}
open func removeValuePossibility(_ varValueIndex: Int) -> Bool { // Return true if the possibility was actually removed
if (varValueIndex < 0 || varValueIndex >= domainSize) { return false}
var result = false
if (possibleSettings[varValueIndex]) {
remainingPossibilityCount -= 1
possibleSettings[varValueIndex] = false
result = true
}
return result
}
open func allowValuePossibility(_ varValueIndex: Int) -> Bool { // Return true if the possibility was actually returned
if (varValueIndex < 0 || varValueIndex >= domainSize) { return false }
var result = false
if (!possibleSettings[varValueIndex]) {
remainingPossibilityCount += 1
possibleSettings[varValueIndex] = true
result = true
}
return result
}
open func assignToNextPossibleValue() ->Bool { // Returns false if value cannot be assigned
if (remainingPossibilityCount == 0) {return false}
if let currentAssignment = assignedValueIndex {
if (currentAssignment == domainSize-1) { // We are on the last possible assignment
assignedValueIndex = nil
return false
}
if (remainingPossibilityCount == 1) { // We are on the only possible assignment
assignedValueIndex = nil
return false
}
for index in currentAssignment+1..<domainSize { // Find the next available assignment
if (possibleSettings[index]) {
assignedValueIndex = index
return true
}
}
// No valid possibility left
assignedValueIndex = nil
return false
}
else {
// Not assigned, find the first assignment available
for index in 0..<domainSize {
if (possibleSettings[index]) {
assignedValueIndex = index
break
}
}
}
return true
}
open func assignSingleton() -> Bool {
if (remainingPossibilityCount != 1) { return false }
for index in 0..<domainSize {
if (possibleSettings[index]) {
assignedValueIndex = index
return true
}
}
return false
}
}
// MARK:- ConstraintProblemConstraint
/// Protocol for a constraint between two nodes
public protocol ConstraintProblemConstraint {
var isSelfConstraint: Bool { get }
func enforceConstraint(_ graphNodeList: [ConstraintProblemNode], forNodeIndex: Int) -> [EnforcedConstraint]
}
public struct EnforcedConstraint {
var nodeAffected: ConstraintProblemNode
var domainIndexRemoved: Int
}
public enum StandardConstraintType {
case cantBeSameValueInOtherNode
case mustBeSameValueInOtherNode
case cantBeValue
case mustBeGreaterThanOtherNode
case mustBeLessThanOtherNode
}
open class InternalConstraint: ConstraintProblemConstraint {
let tType: StandardConstraintType
let nIndex: Int // Variable set index for 'can't be value' types, else node index
public init(type: StandardConstraintType, index: Int) {
tType = type
nIndex = index
}
open func reciprocalConstraint(_ firstNodeIndex: Int) ->InternalConstraint? {
switch tType {
case .cantBeSameValueInOtherNode:
let constraint = InternalConstraint(type: .cantBeSameValueInOtherNode, index: firstNodeIndex)
return constraint
case .mustBeSameValueInOtherNode:
let constraint = InternalConstraint(type: .mustBeSameValueInOtherNode, index: firstNodeIndex)
return constraint
case .cantBeValue:
return nil // No reciprocal for this one
case .mustBeGreaterThanOtherNode:
let constraint = InternalConstraint(type: .mustBeLessThanOtherNode, index: firstNodeIndex)
return constraint
case .mustBeLessThanOtherNode:
let constraint = InternalConstraint(type: .mustBeGreaterThanOtherNode, index: firstNodeIndex)
return constraint
}
}
open var isSelfConstraint: Bool {
return (tType == .cantBeValue)
}
open func enforceConstraint(_ graphNodeList: [ConstraintProblemNode], forNodeIndex: Int) -> [EnforcedConstraint] {
var changeList : [EnforcedConstraint] = []
let variable = graphNodeList[forNodeIndex].variable
switch tType {
case .cantBeSameValueInOtherNode:
if let index = variable.assignedValueIndex {
let otherNode = graphNodeList[nIndex]
if (otherNode.variable.removeValuePossibility(index)) {
changeList.append(EnforcedConstraint(nodeAffected: otherNode, domainIndexRemoved: index))
}
}
case .mustBeSameValueInOtherNode:
if let index = variable.assignedValueIndex {
let otherNode = graphNodeList[nIndex]
for otherIndex in 0..<otherNode.variable.domainSize {
if (otherIndex != index) {
if (otherNode.variable.removeValuePossibility(otherIndex)) {
changeList.append(EnforcedConstraint(nodeAffected: otherNode, domainIndexRemoved: otherIndex))
}
}
}
}
case .cantBeValue:
if (variable.removeValuePossibility(nIndex)) {
changeList.append(EnforcedConstraint(nodeAffected: graphNodeList[forNodeIndex], domainIndexRemoved: nIndex))
}
case .mustBeGreaterThanOtherNode:
// Find smallest value allowed for the node
if let smallestValue = variable.smallestAllowedValue {
if (smallestValue > 0) {
let otherNode = graphNodeList[nIndex]
for otherIndex in 0..<smallestValue {
if (otherNode.variable.removeValuePossibility(otherIndex)) {
changeList.append(EnforcedConstraint(nodeAffected: otherNode, domainIndexRemoved: otherIndex))
}
}
}
}
case .mustBeLessThanOtherNode:
// Find largest value allowed for the node
if let largest = variable.largestAllowedValue {
let otherNode = graphNodeList[nIndex]
if (largest < otherNode.variable.domainSize-1) {
for otherIndex in largest+1..<otherNode.variable.domainSize {
if (otherNode.variable.removeValuePossibility(otherIndex)) {
changeList.append(EnforcedConstraint(nodeAffected: otherNode, domainIndexRemoved: otherIndex))
}
}
}
}
}
return changeList
}
}
// MARK:- ConstraintProblemNode
/// Class for a node with a variable and a set of constraints
open class ConstraintProblemNode {
let variable : ConstraintProblemVariable
var constraints : [ConstraintProblemConstraint] = []
var constraintsLastEnforced: [EnforcedConstraint] = []
var inQueue = false
open var variableIndexValue : Int? {
get {return variable.assignedValueIndex}
}
var nodeIndex = -1
public init(variableDomainSize: Int) {
variable = ConstraintProblemVariable(sizeOfDomain: variableDomainSize)
}
func clearConstraints() {
constraints = []
}
func addConstraint(_ constraint: ConstraintProblemConstraint) {
constraints.append(constraint)
}
open func resetVariable() {
variable.reset()
}
open func processSelfConstraints(_ graphNodeList: [ConstraintProblemNode]) -> Bool
{
for constraint in constraints {
if (constraint.isSelfConstraint) {
_ = constraint.enforceConstraint(graphNodeList, forNodeIndex: nodeIndex)
}
}
// Verify we have a non-empty domain left
return (!variable.hasNoPossibleSettings)
}
open func clearConstraintsLastEnforced() {
constraintsLastEnforced = []
}
open func enforceConstraints(_ graphNodeList: [ConstraintProblemNode], nodeEnforcingConstraints: ConstraintProblemNode) -> Bool {
// Get our assigned domain index
if let _ = variable.assignedValueIndex {
// Go through each attached constraint
for constraint in constraints {
nodeEnforcingConstraints.constraintsLastEnforced += constraint.enforceConstraint(graphNodeList, forNodeIndex: nodeIndex)
}
}
return true
}
open func removeConstraintsLastEnforced() {
for constraintEnforced in constraintsLastEnforced {
constraintEnforced.nodeAffected.resetVariableDomainIndex(constraintEnforced.domainIndexRemoved)
}
}
open func resetVariableDomainIndex(_ resetIndex: Int) {
_ = variable.allowValuePossibility(resetIndex)
// If we were assigned, this un-assigns the node
variable.assignedValueIndex = nil
}
open func assignSingleton() -> Bool {
return variable.assignSingleton()
}
func addChangedNodesToQueue(_ queue: Queue<ConstraintProblemNode>) {
for constraintEnforced in constraintsLastEnforced {
if (!constraintEnforced.nodeAffected.inQueue) {
queue.enqueue(constraintEnforced.nodeAffected)
constraintEnforced.nodeAffected.inQueue = true
}
}
}
}
// MARK: -
// MARK: ConstraintProblem Class
/// Class for a constraint problem consisting of a collection of nodes. The nodes are (sub)classes of ConstraintProblemNode.
/// Constraints are added with the problem set, or creating ConstraintProblemConstraint conforming classes and adding those
open class ConstraintProblem {
// Array of nodes in the list
var graphNodeList : [ConstraintProblemNode] = []
// Empty initializer
public init() {
}
/// Method to set an array of ConstraintProblemNode (or subclass) to the problmeem graph
open func setNodeList(_ list: [ConstraintProblemNode]) {
graphNodeList = list
// Number each of the nodes
var nIndex = 0
for node in graphNodeList {
node.nodeIndex = nIndex
nIndex += 1
}
}
/// Method to clear all constraints for the problem
open func clearConstraints() {
for node in graphNodeList {
node.clearConstraints()
}
}
/// Method to add a value constraint to a node
open func addValueConstraintToNode(_ node: Int, invalidValue: Int) {
let constraint = InternalConstraint(type: .cantBeValue, index: invalidValue)
graphNodeList[node].addConstraint(constraint)
}
/// Method to add a constraint between two nodes
open func addConstraintOfType(_ type: StandardConstraintType, betweenNodeIndex firstnode: Int, andNodeIndex secondNode : Int) {
let constraint = InternalConstraint(type: type, index: secondNode)
graphNodeList[firstnode].addConstraint(constraint)
}
/// Method to add a set of reciprocal constraints between two nodes
open func addReciprocalConstraintsOfType(_ type: StandardConstraintType, betweenNodeIndex firstNode: Int, andNodeIndex secondNode : Int) {
let constraint = InternalConstraint(type: type, index: secondNode)
graphNodeList[firstNode].addConstraint(constraint)
if let reciprocalConstraint = constraint.reciprocalConstraint(firstNode) {
graphNodeList[secondNode].addConstraint(reciprocalConstraint)
}
}
/// Method to add a custom constraint
open func addCustomConstraint(_ constraint: ConstraintProblemConstraint, toNode: Int) {
graphNodeList[toNode].addConstraint(constraint)
}
/// Method to attempt to solve the problem using basic forward constraint propogation
/// Return true if a solution was found. The node's variables will be set with the result
open func solveWithForwardPropogation() -> Bool {
// Reset the variable possibilites for each node, then process self-inflicted constraints
for node in graphNodeList {
node.resetVariable()
if (!node.processSelfConstraints(graphNodeList)) { return false } // self-constraints left an empty domain
}
// Start with the first possible value for node 0
return forwardDFS(0)
}
fileprivate func forwardDFS(_ node: Int) -> Bool { // Return fail if backtracking
// Assign this node
while (true) {
// Reset any previous consraint enforcements from the last assignment
graphNodeList[node].removeConstraintsLastEnforced()
// Assign to the next value
if (!graphNodeList[node].variable.assignToNextPossibleValue()) {
// Reset any previous consraint enforcements from this assignment
graphNodeList[node].removeConstraintsLastEnforced()
return false
}
// Process constraints
graphNodeList[node].clearConstraintsLastEnforced()
if (!graphNodeList[node].enforceConstraints(graphNodeList, nodeEnforcingConstraints: graphNodeList[node])) { continue }
// If this was the last node, return true
if (node == graphNodeList.count-1) { return true}
// Otherwise, iterate down
if (forwardDFS(node+1)) { return true }
}
}
/// Method to attempt to solve the problem using singleton propogation
/// Return true if a solution was found. The node's variables will be set with the result
open func solveWithSingletonPropogation() -> Bool {
// Reset the variable possibilites for each node, then process self-inflicted constraints
for node in graphNodeList {
node.resetVariable()
if (!node.processSelfConstraints(graphNodeList)) { return false } // self-constraints left an empty domain
}
// Start with the first possible value for node 0
return singletonDFS(0)
}
fileprivate func singletonDFS(_ node: Int) -> Bool { // Return fail if backtracking
let nextNode = node + 1
// If the node is assigned already (from singleton propogation), just iterate down
if (graphNodeList[node].variable.assignedValueIndex != nil) {
// If this was the last node, return true
if (nextNode == graphNodeList.count) { return true}
return singletonDFS(nextNode)
}
// Assign this node
assignIteration : while (true) {
// Reset any previous consraint enforcements from the last assignment
graphNodeList[node].removeConstraintsLastEnforced()
// Assign to the next value
if (!graphNodeList[node].variable.assignToNextPossibleValue()) {
// Reset any previous consraint enforcements from this assignment
graphNodeList[node].removeConstraintsLastEnforced()
return false
}
if (nextNode < graphNodeList.count) { // If last node, skip propogation as we are done
// Process constraints
graphNodeList[node].clearConstraintsLastEnforced()
if (!graphNodeList[node].enforceConstraints(graphNodeList, nodeEnforcingConstraints: graphNodeList[node])) { continue }
// Find the singletons
let queue = Queue<ConstraintProblemNode>()
for index in nextNode..<graphNodeList.count {
graphNodeList[index].inQueue = false
if graphNodeList[index].variable.isSingleton {
queue.enqueue(graphNodeList[index])
graphNodeList[index].inQueue = true
}
}
// Propogate all singletons information to constraint nodes
var singleton = queue.dequeue()
while (singleton != nil) {
// Assign the singleton
_ = singleton!.assignSingleton()
// Process constraints, adding the 'backtrack' list to this node
if (!singleton!.enforceConstraints(graphNodeList, nodeEnforcingConstraints: graphNodeList[node])) {
// Backtrack
continue assignIteration
}
// See if there are more singletons to add to the queue
for index in nextNode..<graphNodeList.count {
if (!graphNodeList[index].inQueue && graphNodeList[index].variable.isSingleton) {
queue.enqueue(graphNodeList[index])
graphNodeList[index].inQueue = true
}
}
singleton = queue.dequeue()
}
}
// If this was the last node, return true
if (nextNode == graphNodeList.count) { return true}
// Otherwise, iterate down
if (singletonDFS(nextNode)) { return true }
}
}
/// Method to attempt to solve the problem using full constraint propogation
/// Probably only useful if less-than, greater-than, or appropriate custom constraints are in the problem
/// Return true if a solution was found. The node's variables will be set with the result
open func solveWithFullPropogation() -> Bool {
// Reset the variable possibilites for each node, then process self-inflicted constraints
for node in graphNodeList {
node.resetVariable()
if (!node.processSelfConstraints(graphNodeList)) { return false } // self-constraints left an empty domain
}
// Start with the first possible value for node 0
return fullDFS(0)
}
fileprivate func fullDFS(_ node: Int) -> Bool { // Return fail if backtracking
let nextNode = node + 1
// If the node is assigned already (from constraint propogation), just iterate down
if (graphNodeList[node].variable.assignedValueIndex != nil) {
// If this was the last node, return true
if (nextNode == graphNodeList.count) { return true}
return fullDFS(nextNode)
}
// Assign this node
assignIteration : while (true) {
// Reset any previous consraint enforcements from the last assignment
graphNodeList[node].removeConstraintsLastEnforced()
// Assign to the next value
if (!graphNodeList[node].variable.assignToNextPossibleValue()) {
// Reset any previous consraint enforcements from this assignment
graphNodeList[node].removeConstraintsLastEnforced()
return false
}
if (nextNode < graphNodeList.count) { // If last node, skip propogation as we are done
// Create the queue, reset the 'in queue' flag
let queue = Queue<ConstraintProblemNode>()
for index in nextNode..<graphNodeList.count {
graphNodeList[index].inQueue = false
}
// Process constraints
graphNodeList[node].clearConstraintsLastEnforced()
if (!graphNodeList[node].enforceConstraints(graphNodeList, nodeEnforcingConstraints: graphNodeList[node])) { continue }
// Add the modified nodes to the queue
graphNodeList[node].addChangedNodesToQueue(queue)
// Propogate changes
var changedNode = queue.dequeue()
while (changedNode != nil) {
// Process constraints, adding the 'backtrack' list to this node
if (!changedNode!.enforceConstraints(graphNodeList, nodeEnforcingConstraints: graphNodeList[node])) {
// Backtrack
continue assignIteration
}
// Add the modified nodes to the queue
graphNodeList[node].addChangedNodesToQueue(queue)
changedNode = queue.dequeue()
}
}
// If this was the last node, return true
if (nextNode == graphNodeList.count) { return true}
// Otherwise, iterate down
if (fullDFS(nextNode)) { return true }
}
}
}
|
apache-2.0
|
a523a728269858ca3dd8c02522d74e23
| 36.820513 | 143 | 0.587966 | 5.242115 | false | false | false | false |
wayfindrltd/wayfindr-demo-ios
|
Wayfindr Demo/Classes/View/Maintainer/BeaconsInRangeView.swift
|
1
|
8370
|
//
// BeaconsInRangeView.swift
// Wayfindr Demo
//
// Created by Wayfindr on 12/11/2015.
// Copyright (c) 2016 Wayfindr (http://www.wayfindr.net)
//
// 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
final class BeaconsInRangeView: BaseView {
// MARK: - Properties
fileprivate let locatingLabel = UILabel()
fileprivate let scrollView = UIScrollView()
let headerView = BeaconsInRangeHeaderView()
let bodyView = BeaconsInRangeBodyView()
var locatingLabelHidden = true {
didSet {
locatingLabel.isHidden = locatingLabelHidden
scrollView.isHidden = !locatingLabelHidden
}
}
// MARK: - Setup
override func setup() {
super.setup()
headerView.addBorder(edges: [.bottom], colour: WAYConstants.WAYColors.Border, thickness: 3.0)
locatingLabel.text = WAYStrings.BeaconsInRange.NoBeacons
locatingLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.title1)
locatingLabel.textAlignment = .center
locatingLabel.textColor = WAYConstants.WAYColors.Maintainer
locatingLabel.lineBreakMode = .byWordWrapping
locatingLabel.numberOfLines = 0
locatingLabelHidden = false
addSubview(locatingLabel)
addSubview(scrollView)
scrollView.addSubview(headerView)
scrollView.addSubview(bodyView)
}
// MARK: - Layout
override func setupConstraints() {
super.setupConstraints()
// Turn off autoresizing mask
locatingLabel.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
headerView.translatesAutoresizingMaskIntoConstraints = false
bodyView.translatesAutoresizingMaskIntoConstraints = false
// View Dictionary
let views = ["locatingLabel" : locatingLabel, "scrollView" : scrollView, "headerView" : headerView, "bodyView" : bodyView]
// Vertical Constraints
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[locatingLabel]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: WAYConstants.WAYLayout.metrics, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-HalfMargin-[scrollView]-HalfMargin-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: WAYConstants.WAYLayout.metrics, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[headerView][bodyView]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: WAYConstants.WAYLayout.metrics, views: views))
// Horizontal Constraints
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[locatingLabel]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: WAYConstants.WAYLayout.metrics, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-HalfMargin-[scrollView]-HalfMargin-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: WAYConstants.WAYLayout.metrics, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[headerView]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[bodyView]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraint(NSLayoutConstraint(item: headerView.titleLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1.0, constant: -4.0 * WAYConstants.WAYLayout.HalfMargin))
}
// MARK: - Set Text
func setLocatingLabelText(_ text: String) {
locatingLabel.text = text
}
}
final class BeaconsInRangeHeaderView: BaseStackView {
// MARK: - Properties
let titleLabel = UILabel()
let subtitleLabel = UILabel()
let bodyLabel = UILabel()
// MARK: - Setup
override func setup() {
super.setup()
titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.title1)
subtitleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.title2)
bodyLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
titleLabel.text = WAYStrings.CommonStrings.Beacon.uppercased()
subtitleLabel.text = WAYStrings.CommonStrings.Minor
titleLabel.textAlignment = .center
subtitleLabel.textAlignment = .center
bodyLabel.textAlignment = .center
stackView.alignment = .center
stackView.addArrangedSubview(titleLabel)
stackView.addArrangedSubview(subtitleLabel)
stackView.addArrangedSubview(bodyLabel)
}
}
final class BeaconsInRangeBodyView: BaseStackView {
// MARK: - Properties
let txPowerLabel = KeyValueLabel()
let rssiLabel = KeyValueLabel()
let accuracyLabel = KeyValueLabel()
let advertisingRateLabel = KeyValueLabel()
let batteryLabel = KeyValueLabel()
let uuidLabel = KeyValueLabel()
let majorLabel = KeyValueLabel()
let minorLabel = KeyValueLabel()
// MARK: - Setup
override func setup() {
super.setup()
let colonText = ": "
txPowerLabel.keyLabel.text = WAYStrings.BeaconsInRange.TxPower + colonText
rssiLabel.keyLabel.text = WAYStrings.BeaconsInRange.RSSI + colonText
accuracyLabel.keyLabel.text = WAYStrings.BeaconsInRange.Accuracy + colonText
advertisingRateLabel.keyLabel.text = WAYStrings.BeaconsInRange.AdvertisingRate + colonText
batteryLabel.keyLabel.text = WAYStrings.CommonStrings.Battery + colonText
uuidLabel.keyLabel.text = WAYStrings.BeaconsInRange.UUID + colonText
majorLabel.keyLabel.text = WAYStrings.CommonStrings.Major + colonText
minorLabel.keyLabel.text = WAYStrings.CommonStrings.Minor + colonText
let keyLabelColor = WAYConstants.WAYColors.Maintainer
txPowerLabel.keyLabel.textColor = keyLabelColor
rssiLabel.keyLabel.textColor = keyLabelColor
accuracyLabel.keyLabel.textColor = keyLabelColor
advertisingRateLabel.keyLabel.textColor = keyLabelColor
batteryLabel.keyLabel.textColor = keyLabelColor
uuidLabel.keyLabel.textColor = keyLabelColor
majorLabel.keyLabel.textColor = keyLabelColor
minorLabel.keyLabel.textColor = keyLabelColor
uuidLabel.valueLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.footnote)
stackView.addArrangedSubview(txPowerLabel)
stackView.addArrangedSubview(rssiLabel)
stackView.addArrangedSubview(accuracyLabel)
stackView.addArrangedSubview(advertisingRateLabel)
stackView.addArrangedSubview(batteryLabel)
stackView.addArrangedSubview(uuidLabel)
stackView.addArrangedSubview(majorLabel)
stackView.addArrangedSubview(minorLabel)
}
}
|
mit
|
ea21a576892609974af0c281a22ca924
| 41.48731 | 227 | 0.698327 | 5.157116 | false | false | false | false |
apple/swift-nio-http2
|
Tests/NIOHTTP2Tests/ReentrancyTests.swift
|
1
|
10860
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 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 XCTest
import NIOCore
import NIOEmbedded
import NIOHTTP1
import NIOHTTP2
import NIOHPACK
/// A `ChannelInboundHandler` that re-entrantly calls into a handler that just passed
/// it `channelRead`.
final class ReenterOnReadHandler: ChannelInboundHandler {
public typealias InboundIn = Any
// We only want to re-enter once. Otherwise we could loop indefinitely.
private var shouldReenter = true
private let reEnterCallback: (ChannelPipeline) -> Void
init(reEnterCallback: @escaping (ChannelPipeline) -> Void) {
self.reEnterCallback = reEnterCallback
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
guard self.shouldReenter else {
context.fireChannelRead(data)
return
}
self.shouldReenter = false
context.fireChannelRead(data)
self.reEnterCallback(context.pipeline)
}
}
final class WindowUpdatedEventHandler: ChannelInboundHandler {
public typealias InboundIn = HTTP2Frame
public typealias InboundOut = HTTP2Frame
public typealias OutboundOut = HTTP2Frame
init() {
}
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
guard event is NIOHTTP2WindowUpdatedEvent else { return }
let frame = HTTP2Frame(streamID: .rootStream, payload: .windowUpdate(windowSizeIncrement: 1))
context.writeAndFlush(self.wrapOutboundOut(frame), promise: nil)
}
}
// Tests that the HTTP2Parser is safely re-entrant.
//
// These tests ensure that we don't ever call into the HTTP/2 session more than once at a time.
final class ReentrancyTests: XCTestCase {
var clientChannel: EmbeddedChannel!
var serverChannel: EmbeddedChannel!
override func setUp() {
self.clientChannel = EmbeddedChannel()
self.serverChannel = EmbeddedChannel()
}
override func tearDown() {
self.clientChannel = nil
self.serverChannel = nil
}
/// Establish a basic HTTP/2 connection.
func basicHTTP2Connection() throws {
XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client)).wait())
XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server)).wait())
try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)
}
func testReEnterReadOnRead() throws {
// Start by setting up the connection.
try self.basicHTTP2Connection()
// Here we're going to prepare some frames: specifically, we're going to send a SETTINGS frame and a PING frame at the same time.
// We need to send two frames to try to catch any ordering problems we might hit.
let settings: [HTTP2Setting] = [HTTP2Setting(parameter: .enablePush, value: 0), HTTP2Setting(parameter: .maxConcurrentStreams, value: 5)]
let settingsFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings)))
let pingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(withInteger: 5), ack: false))
self.clientChannel.write(settingsFrame, promise: nil)
self.clientChannel.write(pingFrame, promise: nil)
self.clientChannel.flush()
// Collect the serialized frames.
var frameBuffer = self.clientChannel.allocator.buffer(capacity: 1024)
while case .some(.byteBuffer(var buf)) = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: IOData.self)) {
frameBuffer.writeBuffer(&buf)
}
// Ok, now we can add in the re-entrancy handler to the server channel. When it first gets a frame it's
// going to fire in the buffer again.
let reEntrancyHandler = ReenterOnReadHandler { $0.fireChannelRead(NIOAny(frameBuffer)) }
XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(reEntrancyHandler).wait())
// Now we can deliver these bytes.
XCTAssertTrue(try self.serverChannel.writeInbound(frameBuffer).isFull)
// If this worked, we want to see that the server received SETTINGS, PING, SETTINGS, PING. No other order is
// ok, no errors should have been hit.
try self.serverChannel.assertReceivedFrame().assertFrameMatches(this: settingsFrame)
try self.serverChannel.assertReceivedFrame().assertFrameMatches(this: pingFrame)
try self.serverChannel.assertReceivedFrame().assertFrameMatches(this: settingsFrame)
try self.serverChannel.assertReceivedFrame().assertFrameMatches(this: pingFrame)
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testReenterInactiveOnRead() throws {
// Start by setting up the connection.
try self.basicHTTP2Connection()
// Here we're going to prepare some frames: specifically, we're going to send a SETTINGS frame and a PING frame at the same time.
// We need to send two frames to try to catch any ordering problems we might hit.
let settings: [HTTP2Setting] = [HTTP2Setting(parameter: .enablePush, value: 0), HTTP2Setting(parameter: .maxConcurrentStreams, value: 5)]
let settingsFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings)))
let pingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(withInteger: 5), ack: false))
self.clientChannel.write(settingsFrame, promise: nil)
self.clientChannel.write(pingFrame, promise: nil)
self.clientChannel.flush()
// Ok, now we can add in the re-entrancy handler to the server channel. When it first gets a frame it's
// going to fire channelInactive.
let reEntrancyHandler = ReenterOnReadHandler { $0.fireChannelInactive() }
XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(reEntrancyHandler).wait())
// Now we can deliver these bytes.
self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel)
// If this worked, we want to see that the server received SETTINGS. The PING frame should not be produced, as
// the channelInactive has been fired. No other order is ok, no errors should have been hit, and the channel
// should now be closed.
try self.serverChannel.assertReceivedFrame().assertFrameMatches(this: settingsFrame)
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testReenterReadEOFOnRead() throws {
// Start by setting up the connection.
try self.basicHTTP2Connection()
// Here we're going to prepare some frames: specifically, we're going to send a SETTINGS frame and a PING frame at the same time.
// We need to send two frames to try to catch any ordering problems we might hit.
let settings: [HTTP2Setting] = [HTTP2Setting(parameter: .enablePush, value: 0), HTTP2Setting(parameter: .maxConcurrentStreams, value: 5)]
let settingsFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings)))
let pingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(withInteger: 5), ack: false))
self.clientChannel.write(settingsFrame, promise: nil)
self.clientChannel.write(pingFrame, promise: nil)
self.clientChannel.flush()
// Ok, now we can add in the re-entrancy handler to the server channel. When it first gets a frame it's
// going to fire channelInactive.
let reEntrancyHandler = ReenterOnReadHandler { $0.fireUserInboundEventTriggered(ChannelEvent.inputClosed) }
XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(reEntrancyHandler).wait())
// Now we can deliver these bytes.
self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel)
// If this worked, we want to see that the server received SETTINGS then PING. No other order is
// ok, no errors should have been hit, and the channel should now be closed.
try self.serverChannel.assertReceivedFrame().assertFrameMatches(this: settingsFrame)
try self.serverChannel.assertReceivedFrame().assertFrameMatches(this: pingFrame)
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testReenterAutomaticFrames() throws {
// Start by setting up the connection.
try self.basicHTTP2Connection()
let windowUpdateFrameHandler = WindowUpdatedEventHandler()
XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(windowUpdateFrameHandler).wait())
// Write and flush the header from the client to open a stream
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let reqFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: headers))
self.clientChannel.writeAndFlush(HTTP2Frame(streamID: 1, payload: reqFramePayload), promise: nil)
self.interactInMemory(clientChannel, serverChannel)
// Write and flush the header from the server
let resHeaders = HPACKHeaders([(":status", "200")])
let resFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: resHeaders))
self.serverChannel.writeAndFlush(HTTP2Frame(streamID: 1, payload: resFramePayload), promise: nil)
// Write lots of small data frames and flush them all at once
var requestBody = self.serverChannel.allocator.buffer(capacity: 1)
requestBody.writeBytes(Array(repeating: UInt8(0x04), count: 1))
var reqBodyFramePayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(requestBody)))
for _ in 0..<10000 {
serverChannel.write(HTTP2Frame(streamID: 1, payload: reqBodyFramePayload), promise: nil)
}
reqBodyFramePayload = .data(.init(data: .byteBuffer(requestBody), endStream: true))
serverChannel.writeAndFlush(HTTP2Frame(streamID: 1, payload: reqBodyFramePayload), promise: nil)
// Now we can deliver these bytes.
self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel)
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
}
|
apache-2.0
|
00c39bbcd0f5b6db220ec2bbcada8a89
| 48.816514 | 145 | 0.699448 | 4.725849 | false | false | false | false |
scoremedia/Fisticuffs
|
iOS Example/ViewModels/AddItemViewModel.swift
|
1
|
1715
|
// The MIT License (MIT)
//
// Copyright (c) 2015 theScore Inc.
//
// 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 Fisticuffs
enum AddItemResult {
case NewToDoItem(ToDoItem)
case Cancelled
}
class AddItemViewModel {
let item = ToDoItem()
let finished = Event<AddItemResult>()
lazy var inputIsValid: Computed<Bool> = Computed { [item = self.item] in
return item.title.value.isEmpty == false
}
func doneTapped() {
if !inputIsValid.value {
return
}
finished.fire(.NewToDoItem(item))
}
func cancelTapped() {
finished.fire(.Cancelled)
}
}
|
mit
|
b19a5fde792b697a0ee81234d36714c0
| 30.181818 | 81 | 0.693294 | 4.319899 | false | false | false | false |
apple/swift
|
test/refactoring/RefactoringKind/convert_to_switch_statement.swift
|
7
|
6101
|
enum E {
case first
case second
case third
case fourth
}
func checkForEnum(e: E) {
if e == .first {
print("first")
} else if e == .second {
print("second")
}
else {
print("default")
}
let x = "some other type"
if e == .first {
print("first")
} else if x == "some value" {
print("x")
}
}
func checkBiggerOrSmallerSign(integer: Int) {
if integer > 0 {
print("Positive integer")
} else if integer < 0 {
print("Negative integer")
} else {
print("Zero")
}
}
func checkInverseCondition(e: E) {
if .first == e {
print("first")
} else if .second == e {
print("second")
} else {
print("default")
}
}
func checkAvailabilityCondition() {
if #available(iOS 13, *) {
print("#available may only be used as condition of an 'if', 'guard' or 'while' statement")
}
}
func checkCaseCondition() {
let someOptional: Int? = 42
// Match using an enumeration case pattern.
if case .some(let x) = someOptional {
print(x)
}
// Match using an optional pattern.
if case let x? = someOptional {
print(x)
}
}
func checkOptionalBindingCondition(optional: String?) {
if let unwrapped = optional {
print(unwrapped)
}
if var unwrapped = optional {
unwrapped += "!"
print(unwrapped)
}
}
func checkConditionalList(x: Int, y: Int) -> Bool {
if x > 0, y < 0 {
return false
}
if x > 0, x < 10 {
return true
}
}
func checkFunctionCallExpression() {
if checkConditionalList(x: 0, y: 0) {
print("false")
}
}
func checkMultipleOrConditions(e: E) {
if e == .first || e == .second || e == .third {
print("1-3")
} else if e == .fourth {
print("4")
} else {
print(">4")
}
}
func checkMultipleAndConditions(e: E) {
if e == .first && e == .second && e == .third {
print("Never executed")
} else {
print("Whenever")
}
}
func checkMultipleWithUnrelatedCondition(e: E, x: Int) {
if e == .first || x > 0 {
print("e is the first or x is positive")
} else {
print("Shouldn't convert to switch")
}
}
func checkOperatorIsActuallyBeingUsed(e: E) {
if e != .first {
print("Can't use at case statement")
}
}
func checkLabeledCondition() {
enum Foo { case a, b, c }
let e = Foo.a
let f = Foo.a
outerLabel: if e == .a {
innerLabel: switch f {
case .a:
break outerLabel
default:
break innerLabel
}
print("outside switch")
}
print("outside if")
}
func checkEnumWithAssociatedValues() {
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
let productBarcode = Barcode.upc(8, 85909, 51226, 3)
if case .upc(let numberSystem, let manufacturer, let product, let check) = productBarcode {
print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).")
} else if case let .qrCode(productCode) = productBarcode {
print("QR code: \(productCode).")
}
}
func checkEquatableProtocol(x: Int) {
if x == 5 {
print("5")
} else if x == 4 {
print("4")
} else if 1...3 ~= x {
print("1...3")
} else {
print("default")
}
struct MyType: Equatable { let v: String }
let y = MyType(v: "hello")
if y == MyType(v: "bye") {
print("bye")
} else if y == MyType(v: "tchau") {
print("tchau")
} else {
print("default")
}
}
// RUN: %refactor -pos=9:3 -end-pos=16:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT
// RUN: %refactor -pos=19:3 -end-pos=23:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT2
// RUN: %refactor -pos=27:3 -end-pos=33:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT2
// RUN: %refactor -pos=37:3 -end-pos=43:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT
// RUN: %refactor -pos=47:3 -end-pos=49:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT2
// RUN: %refactor -pos=55:3 -end-pos=57:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT
// RUN: %refactor -pos=60:3 -end-pos=62:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT
// RUN: %refactor -pos=66:3 -end-pos=68:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT
// RUN: %refactor -pos=70:3 -end-pos=73:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT
// RUN: %refactor -pos=77:3 -end-pos=79:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT2
// RUN: %refactor -pos=81:3 -end-pos=83:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT2
// RUN: %refactor -pos=87:3 -end-pos=89:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT2
// RUN: %refactor -pos=93:3 -end-pos=99:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT
// RUN: %refactor -pos=103:3 -end-pos=107:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT2
// RUN: %refactor -pos=111:3 -end-pos=115:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT2
// RUN: %refactor -pos=119:3 -end-pos=121:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT2
// RUN: %refactor -pos=129:3 -end-pos=137:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT
// RUN: %refactor -pos=148:3 -end-pos=152:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT
// RUN: %refactor -pos=156:3 -end-pos=164:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT
// RUN: %refactor -pos=169:3 -end-pos=175:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-SWITCH-STATEMENT
// CHECK-CONVERT-TO-SWITCH-STATEMENT: Convert To Switch Statement
// CHECK-CONVERT-TO-SWITCH-STATEMENT2: Action begins
// CHECK-CONVERT-TO-SWITCH-STATEMENT2-NOT: Convert To Switch Statement
// CHECK-CONVERT-TO-SWITCH-STATEMENT2: Action ends
|
apache-2.0
|
14770b46428add83625a638edff53a7b
| 28.906863 | 128 | 0.651041 | 3.036834 | false | false | false | false |
SandroMachado/BitcoinPaymentURISwift
|
BitcoinPaymentURI/BitcoinPaymentURI.swift
|
1
|
6818
|
//
// BitcoinPaymentURI.swift
// BitcoinPaymentURI
//
// Created by Sandro Machado on 12/07/16.
// Copyright © 2016 Sandro. All rights reserved.
//
import Foundation
/// The Bitcoin Payment URI.
open class BitcoinPaymentURI: BitcoinPaymentURIProtocol {
/// Closure to do the builder.
typealias buildBitcoinPaymentURIClosure = (BitcoinPaymentURI) -> Void
fileprivate static let SCHEME = "bitcoin:"
fileprivate static let PARAMETER_AMOUNT = "amount"
fileprivate static let PARAMETER_LABEL = "label"
fileprivate static let PARAMETER_MESSAGE = "message"
fileprivate static let PARAMETER_REQUIRED_PREFIX = "req-"
fileprivate var allParameters: [String: Parameter]?
/// The address.
open var address: String?
/// The amount.
open var amount: Double? {
set(newValue) {
guard let newValue = newValue else {
return
}
self.allParameters?[BitcoinPaymentURI.PARAMETER_AMOUNT] = Parameter(value: String(newValue), required: false)
}
get {
guard let parameters = self.allParameters, let amount = parameters[BitcoinPaymentURI.PARAMETER_AMOUNT]?.value else {
return nil
}
return Double(amount)
}
}
/// The label.
open var label: String? {
set(newValue) {
guard let newValue = newValue else {
return
}
self.allParameters?[BitcoinPaymentURI.PARAMETER_LABEL] = Parameter(value: newValue, required: false)
}
get {
guard let parameters = self.allParameters, let label = parameters[BitcoinPaymentURI.PARAMETER_LABEL]?.value else {
return nil
}
return label
}
}
/// The message.
open var message: String? {
set(newValue) {
guard let newValue = newValue else {
return
}
self.allParameters?[BitcoinPaymentURI.PARAMETER_MESSAGE] = Parameter(value: newValue, required: false)
}
get {
guard let parameters = self.allParameters, let label = parameters[BitcoinPaymentURI.PARAMETER_MESSAGE]?.value else {
return nil
}
return label
}
}
/// The parameters.
open var parameters: [String: Parameter]? {
set(newValue) {
var newParameters: [String: Parameter] = [:]
guard let allParameters = self.allParameters, let newValue = newValue else {
return
}
for (key, value) in newValue {
newParameters[key] = value
}
for (key, value) in allParameters {
newParameters[key] = value
}
self.allParameters = newParameters
}
get {
guard var parametersFiltered = self.allParameters else {
return nil
}
parametersFiltered.removeValue(forKey: BitcoinPaymentURI.PARAMETER_AMOUNT)
parametersFiltered.removeValue(forKey: BitcoinPaymentURI.PARAMETER_LABEL)
parametersFiltered.removeValue(forKey: BitcoinPaymentURI.PARAMETER_MESSAGE)
return parametersFiltered
}
}
// The uri.
open var uri: String? {
get {
var urlComponents = URLComponents()
urlComponents.scheme = BitcoinPaymentURI.SCHEME.replacingOccurrences(of: ":", with: "");
urlComponents.path = self.address!;
urlComponents.queryItems = []
guard let allParameters = self.allParameters else {
return urlComponents.string
}
for (key, value) in allParameters {
if (value.required) {
urlComponents.queryItems?.append(URLQueryItem(name: "\(BitcoinPaymentURI.PARAMETER_REQUIRED_PREFIX)\(key)", value: value.value))
continue
}
urlComponents.queryItems?.append(URLQueryItem(name: key, value: value.value))
}
return urlComponents.string
}
}
/**
Constructor.
- parameter build: The builder to generate a BitcoinPaymentURI.
*/
init(build: buildBitcoinPaymentURIClosure) {
allParameters = [:]
build(self)
}
/**
Converts a String to a BitcoinPaymentURI.
- parameter bitcoinPaymentURI: The string with the Bitcoin Payment URI.
- returns: a BitcoinPaymentURI.
*/
open static func parse(_ bitcoinPaymentURI: String) -> BitcoinPaymentURI? {
let schemeRange = Range<String.Index>(bitcoinPaymentURI.characters.index(bitcoinPaymentURI.startIndex, offsetBy: 0)..<bitcoinPaymentURI.characters.index(bitcoinPaymentURI.startIndex, offsetBy: SCHEME.characters.count))
let paramReqRange = Range<String.Index>(bitcoinPaymentURI.characters.index(bitcoinPaymentURI.startIndex, offsetBy: 0)..<bitcoinPaymentURI.characters.index(bitcoinPaymentURI.startIndex, offsetBy: PARAMETER_REQUIRED_PREFIX.characters.count))
guard let _ = bitcoinPaymentURI.range(of: SCHEME, options: NSString.CompareOptions.caseInsensitive, range: schemeRange) else {
return nil
}
let urlComponents = URLComponents(string: String(bitcoinPaymentURI))
guard let address = urlComponents?.path, !address.isEmpty else {
return nil
}
return BitcoinPaymentURI(build: {
$0.address = address
var newParameters: [String: Parameter] = [:]
if let queryItems = urlComponents?.queryItems {
for queryItem in queryItems {
guard let value = queryItem.value else {
continue
}
var required: Bool = true
if (queryItem.name.characters.count <= PARAMETER_REQUIRED_PREFIX.characters.count || queryItem.name.range(of: PARAMETER_REQUIRED_PREFIX, options: NSString.CompareOptions.caseInsensitive, range: paramReqRange) == nil) {
required = false
}
newParameters[queryItem.name.replacingOccurrences(of: PARAMETER_REQUIRED_PREFIX, with: "")] = Parameter(value: value, required: required)
}
}
$0.parameters = newParameters
})
}
}
|
mit
|
bcde3f74b8fa03b388f0b2dde36d75ab
| 33.085 | 247 | 0.565645 | 5.251926 | false | false | false | false |
katafo/CPAlertViewController
|
CPAlertViewController/ViewController.swift
|
1
|
2407
|
//
// ViewController.swift
// CPAlertViewController
//
// Created by Phong Cao on 2/19/17.
// Copyright © 2017 admin. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var alertVC: CPAlertVC!
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.
}
@IBAction func openNormalAlert(_ sender: Any) {
alertVC = CPAlertVC(title: "Normal Alert", message: "Normal alert will have only one button.")
alertVC.show(into: self)
}
@IBAction func openAlertWithAction(_ sender: Any) {
alertVC = CPAlertVC(title: "Action Alert", message: "You can add your action to two buttons below. By default: Cancel button will dismiss alert.")
alertVC.addAction(CPAlertAction(title: "OK", type: .normal, handler: {
print("Tapped OK button")
}))
alertVC.addAction(CPAlertAction(title: "CANCEL", type: .cancel, handler: {
print("Tapped Cancel button")
}))
alertVC.show(into: self)
}
@IBAction func openCustomStyleAlert(_ sender: Any) {
let customAlertVC = CustomAlertVC(title: "Success", message: "Have a nice day !")
customAlertVC.showCheckImage(true) // True: show ic_check, False: show ic_music
customAlertVC.show(into: self)
}
@IBAction func openAlertWithRotateAnimation(_ sender: Any) {
alertVC = CPAlertVC(title: "Rotate Animation", message: "Rotate ~90 degrees = 1.5 rad (1 rad = 57 degrees), you can change it in CPAlertVC.swift.", animationType: .rotate)
alertVC.show(into: self)
}
@IBAction func openAlertWithBounceUpAnimation(_ sender: Any) {
alertVC = CPAlertVC(title: "Bounce Up Animation", message: "Animating alert from bottom view to top view", animationType: .bounceUp)
alertVC.springWithDamping = 0.75
alertVC.animateDuration = 0.5
alertVC.show(into: self)
}
@IBAction func openAlertWithBounceDownAniamtion(_ sender: Any) {
alertVC = CPAlertVC(title: "Bounce Down Animation", message: "Animating alert from top view to bottom view", animationType: .bounceDown)
alertVC.show(into: self)
}
}
|
mit
|
48a73072f0847fe5234641c886450320
| 37.190476 | 179 | 0.66251 | 4.235915 | false | false | false | false |
RuiAAPeres/Nuke
|
Nuke/Source/Core/ImageTask.swift
|
1
|
2722
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Alexander Grebenyuk (github.com/kean).
import Foundation
public enum ImageTaskState {
case Suspended, Running, Cancelled, Completed
}
public typealias ImageTaskCompletion = (ImageResponse) -> Void
public typealias ImageTaskProgress = (completedUnitCount: Int64, totalUnitCount: Int64) -> Void
/** Abstract class for image tasks. Tasks are always part of the image manager, you create a task by calling one of the methods on ImageManager.
*/
public class ImageTask: Hashable {
public let request: ImageRequest
public internal(set) var state: ImageTaskState = .Suspended
public internal(set) var response: ImageResponse?
public internal(set) var completedUnitCount: Int64 = 0
public internal(set) var totalUnitCount: Int64 = 0
public var hashValue: Int { return self.identifier }
/** Uniquely identifies the task within an image manager.
*/
public let identifier: Int
/** A progress closure that gets periodically during the lifecycle of the task.
*/
public var progress: ImageTaskProgress?
public init(request: ImageRequest, identifier: Int) {
self.request = request
self.identifier = identifier
}
/** Adds a closure to be called on the main thread when task is either completed or cancelled.
The closure is called synchronously when the requested image can be retrieved from the memory cache and the request was made from the main thread.
The closure is called even if it is added to the already completed or cancelled task.
*/
public func completion(completion: ImageTaskCompletion) -> Self { fatalError("Abstract method") }
public func resume() -> Self { fatalError("Abstract method") }
/** Advices the task to suspend loading. If the task is suspended if might still complete at any time.
A download task can continue transferring data at a later time. All other tasks must start over when resumed. For more info on suspending NSURLSessionTask see NSURLSession documentation.
*/
public func suspend() -> Self { fatalError("Abstract method") }
/** Cancels the task if it hasn't completed yet. Calls a completion closure with an error value of { ImageManagerErrorDomain, ImageManagerErrorCancelled }.
*/
public func cancel() -> Self { fatalError("Abstract method") }
}
public extension ImageTask {
public var fractionCompleted: Double {
guard self.totalUnitCount != 0 else {
return 0.0
}
return Double(self.completedUnitCount) / Double(self.totalUnitCount)
}
}
public func ==(lhs: ImageTask, rhs: ImageTask) -> Bool {
return lhs === rhs
}
|
mit
|
71d154dbc2c95764fbaf8e2e113286d5
| 38.449275 | 190 | 0.709772 | 4.949091 | false | false | false | false |
aiwalle/LiveProject
|
LiveProject/Home/LJHomeController.swift
|
1
|
2596
|
//
// LJHomeController.swift
// LiveProject
//
// Created by liang on 2017/7/28.
// Copyright © 2017年 liang. All rights reserved.
//
import UIKit
class LJHomeController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupNavigationBar()
setupContentView()
}
}
extension LJHomeController {
fileprivate func setupNavigationBar() {
let logoImage = UIImage(named: "home-logo1")?.withRenderingMode(.alwaysOriginal)
navigationItem.leftBarButtonItem = UIBarButtonItem(image: logoImage, style: .done, target: nil, action: nil)
let searchImage = UIImage(named: "search_btn_follow")?.withRenderingMode(.alwaysOriginal)
navigationItem.rightBarButtonItem = UIBarButtonItem(image: searchImage, style: .done, target: nil, action: nil)
let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
searchBar.placeholder = "主播昵称/房间号/链接"
searchBar.searchBarStyle = .minimal
navigationItem.titleView = searchBar
let searchField = searchBar.value(forKeyPath: "_searchField") as? UITextField
searchField?.textColor = .white
navigationController?.navigationBar.barTintColor = .black
}
fileprivate func setupContentView() {
let homeTypes = loadTypeData()
var style = LJPageStyle()
style.isScrollEnable = true
style.isNeedScale = true
// style.isShowCoverView = true
let pageFrame = CGRect(x: 0, y: kStatusBarHeight + kNavigationBarHeight, width: kDeviceWidth, height: kDeviceHeight - kStatusBarHeight - kNavigationBarHeight - kTabBarHeight)
let titles = homeTypes.map({$0.title})
var childVcs = [LJAnchorController]()
for type in homeTypes {
let anchorVc = LJAnchorController()
anchorVc.homeType = type
childVcs.append(anchorVc)
}
let pageView = LJPageView(frame: pageFrame, titles: titles, style: style, childVcs: childVcs, parentVc: self)
view.addSubview(pageView)
}
fileprivate func loadTypeData() -> [HomeType] {
let path = Bundle.main.path(forResource: "types.plist", ofType: nil)!
let dataArray = NSArray(contentsOfFile: path) as! [[String : Any]]
var tempArr = [HomeType]()
for dict in dataArray {
tempArr.append(HomeType(dict: dict))
}
return tempArr
}
}
|
mit
|
ba4000e150fa0b26b758d29d97068fd0
| 32.012821 | 182 | 0.63534 | 4.876894 | false | false | false | false |
quran/quran-ios
|
Sources/QuranKit/Quarter.swift
|
1
|
1709
|
//
// Quarter.swift
// Quran
//
// Created by Mohamed Afifi on 4/25/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import Foundation
public struct Quarter: QuranValueGroup {
public var quarterNumber: Int { storage.value }
let storage: QuranValueStorage<Self>
public var quran: Quran {
storage.quran
}
init(quran: Quran, quarterNumber: Int) {
storage = QuranValueStorage(quran: quran, value: quarterNumber, keyPath: \.quarters)
}
init(_ storage: QuranValueStorage<Self>) {
self.storage = storage
}
public var firstVerse: AyahNumber {
let verse = quran.raw.quarters[quarterNumber - 1]
return AyahNumber(quran: quran, sura: verse.sura, ayah: verse.ayah)!
}
public var page: Page {
firstVerse.page
}
public var hizb: Hizb {
let hizbNumber = (quarterNumber - 1) / (quran.quarters.count / quran.hizbs.count) + 1
return quran.hizbs[hizbNumber - 1]
}
public var juz: Juz {
let juzNumber = (quarterNumber - 1) / (quran.quarters.count / quran.juzs.count) + 1
return quran.juzs[juzNumber - 1]
}
}
|
apache-2.0
|
5bd8a054e71d3ea41ab281347dd4f6ef
| 28.982456 | 93 | 0.668812 | 3.806236 | false | false | false | false |
FuckBoilerplate/RxCache
|
watchOS/Pods/RxSwift/RxSwift/Observables/Implementations/DistinctUntilChanged.swift
|
6
|
2184
|
//
// DistinctUntilChanged.swift
// Rx
//
// Created by Krunoslav Zaher on 3/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class DistinctUntilChangedSink<O: ObserverType, Key>: Sink<O>, ObserverType {
typealias E = O.E
private let _parent: DistinctUntilChanged<E, Key>
private var _currentKey: Key? = nil
init(parent: DistinctUntilChanged<E, Key>, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
switch event {
case .next(let value):
do {
let key = try _parent._selector(value)
var areEqual = false
if let currentKey = _currentKey {
areEqual = try _parent._comparer(currentKey, key)
}
if areEqual {
return
}
_currentKey = key
forwardOn(event)
}
catch let error {
forwardOn(.error(error))
dispose()
}
case .error, .completed:
forwardOn(event)
dispose()
}
}
}
class DistinctUntilChanged<Element, Key>: Producer<Element> {
typealias KeySelector = (Element) throws -> Key
typealias EqualityComparer = (Key, Key) throws -> Bool
fileprivate let _source: Observable<Element>
fileprivate let _selector: KeySelector
fileprivate let _comparer: EqualityComparer
init(source: Observable<Element>, selector: @escaping KeySelector, comparer: @escaping EqualityComparer) {
_source = source
_selector = selector
_comparer = comparer
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = DistinctUntilChangedSink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
|
mit
|
8d475ca88fde375d2248ed2c77da45b2
| 30.185714 | 144 | 0.57169 | 4.927765 | false | false | false | false |
BlurredSoftware/BSWInterfaceKit
|
Sources/BSWInterfaceKit/Extensions/UIImage+Utilities.swift
|
1
|
2526
|
//
// UIImage+InterfaceKit.swift
// Created by Pierluigi Cifani on 22/04/16.
//
#if canImport(UIKit)
import UIKit
import BSWInterfaceKitObjC
public extension UIImage {
/**
Generates an UIImage from a CAGradientLayer
- parameter gradientLayer: The defined gradient layer
- returns: The UIImage based on the gradient layer
*/
static func image(fromGradientLayer gradientLayer: CAGradientLayer) -> UIImage {
UIGraphicsBeginImageContext(gradientLayer.bounds.size)
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
/**
Redraws the `UIImage` to the given size. Use this method
to redraw big PDF based images to smaller sizes and force
a smaller `intrinsicContentSize` to the host `UIImageView`
- parameter newSize: The new size of the image
- returns: The resized UIImage
*/
func scaleTo(_ newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage ?? self
}
@available(iOS, deprecated: 13.0, obsoleted: 14.0, message: "This will be removed in iOS 14; please migrate to a different API.")
func tint(_ tintColor: UIColor) -> UIImage {
return modifiedImage { context, rect in
context.setBlendMode(.multiply)
context.clip(to: rect, mask: self.cgImage!)
tintColor.setFill()
context.fill(rect)
}
}
private func modifiedImage( draw: (CGContext, CGRect) -> ()) -> UIImage {
// using scale correctly preserves retina images
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else { return self }
// correctly rotate image
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
draw(context, rect)
guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else { return self }
return newImage
}
}
#endif
|
mit
|
0429b17beb82cbb0bec293b3b2094e2e
| 32.68 | 133 | 0.651227 | 5.021869 | false | false | false | false |
Acidburn0zzz/firefox-ios
|
Client/Frontend/Browser/BrowserTrayAnimators.swift
|
1
|
16135
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
class TrayToBrowserAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if let bvc = transitionContext.viewController(forKey: .to) as? BrowserViewController,
let tabTray = transitionContext.viewController(forKey: .from) as? TabTrayControllerV1 {
transitionFromTray(tabTray, toBrowser: bvc, usingContext: transitionContext)
}
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.4
}
}
private extension TrayToBrowserAnimator {
func transitionFromTray(_ tabTray: TabTrayControllerV1, toBrowser bvc: BrowserViewController, usingContext transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
guard let selectedTab = bvc.tabManager.selectedTab else { return }
let tabManager = bvc.tabManager
let displayedTabs = selectedTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs
guard let expandFromIndex = displayedTabs.firstIndex(of: selectedTab) else { return }
//Disable toolbar until animation completes
tabTray.toolbar.isUserInteractionEnabled = false
bvc.view.frame = transitionContext.finalFrame(for: bvc)
// Hide browser components
bvc.toggleSnackBarVisibility(show: false)
toggleWebViewVisibility(false, usingTabManager: bvc.tabManager)
bvc.firefoxHomeViewController?.view.isHidden = true
bvc.webViewContainerBackdrop.isHidden = true
bvc.statusBarOverlay.isHidden = false
if let url = selectedTab.url, !url.isReaderModeURL {
bvc.hideReaderModeBar(animated: false)
}
// Take a snapshot of the collection view that we can scale/fade out. We don't need to wait for screen updates since it's already rendered on the screen
let tabCollectionViewSnapshot = tabTray.collectionView.snapshotView(afterScreenUpdates: false)!
tabTray.collectionView.alpha = 0
tabCollectionViewSnapshot.frame = tabTray.collectionView.frame
container.insertSubview(tabCollectionViewSnapshot, at: 0)
// Create a fake cell to use for the upscaling animation
let startingFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView, atIndex: expandFromIndex)
let cell = createTransitionCellFromTab(bvc.tabManager.selectedTab, withFrame: startingFrame)
cell.backgroundHolder.layer.cornerRadius = 0
container.insertSubview(bvc.view, aboveSubview: tabCollectionViewSnapshot)
container.insertSubview(cell, aboveSubview: bvc.view)
// Flush any pending layout/animation code in preperation of the animation call
container.layoutIfNeeded()
let finalFrame = calculateExpandedCellFrameFromBVC(bvc)
bvc.footer.alpha = shouldDisplayFooterForBVC(bvc) ? 1 : 0
bvc.urlBar.isTransitioning = true
// Re-calculate the starting transforms for header/footer views in case we switch orientation
resetTransformsForViews([bvc.header, bvc.readerModeBar, bvc.footer])
transformHeaderFooterForBVC(bvc, toFrame: startingFrame, container: container)
let frameResizeClosure = {
// Scale up the cell and reset the transforms for the header/footers
cell.frame = finalFrame
container.layoutIfNeeded()
cell.title.transform = CGAffineTransform(translationX: 0, y: -cell.title.frame.height)
bvc.tabTrayDidDismiss(tabTray)
tabTray.toolbar.transform = CGAffineTransform(translationX: 0, y: UIConstants.BottomToolbarHeight)
tabCollectionViewSnapshot.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
}
if UIAccessibility.isReduceMotionEnabled {
frameResizeClosure()
}
UIView.animate(withDuration: self.transitionDuration(using: transitionContext),
delay: 0, usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: [],
animations: {
if !UIAccessibility.isReduceMotionEnabled {
frameResizeClosure()
}
UIApplication.shared.windows.first?.backgroundColor = UIColor.theme.browser.background
tabTray.navigationController?.setNeedsStatusBarAppearanceUpdate()
tabCollectionViewSnapshot.alpha = 0
tabTray.statusBarBG.alpha = 0
tabTray.searchBarHolder.alpha = 0
}, completion: { finished in
// Remove any of the views we used for the animation
cell.removeFromSuperview()
tabCollectionViewSnapshot.removeFromSuperview()
bvc.footer.alpha = 1
bvc.toggleSnackBarVisibility(show: true)
toggleWebViewVisibility(true, usingTabManager: bvc.tabManager)
bvc.webViewContainerBackdrop.isHidden = false
bvc.firefoxHomeViewController?.view.isHidden = false
bvc.urlBar.isTransitioning = false
tabTray.toolbar.isUserInteractionEnabled = true
transitionContext.completeTransition(true)
})
}
}
class BrowserToTrayAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if let bvc = transitionContext.viewController(forKey: .from) as? BrowserViewController,
let tabTray = transitionContext.viewController(forKey: .to) as? TabTrayControllerV1 {
transitionFromBrowser(bvc, toTabTray: tabTray, usingContext: transitionContext)
}
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.4
}
}
private extension BrowserToTrayAnimator {
func transitionFromBrowser(_ bvc: BrowserViewController, toTabTray tabTray: TabTrayControllerV1, usingContext transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
guard let selectedTab = bvc.tabManager.selectedTab else { return }
let tabManager = bvc.tabManager
let displayedTabs = selectedTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs
guard let scrollToIndex = displayedTabs.firstIndex(of: selectedTab) else { return }
//Disable toolbar until animation completes
tabTray.toolbar.isUserInteractionEnabled = false
tabTray.view.frame = transitionContext.finalFrame(for: tabTray)
// Insert tab tray below the browser and force a layout so the collection view can get it's frame right
container.insertSubview(tabTray.view, belowSubview: bvc.view)
// Force subview layout on the collection view so we can calculate the correct end frame for the animation
tabTray.view.layoutIfNeeded()
tabTray.focusTab()
// Build a tab cell that we will use to animate the scaling of the browser to the tab
let expandedFrame = calculateExpandedCellFrameFromBVC(bvc)
let cell = createTransitionCellFromTab(bvc.tabManager.selectedTab, withFrame: expandedFrame)
cell.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius
// Take a snapshot of the collection view to perform the scaling/alpha effect
let tabCollectionViewSnapshot = tabTray.collectionView.snapshotView(afterScreenUpdates: true)!
tabCollectionViewSnapshot.frame = tabTray.collectionView.frame
tabCollectionViewSnapshot.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
tabCollectionViewSnapshot.alpha = 0
tabTray.view.insertSubview(tabCollectionViewSnapshot, belowSubview: tabTray.toolbar)
if let toast = bvc.clipboardBarDisplayHandler?.clipboardToast {
toast.removeFromSuperview()
}
container.addSubview(cell)
cell.layoutIfNeeded()
cell.title.transform = CGAffineTransform(translationX: 0, y: -cell.title.frame.size.height)
// Hide views we don't want to show during the animation in the BVC
bvc.firefoxHomeViewController?.view.isHidden = true
bvc.statusBarOverlay.isHidden = true
bvc.toggleSnackBarVisibility(show: false)
toggleWebViewVisibility(false, usingTabManager: bvc.tabManager)
bvc.urlBar.isTransitioning = true
// On iPhone, fading these in produces a darkening at the top of the screen, and then
// it brightens back to full white as they fade in. Setting these to not fade in produces a better effect.
if UIDevice.current.userInterfaceIdiom == .phone {
tabTray.statusBarBG.alpha = 1
tabTray.searchBarHolder.alpha = 1
}
// Since we are hiding the collection view and the snapshot API takes the snapshot after the next screen update,
// the screenshot ends up being blank unless we set the collection view hidden after the screen update happens.
// To work around this, we dispatch the setting of collection view to hidden after the screen update is completed.
DispatchQueue.main.async {
tabTray.collectionView.isHidden = true
let finalFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView,
atIndex: scrollToIndex)
tabTray.toolbar.transform = CGAffineTransform(translationX: 0, y: UIConstants.BottomToolbarHeight)
let frameResizeClosure = {
cell.frame = finalFrame
cell.layoutIfNeeded()
transformHeaderFooterForBVC(bvc, toFrame: finalFrame, container: container)
resetTransformsForViews([tabCollectionViewSnapshot])
}
if UIAccessibility.isReduceMotionEnabled {
frameResizeClosure()
}
UIView.animate(withDuration: self.transitionDuration(using: transitionContext),
delay: 0, usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: [],
animations: {
cell.title.transform = .identity
UIApplication.shared.windows.first?.backgroundColor = UIColor.theme.tabTray.background
tabTray.navigationController?.setNeedsStatusBarAppearanceUpdate()
bvc.urlBar.updateAlphaForSubviews(0)
bvc.footer.alpha = 0
tabCollectionViewSnapshot.alpha = 1
tabTray.statusBarBG.alpha = 1
tabTray.searchBarHolder.alpha = 1
tabTray.toolbar.transform = .identity
if !UIAccessibility.isReduceMotionEnabled {
frameResizeClosure()
}
}, completion: { finished in
// Remove any of the views we used for the animation
cell.removeFromSuperview()
tabCollectionViewSnapshot.removeFromSuperview()
tabTray.collectionView.isHidden = false
bvc.toggleSnackBarVisibility(show: true)
toggleWebViewVisibility(true, usingTabManager: bvc.tabManager)
bvc.firefoxHomeViewController?.view.isHidden = false
resetTransformsForViews([bvc.header, bvc.readerModeBar, bvc.footer])
bvc.urlBar.isTransitioning = false
tabTray.toolbar.isUserInteractionEnabled = true
transitionContext.completeTransition(true)
})
}
}
}
private func transformHeaderFooterForBVC(_ bvc: BrowserViewController, toFrame finalFrame: CGRect, container: UIView) {
let footerForTransform = footerTransform(bvc.footer.frame, toFrame: finalFrame, container: container)
let headerForTransform = headerTransform(bvc.header.frame, toFrame: finalFrame, container: container)
bvc.footer.transform = footerForTransform
bvc.header.transform = headerForTransform
bvc.readerModeBar?.transform = headerForTransform
}
private func footerTransform( _ frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform {
let frame = container.convert(frame, to: container)
let endY = finalFrame.maxY - (frame.size.height / 2)
let endX = finalFrame.midX
let translation = CGPoint(x: endX - frame.midX, y: endY - frame.midY)
let scaleX = finalFrame.width / frame.width
var transform: CGAffineTransform = .identity
transform = transform.translatedBy(x: translation.x, y: translation.y)
transform = transform.scaledBy(x: scaleX, y: scaleX)
return transform
}
private func headerTransform(_ frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform {
let frame = container.convert(frame, to: container)
let endY = finalFrame.minY + (frame.size.height / 2)
let endX = finalFrame.midX
let translation = CGPoint(x: endX - frame.midX, y: endY - frame.midY)
let scaleX = finalFrame.width / frame.width
var transform: CGAffineTransform = .identity
transform = transform.translatedBy(x: translation.x, y: translation.y)
transform = transform.scaledBy(x: scaleX, y: scaleX)
return transform
}
//MARK: Private Helper Methods
private func calculateCollapsedCellFrameUsingCollectionView(_ collectionView: UICollectionView, atIndex index: Int) -> CGRect {
guard index < collectionView.numberOfItems(inSection: 0) else {
return .zero
}
if let attr = collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: index, section: 0)) {
return collectionView.convert(attr.frame, to: collectionView.superview)
} else {
return .zero
}
}
private func calculateExpandedCellFrameFromBVC(_ bvc: BrowserViewController) -> CGRect {
var frame = bvc.webViewContainer.frame
// If we're navigating to a home panel and we were expecting to show the toolbar, add more height to end frame since
// there is no toolbar for home panels
if !bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) {
return frame
}
if let url = bvc.tabManager.selectedTab?.url, bvc.toolbar == nil, let internalPage = InternalURL(url), internalPage.isAboutURL {
frame.size.height += UIConstants.BottomToolbarHeight
}
return frame
}
private func shouldDisplayFooterForBVC(_ bvc: BrowserViewController) -> Bool {
guard let url = bvc.tabManager.selectedTab?.url else { return false }
let isAboutPage = InternalURL(url)?.isAboutURL ?? false
return bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) && !isAboutPage
}
private func toggleWebViewVisibility(_ show: Bool, usingTabManager tabManager: TabManager) {
for i in 0..<tabManager.count {
if let tab = tabManager[i] {
tab.webView?.isHidden = !show
}
}
}
private func resetTransformsForViews(_ views: [UIView?]) {
for view in views {
// Reset back to origin
view?.transform = .identity
}
}
private func createTransitionCellFromTab(_ tab: Tab?, withFrame frame: CGRect) -> TabCell {
let cell = TabCell(frame: frame)
cell.screenshotView.image = tab?.screenshot
cell.titleText.text = tab?.displayTitle
if let favIcon = tab?.displayFavicon {
cell.favicon.sd_setImage(with: URL(string: favIcon.url)!)
} else {
let defaultFavicon = UIImage(named: "defaultFavicon")
if tab?.isPrivate ?? false {
cell.favicon.image = defaultFavicon
cell.favicon.tintColor = (tab?.isPrivate ?? false) ? UIColor.Photon.White100 : UIColor.Photon.Grey60
} else {
cell.favicon.image = defaultFavicon
cell.favicon.tintColor = UIColor.theme.tabTray.faviconTint
}
}
return cell
}
|
mpl-2.0
|
97400d0e9f804b8f0cc51b047643adb4
| 45.232092 | 172 | 0.695259 | 5.586911 | false | false | false | false |
ghotjunwoo/Tiat
|
FriendDetailViewController.swift
|
1
|
7683
|
//
// FriendDetailViewController.swift
// Tiat
//
// Created by 이종승 on 2016. 10. 1..
// Copyright © 2016년 JW. All rights reserved.
//
import UIKit
import Firebase
class FriendDetailViewController: UIViewController {
var friendUid = String()
var friendName = String()
@IBOutlet var informationView: UIView!
@IBOutlet weak var circleGraphView1: UIView!
@IBOutlet weak var happyCircleGraphView: CircleGraphView!
@IBOutlet weak var sadCircleGraphView: CircleGraphView!
@IBOutlet weak var lonleyCircleGraphView: CircleGraphView!
@IBOutlet weak var angerCircleGraphView: CircleGraphView!
@IBOutlet weak var loveCircleGraphView: CircleGraphView!
@IBOutlet weak var unrestCircleGraphView: CircleGraphView!
@IBOutlet weak var circleGraphView2: UIView!
@IBOutlet weak var sleepCircleGraphVIew: CircleGraphView!
@IBOutlet weak var excerciseCircleGraphView: CircleGraphView!
@IBOutlet weak var diseaseCircleGraphView: CircleGraphView!
@IBOutlet weak var hurtCIrcleGraphView: CircleGraphView!
@IBOutlet weak var conditionLabel: UILabel!
@IBOutlet weak var healthConditonLabel: UILabel!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var healthStatusLabel: UILabel!
@IBOutlet weak var problemLabel: UILabel!
@IBOutlet var topBar: UINavigationItem!
override func viewDidLoad() {
super.viewDidLoad()
sadCircleGraphView.arcColor = UIColor.blue
lonleyCircleGraphView.arcColor = UIColor.gray
angerCircleGraphView.arcColor = UIColor.purple
loveCircleGraphView.arcColor = UIColor.magenta
unrestCircleGraphView.arcColor = UIColor.green
sleepCircleGraphVIew.arcColor = UIColor.darkGray
excerciseCircleGraphView.arcColor = UIColor(red:0.00, green:0.39, blue:0.00, alpha:1.0)
diseaseCircleGraphView.arcColor = UIColor.brown
hurtCIrcleGraphView.arcColor = UIColor.purple
self.circleGraphView1.layer.masksToBounds = true
self.circleGraphView1.layer.borderWidth = 1
self.circleGraphView1.layer.borderColor = UIColor.lightGray.cgColor
self.circleGraphView1.layer.cornerRadius = self.informationView.frame.width/12
self.circleGraphView1.layer.masksToBounds = true
self.circleGraphView2.layer.masksToBounds = true
self.circleGraphView2.layer.borderWidth = 1
self.circleGraphView2.layer.borderColor = UIColor.lightGray.cgColor
self.circleGraphView2.layer.cornerRadius = self.informationView.frame.width/12
self.circleGraphView2.layer.masksToBounds = true
}
override func viewDidAppear(_ animated: Bool) {
let feelingRef = FIRDatabase.database().reference().child("users/\(friendUid)/currentdata/feeling")
let healthRef = FIRDatabase.database().reference().child("users/\(friendUid)/currentdata/health")
feelingRef.child("conditions/donotdisturb").observe(.value) { (snap: FIRDataSnapshot) in
if snap.value is NSNull {} else {
if snap.value as! Bool == true {
self.conditionLabel.text = "방해금지"
feelingRef.child("conditions/needsattention").observe(.value) { (snap: FIRDataSnapshot) in
if snap.value as! Bool == true {
self.conditionLabel.text = "관심필요"
}
}
}
}
self.topBar.title = self.friendName
}
healthRef.child("conditions/verysick").observe(.value) { (snap: FIRDataSnapshot) in
if snap.value is NSNull {} else {
if snap.value as! Bool == true {
self.healthConditonLabel.text = "매우아픔"
healthRef.child("conditions/veryhealthy").observe(.value) { (snap: FIRDataSnapshot) in
if snap.value as! Bool == true {
self.healthConditonLabel.text = "매우건강함"
}
}
}
}
}
feelingRef.child("detail").observe(.value) { (snap: FIRDataSnapshot) in
if snap.value is NSNull {} else {
self.statusLabel.text = snap.value as? String
healthRef.child("detail").observe(.value) { (snap: FIRDataSnapshot) in
self.healthStatusLabel.text = snap.value as? String
}
}
}
FIRDatabase.database().reference().child("users/\(friendUid)/currentdata/problem").observe(.value) { (snap: FIRDataSnapshot) in
if snap.value is NSNull {} else {
self.problemLabel.text = snap.value as? String
}
}
feelingRef.child("happy").observe(.value) { (snap: FIRDataSnapshot) in
if snap.value! is NSNull {
} else {
let happyValue = snap.value as! Float / 5
self.happyCircleGraphView
.endArc = CGFloat(happyValue)
feelingRef.child("sad").observe(.value) { (snap: FIRDataSnapshot) in
let sadValue = snap.value as! Float / 5
self.sadCircleGraphView.endArc = CGFloat(sadValue)
}
feelingRef.child("lonley").observe(.value) { (snap: FIRDataSnapshot) in
let lonleyValue = snap.value as! Float / 5
self.lonleyCircleGraphView.endArc = CGFloat(lonleyValue)
}
feelingRef.child("anger").observe(.value) { (snap: FIRDataSnapshot) in
let angerValue = snap.value as! Float / 5
self.angerCircleGraphView.endArc = CGFloat(angerValue)
}
feelingRef.child("love").observe(.value) { (snap: FIRDataSnapshot) in
let loveValue = snap.value as! Float / 5
self.loveCircleGraphView.endArc = CGFloat(loveValue)
}
feelingRef.child("unrest").observe(.value) { (snap: FIRDataSnapshot) in
let unrestValue = snap.value as! Float / 5
self.unrestCircleGraphView.endArc = CGFloat(unrestValue)
}
}
}
healthRef.child("sleep").observe(.value) { (snap: FIRDataSnapshot) in
if snap.value! is NSNull {} else {
let sleepValue = snap.value as! Float / 5
self.sleepCircleGraphVIew.endArc = CGFloat(sleepValue)
healthRef.child("excercise").observe(.value) { (snap: FIRDataSnapshot) in
let Value = snap.value as! Float / 5
self.excerciseCircleGraphView.endArc = CGFloat(Value)
}
healthRef.child("disease").observe(.value) { (snap: FIRDataSnapshot) in
let Value = snap.value as! Float / 5
self.diseaseCircleGraphView.endArc = CGFloat(Value)
}
healthRef.child("hurt").observe(.value) { (snap: FIRDataSnapshot) in
let Value = snap.value as! Float / 5
self.hurtCIrcleGraphView.endArc = CGFloat(Value)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
gpl-3.0
|
b5ae90535994e5ec3dcecab957f52a04
| 42.163842 | 135 | 0.58089 | 4.786967 | false | false | false | false |
trostli/codepath_tip
|
SettingsViewController.swift
|
1
|
2565
|
//
// SettingsViewController.swift
// tips
//
// Created by Daniel Trostli on 3/1/15.
// Copyright (c) 2015 Trostli. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var colorThemeControl: UISegmentedControl!
@IBOutlet weak var tipSettingLabel: UILabel!
@IBOutlet weak var colorThemeLabel: UILabel!
@IBOutlet weak var saveButton: UIButton!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
var defaults = NSUserDefaults.standardUserDefaults()
var defaultTipLevel = defaults.integerForKey("defaultTipLevel")
var selectedColorTheme = defaults.integerForKey("selectedColorTheme")
tipControl.selectedSegmentIndex = defaultTipLevel
colorThemeControl.selectedSegmentIndex = selectedColorTheme
setColorTheme()
}
@IBAction func onColorThemeControlChange(sender: AnyObject) {
setColorTheme()
}
func setColorTheme(){
if colorThemeControl.selectedSegmentIndex == 0 {
UIView.animateWithDuration(0.3, animations: {
self.tipSettingLabel.textColor = UIColor.blackColor()
self.colorThemeLabel.textColor = UIColor.blackColor()
self.view.backgroundColor = UIColor.whiteColor()
self.colorThemeControl.tintColor = self.view.tintColor
self.tipControl.tintColor = self.view.tintColor
self.saveButton.tintColor = self.view.tintColor
})
} else {
UIView.animateWithDuration(0.3, animations: {
self.tipSettingLabel.textColor = UIColor.whiteColor()
self.colorThemeLabel.textColor = UIColor.whiteColor()
self.view.backgroundColor = UIColor.darkGrayColor()
self.colorThemeControl.tintColor = UIColor.whiteColor()
self.tipControl.tintColor = UIColor.whiteColor()
self.saveButton.tintColor = UIColor.whiteColor()
})
}
}
@IBAction func hitSaveButton(sender: AnyObject) {
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(tipControl.selectedSegmentIndex, forKey: "defaultTipLevel")
defaults.setInteger(colorThemeControl.selectedSegmentIndex, forKey: "selectedColorTheme")
defaults.synchronize()
dismissViewControllerAnimated(true, completion: nil)
}
}
|
mit
|
c6326f86bb188015246df258a878135f
| 37.283582 | 97 | 0.663938 | 5.4 | false | false | false | false |
zhanggaoqiang/SwiftLearn
|
Swift语法/Swift方法/Swift方法/main.swift
|
1
|
5179
|
//
// main.swift
// Swift方法
//
// Created by zgq on 16/4/22.
// Copyright © 2016年 zgq. All rights reserved.
//
import Foundation
//在OC中类是唯一能够定义方法的类型
//在Swift中,你不仅能选择是否要定义一个类/结构体/枚举,还能灵活的在你创建的类型上定义方法
//在Swift中实例方法是属于某个特定类,结构体或者枚举类型实例的方法
//实例方法提供以下方法:
//可以访问和修改实例属性
//提供与实例目的相关的功能
//1.实例方法要写在它所属的类型的前后大括号内
//2.实例方法能够隐身访问它所属类型的所有的其他实例方法和属性
//3.实例方法只能被它所属的类的某个特定实例调用
//4.实例方法不能脱离于现存的实例而被调用
class Count {
var count = 0
func increment() {
count += 1
}
func incrementBy(amount:Int){
count+=amount;
}
func reset() {
count=0
}
}
let counter = Count()
counter.increment()
counter.incrementBy(5)
print(counter.count)
counter.reset()
print(counter.count)
//方法的局部参数名称和外部参数名称
//Swift函数可以同时有一个局部名称(在函数体内部使用)和一个外部名称(在调用函数时使用)
//Swift中的方法和OC方法极其相似,SWift中方法名称通常用一个介词指向方法的第一个参数
//Swift默认仅给方法的第一个参数名称一个局部参数名称;默认同时给第二个和后续的参数名称为全局参数名称
class division {
var count1 :Int = 0
func increment1(no1:Int,no2:Int) {
count1=no1/no2;
print(count1)
}
}
let counter1=division()
counter1.increment1(1800, no2: 3)
//是否提供外部名称设置
//我们强制在第一个参数添加外部名称把这个局部名称当做外部名称使用(Swift2.0前使用# 号)
//相反,我们也可以使用下划线(_)设置第二个以及后续的参数不提供一个外部名称
class multiplication {
var count:Int = 0
func increment2(first no1:Int,no2:Int) {
count=no1*no2;
print(count)
}
}
let counter2 = multiplication()
counter2.increment2(first: 800, no2: 3)
//self属性
//类型的每一个实例都有一个隐含属性叫self,self完全等同于该实例本身
//你可以在一个实例的实例方法中使用这个隐含的self属性来引用当前实例
class calculation {
var a:Int = 0
var b:Int = 0
var res:Int = 0
init(a:Int,b:Int) {
self.a = a
self.b=b
res=a+b
print("self内:\(res)")
}
func tot(c:Int) -> Int {
return res-c
}
func result() {
print("结果为: \(tot(20))")
print("结果为:\(tot(50))")
}
}
let pri = calculation(a:600,b:300)
let sum=calculation(a:1200,b:300)
pri.result()
sum.result()
//在实例方法中修改值类型
//Swift语言中结构体和枚举是值类型。一般情况下,值类型的属性不能在它的实例方法中被修改
//但是,如果你确实需要在某个具体的方法中修改结构体或者枚举的属性,你可以选择变异(mutating)
//这个方法,然后方法就可以从方法内部改变它的属性;并且它做的任何改变在方法结束时还会保留在原始结构中
//方法还可以给它隐含的self属性值一个全新的实例,这个新实例在方法结束后将替换原来的实例
struct area {
var length = 1
var breadth = 1
func area() -> Int {
return length*breadth
}
mutating func scaleBy(res:Int) {
length *= res
breadth *= res
print(length)
print(breadth)
}
}
var val = area(length:3,breadth:5)
val.scaleBy(3)
val.scaleBy(30)
val.scaleBy(300)
//在可变方法中给self赋值
//可变方法能够赋给隐含属性self一个全新的实例
struct area1 {
var length = 1
var breadth = 1
func area1() -> Int {
return length*breadth
}
mutating func scaleBy(res:Int) {
self.length *= res
self.breadth *= res
print(length)
print(breadth)
}
}
var val1 = area1(length: 3,breadth: 5)
val.scaleBy(13)
//类型方法
//实例方法是被类型的某个实例调用的方法,你也可以定义类型本身调用的方法,这种方法就叫做类型方法】
//声明结构体和枚举的类型方法,在方法的func关键字之前加上关键字static.类可能会用关键字class来允许子类重写父类的方法
//类型方法和实例方法一样用点号(.)语法调用
class Math {
class func abs(number:Int)->Int {
if number<0 {
return (-number)
}else
{
return number
}
}
}
struct absno {
static func abs(number:Int)->Int
{
if number<0 {
return (-number)
}else{
return number
}
}
}
let no = Math.abs(-35)
let num = absno.abs(-5)
print(no)
print(num)
|
mit
|
e31d51569ae52fbae31e092887134474
| 14.443478 | 66 | 0.61205 | 2.7471 | false | false | false | false |
mikekavouras/Glowb-iOS
|
Glowb/Wizard/ViewControllers/NetworkCredentialsViewController.swift
|
1
|
1393
|
//
// NetworkCredentialsViewController.swift
// ParticleConnect
//
// Created by Michael Kavouras on 8/29/16.
// Copyright © 2016 Mike Kavouras. All rights reserved.
//
import UIKit
class NetworkCredentialsViewController: BaseViewController, StoryboardInitializable {
var network: Network!
var deviceId: String!
static var storyboardName: StaticString = "NetworkCredentials"
@IBOutlet private weak var networkNameLabel: PrimaryTextLabel!
@IBOutlet private weak var passwordTextField: BaseTextField!
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
passwordTextField.delegate = self
networkNameLabel.text = network.ssid
}
// MARK: - Actions
@IBAction func toggleSecurePassword(_ sender: UISwitch) {
passwordTextField.isSecureTextEntry = sender.isOn
}
}
extension NetworkCredentialsViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let text = textField.text {
network.password = text
}
let viewController = ConnectingProgressViewController()
viewController.network = network
viewController.deviceId = deviceId
navigationController?.pushViewController(viewController, animated: true)
return true
}
}
|
mit
|
c698da8bd0c3e59c202e9e6f92122e26
| 26.294118 | 85 | 0.68319 | 5.612903 | false | false | false | false |
richardpiazza/SOSwift
|
Sources/SOSwift/FinancialProduct.swift
|
1
|
2353
|
import Foundation
/// A product provided to consumers and businesses by financial institutions such as banks, insurance companies,
/// brokerage firms, consumer finance companies, and investment companies which comprise the financial services
/// industry.
public class FinancialProduct: Service {
/// The annual rate that is charged for borrowing (or made by investing), expressed as a single percentage number
/// that represents the actual yearly cost of funds over the term of a loan.
///
/// This includes any fees or additional costs associated with the transaction.
public var annualPercentageRate: NumberOrQuantitativeValue?
/// Description of fees, commissions, and other terms applied either to a class of financial product, or by a
/// financial service organization.
public var feesAndCommissionsSpecification: URLOrText?
/// The interest rate, charged or paid, applicable to the financial product.
///
/// - note: This is different from the calculated annualPercentageRate.
public var interestRate: NumberOrQuantitativeValue?
internal enum FinancialProductCodingKeys: String, CodingKey {
case annualPercentageRate
case feesAndCommissionsSpecification
case interestRate
}
public required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let container = try decoder.container(keyedBy: FinancialProductCodingKeys.self)
annualPercentageRate = try container.decodeIfPresent(NumberOrQuantitativeValue.self, forKey: .annualPercentageRate)
feesAndCommissionsSpecification = try container.decodeIfPresent(URLOrText.self, forKey: .feesAndCommissionsSpecification)
interestRate = try container.decodeIfPresent(NumberOrQuantitativeValue.self, forKey: .interestRate)
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: FinancialProductCodingKeys.self)
try container.encodeIfPresent(annualPercentageRate, forKey: .annualPercentageRate)
try container.encodeIfPresent(feesAndCommissionsSpecification, forKey: .feesAndCommissionsSpecification)
try container.encodeIfPresent(interestRate, forKey: .interestRate)
try super.encode(to: encoder)
}
}
|
mit
|
8d99a166142e79c44eb161518900b719
| 48.020833 | 129 | 0.742456 | 5.027778 | false | false | false | false |
natecook1000/swift
|
test/decl/protocol/conforms/associated_type.swift
|
2
|
1714
|
// RUN: %target-typecheck-verify-swift -swift-version 4
class C { }
protocol P {
associatedtype AssocP : C // expected-note{{protocol requires nested type 'AssocP'; do you want to add it?}}
associatedtype AssocA : AnyObject // expected-note{{protocol requires nested type 'AssocA'; do you want to add it?}}
}
struct X : P { // expected-error{{type 'X' does not conform to protocol 'P'}}
typealias AssocP = Int // expected-note{{possibly intended match 'AssocP' (aka 'Int') does not inherit from 'C'}}
typealias AssocA = Int // expected-note{{possibly intended match 'AssocA' (aka 'Int') does not conform to 'AnyObject'}}
}
// SR-5166
protocol FooType {
associatedtype BarType
func foo(bar: BarType)
func foo(action: (BarType) -> Void)
}
protocol Bar {}
class Foo: FooType {
typealias BarType = Bar
func foo(bar: Bar) {
}
func foo(action: (Bar) -> Void) {
}
}
// rdar://problem/35297911: noescape function types
protocol P1 {
associatedtype A
func f(_: A)
}
struct X1a : P1 {
func f(_: @escaping (Int) -> Int) { }
}
struct X1b : P1 {
typealias A = (Int) -> Int
func f(_: @escaping (Int) -> Int) { }
}
struct X1c : P1 {
typealias A = (Int) -> Int
func f(_: (Int) -> Int) { }
}
struct X1d : P1 {
func f(_: (Int) -> Int) { }
}
protocol P2 {
func f(_: (Int) -> Int) // expected-note{{protocol requires function 'f' with type '((Int) -> Int) -> ()'; do you want to add a stub?}}
}
struct X2a : P2 {
func f(_: (Int) -> Int) { }
}
struct X2b : P2 { // expected-error{{type 'X2b' does not conform to protocol 'P2'}}
func f(_: @escaping (Int) -> Int) { } // expected-note{{candidate has non-matching type '(@escaping (Int) -> Int) -> ()'}}
}
|
apache-2.0
|
59e152ac5b61dd2cef6ae7ad2c84761c
| 22.805556 | 137 | 0.61727 | 3.191806 | false | false | false | false |
karstengresch/layout_studies
|
countidon/countidon/CountidonSettings.swift
|
1
|
1313
|
//
// CountidonSettings.swift
// countidon
//
// Created by Karsten Gresch on 26.12.15.
// Copyright © 2015 Closure One. All rights reserved.
//
import UIKit
/**
A class for all general settings (e.g. theme, init screen).
Individual counter settings in class CountidonItem
*/
class CountidonSettings: NSObject, NSCoding {
var theme = Theme.Default
var startScreenUpperButtonText = "New" // TODO constant
var startScreenLowerButtonText = "Settings"
required init?(coder aDecoder: NSCoder) {
self.theme = Theme(rawValue: aDecoder.decodeInteger(forKey: COUNTIDON_SETTING_THEME)) ?? .Default
self.startScreenUpperButtonText = aDecoder.decodeObject(forKey: COUNTIDON_VC_START_SCREEN_UPPER_BUTTON_TEXT) as! String
self.startScreenLowerButtonText = aDecoder.decodeObject(forKey: COUNTIDON_VC_START_SCREEN_LOWER_BUTTON_TEXT) as! String
super.init()
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.theme.rawValue, forKey: COUNTIDON_SETTING_THEME)
aCoder.encode(startScreenUpperButtonText, forKey: COUNTIDON_VC_START_SCREEN_UPPER_BUTTON_TEXT)
aCoder.encode(startScreenLowerButtonText, forKey: COUNTIDON_VC_START_SCREEN_LOWER_BUTTON_TEXT)
}
override init() {
super.init()
}
}
enum Theme: Int {
case Dark = 1, Light, Mixed, Custom, Default
}
|
unlicense
|
2630272367ce440bfcb3c856107100ad
| 31 | 123 | 0.739329 | 3.584699 | false | false | false | false |
griff/metaz
|
Framework/src/Data+Base64URL.swift
|
1
|
1914
|
//
// Data+Base64URLDecode.swift
// MetaZKit
//
// Created by Brian Olsen on 01/03/2020.
//
import Foundation
/// Extension for making base64 representations of `Data` safe for
/// transmitting via URL query parameters
extension Data {
/// Instantiates data by decoding a base64url string into base64
///
/// - Parameter string: A base64url encoded string
public init?(base64URLEncoded string: String) {
self.init(base64Encoded: string.toggleBase64URLSafe(on: false))
}
/// Encodes the string into a base64url safe representation
///
/// - Returns: A string that is base64 encoded but made safe for passing
/// in as a query parameter into a URL string
public func base64URLEncodedString() -> String {
return self.base64EncodedString().toggleBase64URLSafe(on: true)
}
}
extension String {
/// Encodes or decodes into a base64url safe representation
///
/// - Parameter on: Whether or not the string should be made safe for URL strings
/// - Returns: if `on`, then a base64url string; if `off` then a base64 string
public func toggleBase64URLSafe(on: Bool) -> String {
if on {
// Make base64 string safe for passing into URL query params
let base64url = self.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "=", with: "")
return base64url
} else {
// Return to base64 encoding
var base64 = self.replacingOccurrences(of: "_", with: "/")
.replacingOccurrences(of: "-", with: "+")
// Add any necessary padding with `=`
if base64.count % 4 != 0 {
base64.append(String(repeating: "=", count: 4 - base64.count % 4))
}
return base64
}
}
}
|
mit
|
5a6879fd6c0365266afea229a4961024
| 33.178571 | 85 | 0.601358 | 4.410138 | false | false | false | false |
mrkev/eatery
|
Eatery/Eatery/AF+Date+Helper/AF+Date+Extension.swift
|
1
|
16969
|
//
// AF+Date+Extension.swift
//
// Version 1.07
//
// Created by Melvin Rivera on 7/15/14.
// Copyright (c) 2014. All rights reserved.
//
import Foundation
enum DateFormat {
case ISO8601, DotNet, RSS, AltRSS
case Custom(String)
}
extension NSDate {
// MARK: Intervals In Seconds
private class func minuteInSeconds() -> Double { return 60 }
private class func hourInSeconds() -> Double { return 3600 }
private class func dayInSeconds() -> Double { return 86400 }
private class func weekInSeconds() -> Double { return 604800 }
private class func yearInSeconds() -> Double { return 31556926 }
// MARK: Components
private class func componentFlags() -> NSCalendarUnit { return .YearCalendarUnit | .MonthCalendarUnit | .DayCalendarUnit | .WeekCalendarUnit | .HourCalendarUnit | .MinuteCalendarUnit | .SecondCalendarUnit | .WeekdayCalendarUnit | .WeekdayOrdinalCalendarUnit | .CalendarUnitWeekOfYear }
private class func components(#fromDate: NSDate) -> NSDateComponents! {
return NSCalendar.currentCalendar().components(NSDate.componentFlags(), fromDate: fromDate)
}
private func components() -> NSDateComponents {
return NSDate.components(fromDate: self)!
}
// MARK: Date From String
convenience init(fromString string: String, format:DateFormat)
{
if string.isEmpty {
self.init()
return
}
let string = string as NSString
switch format {
case .DotNet:
// Expects "/Date(1268123281843)/"
let startIndex = string.rangeOfString("(").location + 1
let endIndex = string.rangeOfString(")").location
let range = NSRange(location: startIndex, length: endIndex-startIndex)
let milliseconds = (string.substringWithRange(range) as NSString).longLongValue
let interval = NSTimeInterval(milliseconds / 1000)
self.init(timeIntervalSince1970: interval)
case .ISO8601:
var s = string
if string.hasSuffix(" 00:00") {
s = s.substringToIndex(s.length-6) + "GMT"
} else if string.hasSuffix("Z") {
s = s.substringToIndex(s.length-1) + "GMT"
}
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZ"
if let date = formatter.dateFromString(string) {
self.init(timeInterval:0, sinceDate:date)
} else {
self.init()
}
case .RSS:
var s = string
if string.hasSuffix("Z") {
s = s.substringToIndex(s.length-1) + "GMT"
}
let formatter = NSDateFormatter()
formatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss ZZZ"
if let date = formatter.dateFromString(string) {
self.init(timeInterval:0, sinceDate:date)
} else {
self.init()
}
case .AltRSS:
var s = string
if string.hasSuffix("Z") {
s = s.substringToIndex(s.length-1) + "GMT"
}
let formatter = NSDateFormatter()
formatter.dateFormat = "d MMM yyyy HH:mm:ss ZZZ"
if let date = formatter.dateFromString(string) {
self.init(timeInterval:0, sinceDate:date)
} else {
self.init()
}
case .Custom(let dateFormat):
let formatter = NSDateFormatter()
formatter.dateFormat = dateFormat
if let date = formatter.dateFromString(string) {
self.init(timeInterval:0, sinceDate:date)
} else {
self.init()
}
}
}
// MARK: Comparing Dates
func isEqualToDateIgnoringTime(date: NSDate) -> Bool
{
let comp1 = NSDate.components(fromDate: self)
let comp2 = NSDate.components(fromDate: date)
return ((comp1.year == comp2.year) && (comp1.month == comp2.month) && (comp1.day == comp2.day))
}
func isToday() -> Bool
{
return self.isEqualToDateIgnoringTime(NSDate())
}
func isTomorrow() -> Bool
{
return self.isEqualToDateIgnoringTime(NSDate().dateByAddingDays(1))
}
func isYesterday() -> Bool
{
return self.isEqualToDateIgnoringTime(NSDate().dateBySubtractingDays(1))
}
func isSameWeekAsDate(date: NSDate) -> Bool
{
let comp1 = NSDate.components(fromDate: self)
let comp2 = NSDate.components(fromDate: date)
// Must be same week. 12/31 and 1/1 will both be week "1" if they are in the same week
if comp1.weekOfYear != comp2.weekOfYear {
return false
}
// Must have a time interval under 1 week
return abs(self.timeIntervalSinceDate(date)) < NSDate.weekInSeconds()
}
func isThisWeek() -> Bool
{
return self.isSameWeekAsDate(NSDate())
}
func isNextWeek() -> Bool
{
let interval: NSTimeInterval = NSDate().timeIntervalSinceReferenceDate + NSDate.weekInSeconds()
let date = NSDate(timeIntervalSinceReferenceDate: interval)
return self.isSameYearAsDate(date)
}
func isLastWeek() -> Bool
{
let interval: NSTimeInterval = NSDate().timeIntervalSinceReferenceDate - NSDate.weekInSeconds()
let date = NSDate(timeIntervalSinceReferenceDate: interval)
return self.isSameYearAsDate(date)
}
func isSameYearAsDate(date: NSDate) -> Bool
{
let comp1 = NSDate.components(fromDate: self)
let comp2 = NSDate.components(fromDate: date)
return (comp1.year == comp2.year)
}
func isThisYear() -> Bool
{
return self.isSameYearAsDate(NSDate())
}
func isNextYear() -> Bool
{
let comp1 = NSDate.components(fromDate: self)
let comp2 = NSDate.components(fromDate: NSDate())
return (comp1.year == comp2.year + 1)
}
func isLastYear() -> Bool
{
let comp1 = NSDate.components(fromDate: self)
let comp2 = NSDate.components(fromDate: NSDate())
return (comp1.year == comp2.year - 1)
}
func isEarlierThanDate(date: NSDate) -> Bool
{
return self.earlierDate(date) == self
}
func isLaterThanDate(date: NSDate) -> Bool
{
return self.laterDate(date) == self
}
// MARK: Adjusting Dates
func dateByAddingDays(days: Int) -> NSDate
{
let interval: NSTimeInterval = self.timeIntervalSinceReferenceDate + NSDate.dayInSeconds() * Double(days)
return NSDate(timeIntervalSinceReferenceDate: interval)
}
func dateBySubtractingDays(days: Int) -> NSDate
{
let interval: NSTimeInterval = self.timeIntervalSinceReferenceDate - NSDate.dayInSeconds() * Double(days)
return NSDate(timeIntervalSinceReferenceDate: interval)
}
func dateByAddingHours(hours: Int) -> NSDate
{
let interval: NSTimeInterval = self.timeIntervalSinceReferenceDate + NSDate.hourInSeconds() * Double(hours)
return NSDate(timeIntervalSinceReferenceDate: interval)
}
func dateBySubtractingHours(hours: Int) -> NSDate
{
let interval: NSTimeInterval = self.timeIntervalSinceReferenceDate - NSDate.hourInSeconds() * Double(hours)
return NSDate(timeIntervalSinceReferenceDate: interval)
}
func dateByAddingMinutes(minutes: Int) -> NSDate
{
let interval: NSTimeInterval = self.timeIntervalSinceReferenceDate + NSDate.minuteInSeconds() * Double(minutes)
return NSDate(timeIntervalSinceReferenceDate: interval)
}
func dateBySubtractingMinutes(minutes: Int) -> NSDate
{
let interval: NSTimeInterval = self.timeIntervalSinceReferenceDate - NSDate.minuteInSeconds() * Double(minutes)
return NSDate(timeIntervalSinceReferenceDate: interval)
}
func dateAtStartOfDay() -> NSDate
{
var components = self.components()
components.hour = 0
components.minute = 0
components.second = 0
return NSCalendar.currentCalendar().dateFromComponents(components)!
}
func dateAtEndOfDay() -> NSDate
{
var components = self.components()
components.hour = 23
components.minute = 59
components.second = 59
return NSCalendar.currentCalendar().dateFromComponents(components)!
}
func dateAtStartOfWeek() -> NSDate
{
let flags :NSCalendarUnit = .YearCalendarUnit | .MonthCalendarUnit | .WeekCalendarUnit | .WeekdayCalendarUnit
var components = NSCalendar.currentCalendar().components(flags, fromDate: self)
components.weekday = 1 // Sunday
components.hour = 0
components.minute = 0
components.second = 0
return NSCalendar.currentCalendar().dateFromComponents(components)!
}
func dateAtEndOfWeek() -> NSDate
{
let flags :NSCalendarUnit = .YearCalendarUnit | .MonthCalendarUnit | .WeekCalendarUnit | .WeekdayCalendarUnit
var components = NSCalendar.currentCalendar().components(flags, fromDate: self)
components.weekday = 7 // Sunday
components.hour = 0
components.minute = 0
components.second = 0
return NSCalendar.currentCalendar().dateFromComponents(components)!
}
// MARK: Retrieving Intervals
func minutesAfterDate(date: NSDate) -> Int
{
let interval = self.timeIntervalSinceDate(date)
return Int(interval / NSDate.minuteInSeconds())
}
func minutesBeforeDate(date: NSDate) -> Int
{
let interval = date.timeIntervalSinceDate(self)
return Int(interval / NSDate.minuteInSeconds())
}
func hoursAfterDate(date: NSDate) -> Int
{
let interval = self.timeIntervalSinceDate(date)
return Int(interval / NSDate.hourInSeconds())
}
func hoursBeforeDate(date: NSDate) -> Int
{
let interval = date.timeIntervalSinceDate(self)
return Int(interval / NSDate.hourInSeconds())
}
func daysAfterDate(date: NSDate) -> Int
{
let interval = self.timeIntervalSinceDate(date)
return Int(interval / NSDate.dayInSeconds())
}
func daysBeforeDate(date: NSDate) -> Int
{
let interval = date.timeIntervalSinceDate(self)
return Int(interval / NSDate.dayInSeconds())
}
// MARK: Decomposing Dates
func nearestHour () -> Int {
let halfHour = NSDate.minuteInSeconds() * 30
var interval = self.timeIntervalSinceReferenceDate
if self.seconds() < 30 {
interval -= halfHour
} else {
interval += halfHour
}
let date = NSDate(timeIntervalSinceReferenceDate: interval)
return date.hour()
}
func year () -> Int { return self.components().year }
func month () -> Int { return self.components().month }
func week () -> Int { return self.components().weekOfYear }
func day () -> Int { return self.components().day }
func hour () -> Int { return self.components().hour }
func minute () -> Int { return self.components().minute }
func seconds () -> Int { return self.components().second }
func weekday () -> Int { return self.components().weekday }
func nthWeekday () -> Int { return self.components().weekdayOrdinal } //// e.g. 2nd Tuesday of the month is 2
func monthDays () -> Int { return NSCalendar.currentCalendar().rangeOfUnit(.DayCalendarUnit, inUnit: .MonthCalendarUnit, forDate: self).length }
func firstDayOfWeek () -> Int {
let distanceToStartOfWeek = NSDate.dayInSeconds() * Double(self.components().weekday - 1)
let interval: NSTimeInterval = self.timeIntervalSinceReferenceDate - distanceToStartOfWeek
return NSDate(timeIntervalSinceReferenceDate: interval).day()
}
func lastDayOfWeek () -> Int {
let distanceToStartOfWeek = NSDate.dayInSeconds() * Double(self.components().weekday - 1)
let distanceToEndOfWeek = NSDate.dayInSeconds() * Double(7)
let interval: NSTimeInterval = self.timeIntervalSinceReferenceDate - distanceToStartOfWeek + distanceToEndOfWeek
return NSDate(timeIntervalSinceReferenceDate: interval).day()
}
func isWeekday() -> Bool {
return !self.isWeekend()
}
func isWeekend() -> Bool {
let range = NSCalendar.currentCalendar().maximumRangeOfUnit(.WeekdayCalendarUnit)
return (self.weekday() == range.location || self.weekday() == range.length)
}
// MARK: To String
func toString() -> String {
return self.toString(dateStyle: .ShortStyle, timeStyle: .ShortStyle, doesRelativeDateFormatting: false)
}
func toString(#format: DateFormat) -> String
{
var dateFormat: String
switch format {
case .DotNet:
let offset = NSTimeZone.defaultTimeZone().secondsFromGMT / 3600
let nowMillis = 1000 * self.timeIntervalSince1970
return "/Date(\(nowMillis)\(offset))/"
case .ISO8601:
dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
case .RSS:
dateFormat = "EEE, d MMM yyyy HH:mm:ss ZZZ"
case .AltRSS:
dateFormat = "d MMM yyyy HH:mm:ss ZZZ"
case .Custom(let string):
dateFormat = string
}
let formatter = NSDateFormatter()
formatter.dateFormat = dateFormat
return formatter.stringFromDate(self)
}
func toString(#dateStyle: NSDateFormatterStyle, timeStyle: NSDateFormatterStyle, doesRelativeDateFormatting: Bool = false) -> String
{
let formatter = NSDateFormatter()
formatter.dateStyle = dateStyle
formatter.timeStyle = timeStyle
formatter.doesRelativeDateFormatting = doesRelativeDateFormatting
return formatter.stringFromDate(self)
}
func relativeTimeToString() -> String
{
let time = self.timeIntervalSince1970
let now = NSDate().timeIntervalSince1970
let seconds = now - time
let minutes = round(seconds/60)
let hours = round(minutes/60)
let days = round(hours/24)
if seconds < 10 {
return NSLocalizedString("just now", comment: "relative time")
} else if seconds < 60 {
return NSLocalizedString("\(seconds) seconds ago", comment: "relative time")
}
if minutes < 60 {
if minutes == 1 {
return NSLocalizedString("1 minute ago", comment: "relative time")
} else {
return NSLocalizedString("\(minutes) minutes ago", comment: "relative time")
}
}
if hours < 24 {
if hours == 1 {
return NSLocalizedString("1 hour ago", comment: "relative time")
} else {
return NSLocalizedString("\(hours) hours ago", comment: "relative time")
}
}
if days < 7 {
if days == 1 {
return NSLocalizedString("1 day ago", comment: "relative time")
} else {
return NSLocalizedString("\(days) days ago", comment: "relative time")
}
}
return self.toString()
}
func weekdayToString() -> String {
let formatter = NSDateFormatter()
return formatter.weekdaySymbols[self.weekday()-1] as String
}
func shortWeekdayToString() -> String {
let formatter = NSDateFormatter()
return formatter.shortWeekdaySymbols[self.weekday()-1] as String
}
func veryShortWeekdayToString() -> String {
let formatter = NSDateFormatter()
return formatter.veryShortWeekdaySymbols[self.weekday()-1] as String
}
func monthToString() -> String {
let formatter = NSDateFormatter()
return formatter.monthSymbols[self.month()-1] as String
}
func shortMonthToString() -> String {
let formatter = NSDateFormatter()
return formatter.shortMonthSymbols[self.month()-1] as String
}
func veryShortMonthToString() -> String {
let formatter = NSDateFormatter()
return formatter.veryShortMonthSymbols[self.month()-1] as String
}
}
|
mit
|
7ca7f0747594c2430c01e6aaf7c75ba9
| 33.989691 | 289 | 0.597914 | 5.095796 | false | false | false | false |
JGiola/swift-package-manager
|
Sources/Basic/Result.swift
|
2
|
6536
|
/*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
/// An simple enum which is either a value or an error.
/// It can be used for error handling in situations where try catch is
/// problematic to use, for eg: asynchronous APIs.
public enum Result<Value, ErrorType: Swift.Error> {
/// Indicates success with value in the associated object.
case success(Value)
/// Indicates failure with error inside the associated object.
case failure(ErrorType)
/// Initialiser for value.
public init(_ value: Value) {
self = .success(value)
}
/// Initialiser for error.
public init(_ error: ErrorType) {
self = .failure(error)
}
/// Initialise with something that can throw ErrorType.
public init(_ body: () throws -> Value) throws {
do {
self = .success(try body())
} catch let error as ErrorType {
self = .failure(error)
}
}
/// Get the value if success else throw the saved error.
public func dematerialize() throws -> Value {
switch self {
case .success(let value):
return value
case .failure(let error):
throw error
}
}
/// Evaluates the given closure when this Result instance has a value.
public func map<U>(_ transform: (Value) throws -> U) rethrows -> Result<U, ErrorType> {
switch self {
case .success(let value):
return Result<U, ErrorType>(try transform(value))
case .failure(let error):
return Result<U, ErrorType>(error)
}
}
/// Evaluates the given closure when this Result instance has a value, passing the unwrapped value as a parameter.
///
/// The closure returns a Result instance itself which can have value or not.
public func flatMap<U>(_ transform: (Value) -> Result<U, ErrorType>) -> Result<U, ErrorType> {
switch self {
case .success(let value):
return transform(value)
case .failure(let error):
return Result<U, ErrorType>(error)
}
}
}
extension Result: CustomStringConvertible {
public var description: String {
switch self {
case .success(let value):
return "Result(\(value))"
case .failure(let error):
return "Result(\(error))"
}
}
}
/// A type erased error enum.
public struct AnyError: Swift.Error, CustomStringConvertible {
/// The underlying error.
public let underlyingError: Swift.Error
public init(_ error: Swift.Error) {
// If we already have any error, don't nest it.
if case let error as AnyError = error {
self = error
} else {
self.underlyingError = error
}
}
public var description: String {
return String(describing: underlyingError)
}
}
/// Represents a string error.
public struct StringError: Equatable, Codable, CustomStringConvertible, Error {
/// The description of the error.
public let description: String
/// Create an instance of StringError.
public init(_ description: String) {
self.description = description
}
}
// AnyError specific helpers.
extension Result where ErrorType == AnyError {
/// Initialise with something that throws AnyError.
public init(anyError body: () throws -> Value) {
do {
self = .success(try body())
} catch {
self = .failure(AnyError(error))
}
}
/// Initialise with an error, it will be automatically converted to AnyError.
public init(_ error: Swift.Error) {
self = .failure(AnyError(error))
}
/// Evaluates the given throwing closure when this Result instance has a value.
///
/// The final result will either be the transformed value or any error thrown by the closure.
public func mapAny<U>(_ transform: (Value) throws -> U) -> Result<U, AnyError> {
switch self {
case .success(let value):
do {
return Result<U, AnyError>(try transform(value))
} catch {
return Result<U, AnyError>(error)
}
case .failure(let error):
return Result<U, AnyError>(error)
}
}
}
extension Result where ErrorType == StringError {
/// Create an instance of Result<Value, StringError>.
///
/// Errors will be encoded as StringError using their description.
public init(string body: () throws -> Value) {
do {
self = .success(try body())
} catch let error as StringError {
self = .failure(error)
} catch {
self = .failure(StringError(String(describing: error)))
}
}
}
extension Result: Equatable where Value: Equatable, ErrorType: Equatable {}
extension Result: Codable where Value: Codable, ErrorType: Codable {
private enum CodingKeys: String, CodingKey {
case success, failure
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .success(let value):
var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .success)
try unkeyedContainer.encode(value)
case .failure(let error):
var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .failure)
try unkeyedContainer.encode(error)
}
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
guard let key = values.allKeys.first(where: values.contains) else {
throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Did not find a matching key"))
}
switch key {
case .success:
var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
let value = try unkeyedValues.decode(Value.self)
self = .success(value)
case .failure:
var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
let error = try unkeyedValues.decode(ErrorType.self)
self = .failure(error)
}
}
}
|
apache-2.0
|
3b5cf1ef40f12c7c7e33dcbbbd90c154
| 31.844221 | 133 | 0.620104 | 4.715729 | false | false | false | false |
mislavjavor/LambdaUI
|
Source/Utilities/Event.swift
|
1
|
1432
|
//
// Event.swift
// LambdaUI
//
// Created by Mislav Javor on 05/05/16.
// Copyright © 2016 Mislav Javor. All rights reserved.
//
import Foundation
import Dispatch
public struct Event {
public typealias EventFunction = (EventWrapper) -> Void
fileprivate var shouldPerformAsync : Bool = false
fileprivate var asyncQueue : Dispatch.DispatchQueue? = DispatchQueue.global(qos: DispatchQoS.userInteractive.qosClass)
fileprivate var eventFunction : EventFunction = { _ in }
public var uuid : String!
init(shouldAsync: Bool = false, queue : Dispatch.DispatchQueue? = nil, eventFunction: @escaping EventFunction) {
self.shouldPerformAsync = shouldAsync
self.asyncQueue = queue
self.eventFunction = eventFunction
self.uuid = UUID().uuidString
}
fileprivate func performAsync(_ event: EventWrapper) {
if let queue = asyncQueue {
queue.async {
self.eventFunction(event)
}
} else {
DispatchQueue.main.async {
self.eventFunction(event)
}
}
}
fileprivate func performSync(_ event: EventWrapper) {
eventFunction(event)
}
public func performEvent(_ event: EventWrapper) {
if shouldPerformAsync {
performAsync(event)
} else {
performSync(event)
}
}
}
|
mit
|
e833683a592bde3b37fc362d50a3f5b1
| 25.018182 | 122 | 0.610063 | 4.631068 | false | false | false | false |
Dinh-Le/XIB-to-Nativescript
|
Pod/Classes/PostTableViewCell.swift
|
1
|
3049
|
//
// PostTableViewCell.swift
// Pods
//
// Created by Le Dinh on 19/10/16.
//
//
import UIKit
class PostTableViewCell: UITableViewCell {
@IBOutlet weak var post: UIView!
@IBOutlet weak var postImage: UIImageView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var body: UILabel!
@IBOutlet weak var date: UILabel!
@IBOutlet weak var editButton: UIButton!
@IBOutlet weak var commentCount: UILabel!
@IBOutlet weak var comment: UIButton!
@IBOutlet weak var separateDot: UILabel!
@IBOutlet weak var shareButton: UIButton!
var parentVC: UIViewController!
var socnetList: [String] = []
var postReading: ((Int)->())?
var editTapping: ((Int)->())?
var commentTapping: ((Int, Bool)->())?
var showPopover: ((UIButton)->())?
var shareTap: ((Int)->())?
var copyLinkTap: ((Int)->())?
var wechatTap: ((Int)->())?
var viadeoTap: ((Int)->())?
var instagramTap: ((Int)->())?
@IBAction func shareTap(sender: UIButton) {
var popBundle = NSBundle(path: NSBundle(forClass: PopViewController.self).pathForResource("SGSnackBar", ofType: "bundle")!)
let popVC = PopViewController(nibName: "PopView", bundle: popBundle)
popVC.postIndex = sender.tag
popVC.socnetList = socnetList
popVC.shareTap = shareTap
popVC.copyLinkTap = copyLinkTap
popVC.wechatTap = wechatTap
popVC.viadeoTap = viadeoTap
popVC.instagramTap = instagramTap
let screen = UIScreen.mainScreen().bounds.width
popVC.preferredContentSize = CGSizeMake(screen, 280)
popVC.modalPresentationStyle = .Popover
let popoverPresentationViewController = popVC.popoverPresentationController!
popoverPresentationViewController.permittedArrowDirections = [.Up, .Down]
popoverPresentationViewController.delegate = parentVC as! UIPopoverPresentationControllerDelegate
popoverPresentationViewController.sourceView = self;
popoverPresentationViewController.sourceRect = sender.frame
parentVC.presentViewController(popVC, animated: true, completion: nil)
}
@IBAction func editTap(sender: UIButton) {
editTapping!(sender.tag)
}
@IBAction func commentTap(sender: UIButton) {
commentTapping!(sender.tag, true)
}
private func myIndex() -> Int {
return (self.superview?.superview as! UITableView).indexPathForCell(self)!.row
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
public func addHandler(function: ((Int)->())?){
postReading = function
}
public func addEditTap(function: ((Int)->())?){
editTapping = function
}
public func addCommentTapping(function: ((Int, Bool)->())?){
commentTapping = function
}
}
|
mit
|
ea14d6123e4d85152f0ebc23a1d74ebe
| 32.505495 | 131 | 0.658249 | 4.801575 | false | false | false | false |
powfulhong/THCalendarDatePicker
|
THCalendarDatePickerSwiftExample/THCalendarDatePickerSwiftExample/ViewController.swift
|
1
|
3036
|
//
// ViewController.swift
// THCalendarDatePickerSwiftExample
//
// Created by Hannes Tribus on 04/09/15.
// Copyright (c) 2015 3Bus. All rights reserved.
//
import UIKit
import THCalendarDatePicker
class ViewController: UIViewController, THDatePickerDelegate {
@IBOutlet weak var dateButton: UIButton!
var curDate : NSDate? = NSDate()
lazy var formatter: NSDateFormatter = {
var tmpFormatter = NSDateFormatter()
tmpFormatter.dateFormat = "dd/MM/yyyy --- HH:mm"
return tmpFormatter
}()
lazy var datePicker : THDatePickerViewController = {
let picker = THDatePickerViewController.datePicker()
picker.delegate = self
picker.date = self.curDate
picker.setAllowClearDate(false)
picker.setClearAsToday(true)
picker.setAutoCloseOnSelectDate(false)
picker.setAllowSelectionOfSelectedDate(true)
picker.setDisableYearSwitch(true)
//picker.setDisableFutureSelection(false)
picker.setDaysInHistorySelection(1)
picker.setDaysInFutureSelection(0)
picker.setDateTimeZoneWithName("UTC")
picker.autoCloseCancelDelay = 5.0
picker.rounded = true
picker.selectedBackgroundColor = UIColor(red: 125.0/255.0, green: 208.0/255.0, blue: 0.0/255.0, alpha: 1.0)
picker.currentDateColor = UIColor(red: 242.0/255.0, green: 121.0/255.0, blue: 53.0/255.0, alpha: 1.0)
picker.currentDateColorSelected = UIColor.yellowColor()
return picker
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
refreshTitle()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func refreshTitle() {
dateButton.setTitle((curDate != nil ? formatter.stringFromDate(curDate!) : "No date selected"), forState: UIControlState.Normal)
}
@IBAction func touchedButton(sender: AnyObject) {
datePicker.date = self.curDate
datePicker.setDateHasItemsCallback { (date: NSDate!) -> Bool in
let tmp = (arc4random() % 30)+1
return (tmp % 5 == 0)
}
presentSemiViewController(datePicker, withOptions: [
KNSemiModalOptionKeys.pushParentBack : false,
KNSemiModalOptionKeys.animationDuration : 1.0,
KNSemiModalOptionKeys.shadowOpacity : 0.3
])
}
// MARK: THDatePickerDelegate
func datePickerDonePressed(datePicker: THDatePickerViewController!) {
curDate = datePicker.date
refreshTitle()
dismissSemiModalView()
}
func datePickerCancelPressed(datePicker: THDatePickerViewController!) {
dismissSemiModalView()
}
func datePicker(datePicker: THDatePickerViewController!, selectedDate: NSDate!) {
println("Date selected: ", formatter.stringFromDate(selectedDate))
}
}
|
mit
|
8af5d7476bbcf86fa6513de073d084ac
| 33.5 | 136 | 0.66502 | 4.52459 | false | false | false | false |
The-iPocalypse/BA-iOS-Application
|
src/OffersViewController.swift
|
1
|
4107
|
//
// OffersViewController.swift
// BA-iOS-Application
//
// Created by Vincent Dupuis on 2016-02-13.
// Copyright © 2016 Samuel Bellerose. All rights reserved.
//
import UIKit
class OffersViewController : UITableViewController {
static let storyboardName = "Profile"
static let viewControllerIdentifier = "OffersViewController"
static let offersCellNibName = "OffersTableViewCell"
static let offersCellIdentifier = "OffersTableViewCell"
var offers: [Participation] = []
override func viewDidLoad() {
super.viewDidLoad()
let offerCellNib = UINib(nibName: OffersViewController.offersCellNibName, bundle: nil)
self.tableView.registerNib(offerCellNib, forCellReuseIdentifier: OffersViewController.offersCellIdentifier)
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.rowHeight = 70.0
self.tableView.tableFooterView = UIView(frame: CGRect.zero)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(OffersViewController.offersCellIdentifier, forIndexPath: indexPath) as! OffersTableViewCell
let offer = self.offers[indexPath.row]
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.offerImage.image = UIImage(named: offer.user.photo)
cell.offerDescription.text = offer.user.description
cell.offerButton.addTarget(self, action: "selectOffer:", forControlEvents: .TouchUpInside)
cell.offerButton.tag = indexPath.row
cell.offerButton.layer.cornerRadius = 5
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.offers.count
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
self.offers.removeAtIndex(indexPath.row)
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
func selectOffer(sender: UIButton!) {
let alert = UIAlertController(title: "", message: "Êtes-vous certain(e) de vouloir accepter cette offre?", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
switch action.style{
case .Default:
let indexPath = self.tableView.indexPathForCell(sender.superview?.superview as! UITableViewCell)
self.offers.removeAtIndex(indexPath!.row)
self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Cancel:
print("cancel")
case .Destructive:
print("destructive")
}
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { action in
switch action.style{
case .Default:
print("default")
case .Cancel:
print("cancel")
case .Destructive:
print("destructive")
}
}))
self.presentViewController(alert, animated: true, completion: nil)
}
class func detailViewControllerForOffers(offers: [Participation]) -> OffersViewController {
let storyboard = UIStoryboard(name: OffersViewController.storyboardName, bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier(OffersViewController.viewControllerIdentifier) as! OffersViewController
vc.offers = offers
return vc
}
}
|
mit
|
d645f31c4e47b3f313339f329caa4503
| 38.104762 | 160 | 0.658222 | 5.532345 | false | false | false | false |
SuperAwesomeLTD/sa-kws-app-demo-ios
|
KWSDemo/LoginModel.swift
|
1
|
951
|
//
// SignInModel.swift
// KWSDemo
//
// Created by Gabriel Coman on 09/12/2016.
// Copyright © 2016 Gabriel Coman. All rights reserved.
//
import UIKit
class LoginModel: NSObject {
private var username: String?
private var password: String?
init(username: String?, password: String?) {
super.init()
self.username = username
self.password = password
}
static func createEmpty () -> LoginModel {
return LoginModel (username: nil, password: nil)
}
func isValid () -> Bool {
if let _ = username, let _ = password {
return true
}
return false
}
func getUsername () -> String {
if let username = username {
return username
}
return ""
}
func getPassword () -> String {
if let password = password {
return password
}
return ""
}
}
|
gpl-3.0
|
6c9b40f5ea57bccff4da7c4467575e32
| 19.212766 | 56 | 0.538947 | 4.634146 | false | false | false | false |
yonaskolb/XcodeGen
|
Sources/XcodeGenKit/InfoPlistGenerator.swift
|
1
|
1806
|
import Foundation
import PathKit
import ProjectSpec
public class InfoPlistGenerator {
/**
Default info plist attributes taken from:
/Applications/Xcode.app/Contents/Developer/Library/Xcode/Templates/Project Templates/Base/Base_DefinitionsInfoPlist.xctemplate/TemplateInfo.plist
*/
private func generateDefaultInfoPlist(for target: Target) -> [String: Any] {
var dictionary: [String: Any] = [:]
dictionary["CFBundleIdentifier"] = "$(PRODUCT_BUNDLE_IDENTIFIER)"
dictionary["CFBundleInfoDictionaryVersion"] = "6.0"
dictionary["CFBundleName"] = "$(PRODUCT_NAME)"
dictionary["CFBundleDevelopmentRegion"] = "$(DEVELOPMENT_LANGUAGE)"
dictionary["CFBundleShortVersionString"] = "1.0"
dictionary["CFBundleVersion"] = "1"
// Bundles should not contain any CFBundleExecutable otherwise they will be rejected when uploading.
if target.type != .bundle {
dictionary["CFBundleExecutable"] = "$(EXECUTABLE_NAME)"
}
return dictionary
}
public func generateProperties(for target: Target) -> [String: Any] {
var targetInfoPlist = generateDefaultInfoPlist(for: target)
switch target.type {
case .uiTestBundle,
.unitTestBundle:
targetInfoPlist["CFBundlePackageType"] = "BNDL"
case .application,
.watch2App:
targetInfoPlist["CFBundlePackageType"] = "APPL"
case .framework:
targetInfoPlist["CFBundlePackageType"] = "FMWK"
case .bundle:
targetInfoPlist["CFBundlePackageType"] = "BNDL"
case .xpcService,
.appExtension:
targetInfoPlist["CFBundlePackageType"] = "XPC!"
default: break
}
return targetInfoPlist
}
}
|
mit
|
ddee7dbb848fa4a780452a17ea98d42f
| 35.857143 | 150 | 0.646179 | 4.777778 | false | false | false | false |
icylydia/PlayWithLeetCode
|
231. Power of Two/solution.swift
|
1
|
270
|
class Solution {
func isPowerOfTwo(n: Int) -> Bool {
if n == 0 {
return false
}
var m = n
while m != 0 {
if (m & 1) == 1 {
if (m >> 1) == 0 {
return true
} else {
return false
}
} else {
m = m >> 1
}
}
return false
}
}
|
mit
|
5183db210b3dcef351c0e3574f832b46
| 12.55 | 36 | 0.433333 | 2.5 | false | false | false | false |
esttorhe/SlackTeamExplorer
|
SlackTeamExplorer/SlackTeamExplorer/ViewControllers/ViewController.swift
|
1
|
5670
|
//
// ViewController.swift
// SlackTeamExplorer
//
// Created by Esteban Torres on 29/6/15.
// Copyright (c) 2015 Esteban Torres. All rights reserved.
//
// Native Frameworks
import UIKit
// Shared
import SlackTeamCoreDataProxy
// Misc.
import HexColors
// Network
import SDWebImage
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var loadingActivityIndicator: UIActivityIndicatorView!
// ViewModels
let membersViewModel = MembersViewModel()
override func viewDidLoad() {
super.viewDidLoad()
// Configure transparent nav bar
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.translucent = true
self.navigationController?.navigationBar.tintColor = UIColor.blackColor()
// Configure the view models
membersViewModel.beginLoadingSignal.deliverOnMainThread().subscribeNext { [unowned self] _ in
self.loadingActivityIndicator.startAnimating()
}
membersViewModel.endLoadingSignal.deliverOnMainThread().subscribeNext { [unowned self] _ in
self.loadingActivityIndicator.stopAnimating()
}
membersViewModel.updateContentSignal.deliverOnMainThread().subscribeNext({ [unowned self] members in
self.collectionView.reloadData()
}, error: { [unowned self] error in
let alertController = UIAlertController(title: "Unable to fetch members", message: error?.description, preferredStyle: .Alert)
let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
alertController.dismissViewControllerAnimated(true, completion: nil)
})
alertController.addAction(ok)
self.presentViewController(alertController, animated: true, completion: nil)
println("• Unable to load members: \(error)")
})
// Trigger first load
membersViewModel.active = true
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.collectionView.collectionViewLayout.invalidateLayout()
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let detailVC = segue.destinationViewController as? DetailViewController,
cell = sender as? MemberCell,
indexPath = collectionView.indexPathForCell(cell) {
let member = membersViewModel.memberAtIndexPath(indexPath)
detailVC.memberViewModel = MemberViewModel(memberID: member.objectID)
}
}
// MARK: - Collection View
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.membersViewModel.numberOfItemsInSection(section)
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MemberCell", forIndexPath: indexPath) as! MemberCell
cell.avatarImageView.image = nil
cell.avatarImageView.backgroundColor = UIColor.slackPurpleColor()
cell.usernameLabel.text = nil
cell.titleLabel.text = nil
let member = membersViewModel.memberAtIndexPath(indexPath)
cell.usernameLabel.text = "@\(member.name)"
if let profile = member.profile {
if let imageURL = profile.image192 {
cell.avatarImageView.sd_setImageWithURL(NSURL(string: imageURL), placeholderImage: nil) { (image, error, cacheType, url) in
if let img = image {
cell.avatarImageView.image = img
} else if let fburl = profile.fallBackImageURL {
cell.avatarImageView.sd_setImageWithURL(fburl)
}
}
}
if let title = profile.title {
cell.titleLabel.text = title
}
}
if let strColor = member.color, color = UIColor(hexString: strColor) {
cell.avatarImageView.layer.borderWidth = 4.0
cell.avatarImageView.layer.borderColor = color.CGColor
cell.layer.cornerRadius = 10.0
}
return cell
}
override func didRotateFromInterfaceOrientation(_: UIInterfaceOrientation) {
collectionView.collectionViewLayout.invalidateLayout()
}
// MARK: - Collection View Flow Layout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
collectionView.layoutIfNeeded()
return CGSizeMake(CGRectGetWidth(collectionView.bounds) - 30.0, 81.0)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 10.0
}
}
|
mit
|
1e9e92345e4ebccc251a74b5aa56ecbf
| 39.492857 | 178 | 0.663197 | 5.861427 | false | false | false | false |
miguelc95/MedicaT
|
MedicaT/HistorialTableViewController.swift
|
1
|
11035
|
//
// HistorialTableViewController.swift
// MedicaT
//
// Created by alumno on 21/11/16.
// Copyright © 2016 ITESM. All rights reserved.
//
import UIKit
import CoreData
import MessageUI
class HistorialTableViewController: UITableViewController, MFMailComposeViewControllerDelegate {
@IBOutlet weak var outletSegmentedControl: UISegmentedControl!
var registros : [NSManagedObject]!
var datos : [NSManagedObject]!
var mailsMedicos = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
outletSegmentedControl.tintColor = hexStringToUIColor(hex: "007CF7")
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
tableView.refreshControl?.addTarget(self, action: #selector(refreshTable), for: .valueChanged)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Medico")
do {
datos = try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
for i in datos {
let dato = i as NSManagedObject
mailsMedicos.append(dato.value(forKey: "email") as! String)
}
getTableData()
tableView.tableFooterView = UIView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return registros.count
}
func getTableData() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest : NSFetchRequest<Historial> = Historial.fetchRequest()
fetchRequest.returnsObjectsAsFaults = false
do {
let results = try managedContext.fetch(fetchRequest)
registros = results as [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
let registro = registros[indexPath.row]
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy H:mm a"
let medicamento = registro.value(forKey: "medicamento") as! String
let tomado = registro.value(forKey: "tomada") as! Bool
let fecha = registro.value(forKey: "fecha") as! Date
cell.textLabel?.text = medicamento
cell.detailTextLabel?.text = "Tomado: \(tomado ? "Si" : "No"), Fecha: \(dateFormatter.string(from: fecha))"
let blueColor = UIColor(red: (110/255.0), green: (171/255.0), blue: (247/255.0), alpha: 1.0)
let redColor = UIColor(red: (253/255) as CGFloat, green: (118/255) as CGFloat, blue: (120/255) as CGFloat, alpha: 1.0 as CGFloat)
if tomado {
cell.detailTextLabel?.textColor = blueColor
cell.imageView?.image = UIImage(named: "tomado")
} else {
cell.detailTextLabel?.textColor = redColor
cell.imageView?.image = UIImage(named: "noTomado")
}
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
func deleteRegistro(registro: NSManagedObject) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
managedContext.delete(registro)
do {
try managedContext.save()
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
tableView.reloadData()
}
func refreshTable() {
getTableData()
refreshControl?.endRefreshing()
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
let alert = UIAlertController(title: "Alerta", message: "¿Deseas borrar este registro del sistema?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancelar", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Borrar", style: .destructive, handler: { (UIAlertAction) in
self.deleteRegistro(registro: self.registros[indexPath.row])
self.registros.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}))
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
@IBAction func sendEmail(_ sender: Any) {
sendEmail()
}
func sendEmail() {
if MFMailComposeViewController.canSendMail() {
var bodyMail = String()
for i in 0..<registros.count {
let registro = registros[i] as NSManagedObject
let desc = (registro.value(forKey: "tomada") as! Int)
let tomadoDesc = desc == 1 ? "SI" : "NO"
let fecha = registro.value(forKey: "fecha") as! Date
let timestamp = DateFormatter.localizedString(from: fecha, dateStyle: .short, timeStyle: .short)
bodyMail = "\(bodyMail) \n MEDICAMENTO: \((registro.value(forKey: "medicamento") as! String!)!) TOMADO: \(tomadoDesc) DÍA: \(timestamp)"
}
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
let result = formatter.string(from: date)
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients(mailsMedicos)
mail.setSubject("Medicamentos de \(result)")
mail.setMessageBody("\(bodyMail)", isHTML: true)
present(mail, animated: true)
} else {
// show failure alert
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?){
dismiss(animated: true, completion: nil)
}
@IBAction func SortChanger(_ sender: UISegmentedControl) {
sender.selectedSegmentIndex == 0 ? getTableData(sorted: true) : getTableData(sorted: false)
}
func getTableData(sorted : Bool) {
if sorted {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let sortDescriptor = NSSortDescriptor(key: "fecha", ascending: false)
let fetchRequest : NSFetchRequest<Historial> = Historial.fetchRequest()
fetchRequest.returnsObjectsAsFaults = false
fetchRequest.sortDescriptors = [sortDescriptor]
do {
let results = try managedContext.fetch(fetchRequest)
registros = results as [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}else{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest : NSFetchRequest<Historial> = Historial.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "medicamento", ascending: true)
fetchRequest.returnsObjectsAsFaults = false
fetchRequest.sortDescriptors = [sortDescriptor]
do {
let results = try managedContext.fetch(fetchRequest)
registros = results as [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
tableView.reloadData()
}
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.characters.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
|
mit
|
818441417f371471d8f9bf67c6c0b65c
| 34.587097 | 152 | 0.626178 | 5.07919 | false | false | false | false |
dangquochoi2007/cleancodeswift
|
CleanStore/CleanStore/App/Scenes/MoviesDetails/View/UIView/MoviesDetailsFooterView.swift
|
1
|
1997
|
//
// MoviesDetailsFooterView.swift
// CleanStore
//
// Created by QuocHoi on 2/7/17.
// Copyright © 2017 hoi. All rights reserved.
//
import UIKit
class MoviesDetailsFooterView: UIView {
@IBOutlet weak var recommandCollectionView: UICollectionView!
lazy var moviesLikeAlsoList: [String] = ["Movie_#5","Movie_#4", "Movie_#2"]
override func awakeFromNib() {
super.awakeFromNib()
configureViewWhenAwake()
}
func configureViewWhenAwake() {
recommandCollectionView.showsHorizontalScrollIndicator = false
recommandCollectionView.showsVerticalScrollIndicator = false
recommandCollectionView.delegate = self
recommandCollectionView.dataSource = self
recommandCollectionView.register(RecommandationsCollectionViewCell.nib, forCellWithReuseIdentifier: RecommandationsCollectionViewCell.nibName)
}
}
extension MoviesDetailsFooterView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return moviesLikeAlsoList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RecommandationsCollectionViewCell.nibName, for: indexPath) as! RecommandationsCollectionViewCell
cell.movieCoverImageView.image = UIImage(named: moviesLikeAlsoList[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 138, height: collectionView.frame.size.height)
}
}
|
mit
|
8485ea2eb767da8f345c0c323141f98f
| 32.830508 | 171 | 0.727455 | 5.853372 | false | false | false | false |
wangwugang1314/weiBoSwift
|
weiBoSwift/weiBoSwift/Classes/Home/View/YBHomeCellImageCollectionView.swift
|
1
|
3811
|
//
// YBHomeCellImageCollectionView.swift
// weiBoSwift
//
// Created by MAC on 15/12/4.
// Copyright © 2015年 MAC. All rights reserved.
//
import UIKit
/// 点击图片通知
let YBHomeCellImageClickNotification = "YBHomeCellImageClickNotification"
class YBHomeCellImageCollectionView: UICollectionView {
// MARK: - 属性
/// 布局方式
private let layout = UICollectionViewFlowLayout()
/// 数据
var dataModel: YBWeiBoModel? {
didSet {
// 设置布局
setLayout()
reloadData()
}
}
// MARK: -构造方法
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: self.layout)
self.delegate = self;
self.dataSource = self;
registerClass(YBHomeImageCell.self, forCellWithReuseIdentifier: "YBHomeImageCell")
// 准备UI
prepareUI()
backgroundColor = UIColor.whiteColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - 准备UI
/// 准备UI
private func prepareUI(){
// 设置间隔
layout.minimumInteritemSpacing = 5
layout.minimumLineSpacing = 5
}
/// 设置布局
func setLayout() {
// 设置间距
let itemWid = (UIScreen.width() - 30) / 3
if let count = dataModel?.imageURLs.count {
if count == 1 {
layout.itemSize = dataModel!.imageSize
} else if count > 1 {
layout.itemSize = CGSizeMake(itemWid, itemWid)
}
}
}
/// 计算collectionView大小
func countCollectionSize() -> CGSize {
let count = dataModel?.imageURLs.count ?? 0
let itemWid = (UIScreen.width() - 30) / 3
switch count {
case 1: return dataModel!.imageSize
case 2, 3: return CGSizeMake(CGFloat(count) * itemWid + (CGFloat(count) - 1) * 5, itemWid)
case 4: return CGSizeMake(2 * itemWid + 5, 2 * itemWid + 5)
case 5, 6: return CGSizeMake(3 * itemWid + 10, 2 * itemWid + 5)
case 7, 8, 9: return CGSizeMake(3 * itemWid + 10, 3 * itemWid + 10)
default : return CGSizeZero
}
}
// MARK: - 懒加载
}
/// 代理、扩展
extension YBHomeCellImageCollectionView: UICollectionViewDataSource, UICollectionViewDelegate {
// MARK: - 数据源方法
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataModel?.imageURLs.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = dequeueReusableCellWithReuseIdentifier("YBHomeImageCell", forIndexPath: indexPath) as! YBHomeImageCell
cell.dataUrl = dataModel?.imageURLs[indexPath.row];
return cell
}
// MA
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
dataModel!.index = indexPath.item
/// 获取所有的frame
var frames = [CGRect]()
let count = dataModel!.imageURLs.count
for i in 0..<count {
let cell = cellForItemAtIndexPath(NSIndexPath(forItem: i, inSection: 0))
frames.append(cell!.superview!.convertRect((cell?.frame)!, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!))
}
dataModel?.imageViewFrames = frames
// 发送通知
NSNotificationCenter.defaultCenter().postNotificationName(YBHomeCellImageClickNotification, object: nil, userInfo: ["dataModel" : dataModel!])
}
}
|
apache-2.0
|
48498e6240809a88d75a8c2299898e4e
| 31.254386 | 150 | 0.621872 | 4.888298 | false | false | false | false |
lynnx4869/LYAutoPhotoPickers
|
Classes/Classes/LYAutoPhotoPickers.swift
|
1
|
5187
|
//
// LYAutoPhotoPickers.swift
// LYAutoPhotoPickers
//
// Created by xianing on 2017/6/27.
// Copyright © 2017年 lyning. All rights reserved.
//
import UIKit
import Photos
/// 相册枚举
///
/// - camera: 相机
/// - album: 相册
/// - qrcode: 二维码
public enum LYAutoPhotoType {
/// 相机
case camera
/// 相册
case album
/// 二维码
case qrcode
}
open class LYAutoPhoto: NSObject {
open var asset: PHAsset!
private var _image: UIImage!
open var image: UIImage! {
get {
if _image == nil, let a = asset {
_image = a.getOriginAssetImage()
clear()
}
return _image
}
set {
_image = newValue
}
}
open lazy var tumImage: UIImage! = {
if let a = asset {
return a.getTumAssetImage()
}
return nil
}()
private func clear() {
DispatchQueue.global().asyncAfter(deadline: .now()+5.0) {
[weak self] in
self?._image = nil
}
}
}
public typealias LYAutoCallback = ([LYAutoPhoto]?) -> Void
public typealias LYAutoQRCallback = (String?) -> Void
public extension UIViewController {
func showPickers(type: LYAutoPhotoType = .camera,
maxSelects: Int = 1,
isRateTailor: Bool = false,
tailoringRate: Double = 0.0,
callback: @escaping LYAutoCallback = { _ in },
qr: @escaping LYAutoQRCallback = { _ in }) {
let picker = LYAutoPhotoPickers()
picker.checkPhotoAuth(type) { result in
DispatchQueue.main.async {
var vc: UIViewController!
if result {
switch type {
case .camera:
let cuvc = LYAutoCameraController()
cuvc.isRateTailor = isRateTailor
cuvc.tailoringRate = tailoringRate
cuvc.block = callback
vc = cuvc
case .album:
let avc = LYAutoAlbumsController()
avc.maxSelects = maxSelects
avc.isRateTailor = isRateTailor
avc.tailoringRate = tailoringRate
avc.block = callback
let nav = UINavigationController(rootViewController: avc)
nav.navigationBar.isTranslucent = false
vc = nav
case .qrcode:
let qc = LYAutoQRCodeController()
qc.qrBlock = qr
let nav = UINavigationController(rootViewController: qc)
nav.navigationBar.tintColor = .white
nav.navigationBar.barStyle = .black
nav.navigationBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
nav.navigationBar.shadowImage = UIImage()
vc = nav
}
} else {
let errorVc = picker.getErrorController(type)
vc = errorVc
}
self.present(vc, animated: true, completion: nil)
}
}
}
}
open class LYAutoPhotoPickers {
public init() {}
open func checkPhotoAuth(_ type: LYAutoPhotoType, _ authBlock: @escaping (Bool)->Void) {
if type == .camera || type == .qrcode {
let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
if authStatus == .notDetermined {
AVCaptureDevice.requestAccess(for: AVMediaType.video) { (granted) in
authBlock(granted)
}
} else if authStatus == .denied {
authBlock(false)
} else if authStatus == .authorized {
authBlock(true)
}
} else if type == .album {
let authStatus = PHPhotoLibrary.authorizationStatus()
if authStatus == .notDetermined {
PHPhotoLibrary.requestAuthorization { (status) in
if status == .denied {
authBlock(false)
} else if status == .authorized {
authBlock(true)
}
}
} else if authStatus == .denied {
authBlock(false)
} else if authStatus == .authorized {
authBlock(true)
}
}
}
open func getErrorController(_ type: LYAutoPhotoType) -> UIViewController {
let aec = LYAutoAuthErrorController(nibName: "LYAutoAuthErrorController", bundle: Bundle(for: LYAutoPhotoPickers.self))
aec.type = type
let nav = UINavigationController(rootViewController: aec)
nav.navigationBar.isTranslucent = false
return nav
}
}
|
mit
|
a2b8f066c0869d61206ee6584bf16469
| 30.975155 | 127 | 0.486208 | 5.215805 | false | false | false | false |
DopamineLabs/DopamineKit-iOS
|
BoundlessKit/Classes/Integration/Dashboard/Reinforcement/NotificationCenter/BoundlessNotificationCenter.swift
|
1
|
10573
|
//
// BoundlessNotificationCenter.swift
// BoundlessKit
//
// Created by Akash Desai on 3/7/18.
//
import Foundation
internal extension Array where Element == Notification.Name {
static var visualizerNotifications: [Notification.Name] {
return [.UIApplicationSendAction]
+ UIViewControllerChildrenDidAppear
+ UICollectionViewControllerChildrenDidSelect
}
static var UIViewControllerChildrenDidAppear: [Notification.Name] {
return forSubclasses(parentClass: UIViewController.self, #selector(UIViewController.viewDidAppear(_:)))
}
static var UICollectionViewControllerChildrenDidSelect: [Notification.Name] {
return forSubclasses(parentClass: UICollectionViewController.self, #selector(UICollectionViewController.collectionView(_:didSelectItemAt:)))
}
static func forSubclasses(parentClass: AnyClass, _ selector: Selector) -> [Notification.Name] {
return (InstanceSelectorHelper.classesInheriting(parentClass) as? [AnyClass])?.compactMap({InstanceSelector($0, selector)?.notificationName}) ?? []
}
static func forClassesConforming(to searchProtocol: Protocol, with selector: Selector) -> [Notification.Name] {
return (InstanceSelectorHelper.classesConforming(searchProtocol) as? [AnyClass])?.compactMap({InstanceSelector.init($0, selector)?.notificationName}) ?? []
}
}
internal extension Notification.Name {
static let actionIndicatorTerm = "codeless"
static let CodelessUIApplicationDidFinishLaunching: String = [actionIndicatorTerm, UIApplication.didFinishLaunchingNotification.rawValue].joined(separator: "-")
static let CodelessUIApplicationDidBecomeActive: String = [actionIndicatorTerm, UIApplication.didBecomeActiveNotification.rawValue].joined(separator: "-")
static let UIApplicationSendAction: Notification.Name = {
return InstanceSelector(UIApplication.self, #selector(UIApplication.sendAction(_:to:from:for:)))!.notificationName
}()
static let UIViewControllerDidAppear: Notification.Name = {
return InstanceSelector(UIViewController.self, #selector(UIViewController.viewDidAppear(_:)))!.notificationName
}()
static let UIViewControllerDidDisappear: Notification.Name = {
return InstanceSelector(UIViewController.self, #selector(UIViewController.viewDidDisappear(_:)))!.notificationName
}()
}
internal class BoundlessNotificationCenter : NotificationCenter {
static let _default = BoundlessNotificationCenter()
override public class var `default`: BoundlessNotificationCenter {
return _default
}
fileprivate var posters = [Notification.Name: Poster]()
fileprivate let queue = DispatchQueue(label: "BoundlessNotificationObserverQueue")
override public func addObserver(_ observer: Any, selector aSelector: Selector, name aName: NSNotification.Name?, object anObject: Any?) {
queue.sync {
super.addObserver(observer, selector: aSelector, name: aName, object: anObject)
guard let aName = aName else { return }
if let aPoster = self.posters[aName] {
aPoster.addObserver(observer as AnyObject)
// BKLog.debug("Added observer for instance method:\(aName.rawValue)")
return
}
let aPoster: Poster
if let instanceSelector = InstanceSelector(aName.rawValue),
let poster = InstanceSelectorPoster(instanceSelector) {
aPoster = poster
} else if aName.rawValue == Notification.Name.CodelessUIApplicationDidFinishLaunching {
NotificationCenter.default.addObserver(observer, selector: aSelector, name: UIApplication.didFinishLaunchingNotification, object: anObject)
return
} else if aName.rawValue == Notification.Name.CodelessUIApplicationDidBecomeActive {
NotificationCenter.default.addObserver(observer, selector: aSelector, name: UIApplication.didBecomeActiveNotification, object: anObject)
return
} else {
return
}
self.posters[aName] = aPoster
aPoster.addObserver(observer as AnyObject)
// BKLog.debug("Added first observer for instance method:\(aName.rawValue)")
}
}
override public func removeObserver(_ observer: Any) {
self.removeObserver(observer, name: nil, object: nil)
}
override public func removeObserver(_ observer: Any, name aName: NSNotification.Name?, object anObject: Any?) {
queue.sync {
if let aName = aName {
if let poster = self.posters[aName] {
poster.removeObserver(observer as AnyObject)
// BKLog.debug("Removed observer for notification:\(aName.rawValue)")
}
} else {
for poster in self.posters.values {
poster.removeObserver(observer as AnyObject)
}
}
super.removeObserver(observer, name: aName, object: anObject)
}
}
public func removeAllObservers(name aName: NSNotification.Name?) {
queue.sync {
if let aName = aName {
for observer in self.posters[aName]?.removeAllObservers() ?? [] {
super.removeObserver(observer, name: aName, object: nil)
}
} else {
for (notification, poster) in self.posters {
for observer in poster.removeAllObservers() {
super.removeObserver(observer, name: notification, object: nil)
}
}
}
}
}
}
fileprivate class Poster : NSObject {
struct WeakObject {
weak var value: AnyObject?
init (value: AnyObject) {
self.value = value
}
}
var notificationName: Notification.Name? { get { return nil } }
var observers = [WeakObject]()
func addObserver(_ observer: AnyObject) {
observers.append(WeakObject(value: observer))
}
func removeObserver(_ observer: AnyObject) {
observers = observers.filter({$0.value != nil && $0.value !== observer})
}
func removeAllObservers() -> [AnyObject] {
let oldObservers = observers.compactMap({$0.value})
observers = []
return oldObservers
}
}
fileprivate class InstanceSelectorPoster : Poster {
override var notificationName: Notification.Name? { get { return originalSelector.notificationName } }
let originalSelector: InstanceSelector
let notificationSelector: InstanceSelector
init?(_ instanceSelector: InstanceSelector) {
guard let notificationMethod = InstanceSelectorHelper.createMethod(beforeInstance: instanceSelector.classType, selector: instanceSelector.selector, with: InstanceSelectorPoster.postInstanceSelection),
let notificationSelector = InstanceSelector(instanceSelector.classType, notificationMethod) else {
BKLog.debug(error: "Could not create notification method for actionID<\(instanceSelector.notificationName)")
return nil
}
self.originalSelector = instanceSelector
self.notificationSelector = notificationSelector
super.init()
}
override func addObserver(_ observer: AnyObject) {
if observers.count == 0 {
originalSelector.exchange(with: notificationSelector)
}
super.addObserver(observer)
}
override func removeObserver(_ observer: AnyObject) {
let oldCount = observers.count
super.removeObserver(observer)
if observers.count == 0 && oldCount != 0 {
originalSelector.exchange(with: notificationSelector)
}
}
override func removeAllObservers() -> [AnyObject] {
if observers.count != 0 {
originalSelector.exchange(with: notificationSelector)
}
return super.removeAllObservers()
}
static var postInstanceSelection: InstanceSelectionBlock {
return { aClassType, aSelector, aTarget, aSender in
guard let classType = aClassType,
let selector = aSelector,
let instanceSelector = InstanceSelector(classType, selector) else {
BKLog.debug("Not posting because <\(String(describing: aClassType))-\(String(describing: aSelector))> is not a valid instance selector")
return
}
var userInfo = [String: Any]()
userInfo["classType"] = classType
userInfo["selector"] = selector
userInfo["sender"] = aSender
userInfo["target"] = aTarget
BoundlessNotificationCenter.default.post(name: instanceSelector.notificationName,
object: nil,
userInfo: userInfo)
}
// BKLog.print("Posted instance method notification with name:\(instanceSelector.notificationName.rawValue)")
}
}
fileprivate struct InstanceSelector {
let classType: AnyClass
let selector: Selector
var name: String { return [NSStringFromClass(classType), NSStringFromSelector(selector)].joined(separator: "-") }
init?(_ classType: AnyClass, _ selector: Selector) {
guard classType.instancesRespond(to: selector) else {
BKLog.debug("Could not initialize InstanceSelector because class <\(classType)> does not respond to selector <\(selector)>")
return nil
}
self.classType = classType
self.selector = selector
}
init?(_ name: String) {
let components = name.components(separatedBy: "-")
if components.count == 2,
let classType = NSClassFromString(components[0]) {
let selector = NSSelectorFromString(components[1])
self.init(classType, selector)
} else {
return nil
}
}
init?(_ notification: Notification.Name) {
self.init(notification.rawValue)
}
var notificationName: Notification.Name {
return Notification.Name(self.name)
}
func exchange(with other: InstanceSelector) {
InstanceSelectorHelper.injectSelector(other.classType, other.selector, self.classType, self.selector)
}
}
|
mit
|
3b9a7a3057714e97a6ecf9b5330a30e0
| 39.509579 | 208 | 0.642107 | 5.541405 | false | false | false | false |
liuqing520it/simple_game
|
SimpleGames/SimpleGames/FlappyBird/ViewController/FlappyMainViewController.swift
|
1
|
3424
|
//
// FlappyMainViewController.swift
// SimpleGames
//
// Created by liuqing on 2017/11/5.
// Copyright © 2017年 liuqing. All rights reserved.
//
import UIKit
///小鸟的高
let kBirdWidth : CGFloat = 80
///小鸟的宽
let kBirdHeight = kBirdWidth
///障碍物的宽度
let kBarrierWidth : CGFloat = 100
///障碍物的高度
let kBarrierHeight : CGFloat = 512
//游戏主界面
class FlappyMainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
initTimer()
configUI()
}
private func configUI(){
view.addSubview(birdView)
if birdView.isAnimating == false{
birdView.startAnimating()
}
}
//屏幕点击
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print(">>>>>>")
}
///记录小鸟是上升还是下降 是否点击默认是未点击
private lazy var isTap = false
///顶部障碍物
private lazy var topArray = [TopBarrier]()
///底部障碍物
private lazy var bottomArray = [BottomBarrier]()
///bird
private lazy var birdView = BirdImageView(frame: CGRect(x: 30, y: SCREEN_HEIGHT * 0.5, width: kBirdWidth, height: kBirdHeight))
///定时器
private var timer : Timer?
}
//MARK: - 定时器开启
extension FlappyMainViewController {
/// 初始化定时器
private func initTimer(){
timer = Timer.init(timeInterval: 0.02, repeats: true, block: { (timer) in
self.startGame()
});
RunLoop.current.add(timer!, forMode: RunLoop.Mode.default)
}
static var i : Int = 0
private func startGame(){
if FlappyMainViewController.i % 150 == 0 {
let topBarrier = TopBarrier(frame: CGRect(x: SCREEN_WIDTH , y: 0, width: kBarrierWidth, height: kBarrierHeight))
view.insertSubview(topBarrier, belowSubview: birdView)
topArray.append(topBarrier)
let bottomBarrier = BottomBarrier(frame: CGRect(x: SCREEN_WIDTH, y: SCREEN_HEIGHT - 100, width: kBarrierWidth, height: kBarrierHeight))
view.insertSubview(bottomBarrier, belowSubview: birdView)
bottomArray.append(bottomBarrier)
}
moves()
FlappyMainViewController.i += 1
}
// 开始移动
private func moves(){
for top in topArray{
top.moveToLeft()
if top.frame.maxX < 0{
removeBarriers(top)
}
}
for bottom in bottomArray{
bottom.moveToLeft()
if bottom.frame.maxX < 0{
removeBarriers(bottom)
}
}
}
// 超出部分删除
private func removeBarriers(_ barrier : BarrierMain){
var index : Int?
if barrier.isMember(of: TopBarrier.self){
index = topArray.firstIndex(of: barrier as! TopBarrier)
topArray.remove(at: index!)
}else if barrier.isMember(of: BottomBarrier.self){
index = bottomArray.firstIndex(of: barrier as! BottomBarrier)
bottomArray.remove(at: index!)
}
///从父控件中移除
barrier.removeFromSuperview()
}
}
|
mit
|
138a04db634dd878a00ead77ccfc5512
| 24.304688 | 147 | 0.572399 | 4.195596 | false | false | false | false |
ALiOSDev/ALTableView
|
ALTableViewSwift/TestALTableView/TestALTableView/AppDelegate.swift
|
1
|
3352
|
//
// AppDelegate.swift
// TestALTableView
//
// Created by lorenzo villarroel perez on 20/4/18.
// Copyright © 2018 lorenzo villarroel perez. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
splitViewController.delegate = self
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
|
mit
|
4ae0e92ab1e334f7594f4bc853c39e21
| 53.934426 | 285 | 0.762757 | 6.092727 | false | false | false | false |
BenEmdon/swift-algorithm-club
|
All-Pairs Shortest Paths/APSP/APSP/FloydWarshall.swift
|
1
|
7787
|
//
// FloydWarshall.swift
// APSP
//
// Created by Andrew McKnight on 5/5/16.
//
import Foundation
import Graph
private typealias Distances = [[Double]]
private typealias Predecessors = [[Int?]]
private typealias StepResult = (distances: Distances, predecessors: Predecessors)
/**
Encapsulation of the Floyd-Warshall All-Pairs Shortest Paths algorithm, conforming to the `APSPAlgorithm` protocol.
- note: In all complexity bounds, `V` is the number of vertices in the graph, and `E` is the number of edges.
*/
public struct FloydWarshall<T where T: Hashable>: APSPAlgorithm {
public typealias Q = T
public typealias P = FloydWarshallResult<T>
/**
Floyd-Warshall algorithm for computing all-pairs shortest paths in a weighted directed graph.
- precondition: `graph` must have no negative weight cycles
- complexity: `Θ(V^3)` time, `Θ(V^2)` space
- returns a `FloydWarshallResult` struct which can be queried for shortest paths and their total weights
*/
public static func apply<T>(graph: AbstractGraph<T>) -> FloydWarshallResult<T> {
var previousDistance = constructInitialDistanceMatrix(graph)
var previousPredecessor = constructInitialPredecessorMatrix(previousDistance)
for intermediateIdx in 0 ..< graph.vertices.count {
let nextResult = nextStep(intermediateIdx, previousDistances: previousDistance, previousPredecessors: previousPredecessor, graph: graph)
previousDistance = nextResult.distances
previousPredecessor = nextResult.predecessors
// // uncomment to see each new weight matrix
// print(" D(\(k)):\n")
// printMatrix(nextResult.distances)
//
// // uncomment to see each new predecessor matrix
// print(" ∏(\(k)):\n")
// printIntMatrix(nextResult.predecessors)
}
return FloydWarshallResult<T>(weights: previousDistance, predecessors: previousPredecessor)
}
/**
For each iteration of `intermediateIdx`, perform the comparison for the dynamic algorith,
checking for each pair of start/end vertices, whether a path taken through another vertex
produces a shorter path.
- complexity: `Θ(V^2)` time/space
- returns: a tuple containing the next distance matrix with weights of currently known
shortest paths and the corresponding predecessor matrix
*/
static private func nextStep<T>(intermediateIdx: Int, previousDistances: Distances,
previousPredecessors: Predecessors, graph: AbstractGraph<T>) -> StepResult {
let vertexCount = graph.vertices.count
var nextDistances = Array(count: vertexCount, repeatedValue: Array(count: vertexCount, repeatedValue: Double.infinity))
var nextPredecessors = Array(count: vertexCount, repeatedValue: Array<Int?>(count: vertexCount, repeatedValue: nil))
for fromIdx in 0 ..< vertexCount {
for toIndex in 0 ..< vertexCount {
// printMatrix(previousDistances, i: fromIdx, j: toIdx, k: intermediateIdx) // uncomment to see each comparison being made
let originalPathWeight = previousDistances[fromIdx][toIndex]
let newPathWeightBefore = previousDistances[fromIdx][intermediateIdx]
let newPathWeightAfter = previousDistances[intermediateIdx][toIndex]
let minimum = min(originalPathWeight, newPathWeightBefore + newPathWeightAfter)
nextDistances[fromIdx][toIndex] = minimum
var predecessor: Int?
if originalPathWeight <= newPathWeightBefore + newPathWeightAfter {
predecessor = previousPredecessors[fromIdx][toIndex]
} else {
predecessor = previousPredecessors[intermediateIdx][toIndex]
}
nextPredecessors[fromIdx][toIndex] = predecessor
}
}
return (nextDistances, nextPredecessors)
}
/**
We need to map the graph's weight domain onto the one required by the algorithm: the graph
stores either a weight as a `Double` or `nil` if no edge exists between two vertices, but
the algorithm needs a lack of an edge represented as ∞ for the `min` comparison to work correctly.
- complexity: `Θ(V^2)` time/space
- returns: weighted adjacency matrix in form ready for processing with Floyd-Warshall
*/
static private func constructInitialDistanceMatrix<T>(graph: AbstractGraph<T>) -> Distances {
let vertices = graph.vertices
let vertexCount = graph.vertices.count
var distances = Array(count: vertexCount, repeatedValue: Array(count: vertexCount, repeatedValue: Double.infinity))
for row in vertices {
for col in vertices {
let rowIdx = row.index
let colIdx = col.index
if rowIdx == colIdx {
distances[rowIdx][colIdx] = 0.0
} else if let w = graph.weightFrom(row, to: col) {
distances[rowIdx][colIdx] = w
}
}
}
return distances
}
/**
Make the initial predecessor index matrix. Initially each value is equal to it's row index, it's "from" index when querying into it.
- complexity: `Θ(V^2)` time/space
*/
static private func constructInitialPredecessorMatrix(distances: Distances) -> Predecessors {
let vertexCount = distances.count
var predecessors = Array(count: vertexCount, repeatedValue: Array<Int?>(count: vertexCount, repeatedValue: nil))
for fromIdx in 0 ..< vertexCount {
for toIdx in 0 ..< vertexCount {
if fromIdx != toIdx && distances[fromIdx][toIdx] < Double.infinity {
predecessors[fromIdx][toIdx] = fromIdx
}
}
}
return predecessors
}
}
/**
`FloydWarshallResult` encapsulates the result of the computation, namely the
minimized distance adjacency matrix, and the matrix of predecessor indices.
It conforms to the `APSPResult` procotol which provides methods to retrieve
distances and paths between given pairs of start and end nodes.
*/
public struct FloydWarshallResult<T where T: Hashable>: APSPResult {
private var weights: Distances
private var predecessors: Predecessors
/**
- returns: the total weight of the path from a starting vertex to a destination.
This value is the minimal connected weight between the two vertices, or `nil` if no path exists
- complexity: `Θ(1)` time/space
*/
public func distance(fromVertex from: Vertex<T>, toVertex to: Vertex<T>) -> Double? {
return weights[from.index][to.index]
}
/**
- returns: the reconstructed path from a starting vertex to a destination,
as an array containing the data property of each vertex, or `nil` if no path exists
- complexity: `Θ(V)` time, `Θ(V^2)` space
*/
public func path(fromVertex from: Vertex<T>, toVertex to: Vertex<T>, inGraph graph: AbstractGraph<T>) -> [T]? {
if let path = recursePathFrom(fromVertex: from, toVertex: to, path: [ to ], inGraph: graph) {
let pathValues = path.map() { vertex in
vertex.data
}
return pathValues
}
return nil
}
/**
The recursive component to rebuilding the shortest path between
two vertices using the predecessor matrix.
- returns: the list of predecessors discovered so far
*/
private func recursePathFrom(fromVertex from: Vertex<T>, toVertex to: Vertex<T>, path: [Vertex<T>],
inGraph graph: AbstractGraph<T>) -> [Vertex<T>]? {
if from.index == to.index {
return [ from, to ]
}
if let predecessor = predecessors[from.index][to.index] {
let predecessorVertex = graph.vertices[predecessor]
if predecessor == from.index {
let newPath = [ from, to ]
return newPath
} else {
let buildPath = recursePathFrom(fromVertex: from, toVertex: predecessorVertex, path: path, inGraph: graph)
let newPath = buildPath! + [ to ]
return newPath
}
}
return nil
}
}
|
mit
|
c4ee010ac67bf1b1a178f6e9a000c004
| 35.162791 | 142 | 0.694534 | 4.25561 | false | false | false | false |
pj4533/OpenPics
|
Pods/Moya/Source/Moya+Alamofire.swift
|
4
|
1766
|
import Foundation
import Alamofire
public typealias Manager = Alamofire.Manager
/// Choice of parameter encoding.
public enum ParameterEncoding {
case URL
case JSON
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
internal var toAlamofire: Alamofire.ParameterEncoding {
switch self {
case .URL:
return .URL
case .JSON:
return .JSON
case .PropertyList(let format, let options):
return .PropertyList(format, options)
case .Custom(let closure):
return .Custom(closure)
}
}
}
/// Make the Alamofire Request type conform to our type, to prevent leaking Alamofire to plugins.
extension Request: RequestType { }
/// Internal token that can be used to cancel requests
internal final class CancellableToken: Cancellable , CustomDebugStringConvertible {
let cancelAction: () -> Void
let request : Request?
private(set) var canceled: Bool = false
private var lock: OSSpinLock = OS_SPINLOCK_INIT
func cancel() {
OSSpinLockLock(&lock)
defer { OSSpinLockUnlock(&lock) }
guard !canceled else { return }
canceled = true
cancelAction()
}
init(action: () -> Void){
self.cancelAction = action
self.request = nil
}
init(request : Request){
self.request = request
self.cancelAction = {
request.cancel()
}
}
var debugDescription: String {
guard let request = self.request else {
return "Empty Request"
}
return request.debugDescription
}
}
|
gpl-3.0
|
7286030a734cbcf0dfa28519a613a11a
| 26.169231 | 97 | 0.62684 | 5.163743 | false | false | false | false |
turekj/ReactiveTODO
|
ReactiveTODOFramework/Classes/Controls/DatePickers/Impl/PopupDatePicker.swift
|
1
|
3992
|
import Cartography
import ReactiveKit
import ReactiveUIKit
import UIKit
class PopupDatePicker: UIView, PopupDatePickerProtocol {
let date: ReactiveKit.Property<NSDate?>
let validator: Validator<NSDate?>
let dateFormatter: DateFormatterProtocol
let datePicker: UIDatePicker
let triggerPickerButton: UIButton
init(validator: Validator<NSDate?>,
dateFormatter: DateFormatterProtocol,
datePicker: UIDatePicker,
triggerPickerButton: UIButton) {
self.date = ReactiveKit.Property(nil)
self.validator = validator
self.dateFormatter = dateFormatter
self.datePicker = datePicker
self.triggerPickerButton = triggerPickerButton
super.init(frame: CGRectZero)
self.configureView()
self.bindViewModel()
}
func configureView() {
self.configureTriggerPickerButton()
self.configureDatePicker()
}
func configureTriggerPickerButton() {
self.triggerPickerButton.titleEdgeInsets =
UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0)
self.triggerPickerButton.layer.borderWidth = 1.0
self.triggerPickerButton.layer.cornerRadius = 5.0
self.addSubview(self.triggerPickerButton)
constrain(self.triggerPickerButton) { b in
b.width == 200
b.height == 28
b.bottom == b.superview!.bottom
b.leading == b.superview!.leading
}
}
func configureDatePicker() {
self.datePicker.backgroundColor = UIColor.whiteColor()
self.datePicker.datePickerMode = .DateAndTime
self.datePicker.hidden = true
self.addSubview(self.datePicker)
constrain(self.datePicker, self.triggerPickerButton) { p, b in
p.top == p.superview!.top
p.leading == p.superview!.leading
p.trailing == p.superview!.trailing
p.bottom == b.top - 10
}
}
func bindViewModel() {
self.bindDateProperty()
self.bindDatePickerVisibility()
self.bindButtonCaption()
self.bindButtonValidityStyle()
}
func bindDateProperty() {
self.datePicker.rDate.map { (date: NSDate) -> NSDate? in
if (self.validator.validate(date)) {
return date
}
else {
return nil
}
}.bindTo(self.date)
}
func bindDatePickerVisibility() {
self.triggerPickerButton.rTap
.observeIn(ImmediateOnMainExecutionContext)
.observeNext { _ in
self.datePicker.hidden = !self.datePicker.hidden
}.disposeIn(self.rBag)
}
func bindButtonCaption() {
self.date.map { (date: NSDate?) -> String in
guard let date = date else {
return "Select future date"
}
return self.dateFormatter.format(date)
}.bindTo(self.triggerPickerButton.rTitle)
}
func bindButtonValidityStyle() {
self.date.map {
$0 != nil ? UIColor.validValueColor() : UIColor.invalidValueColor()
}.observeIn(ImmediateOnMainExecutionContext)
.observeNext { color in
self.triggerPickerButton.layer.borderColor = color.CGColor
self.triggerPickerButton.setTitleColor(color, forState: .Normal)
}.disposeIn(self.rBag)
}
// MARK: - Touch handling
override func pointInside(point: CGPoint,
withEvent event: UIEvent?) -> Bool {
for subview in self.subviews {
guard !subview.hidden else {
continue
}
let point = self.convertPoint(point, toView: subview)
if (subview.pointInside(point, withEvent: event)) {
return true
}
}
return false
}
// MARK: - Required init
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
678ca87358b2e439683ee08f91eb2cff
| 28.57037 | 79 | 0.604208 | 4.946716 | false | false | false | false |
dreamsxin/swift
|
test/SILGen/newtype.swift
|
3
|
2183
|
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import -enable-swift-newtype %s | FileCheck %s -check-prefix=CHECK-RAW
// RUN: %target-swift-frontend -emit-sil -sdk %S/Inputs -I %S/Inputs -enable-source-import -enable-swift-newtype %s | FileCheck %s -check-prefix=CHECK-CANONICAL
// REQUIRES: objc_interop
import Newtype
// CHECK-CANONICAL-LABEL: sil hidden @_TF7newtype17createErrorDomain
// CHECK-CANONICAL: bb0([[STR:%[0-9]+]] : $String)
func createErrorDomain(str: String) -> ErrorDomain {
// CHECK-CANONICAL: [[BRIDGE_FN:%[0-9]+]] = function_ref @{{.*}}_bridgeToObjectiveC
// CHECK-CANONICAL-NEXT: [[BRIDGED:%[0-9]+]] = apply [[BRIDGE_FN]]([[STR]])
// CHECK-CANONICAL: struct $ErrorDomain ([[BRIDGED]] : $NSString)
return ErrorDomain(rawValue: str)
}
// CHECK-RAW-LABEL: sil shared [transparent] [fragile] @_TFVSC11ErrorDomainCfT8rawValueSS_S_
// CHECK-RAW: bb0([[STR:%[0-9]+]] : $String,
// CHECK-RAW: [[SELF_BOX:%[0-9]+]] = alloc_box $ErrorDomain, var, name "self"
// CHECK-RAW: [[SELF:%[0-9]+]] = project_box [[SELF_BOX]]
// CHECK-RAW: [[UNINIT_SELF:%[0-9]+]] = mark_uninitialized [rootself] [[SELF]]
// CHECK-RAW: [[BRIDGE_FN:%[0-9]+]] = function_ref @{{.*}}_bridgeToObjectiveC
// CHECK-RAW: [[BRIDGED:%[0-9]+]] = apply [[BRIDGE_FN]]([[STR]])
// CHECK-RAW: [[RAWVALUE_ADDR:%[0-9]+]] = struct_element_addr [[UNINIT_SELF]]
// CHECK-RAW: assign [[BRIDGED]] to [[RAWVALUE_ADDR]]
func getRawValue(ed: ErrorDomain) -> String {
return ed.rawValue
}
// CHECK-RAW-LABEL: sil shared @_TFVSC11ErrorDomaing8rawValueSS
// CHECK-RAW: bb0([[SELF:%[0-9]+]] : $ErrorDomain):
// CHECK-RAW: [[FORCE_BRIDGE:%[0-9]+]] = function_ref @_forceBridgeFromObjectiveC_bridgeable
// CHECK-RAW: [[STORED_VALUE:%[0-9]+]] = struct_extract [[SELF]] : $ErrorDomain, #ErrorDomain._rawValue
// CHECK-RAW: [[STRING_META:%[0-9]+]] = metatype $@thick String.Type
// CHECK-RAW: [[STRING_RESULT_ADDR:%[0-9]+]] = alloc_stack $String
// CHECK-RAW: apply [[FORCE_BRIDGE]]<String, NSString>([[STRING_RESULT_ADDR]], [[STORED_VALUE]], [[STRING_META]])
// CHECK-RAW: [[STRING_RESULT:%[0-9]+]] = load [[STRING_RESULT_ADDR]]
// CHECK-RAW: return [[STRING_RESULT]]
|
apache-2.0
|
ef7b1a6e556d4a68c9d569bdafeb4bdb
| 52.243902 | 161 | 0.660559 | 3.219764 | false | false | false | false |
yeokm1/SwiftSerial
|
Examples/SwiftSerialBinary/Sources/main.swift
|
1
|
1900
|
import Foundation
import SwiftSerial
print("You should do a loopback i.e short the TX and RX pins of the target serial port before testing.")
let testBinaryArray : [UInt8] = [0x11, 0x22, 0x33, 0x0D, 0x44]
let arguments = CommandLine.arguments
guard arguments.count >= 2 else {
print("Need serial port name, e.g. /dev/ttyUSB0 or /dev/cu.usbserial as the first argument.")
exit(1)
}
let portName = arguments[1]
let serialPort: SerialPort = SerialPort(path: portName)
do {
print("Attempting to open port: \(portName)")
try serialPort.openPort()
print("Serial port \(portName) opened successfully.")
defer {
serialPort.closePort()
print("Port Closed")
}
serialPort.setSettings(receiveRate: .baud9600,
transmitRate: .baud9600,
minimumBytesToRead: 1)
print("Sending: ", terminator:"")
print(testBinaryArray.map { String($0, radix: 16, uppercase: false) })
let dataToSend: Data = Data(_: testBinaryArray)
let bytesWritten = try serialPort.writeData(dataToSend)
print("Successfully wrote \(bytesWritten) bytes")
print("Waiting to receive what was written...")
let dataReceived = try serialPort.readData(ofLength: bytesWritten)
print("Received: ", terminator:"")
print(dataReceived.map { String($0, radix: 16, uppercase: false) })
if(dataToSend.elementsEqual(dataReceived)){
print("Received data is the same as transmitted data. Test successful!")
} else {
print("Uh oh! Received data is not the same as what was transmitted. This was what we received,")
print(dataReceived.map { String($0, radix: 16, uppercase: false) })
}
print("End of example");
} catch PortError.failedToOpen {
print("Serial port \(portName) failed to open. You might need root permissions.")
} catch {
print("Error: \(error)")
}
|
mit
|
6fc593f140cabe00edc17ef8c3e5d9b8
| 30.666667 | 105 | 0.667895 | 4.051173 | false | true | false | false |
Ramotion/reel-search
|
RAMReel/Framework/CollectionViewLayout.swift
|
1
|
3408
|
//
// RAMCollectionViewLayout.swift
// RAMReel
//
// Created by Mikhail Stepkin on 4/9/15.
// Copyright (c) 2015 Ramotion. All rights reserved.
//
import UIKit
/**
Example collection view layout
*/
@objc(RAMCollectionViewLayout)
class RAMCollectionViewLayout: UICollectionViewFlowLayout {
internal override func prepare() {
super.prepare()
updateInsets()
}
func updateInsets() {
if let collectionView = self.collectionView {
let insets = (collectionView.bounds.height - itemHeight)/2
collectionView.contentInset = UIEdgeInsets(top: insets, left: 0, bottom: insets, right: 0)
}
}
internal override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return self.layoutAttributesForItem(at: itemIndexPath)
}
internal override func layoutAttributesForItem(at indexPath:IndexPath) -> UICollectionViewLayoutAttributes {
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
self.modifyLayoutAttributes(attributes)
return attributes
}
internal override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var allAttributesInRect = [(UICollectionViewLayoutAttributes, CGFloat)]()
if let numberOfItems = collectionView?.numberOfItems(inSection: 0) {
for item in 0 ..< numberOfItems {
let indexPath = IndexPath(item: item, section: 0)
let attributes = self.layoutAttributesForItem(at: indexPath)
if rect.intersects(attributes.frame) {
let intersection = rect.intersection(attributes.frame)
allAttributesInRect.append((attributes, intersection.area))
}
}
}
allAttributesInRect.sort {
let (_, a1) = $0
let (_, a2) = $1
return a1 > a2
}
let attributes = allAttributesInRect.map ({ (attr, _) in
attr
})
return attributes
}
var itemHeight: CGFloat = 44
func modifyLayoutAttributes(_ layoutattributes: UICollectionViewLayoutAttributes) {
if
let collectionView = self.collectionView
{
var frame = layoutattributes.frame
frame.size.height = itemHeight
frame.size.width = collectionView.bounds.width
frame.origin.x = collectionView.bounds.origin.x
frame.origin.y = itemHeight * CGFloat((layoutattributes.indexPath as NSIndexPath).item)
layoutattributes.frame = frame
}
}
internal override var collectionViewContentSize : CGSize {
guard let collectionView = self.collectionView else {
return CGSize.zero
}
let number = collectionView.numberOfItems(inSection: 0)
let height = CGFloat(number) * itemHeight
let size = CGSize(width: collectionView.bounds.width, height: height)
return size
}
}
private extension CGRect {
var area: CGFloat {
return self.height * self.width
}
}
|
mit
|
fec3e9e6fcd70c686ae2f46d4927c9f6
| 29.702703 | 134 | 0.600059 | 5.786078 | false | false | false | false |
nextcloud/ios
|
File Provider Extension/FileProviderData.swift
|
1
|
8847
|
//
// FileProviderData.swift
// Files
//
// Created by Marino Faggiana on 27/05/18.
// Copyright © 2018 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
import NextcloudKit
class fileProviderData: NSObject {
static let shared: fileProviderData = {
let instance = fileProviderData()
return instance
}()
var domain: NSFileProviderDomain?
var fileProviderManager: NSFileProviderManager = NSFileProviderManager.default
var account = ""
var user = ""
var userId = ""
var accountUrlBase = ""
var homeServerUrl = ""
// Max item for page
let itemForPage = 100
// Anchor
var currentAnchor: UInt64 = 0
// Rank favorite
var listFavoriteIdentifierRank: [String: NSNumber] = [:]
// Item for signalEnumerator
var fileProviderSignalDeleteContainerItemIdentifier: [NSFileProviderItemIdentifier: NSFileProviderItemIdentifier] = [:]
var fileProviderSignalUpdateContainerItem: [NSFileProviderItemIdentifier: FileProviderItem] = [:]
var fileProviderSignalDeleteWorkingSetItemIdentifier: [NSFileProviderItemIdentifier: NSFileProviderItemIdentifier] = [:]
var fileProviderSignalUpdateWorkingSetItem: [NSFileProviderItemIdentifier: FileProviderItem] = [:]
// Error
enum FileProviderError: Error {
case downloadError
case uploadError
}
// MARK: -
func setupAccount(domain: NSFileProviderDomain?, providerExtension: NSFileProviderExtension) -> tableAccount? {
if CCUtility.getDisableFilesApp() || NCBrandOptions.shared.disable_openin_file {
return nil
}
self.domain = domain
if domain != nil {
if let fileProviderManager = NSFileProviderManager(for: domain!) {
self.fileProviderManager = fileProviderManager
}
}
// LOG
if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
NKCommon.shared.pathLog = pathDirectoryGroup
let levelLog = CCUtility.getLogLevel()
NKCommon.shared.levelLog = levelLog
let version = NSString(format: NCBrandOptions.shared.textCopyrightNextcloudiOS as NSString, NCUtility.shared.getVersionApp()) as String
NKCommon.shared.writeLog("[INFO] Start File Provider session with level \(levelLog) " + version + " (File Provider Extension)")
}
// NO DOMAIN -> Set default account
if domain == nil {
guard let activeAccount = NCManageDatabase.shared.getActiveAccount() else { return nil }
let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: activeAccount.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
account = activeAccount.account
user = activeAccount.user
userId = activeAccount.userId
accountUrlBase = activeAccount.urlBase
homeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, userId: activeAccount.userId)
NKCommon.shared.setup(account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account), urlBase: activeAccount.urlBase, userAgent: CCUtility.getUserAgent(), nextcloudVersion: serverVersionMajor, delegate: NCNetworking.shared)
NCNetworking.shared.delegate = providerExtension as? NCNetworkingDelegate
return tableAccount.init(value: activeAccount)
}
// DOMAIN
let accounts = NCManageDatabase.shared.getAllAccount()
if accounts.count == 0 { return nil }
for activeAccount in accounts {
guard let url = NSURL(string: activeAccount.urlBase) else { continue }
guard let host = url.host else { continue }
let accountDomain = activeAccount.userId + " (" + host + ")"
if accountDomain == domain!.identifier.rawValue {
let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: activeAccount.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
account = activeAccount.account
user = activeAccount.user
userId = activeAccount.userId
accountUrlBase = activeAccount.urlBase
homeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, userId: activeAccount.userId)
NKCommon.shared.setup(account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account), urlBase: activeAccount.urlBase, userAgent: CCUtility.getUserAgent(), nextcloudVersion: serverVersionMajor, delegate: NCNetworking.shared)
NCNetworking.shared.delegate = providerExtension as? NCNetworkingDelegate
return tableAccount.init(value: activeAccount)
}
}
return nil
}
// MARK: -
@discardableResult
func signalEnumerator(ocId: String, delete: Bool = false, update: Bool = false) -> FileProviderItem? {
guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return nil }
guard let parentItemIdentifier = fileProviderUtility.shared.getParentItemIdentifier(metadata: metadata) else { return nil }
let item = FileProviderItem(metadata: metadata, parentItemIdentifier: parentItemIdentifier)
if delete {
fileProviderData.shared.fileProviderSignalDeleteContainerItemIdentifier[item.itemIdentifier] = item.itemIdentifier
fileProviderData.shared.fileProviderSignalDeleteWorkingSetItemIdentifier[item.itemIdentifier] = item.itemIdentifier
}
if update {
fileProviderData.shared.fileProviderSignalUpdateContainerItem[item.itemIdentifier] = item
fileProviderData.shared.fileProviderSignalUpdateWorkingSetItem[item.itemIdentifier] = item
}
if !update && !delete {
fileProviderData.shared.fileProviderSignalUpdateWorkingSetItem[item.itemIdentifier] = item
}
if update || delete {
currentAnchor += 1
fileProviderManager.signalEnumerator(for: parentItemIdentifier) { _ in }
}
fileProviderManager.signalEnumerator(for: .workingSet) { _ in }
return item
}
/*
func updateFavoriteForWorkingSet() {
var updateWorkingSet = false
let oldListFavoriteIdentifierRank = listFavoriteIdentifierRank
listFavoriteIdentifierRank = NCManageDatabase.shared.getTableMetadatasDirectoryFavoriteIdentifierRank(account: account)
// (ADD)
for (identifier, _) in listFavoriteIdentifierRank {
guard let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "ocId == %@", identifier)) else { continue }
guard let parentItemIdentifier = fileProviderUtility.sharedInstance.getParentItemIdentifier(metadata: metadata, homeServerUrl: homeServerUrl) else { continue }
let item = FileProviderItem(metadata: metadata, parentItemIdentifier: parentItemIdentifier)
fileProviderSignalUpdateWorkingSetItem[item.itemIdentifier] = item
updateWorkingSet = true
}
// (REMOVE)
for (identifier, _) in oldListFavoriteIdentifierRank {
if !listFavoriteIdentifierRank.keys.contains(identifier) {
guard let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "ocId == %@", identifier)) else { continue }
let itemIdentifier = fileProviderUtility.sharedInstance.getItemIdentifier(metadata: metadata)
fileProviderSignalDeleteWorkingSetItemIdentifier[itemIdentifier] = itemIdentifier
updateWorkingSet = true
}
}
if updateWorkingSet {
signalEnumerator(for: [.workingSet])
}
}
*/
}
|
gpl-3.0
|
189aad62af999bff5499e259d9d76a49
| 42.362745 | 319 | 0.685847 | 5.128116 | false | false | false | false |
nextcloud/ios
|
iOSClient/Viewer/NCViewerMedia/NCViewerMediaPage.swift
|
1
|
25965
|
//
// NCViewerMediaPage.swift
// Nextcloud
//
// Created by Marino Faggiana on 24/10/2020.
// Copyright © 2020 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
import NextcloudKit
import MediaPlayer
class NCViewerMediaPage: UIViewController {
@IBOutlet weak var progressView: UIProgressView!
enum ScreenMode {
case full, normal
}
var currentScreenMode: ScreenMode = .normal
var saveScreenModeImage: ScreenMode = .normal
var pageViewController: UIPageViewController {
return self.children[0] as! UIPageViewController
}
var currentViewController: NCViewerMedia {
return self.pageViewController.viewControllers![0] as! NCViewerMedia
}
var metadatas: [tableMetadata] = []
var modifiedOcId: [String] = []
var currentIndex = 0
var nextIndex: Int?
var ncplayerLivePhoto: NCPlayer?
var panGestureRecognizer: UIPanGestureRecognizer!
var singleTapGestureRecognizer: UITapGestureRecognizer!
var longtapGestureRecognizer: UILongPressGestureRecognizer!
var textColor: UIColor = .label
var playCommand: Any?
var pauseCommand: Any?
var skipForwardCommand: Any?
var skipBackwardCommand: Any?
var nextTrackCommand: Any?
var previousTrackCommand: Any?
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "more")!.image(color: .label, size: 25), style: .plain, target: self, action: #selector(self.openMenuMore))
singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didSingleTapWith(gestureRecognizer:)))
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didPanWith(gestureRecognizer:)))
longtapGestureRecognizer = UILongPressGestureRecognizer()
longtapGestureRecognizer.delaysTouchesBegan = true
longtapGestureRecognizer.minimumPressDuration = 0.3
longtapGestureRecognizer.delegate = self
longtapGestureRecognizer.addTarget(self, action: #selector(didLongpressGestureEvent(gestureRecognizer:)))
pageViewController.delegate = self
pageViewController.dataSource = self
pageViewController.view.addGestureRecognizer(panGestureRecognizer)
pageViewController.view.addGestureRecognizer(singleTapGestureRecognizer)
pageViewController.view.addGestureRecognizer(longtapGestureRecognizer)
let viewerMedia = getViewerMedia(index: currentIndex, metadata: metadatas[currentIndex])
pageViewController.setViewControllers([viewerMedia], direction: .forward, animated: true, completion: nil)
NotificationCenter.default.addObserver(self, selector: #selector(viewUnload), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuDetailClose), object: nil)
progressView.tintColor = NCBrandColor.shared.brandElement
progressView.trackTintColor = .clear
progressView.progress = 0
NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(hidePlayerToolBar(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterHidePlayerToolBar), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(showPlayerToolBar(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterShowPlayerToolBar), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(reloadMediaPage(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadMediaPage), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterHidePlayerToolBar), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterShowPlayerToolBar), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadMediaPage), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if let ncplayer = currentViewController.ncplayer, ncplayer.isPlay() {
ncplayer.playerPause()
ncplayer.saveCurrentTime()
}
currentViewController.playerToolBar?.stopTimerAutoHide()
clearCommandCenter()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
if currentScreenMode == .normal {
return .default
} else {
return .lightContent
}
}
override var prefersHomeIndicatorAutoHidden: Bool {
return currentScreenMode == .full
}
// MARK: -
func getViewerMedia(index: Int, metadata: tableMetadata) -> NCViewerMedia {
let viewerMedia = UIStoryboard(name: "NCViewerMediaPage", bundle: nil).instantiateViewController(withIdentifier: "NCViewerMedia") as! NCViewerMedia
viewerMedia.index = index
viewerMedia.metadata = metadata
viewerMedia.viewerMediaPage = self
singleTapGestureRecognizer.require(toFail: viewerMedia.doubleTapGestureRecognizer)
return viewerMedia
}
@objc func viewUnload() {
navigationController?.popViewController(animated: true)
}
@objc func openMenuMore() {
let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(currentViewController.metadata.ocId, etag: currentViewController.metadata.etag))
NCViewer.shared.toggleMenu(viewController: self, metadata: currentViewController.metadata, webView: false, imageIcon: imageIcon)
}
func changeScreenMode(mode: ScreenMode, enableTimerAutoHide: Bool = false) {
if mode == .normal {
navigationController?.setNavigationBarHidden(false, animated: true)
progressView.isHidden = false
if !currentViewController.detailView.isShow() {
currentViewController.playerToolBar?.show(enableTimerAutoHide: enableTimerAutoHide)
}
NCUtility.shared.colorNavigationController(navigationController, backgroundColor: .systemBackground, titleColor: .label, tintColor: nil, withoutShadow: false)
view.backgroundColor = .systemBackground
textColor = .label
} else {
navigationController?.setNavigationBarHidden(true, animated: true)
progressView.isHidden = true
currentViewController.playerToolBar?.hide()
view.backgroundColor = .black
textColor = .white
}
currentScreenMode = mode
if currentViewController.metadata.classFile == NKCommon.typeClassFile.image.rawValue {
saveScreenModeImage = mode
}
setNeedsStatusBarAppearanceUpdate()
setNeedsUpdateOfHomeIndicatorAutoHidden()
currentViewController.reloadDetail()
}
// MARK: - NotificationCenter
@objc func downloadedFile(_ notification: NSNotification) {
progressView.progress = 0
}
@objc func triggerProgressTask(_ notification: NSNotification) {
guard let userInfo = notification.userInfo as NSDictionary?,
let progressNumber = userInfo["progress"] as? NSNumber
else { return }
let progress = progressNumber.floatValue
if progress == 1 {
self.progressView.progress = 0
} else {
self.progressView.progress = progress
}
}
@objc func uploadStartFile(_ notification: NSNotification) {
/*
guard let userInfo = notification.userInfo as NSDictionary?,
let serverUrl = userInfo["serverUrl"] as? String,
let fileName = userInfo["fileName"] as? String,
let sessionSelector = userInfo["sessionSelector"] as? String
else { return }
*/
}
@objc func uploadedFile(_ notification: NSNotification) {
guard let userInfo = notification.userInfo as NSDictionary?,
let ocId = userInfo["ocId"] as? String,
let error = userInfo["error"] as? NKError,
error == .success,
let index = metadatas.firstIndex(where: {$0.ocId == ocId}),
let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
else {
return
}
metadatas[index] = metadata
if currentViewController.metadata.ocId == ocId {
currentViewController.reloadImage()
} else {
modifiedOcId.append(ocId)
}
}
@objc func deleteFile(_ notification: NSNotification) {
guard let userInfo = notification.userInfo as NSDictionary?,
let ocId = userInfo["ocId"] as? String
else { return }
// Stop media
if let ncplayer = currentViewController.ncplayer, ncplayer.isPlay() {
ncplayer.playerPause()
}
let metadatas = self.metadatas.filter { $0.ocId != ocId }
if self.metadatas.count == metadatas.count { return }
self.metadatas = metadatas
if ocId == currentViewController.metadata.ocId {
shiftCurrentPage()
}
}
@objc func renameFile(_ notification: NSNotification) {
guard let userInfo = notification.userInfo as NSDictionary?,
let ocId = userInfo["ocId"] as? String,
let index = metadatas.firstIndex(where: {$0.ocId == ocId}),
let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
else { return }
// Stop media
if let ncplayer = currentViewController.ncplayer, ncplayer.isPlay() {
ncplayer.playerPause()
}
metadatas[index] = metadata
if index == currentIndex {
navigationItem.title = metadata.fileNameView
currentViewController.metadata = metadata
self.currentViewController.metadata = metadata
}
}
@objc func moveFile(_ notification: NSNotification) {
guard let userInfo = notification.userInfo as NSDictionary?,
let ocId = userInfo["ocId"] as? String
else { return }
// Stop media
if let ncplayer = currentViewController.ncplayer, ncplayer.isPlay() {
ncplayer.playerPause()
}
if metadatas.firstIndex(where: {$0.ocId == ocId}) != nil {
deleteFile(notification)
}
}
@objc func hidePlayerToolBar(_ notification: NSNotification) {
if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String {
if currentViewController.metadata.ocId == ocId {
changeScreenMode(mode: .full)
}
}
}
@objc func showPlayerToolBar(_ notification: NSNotification) {
if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String, let enableTimerAutoHide = userInfo["enableTimerAutoHide"] as? Bool {
if currentViewController.metadata.ocId == ocId, let playerToolBar = currentViewController.playerToolBar, !playerToolBar.isPictureInPictureActive() {
changeScreenMode(mode: .normal, enableTimerAutoHide: enableTimerAutoHide)
}
}
}
@objc func reloadMediaPage(_ notification: NSNotification) {
self.reloadCurrentPage()
}
@objc func applicationDidBecomeActive(_ notification: NSNotification) {
progressView.progress = 0
}
// MARK: - Command Center
func updateCommandCenter(ncplayer: NCPlayer, metadata: tableMetadata) {
var nowPlayingInfo = [String: Any]()
// Clear
clearCommandCenter()
UIApplication.shared.beginReceivingRemoteControlEvents()
// Add handler for Play Command
MPRemoteCommandCenter.shared().playCommand.isEnabled = true
playCommand = MPRemoteCommandCenter.shared().playCommand.addTarget { _ in
if !ncplayer.isPlay() {
ncplayer.playerPlay()
return .success
}
return .commandFailed
}
// Add handler for Pause Command
MPRemoteCommandCenter.shared().pauseCommand.isEnabled = true
pauseCommand = MPRemoteCommandCenter.shared().pauseCommand.addTarget { _ in
if ncplayer.isPlay() {
ncplayer.playerPause()
return .success
}
return .commandFailed
}
// VIDEO / AUDIO () ()
if metadata.classFile == NKCommon.typeClassFile.video.rawValue || metadata.classFile == NKCommon.typeClassFile.audio.rawValue {
MPRemoteCommandCenter.shared().skipForwardCommand.isEnabled = true
skipForwardCommand = MPRemoteCommandCenter.shared().skipForwardCommand.addTarget { event in
let seconds = Float64((event as! MPSkipIntervalCommandEvent).interval)
self.currentViewController.playerToolBar?.skip(seconds: seconds)
return.success
}
MPRemoteCommandCenter.shared().skipBackwardCommand.isEnabled = true
skipBackwardCommand = MPRemoteCommandCenter.shared().skipBackwardCommand.addTarget { event in
let seconds = Float64((event as! MPSkipIntervalCommandEvent).interval)
self.currentViewController.playerToolBar?.skip(seconds: -seconds)
return.success
}
}
nowPlayingInfo[MPMediaItemPropertyTitle] = metadata.fileNameView
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = ncplayer.durationTime.seconds
if let image = currentViewController.image {
nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in
return image
}
}
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
func clearCommandCenter() {
UIApplication.shared.endReceivingRemoteControlEvents()
MPNowPlayingInfoCenter.default().nowPlayingInfo = [:]
MPRemoteCommandCenter.shared().playCommand.isEnabled = false
MPRemoteCommandCenter.shared().pauseCommand.isEnabled = false
MPRemoteCommandCenter.shared().skipForwardCommand.isEnabled = false
MPRemoteCommandCenter.shared().skipBackwardCommand.isEnabled = false
MPRemoteCommandCenter.shared().nextTrackCommand.isEnabled = false
MPRemoteCommandCenter.shared().previousTrackCommand.isEnabled = false
if let playCommand = playCommand {
MPRemoteCommandCenter.shared().playCommand.removeTarget(playCommand)
self.playCommand = nil
}
if let pauseCommand = pauseCommand {
MPRemoteCommandCenter.shared().pauseCommand.removeTarget(pauseCommand)
self.pauseCommand = nil
}
if let skipForwardCommand = skipForwardCommand {
MPRemoteCommandCenter.shared().skipForwardCommand.removeTarget(skipForwardCommand)
self.skipForwardCommand = nil
}
if let skipBackwardCommand = skipBackwardCommand {
MPRemoteCommandCenter.shared().skipBackwardCommand.removeTarget(skipBackwardCommand)
self.skipBackwardCommand = nil
}
if let nextTrackCommand = nextTrackCommand {
MPRemoteCommandCenter.shared().nextTrackCommand.removeTarget(nextTrackCommand)
self.nextTrackCommand = nil
}
if let previousTrackCommand = previousTrackCommand {
MPRemoteCommandCenter.shared().previousTrackCommand.removeTarget(previousTrackCommand)
self.previousTrackCommand = nil
}
}
}
// MARK: - UIPageViewController Delegate Datasource
extension NCViewerMediaPage: UIPageViewControllerDelegate, UIPageViewControllerDataSource {
func shiftCurrentPage() {
if metadatas.count == 0 {
self.viewUnload()
return
}
var direction: UIPageViewController.NavigationDirection = .forward
if currentIndex == metadatas.count {
currentIndex -= 1
direction = .reverse
}
let viewerMedia = getViewerMedia(index: currentIndex, metadata: metadatas[currentIndex])
pageViewController.setViewControllers([viewerMedia], direction: direction, animated: true, completion: nil)
}
func reloadCurrentPage() {
let viewerMedia = getViewerMedia(index: currentIndex, metadata: metadatas[currentIndex])
viewerMedia.autoPlay = false
pageViewController.setViewControllers([viewerMedia], direction: .forward, animated: false, completion: nil)
}
func goTo(index: Int, direction: UIPageViewController.NavigationDirection, autoPlay: Bool) {
currentIndex = index
let viewerMedia = getViewerMedia(index: currentIndex, metadata: metadatas[currentIndex])
viewerMedia.autoPlay = autoPlay
pageViewController.setViewControllers([viewerMedia], direction: direction, animated: true, completion: nil)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if currentIndex == 0 { return nil }
let viewerMedia = getViewerMedia(index: currentIndex - 1, metadata: metadatas[currentIndex - 1])
return viewerMedia
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if currentIndex == metadatas.count - 1 { return nil }
let viewerMedia = getViewerMedia(index: currentIndex + 1, metadata: metadatas[currentIndex + 1])
return viewerMedia
}
// START TRANSITION
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
// Save time video
if let ncplayer = currentViewController.ncplayer, ncplayer.isPlay() {
ncplayer.saveCurrentTime()
}
guard let nextViewController = pendingViewControllers.first as? NCViewerMedia else { return }
nextIndex = nextViewController.index
}
// END TRANSITION
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed && nextIndex != nil {
previousViewControllers.forEach { viewController in
let viewerMedia = viewController as! NCViewerMedia
viewerMedia.ncplayer?.deactivateObserver()
}
currentIndex = nextIndex!
}
self.nextIndex = nil
}
}
// MARK: - UIGestureRecognizerDelegate
extension NCViewerMediaPage: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if let gestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer {
let velocity = gestureRecognizer.velocity(in: self.view)
var velocityCheck: Bool = false
if UIDevice.current.orientation.isLandscape {
velocityCheck = velocity.x < 0
} else {
velocityCheck = velocity.y < 0
}
if velocityCheck {
return false
}
}
return true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if otherGestureRecognizer == currentViewController.scrollView.panGestureRecognizer {
if self.currentViewController.scrollView.contentOffset.y == 0 {
return true
}
}
return false
}
@objc func didPanWith(gestureRecognizer: UIPanGestureRecognizer) {
currentViewController.didPanWith(gestureRecognizer: gestureRecognizer)
}
@objc func didSingleTapWith(gestureRecognizer: UITapGestureRecognizer) {
if let playerToolBar = currentViewController.playerToolBar, playerToolBar.isPictureInPictureActive() {
playerToolBar.pictureInPictureController?.stopPictureInPicture()
}
if currentScreenMode == .full {
changeScreenMode(mode: .normal, enableTimerAutoHide: true)
} else {
changeScreenMode(mode: .full)
}
}
//
// LIVE PHOTO
//
@objc func didLongpressGestureEvent(gestureRecognizer: UITapGestureRecognizer) {
if !currentViewController.metadata.livePhoto { return }
if gestureRecognizer.state == .began {
currentViewController.updateViewConstraints()
currentViewController.statusViewImage.isHidden = true
currentViewController.statusLabel.isHidden = true
let fileName = (currentViewController.metadata.fileNameView as NSString).deletingPathExtension + ".mov"
if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", currentViewController.metadata.account, currentViewController.metadata.serverUrl, fileName)), CCUtility.fileProviderStorageExists(metadata) {
AudioServicesPlaySystemSound(1519) // peek feedback
let urlVideo = NCKTVHTTPCache.shared.getVideoURL(metadata: metadata)
if let url = urlVideo.url {
self.ncplayerLivePhoto = NCPlayer.init(url: url, autoPlay: true, isProxy: urlVideo.isProxy, imageVideoContainer: self.currentViewController.imageVideoContainer, playerToolBar: nil, metadata: metadata, detailView: nil, viewController: self)
self.ncplayerLivePhoto?.openAVPlayer()
}
}
} else if gestureRecognizer.state == .ended {
currentViewController.statusViewImage.isHidden = false
currentViewController.statusLabel.isHidden = false
currentViewController.imageVideoContainer.image = currentViewController.image
ncplayerLivePhoto?.videoLayer?.removeFromSuperlayer()
ncplayerLivePhoto?.deactivateObserver()
}
}
}
|
gpl-3.0
|
42de77bd49d52a440b3571544da24687
| 40.476038 | 303 | 0.693191 | 5.452331 | false | false | false | false |
cplaverty/KeitaiWaniKani
|
AlliCrab/ViewControllers/WaniKaniLoginWebViewController.swift
|
1
|
6401
|
//
// WaniKaniLoginWebViewController.swift
// AlliCrab
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
import os
import WaniKaniKit
import WebKit
private enum MessageHandlerName: String {
case apiKey
}
private struct MessageKey {
static let success = "apiKey"
static let error = "apiKeyError"
}
private let getAPIKeyScript = """
"use strict";
$.get('/settings/personal_access_tokens').done(function(data, textStatus, jqXHR) {
var apiKey =
$(data).find('#personal-access-tokens-list .personal-access-token-description:contains("AlliCrab") ~ .personal-access-token-token > code:eq(0)').text().trim()
|| $(data).find('#personal-access-tokens-list .personal-access-token-description:contains("Default read-only") ~ .personal-access-token-token > code:eq(0)').text().trim()
|| $(data).find('#personal-access-tokens-list .personal-access-token-description ~ .personal-access-token-token > code:eq(0)').text().trim();
if (typeof apiKey === 'string' && trim(apiKey).length == 1) {
window.webkit.messageHandlers.\(MessageHandlerName.apiKey.rawValue).postMessage({ '\(MessageKey.success)': apiKey });
}
}).fail(function(jqXHR, textStatus) {
window.webkit.messageHandlers.\(MessageHandlerName.apiKey.rawValue).postMessage({ '\(MessageKey.error)': textStatus });
});
"""
class WaniKaniLoginWebViewController: WebViewController {
override func registerMessageHandlers(_ userContentController: WKUserContentController) {
userContentController.add(self, name: MessageHandlerName.apiKey.rawValue)
super.registerMessageHandlers(userContentController)
}
override func unregisterMessageHandlers(_ userContentController: WKUserContentController) {
userContentController.removeScriptMessageHandler(forName: MessageHandlerName.apiKey.rawValue)
super.unregisterMessageHandlers(userContentController)
}
// MARK: - Implementation
func validate(apiKey: String) {
guard !apiKey.isEmpty else {
os_log("Got blank API key", type: .info)
self.showAlert(title: "No WaniKani API version 2 token found",
message: "A WaniKani API version 2 personal access token could not be found for your account. If you've never used a third-party app or user script, one may not have been generated and you should generate one now from the API Tokens settings on the WaniKani web site.")
return
}
os_log("Received API Key %@", type: .debug, apiKey)
ApplicationSettings.apiKey = apiKey
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let resourceRepository = appDelegate.makeResourceRepository(forAPIKey: apiKey)
appDelegate.resourceRepository = resourceRepository
appDelegate.presentDashboardViewController(animated: true)
dismiss(animated: true, completion: nil)
}
}
// MARK: - WKNavigationDelegate
extension WaniKaniLoginWebViewController {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else {
decisionHandler(.allow)
return
}
switch url {
case WaniKaniURL.dashboard:
os_log("Logged in: redirecting to settings", type: .debug)
decisionHandler(.cancel)
DispatchQueue.main.async {
webView.load(URLRequest(url: WaniKaniURL.tokenSettings))
}
default:
decisionHandler(.allow)
}
}
override func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard let url = webView.url, url == WaniKaniURL.tokenSettings else {
super.webView(webView, didFinish: navigation)
return
}
os_log("On settings page: fetching API Key", type: .debug)
webView.evaluateJavaScript("""
$('#personal-access-tokens-list .personal-access-token-description:contains("AlliCrab") ~ .personal-access-token-token > code:eq(0)').text().trim()
|| $('#personal-access-tokens-list .personal-access-token-description:contains("Default read-only") ~ .personal-access-token-token > code:eq(0)').text().trim()
|| $('#personal-access-tokens-list .personal-access-token-description ~ .personal-access-token-token > code:eq(0)').text().trim();
""") { apiKey, error in
if let apiKey = apiKey as? String {
DispatchQueue.main.async {
self.validate(apiKey: apiKey)
}
} else if let error = error {
os_log("Failed to execute API key fetch script: %@", type: .error, error as NSError)
webView.configuration.userContentController.addUserScript(WKUserScript(source: getAPIKeyScript, injectionTime: .atDocumentStart, forMainFrameOnly: true))
}
}
}
}
// MARK: - WKScriptMessageHandler
extension WaniKaniLoginWebViewController {
override func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard let messageName = MessageHandlerName(rawValue: message.name) else {
super.userContentController(userContentController, didReceive: message)
return
}
switch messageName {
case .apiKey:
os_log("Received apiKey script message body %@", type: .debug, String(describing: message.body))
let payload = message.body as! [String: Any]
if let apiKey = payload[MessageKey.success] as? String {
DispatchQueue.main.async {
self.validate(apiKey: apiKey)
}
} else if let error = payload[MessageKey.error] {
os_log("Received script message error: %@", type: .debug, String(describing: error))
DispatchQueue.main.async {
self.showAlert(title: "Unable to find WaniKani API tokens", message: "Please close this page and enter the API version 2 personal access token manually")
}
}
}
}
}
|
mit
|
f93b18975d532adcb7226e03a3126db0
| 45.715328 | 297 | 0.646563 | 4.889228 | false | false | false | false |
1aurabrown/eidolon
|
Kiosk/App/Views/Spinner.swift
|
1
|
1243
|
import UIKit
class Spinner: UIView {
var spinner:UIView!
let rotationDuration = 0.9;
func createSpinner() -> UIView {
let view = UIView(frame: CGRectMake(0, 0, 20, 5))
view.backgroundColor = UIColor.blackColor()
return view
}
override func awakeFromNib() {
spinner = createSpinner()
addSubview(spinner)
backgroundColor = UIColor.clearColor()
animate(Float.infinity)
}
override func layoutSubviews() {
// .center uses frame
spinner.center = CGPointMake( CGRectGetWidth(bounds) / 2, CGRectGetHeight(bounds) / 2)
}
func animate(times: Float) {
let transformOffset = -1.01 * M_PI
let transform = CATransform3DMakeRotation( CGFloat(transformOffset), 0, 0, 1);
let rotationAnimation = CABasicAnimation(keyPath:"transform");
rotationAnimation.toValue = NSValue(CATransform3D:transform)
rotationAnimation.duration = rotationDuration;
rotationAnimation.cumulative = true;
rotationAnimation.repeatCount = Float(times);
layer.addAnimation(rotationAnimation, forKey:"transform");
}
func stopAnimating() {
layer.removeAllAnimations()
animate(1)
}
}
|
mit
|
1aaf301d60fe5da5c306a2c1b4420397
| 29.317073 | 94 | 0.650845 | 4.913043 | false | false | false | false |
mapsme/omim
|
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/Gallery/Photos/PhotosOverlayView.swift
|
5
|
2777
|
final class PhotosOverlayView: UIView {
private var navigationBar: UINavigationBar!
private var navigationItem: UINavigationItem!
weak var photosViewController: PhotosViewController?
var photo: HotelPhotoUrl? {
didSet {
guard let photo = photo else {
navigationItem.title = nil
return
}
guard let photosViewController = photosViewController else { return }
if let index = photosViewController.photos.firstIndex(where: { $0 === photo }) {
navigationItem.title = "\(index + 1) / \(photosViewController.photos.count)"
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupNavigationBar()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc
private func closeButtonTapped(_: UIBarButtonItem) {
photosViewController?.dismiss(animated: true, completion: nil)
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let hitView = super.hitTest(point, with: event), hitView != self {
return hitView
}
return nil
}
private func setupNavigationBar() {
navigationBar = UINavigationBar()
navigationBar.translatesAutoresizingMaskIntoConstraints = false
navigationBar.backgroundColor = UIColor.clear
navigationBar.barTintColor = nil
navigationBar.isTranslucent = true
navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationItem = UINavigationItem(title: "")
navigationBar.items = [navigationItem]
addSubview(navigationBar)
navigationBar.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor).isActive = true
navigationBar.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
navigationBar.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "ic_nav_bar_back"), style: .plain, target: self, action: #selector(closeButtonTapped(_:)))
}
func setHidden(_ hidden: Bool, animated: Bool, animation: @escaping (() -> Void)) {
guard isHidden != hidden else { return }
guard animated else {
isHidden = hidden
animation()
return
}
isHidden = false
alpha = hidden ? 1.0 : 0.0
UIView.animate(withDuration: kDefaultAnimationDuration,
delay: 0.0,
options: [.allowAnimatedContent, .allowUserInteraction],
animations: { [weak self] in
self?.alpha = hidden ? 0.0 : 1.0
animation()
},
completion: { [weak self] _ in
self?.alpha = 1.0
self?.isHidden = hidden
})
}
}
|
apache-2.0
|
a5b581bd7076f0c1566f4cb3920acfc8
| 32.865854 | 180 | 0.657544 | 5.142593 | false | false | false | false |
mrackwitz/Stencil
|
Stencil/Parser.swift
|
1
|
2915
|
import Foundation
public func until(tags:[String])(parser:TokenParser, token:Token) -> Bool {
if let name = token.components().first {
for tag in tags {
if name == tag {
return true
}
}
}
return false
}
/// A class for parsing an array of tokens and converts them into a collection of Node's
public class TokenParser {
public typealias TagParser = (TokenParser, Token) -> Result
public typealias NodeList = [Node]
public enum Result {
case Success(node: Node)
case Error(error: Stencil.Error)
}
public enum Results {
case Success(nodes: NodeList)
case Error(error: Stencil.Error)
}
private var tokens:[Token]
private var tags = Dictionary<String, TagParser>()
public init(tokens:[Token]) {
self.tokens = tokens
registerTag("for", parser: ForNode.parse)
registerTag("if", parser: IfNode.parse)
registerTag("ifnot", parser: IfNode.parse_ifnot)
registerTag("now", parser: NowNode.parse)
registerTag("include", parser: IncludeNode.parse)
registerTag("extends", parser: ExtendsNode.parse)
registerTag("block", parser: BlockNode.parse)
}
/// Registers a new template tag
public func registerTag(name:String, parser:TagParser) {
tags[name] = parser
}
/// Registers a simple template tag with a name and a handler
public func registerSimpleTag(name:String, handler:((Context) -> (Stencil.Result))) {
registerTag(name, parser: { (parser, token) -> TokenParser.Result in
return .Success(node:SimpleNode(handler: handler))
})
}
/// Parse the given tokens into nodes
public func parse() -> Results {
return parse(nil)
}
public func parse(parse_until:((parser:TokenParser, token:Token) -> (Bool))?) -> TokenParser.Results {
var nodes = NodeList()
while tokens.count > 0 {
let token = nextToken()!
switch token {
case .Text(let text):
nodes.append(TextNode(text: text))
case .Variable(let variable):
nodes.append(VariableNode(variable: variable))
case .Block(let value):
let tag = token.components().first
if let parse_until = parse_until {
if parse_until(parser: self, token: token) {
prependToken(token)
return .Success(nodes:nodes)
}
}
if let tag = tag {
if let parser = self.tags[tag] {
switch parser(self, token) {
case .Success(let node):
nodes.append(node)
case .Error(let error):
return .Error(error:error)
}
}
}
case .Comment(let value):
continue
}
}
return .Success(nodes:nodes)
}
public func nextToken() -> Token? {
if tokens.count > 0 {
return tokens.removeAtIndex(0)
}
return nil
}
public func prependToken(token:Token) {
tokens.insert(token, atIndex: 0)
}
}
|
bsd-2-clause
|
a2dcfbe7e5fa1a36adf65c9726fd1898
| 25.261261 | 104 | 0.622298 | 4.071229 | false | false | false | false |
psharanda/vmc2
|
7. SilverMVC/SilverMVC/Wireframe.swift
|
1
|
1204
|
//
// Created by Pavel Sharanda on 17.11.16.
// Copyright © 2016 psharanda. All rights reserved.
//
import Foundation
typealias AppContext = TextLoaderContainer & MainViewContainer & NavigationControllerContainer & WindowContainer & DetailsViewContainer
class Wireframe {
let window: Window
let navigationView: NavigationView
let context: AppContext
init(context: AppContext) {
self.context = context
window = context.makeWindow()
navigationView = context.makeNavigationView()
navigationView.views = [setupMainView()]
window.rootView = navigationView
window.install()
}
func setupMainView() -> MainViewProtocol {
let view = context.makeMainView()
let presenter = MainPresenter(textLoader: context.makeTextLoader(), view: view)
view.presenter = presenter
presenter.showDetails.subscribe {[unowned self, unowned presenter] in
let vc = self.context.makeDetailsView(text: presenter.view.state.text ?? "WTF?")
self.navigationView.pushView(view: vc, animated: true)
}
return view
}
}
|
mit
|
83d00eb8b2758a400f822c267e618f44
| 29.075 | 135 | 0.644223 | 5.141026 | false | false | false | false |
koutalou/Shoyu
|
Classes/Source.swift
|
1
|
6851
|
//
// Source.swift
// Shoyu
//
// Created by asai.yuki on 2015/12/12.
// Copyright © 2015年 yukiasai. All rights reserved.
//
import UIKit
public class Source: NSObject {
internal var sections = [SectionType]()
public override init() {
super.init()
}
public convenience init(@noescape clousure: (Source -> Void)) {
self.init()
clousure(self)
}
public func addSection(section: SectionType) -> Self {
sections.append(section)
return self
}
public func addSections(sections: [SectionType]) -> Self {
self.sections.appendContentsOf(sections)
return self
}
public func createSection<H, F>(@noescape clousure: (Section<H, F> -> Void)) -> Self {
return addSection(Section<H, F>() { clousure($0) })
}
public func createSections<H, F, E>(elements: [E], @noescape clousure: ((E, Section<H, F>) -> Void)) -> Self {
return addSections(
elements.map { element -> Section<H, F> in
return Section<H, F>() { clousure(element, $0) }
}.map { $0 as SectionType }
)
}
public func createSections<H, F>(count: UInt, @noescape clousure: ((UInt, Section<H, F>) -> Void)) -> Self {
return createSections([UInt](0..<count), clousure: clousure)
}
}
public extension Source {
public func sectionFor(section: Int) -> SectionType {
return sections[section]
}
public func sectionFor(indexPath: NSIndexPath) -> SectionType {
return sectionFor(indexPath.section)
}
}
// MARK: - Table view data source
extension Source: UITableViewDataSource {
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sectionFor(section).rowCount
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let row = sectionFor(indexPath).rowFor(indexPath)
let cell = tableView.dequeueReusableCellWithIdentifier(row.reuseIdentifier, forIndexPath: indexPath)
if let delegate = row as? RowDelegateType {
delegate.configureCell(cell, indexPath: indexPath)
}
return cell
}
public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let header = sectionFor(section).header else {
return nil
}
return sectionHeaderFooterViewFor(header, tableView: tableView, section: section)
}
public func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard let footer = sectionFor(section).footer else {
return nil
}
return sectionHeaderFooterViewFor(footer, tableView: tableView, section: section)
}
private func sectionHeaderFooterViewFor(headerFooter: SectionHeaderFooterType, tableView: UITableView, section: Int) -> UIView? {
// Create view
if let delegate = headerFooter as? SectionHeaderFooterDelegateType,
let view = delegate.viewFor(section) {
delegate.configureView(view, section: section)
return view
}
// Dequeue
if let identifier = headerFooter.reuseIdentifier,
let view = dequeueReusableView(tableView, identifier: identifier) {
if let delegate = headerFooter as? SectionHeaderFooterDelegateType {
delegate.configureView(view, section: section)
}
return view
}
return nil
}
private func dequeueReusableView(tableView: UITableView, identifier: String) -> UIView? {
if let view = tableView.dequeueReusableHeaderFooterViewWithIdentifier(identifier) {
return view
}
if let cell = tableView.dequeueReusableCellWithIdentifier(identifier) {
return cell.contentView
}
return nil
}
}
// MARK: - Table view delegate
extension Source: UITableViewDelegate {
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let row = sectionFor(indexPath).rowFor(indexPath)
if let delegate = row as? RowDelegateType,
let height = delegate.heightFor(indexPath) {
return height
}
return tableView.rowHeight
}
public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionFor(section).header?.title
}
public func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return sectionFor(section).footer?.title
}
public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard let header = sectionFor(section).header else {
return 0
}
return sectionHeaderFooterHeightFor(header, section: section) ?? tableView.sectionHeaderHeight
}
public func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
guard let footer = sectionFor(section).footer else {
return 0
}
return sectionHeaderFooterHeightFor(footer, section: section) ?? tableView.sectionFooterHeight
}
private func sectionHeaderFooterHeightFor(headerFooter: SectionHeaderFooterType, section: Int) -> CGFloat? {
if let delegate = headerFooter as? SectionHeaderFooterDelegateType,
let height = delegate.heightFor(section) {
return height
}
return nil
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let row = sectionFor(indexPath).rowFor(indexPath) as? RowDelegateType
row?.didSelect(indexPath)
}
public func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let row = sectionFor(indexPath).rowFor(indexPath) as? RowDelegateType
row?.didDeselect(indexPath)
}
public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let row = sectionFor(indexPath).rowFor(indexPath) as? RowDelegateType
row?.willDisplayCell(cell, indexPath: indexPath)
}
public func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let row = sectionFor(indexPath).rowFor(indexPath) as? RowDelegateType
row?.didEndDisplayCell(cell, indexPath: indexPath)
}
}
|
mit
|
bf13cf7b5f90938bdd75973b0f494664
| 35.620321 | 137 | 0.655666 | 5.160512 | false | false | false | false |
Beaver/BeaverCodeGen
|
Sources/BeaverCodeGen/Generator/Reducer.swift
|
1
|
5958
|
struct ModuleReducer: SwiftGenerating {
let objectType: ObjectType = .reducer
let moduleName: String
}
extension ModuleReducer {
var name: String {
return moduleName
}
var description: String {
return """
import Beaver
import Core
public struct \(moduleName.typeName)Reducer: Beaver.ChildReducing {
public typealias ActionType = \(moduleName.typeName)Action
public typealias StateType = \(moduleName.typeName)State
public init() {
}
public func handle(action: \(moduleName.typeName)Action,
state: \(moduleName.typeName)State,
completion: @escaping (\(moduleName.typeName)State) -> ()) -> \(moduleName.typeName)State {
var newState = state
switch ExhaustiveAction<\(moduleName.typeName)RoutingAction, \(moduleName.typeName)UIAction>(action) {
case .routing(.start):
newState.currentScreen = .main
case .routing(.stop):
newState.currentScreen = .none
case .ui:
break
}
return newState
}
}
"""
}
}
struct AppReducer: SwiftGenerating {
let objectType: ObjectType = .reducer
var moduleNames: [String]
}
extension AppReducer {
var name: String {
return "App"
}
var description: String {
return """
import Beaver
import Core
\(moduleNames.map {
"import \($0.typeName)"
}.joined(separator: .br))
struct AppReducer: Beaver.Reducing {
\(moduleNames.count > 0 ? moduleNames.map {
"let \($0.varName): \($0.typeName)Reducer"
}.joined(separator: .br).indented.br : "")
typealias StateType = AppState
func handle(envelop: ActionEnvelop,
state: AppState,
completion: @escaping (AppState) -> ()) -> AppState {
var newState = state
// Reduce start action
if case AppAction.start(let startAction) = envelop.action {
return handle(envelop: envelop.update(action: startAction), state: newState, completion: completion)
}
\(moduleNames.count > 0 ? .br + moduleActionCase(moduleNames).indented(count: 2).br : "")
return newState
}
}
"""
}
private func moduleActionCase(_ moduleNames: [String]) -> String {
return moduleNames.map {
"""
// Reduce \($0.typeName)'s actions
if envelop.action is \($0.typeName)Action {
newState.\($0.varName)State = \($0.varName).handle(envelop: envelop, state: state.\($0.varName)State ?? \($0.typeName)State()) { \($0.varName)State in
newState.\($0.varName)State = \($0.varName)State
completion(newState)
}
}
if case AppAction.stop(module: \($0.typeName)RoutingAction.stop) = envelop.action {
newState.\($0.varName)State = nil
}
"""
}.joined(separator: .br(2))
}
func byInserting(module moduleName: String, in fileHandler: FileHandling) -> AppReducer {
let swiftFile = SwiftFile.read(from: fileHandler, atPath: path)
guard let reducerStruct = swiftFile.find(recursive: true, isMatching: {
$0.typeName == .appReducer && $0.kind == .`struct` && $0.doesInherit(from: [.beaverReducing])
}).first as? SwiftSubstructure else {
fatalError("Couldn't find AppReducer in \(fileHandler)")
}
let reducerVars = reducerStruct.find { ($0.typeName?.isModuleReducer ?? false) && $0.kind == .`var` }
// Insert module import
let selectorString = "import \(reducerVars.last?.typeName?.name.replacingOccurrences(of: "Reducer", with: "") ?? "Core")".br
var insertedCharacterCount = fileHandler.insert(content: "import \(moduleName.typeName)\(reducerVars.count > 0 ? .br : "")",
atOffset: 0,
withSelector: .matching(string: selectorString, insert: .after),
inFileAtPath: path)
let varOffset = reducerVars.last?.offset ?? reducerStruct.offset
// Insert module reducer var
insertedCharacterCount += fileHandler.insert(content: "let \(moduleName.varName): \(moduleName.typeName)Reducer".indented.br,
atOffset: varOffset + insertedCharacterCount,
withSelector: .matching(string: .br, insert: .after),
inFileAtPath: path)
guard let handleMethod = reducerStruct.find(recursive: true, isMatching: {
$0.typeName == .beaverReducingHandleMethod
}).first as? SwiftSubstructure else {
fatalError("Couldn't find switch in \(SwiftTypeName.beaverReducingHandleMethod.name) in \(fileHandler)")
}
// Insert module action case
_ = fileHandler.insert(content: moduleActionCase([moduleName]).indented(count: 2).br(2),
atOffset: handleMethod.offset + insertedCharacterCount,
withSelector: .matching(string: "return newState".indented(count: 2), insert: .before),
inFileAtPath: path)
return AppReducer(moduleNames: moduleNames + [moduleName])
}
}
|
mit
|
179dbeb71e269fc4e633e88d0fcff62c
| 38.986577 | 166 | 0.527526 | 5.140638 | false | false | false | false |
boostcode/tori
|
Sources/tori/Core/Database.swift
|
1
|
1533
|
/**
* Copyright boostco.de 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import LoggerAPI
import MongoKitten
func setupDb() -> MongoKitten.Database {
// TODO: if not existing create db
// database setup
let (dbHost, dbPort, dbName, _, adminName, adminPassword) = getConfiguration()
let dbServer = try! Server(
at: dbHost,
port: dbPort,
automatically: true
)
let db = dbServer[dbName]
// default user admin
let userCollection = db["User"]
if try! userCollection.count(matching: "username" == adminName) == 0 {
let adminUser: Document = [
"username": .string(adminName),
"password": .string("\(adminPassword.md5())"),
"role": ~Role.Admin.hashValue
]
let _ = try! userCollection.insert(adminUser)
Log.debug("Setup / Added default admin user: \(adminName)")
}
return db
}
|
apache-2.0
|
3069f9776204bc5a6b1498e559711064
| 29.058824 | 84 | 0.624266 | 4.405172 | false | false | false | false |
thehung111/visearch-widget-swift
|
ViSearchWidgets/ViSearchWidgets/Camera/Views/ImageCell.swift
|
2
|
1290
|
//
// ImageCell.swift
import UIKit
import Photos
/// photo cell when loading images from photo library
class ImageCell: UICollectionViewCell {
let imageView : UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.layer.masksToBounds = true
imageView.image = ViIcon.placeholder
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
contentView.addSubview(imageView)
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = bounds
}
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = ViIcon.placeholder
}
func configureWithModel(_ model: PHAsset) {
if tag != 0 {
PHImageManager.default().cancelImageRequest(PHImageRequestID(tag))
}
tag = Int(PHImageManager.default().requestImage(for: model, targetSize: contentView.bounds.size, contentMode: .aspectFill, options: nil) { image, info in
self.imageView.image = image
})
}
}
|
mit
|
668e109e30ed847641d62443baf126cc
| 26.446809 | 161 | 0.628682 | 5.139442 | false | false | false | false |
JiongXing/PhotoBrowser
|
Example/Example/KingfisherImageViewController.swift
|
1
|
2197
|
//
// KingfisherImageViewController.swift
// Example
//
// Created by JiongXing on 2019/11/28.
// Copyright © 2019 JiongXing. All rights reserved.
//
import UIKit
import JXPhotoBrowser
import Kingfisher
class KingfisherImageViewController: BaseCollectionViewController {
override class func name() -> String { "网络图片-Kingfisher" }
override class func remark() -> String { "举例如何用Kingfisher加载网络图片" }
override func makeDataSource() -> [ResourceModel] {
makeNetworkDataSource()
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.jx.dequeueReusableCell(BaseCollectionViewCell.self, for: indexPath)
if let firstLevel = self.dataSource[indexPath.item].firstLevelUrl {
let url = URL(string: firstLevel)
cell.imageView.kf.setImage(with: url)
}
return cell
}
override func openPhotoBrowser(with collectionView: UICollectionView, indexPath: IndexPath) {
let browser = JXPhotoBrowser()
browser.numberOfItems = {
self.dataSource.count
}
browser.reloadCellAtIndex = { context in
let url = self.dataSource[context.index].secondLevelUrl.flatMap { URL(string: $0) }
let browserCell = context.cell as? JXPhotoBrowserImageCell
let collectionPath = IndexPath(item: context.index, section: indexPath.section)
let collectionCell = collectionView.cellForItem(at: collectionPath) as? BaseCollectionViewCell
let placeholder = collectionCell?.imageView.image
// 用 Kingfisher 加载
browserCell?.imageView.kf.setImage(with: url, placeholder: placeholder)
}
browser.transitionAnimator = JXPhotoBrowserZoomAnimator(previousView: { index -> UIView? in
let path = IndexPath(item: index, section: indexPath.section)
let cell = collectionView.cellForItem(at: path) as? BaseCollectionViewCell
return cell?.imageView
})
browser.pageIndex = indexPath.item
browser.show()
}
}
|
mit
|
fb6bbd92687a6ffbf5d6501f0790ba0b
| 39.754717 | 130 | 0.680556 | 5.058548 | false | false | false | false |
multinerd/Mia
|
Example/Mia/CollapsibleTableViewDemo/DefaultTableViewDemo.swift
|
1
|
1514
|
import UIKit
import Mia
class DefaultTableViewDemo: CollapsibleTableSectionViewController {
var sections: [Section] = sectionsData
var runOnce = true
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}
}
extension DefaultTableViewDemo: CollapsibleTableSectionDelegate {
func numberOfSections(_ tableView: UITableView) -> Int {
if runOnce {
let blurredBackgroundView = BlurredBackgroundView(style: .extraLight, image: UIImage(named: "tableViewBG"))
tableView.backgroundView = blurredBackgroundView
tableView.separatorEffect = blurredBackgroundView.separatorEffect
runOnce = false
}
return sections.count
}
func collapsibleTableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].items.count
}
func collapsibleTableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item: Item = sections[indexPath.section].items[indexPath.row] as! Item
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "BasicCell")
cell.backgroundColor = .clear
cell.textLabel?.text = item.name
cell.detailTextLabel?.text = item.detail
return cell
}
func collapsibleTableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].name
}
}
|
mit
|
f3bf042cdf56d123332463028f81dccb
| 25.103448 | 119 | 0.680978 | 5.368794 | false | false | false | false |
WSUCSClub/upac-ios
|
UPAC/StringExtension.swift
|
1
|
766
|
//
// StringExtension.swift
// UPAC
//
// Created by Marquez, Richard A on 11/15/14.
// Copyright (c) 2014 wsu. All rights reserved.
//
import Foundation
extension String {
func md5() -> String! {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!, strLen, result)
var hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.destroy()
return String(format: hash as String)
}
}
|
gpl-3.0
|
b6220e3bb3bac2f3a29ea7d0e4be9b2b
| 25.448276 | 88 | 0.613577 | 4.303371 | false | false | false | false |
ferusinfo/OctoAPI
|
Example/GetResponseBlog/GetResponseBlogAdapter.swift
|
1
|
2379
|
//
// GetResponseBlogAdapter.swift
// OctoAPI
//
// Copyright (c) 2016 Maciej Kołek
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import Alamofire
class GetResponseBlogAdapter : Adapter {
var mode: AdapterMode = .production
var authorizer: Authorizable? = nil
var errorDomain: String = "com.getresponse.GetResponseBlog.error"
var productionVersion: String = "v2"
var logLevel: LogLevel = .debug
var logger: OctoLogger? {
get {
return storedLogger
}
}
var productionURL: String {
get {
var domainExt = "com"
if let prefferedLoc = Bundle.main.preferredLocalizations.first , prefferedLoc == "pl" {
domainExt = prefferedLoc
}
return "https://blog.getresponse.\(domainExt)/wp-json/wp/"
}
}
lazy var storedLogger : OctoLogger = {
let logger = OctoLogger(logLevel: self.logLevel)
return logger
}()
var sandboxURL: String {
get {
return productionURL
}
}
var sandboxVersion: String {
get {
return productionVersion
}
}
var perRequestHeaders: HTTPHeaders? {
get {
return ["Test-Header":"Test-Value"]
}
}
}
|
mit
|
230d51f60413e204e988b4a35fba58e2
| 30.706667 | 99 | 0.65307 | 4.436567 | false | false | false | false |
kyouko-taiga/anzen
|
Sources/Parser/Parser.swift
|
1
|
8484
|
import AST
import Utils
/// A recursive descent parser for the Anzen language.
///
/// This structure provides an interface to turn a stream of tokens into an AST.
///
/// In order to create the most complete error reports possible, the parser does not stop when it
/// encounters a syntax error. Instead, it saves the error before moving into a "degraded" mode in
/// which it skips tokens until it can find the beginning the next construct. It follows that the
/// result of an input's parsing is a (possibly incomplete) AST and a set of errors.
public class Parser {
/// The result of construction's parsing.
public struct Result<T> {
public let value: T
public let errors: [ParseError]
}
/// Initializes a parser with a token stream.
///
/// - Note:
/// The token stream must have at least one token and ends with `.eof`.
public init<S>(_ tokens: S) where S: Sequence, S.Element == Token {
let stream = Array(tokens)
assert((stream.count > 0) && (stream.last!.kind == .eof), "invalid token stream")
self.stream = stream
self.module = ModuleDecl(statements: [], range: self.stream.first!.range)
}
/// Initializes a parser from a text input.
public convenience init(source: TextInputBuffer) throws {
self.init(try Lexer(source: source))
}
/// Parses the token stream into a module declaration.
public func parse() -> Result<ModuleDecl> {
var errors: [ParseError] = []
while true {
// Skip statement delimiters.
consumeMany { $0.isStatementDelimiter }
// Check for end of file.
guard peek().kind != .eof else { break }
// Parse a statement.
let parseResult = parseStatement()
errors.append(contentsOf: parseResult.errors)
if let statement = parseResult.value {
module.statements.append(statement)
}
}
module.range = module.statements.isEmpty
? self.stream.last!.range
: SourceRange(
from: module.statements.first!.range.start,
to: module.statements.last!.range.end)
return Result(value: module, errors: errors)
}
/// Attempts to run the given parsing function but backtracks if it failed.
@available(*, deprecated)
func attempt<R>(_ parse: () throws -> R) -> R? {
let backtrackingPosition = streamPosition
guard let result = try? parse() else {
rewind(to: backtrackingPosition)
return nil
}
return result
}
/// Attempts to run the given parsing function but backtracks if it failed.
func attempt<T>(_ parse: () -> Result<T?>) -> Result<T>? {
let backtrackingPosition = streamPosition
let parseResult = parse()
guard let node = parseResult.value else {
rewind(to: backtrackingPosition)
return nil
}
return Result(value: node, errors: parseResult.errors)
}
/// Parses a list of elements, separated by a `,`.
///
/// This helper will parse a list of elements, separated by a `,` and optionally ending with one,
/// until it finds `delimiter`. New lines before and after each element will be consumed, but the
/// delimiter won't.
func parseList<Element>(
delimitedBy delimiter: TokenKind,
parsingElementWith parse: () throws -> Result<Element?>)
rethrows -> Result<[Element]>
{
// Skip leading new lines.
consumeNewlines()
var elements: [Element] = []
var errors: [ParseError] = []
// Parse as many elements as possible.
while peek().kind != delimiter {
// Parse an element.
let elementParseResult = try parse()
errors.append(contentsOf: elementParseResult.errors)
if let element = elementParseResult.value {
elements.append(element)
}
// If the next consumable token isn't a separator, stop parsing here.
consumeNewlines()
if consume(.comma) == nil {
break
}
// Skip trailing new lines after the separator.
consumeNewlines()
}
return Result(value: elements, errors: errors)
}
/// Tiny helper to build parse errors.
func parseFailure(_ syntaxError: SyntaxError, range: SourceRange? = nil) -> ParseError {
return ParseError(syntaxError, range: range ?? peek().range)
}
/// Tiny helper to build unexpected construction errors.
func unexpectedConstruction(expected: String? = nil, got node: Node) -> ParseError {
return ParseError(.unexpectedConstruction(expected: expected, got: node), range: node.range)
}
/// Tiny helper to build unexpected token errors.
func unexpectedToken(expected: String? = nil, got token: Token? = nil) -> ParseError {
let t = token ?? peek()
return ParseError(.unexpectedToken(expected: expected, got: t), range: t.range)
}
/// The stream of tokens.
var stream: [Token]
/// The current position in the token stream.
var streamPosition: Int = 0
/// The module being parser.
var module: ModuleDecl
}
extension Parser {
/// Returns the token 1 position ahead, without consuming the stream.
func peek() -> Token {
guard streamPosition < stream.count
else { return stream.last! }
return stream[streamPosition]
}
/// Attempts to consume a single token.
@discardableResult
func consume() -> Token? {
guard streamPosition < stream.count
else { return nil }
defer { streamPosition += 1 }
return stream[streamPosition]
}
/// Attempts to consume a single token of the given kind from the stream.
@discardableResult
func consume(_ kind: TokenKind) -> Token? {
guard (streamPosition < stream.count) && (stream[streamPosition].kind == kind)
else { return nil }
defer { streamPosition += 1 }
return stream[streamPosition]
}
/// Attempts to consume a single token of the given kinds from the stream.
@discardableResult
func consume(_ kinds: Set<TokenKind>) -> Token? {
guard (streamPosition < stream.count) && (kinds.contains(stream[streamPosition].kind))
else { return nil }
defer { streamPosition += 1 }
return stream[streamPosition]
}
/// Attempts to consume a single token of the given kind, after a sequence of specific tokens.
@discardableResult
func consume(_ kind: TokenKind, afterMany skipKind: TokenKind) -> Token? {
let backtrackPosition = streamPosition
consumeMany { $0.kind == skipKind }
if let result = consume(kind) {
return result
}
rewind(to: backtrackPosition)
return nil
}
/// Attemps to consume a single token, if it satisfies the given predicate.
@discardableResult
func consume(if predicate: (Token) throws -> Bool) rethrows -> Token? {
guard try (streamPosition < stream.count) && predicate(stream[streamPosition])
else { return nil }
defer { streamPosition += 1 }
return stream[streamPosition]
}
/// Attemps to consume a single token, if it satisfies the given predicate, after a sequence of
/// specific tokens.
@discardableResult
func consume(afterMany skipKind: TokenKind, if predicate: (Token) throws -> Bool)
rethrows -> Token?
{
let backtrackPosition = streamPosition
consumeMany { $0.kind == skipKind }
if let result = try consume(if: predicate) {
return result
}
rewind(to: backtrackPosition)
return nil
}
/// Consumes up to the given number of elements from the stream.
@discardableResult
func consumeMany(upTo n: Int = 1) -> ArraySlice<Token> {
let consumed = stream[streamPosition ..< streamPosition + n]
streamPosition += consumed.count
return consumed
}
/// Consumes tokens from the stream as long as they satisfy the given predicate.
@discardableResult
func consumeMany(while predicate: (Token) throws -> Bool) rethrows -> ArraySlice<Token> {
let consumed: ArraySlice = try stream[streamPosition...].prefix(while: predicate)
streamPosition += consumed.count
return consumed
}
/// Consume new lines.
func consumeNewlines() {
for token in stream[streamPosition...] {
guard token.kind == .newline else { break }
streamPosition += 1
}
}
/// Consume all tokens until the next statement delimiter.
func consumeUpToNextStatementDelimiter() {
consumeMany(while: { !$0.isStatementDelimiter && ($0.kind != .eof) })
}
/// Rewinds the token stream by the given number of positions.
func rewind(_ n: Int = 1) {
streamPosition = Swift.max(streamPosition - 1, 0)
}
/// Rewinds the stream to the specified position.
func rewind(to position: Int) {
streamPosition = position
}
}
|
apache-2.0
|
18c2bdeb4efc783e7835167e5f077b52
| 31.258555 | 99 | 0.67421 | 4.332993 | false | false | false | false |
likumb/LJWebImage
|
LJWebImage/LJWebImage/LIJWebImage/LIJOperation.swift
|
1
|
1507
|
//
// LIJOperation.swift
// LIJWebImage
//
// Created by 李俊 on 15/7/15.
// Copyright (c) 2015年 李俊. All rights reserved.
//
import UIKit
class LIJOperation: NSOperation {
var path: String?
var completion: ((UIImage) -> Void)?
class func operationWith(path: String , complition: (image:UIImage) -> ()) -> LIJOperation{
let op = LIJOperation()
op.path = path
op.completion = complition
return op
}
override func main() {
if self.cancelled {
return
}
var image: UIImage?
if path != nil{
// NSThread.sleepForTimeInterval(5)
let url = NSURL(string: path!)
let data = NSData(contentsOfURL: url!)
if (self.cancelled) {return}
if let imageData = data {
image = UIImage(data: imageData)
imageData.writeToFile(path!.cachesPath(), atomically: true)
} else {
print("网络不给力")
}
}
if (self.cancelled) {return}
if completion != nil && image != nil{
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.completion!(image!)
})
}
}
}
|
mit
|
e72880ec8809f41de057945d8bb323d8
| 20.214286 | 95 | 0.444444 | 5.05102 | false | false | false | false |
Shopify/mobile-buy-sdk-ios
|
Pay/PayShippingRate.swift
|
1
|
4614
|
//
// PayShippingRate.swift
// Pay
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Represents a shipping rate quote, usually provided for a specific address.
///
public struct PayShippingRate {
/// Represents a `from` and `to` date for the expected delivery time frame. If the `to` date is `nil`, then the expected delivery window is roughly around the `from` date.
///
public struct DeliveryRange {
/// Delivery is expected no earlier than `from` date.
public let from: Date
/// Delivery is expected no later than `to` date.
public let to: Date?
/// Create a delivery range.
///
/// - parameters:
/// - from: A date from which to expect delivery.
/// - to: A date until which to expect delivery.
///
public init(from: Date, to: Date? = nil) {
self.from = from
self.to = to
}
/// A string that describes how many days until expected delivery (eg: "1 - 2 days").
public func descriptionFrom(_ date: Date) -> String {
let firstDelta = date.daysUntil(self.from)
guard let toDate = self.to else {
let suffix = firstDelta == 1 ? "" : "s"
return "\(firstDelta) day\(suffix)"
}
let secondDelta = date.daysUntil(toDate)
return "\(firstDelta) - \(secondDelta) days"
}
}
/// A handle that uniquely identifies this shipping rate.
public let handle: String
/// A human-friendly name for this shipping rate.
public let title: String
/// Shipping rate price.
public let price: Decimal
/// A delivery range that represents a timeframe during which a delivery is expected.
public let deliveryRange: DeliveryRange?
// ----------------------------------
// MARK: - Init -
//
public init(handle: String, title: String, price: Decimal, deliveryRange: DeliveryRange? = nil) {
self.handle = handle
self.title = title
self.price = price
self.deliveryRange = deliveryRange
}
}
// ----------------------------------
// MARK: - Date -
//
private extension Date {
static let calendar = Calendar.current
func daysUntil(_ date: Date) -> Int {
let calendar = Date.calendar
let start = calendar.startOfDay(for: self)
let end = calendar.startOfDay(for: date)
let delta = calendar.dateComponents([.day], from: start, to: end)
return delta.day!
}
}
#if canImport(PassKit)
import PassKit
// ----------------------------------
// MARK: - PassKit -
//
internal extension PayShippingRate {
var summaryItem: PKShippingMethod {
let item = PKShippingMethod(label: self.title, amount: self.price)
if let deliveryRange = self.deliveryRange {
item.detail = deliveryRange.descriptionFrom(Date())
} else {
item.detail = "No delivery estimate provided."
}
item.identifier = self.handle
return item
}
}
internal extension Array where Element == PayShippingRate {
var summaryItems: [PKShippingMethod] {
return self.map {
$0.summaryItem
}
}
func shippingRateFor(_ shippingMethod: PKShippingMethod) -> Element? {
return self.filter {
$0.handle == shippingMethod.identifier!
}.first
}
}
#endif
|
mit
|
bd9cf4c0604da2acb08c2b2c1be4c936
| 30.387755 | 175 | 0.618986 | 4.47093 | false | false | false | false |
daniel-beard/SwiftAndObjCAlgorithms
|
Algorithms/SelectionSort.swift
|
1
|
567
|
//
// SelectionSort.swift
// Algorithms
//
// Created by Daniel Beard on 11/16/14.
// Copyright (c) 2014 Daniel Beard. All rights reserved.
//
import Foundation
public func SelectionSort<T: Comparable>(inputArray: [T]) -> [T] {
var array = inputArray
if array.count <= 1 {
return array;
}
for i in 0..<array.count {
var minIndex = i
for var j = i; j<array.count; j++ {
minIndex = (array[minIndex] < array[j]) ? minIndex : j
}
swap(&array[i], &array[minIndex])
}
return array
}
|
mit
|
f1dcbaa2e4e48d3534ce73fda96ba9c9
| 20.846154 | 66 | 0.566138 | 3.478528 | false | false | false | false |
PedroTrujilloV/TIY-Assignments
|
17--Anybody-Out-There?/GitHub Friends/GitHub Friends/GitHubFriendListViewController.swift
|
1
|
5660
|
//
// ViewController.swift
// GitHub Friends
//
// Created by Pedro Trujillo on 10/27/15.
// Copyright © 2015 Pedro Trujillo. All rights reserved.
//
import UIKit
protocol APIControllerProtocol
{
func didReceiveAPIResults(results:NSArray)
}
protocol SearchTableViewProtocol
{
func friendWasFound(friend:String)
}
class GitHubFriendListViewController: UITableViewController, APIControllerProtocol,SearchTableViewProtocol
{
var rigthAddButtonItem:UIBarButtonItem!
var gitHubFriends = Array<GitHubFriend>()
var friendRegister = Array<String>()
var api: APIController!
var friendForSearch = ""
override func viewDidLoad()
{
super.viewDidLoad()
title = "GitHub Friends 👥"
// Do any additional setup after loading the view, typically from a nib.
api = APIController(delegate: self)
//api.searchGitHubFor("jcgohlke")
//api.searchGitHubFor("Ben Gohlke")
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
rigthAddButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addButtonActionTapped:")
self.navigationItem.setRightBarButtonItems([rigthAddButtonItem], animated: true)
self.tableView.registerClass(GitHubFriendCell.self, forCellReuseIdentifier: "GitHubFriendCell")
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return gitHubFriends.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return 50.0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("GitHubFriendCell", forIndexPath: indexPath) as! GitHubFriendCell
let friend = gitHubFriends[indexPath.row]
print("friend: "+friend.name)
cell.textLabel!.text = friend.name
cell.loadImage(friend.thumbnailImageURL)
//cell.editing = true
//cell.detailTextLabel?.text = "Penpenuche"
return cell
}
//
// // Override to support conditional editing of the table view.
// override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// // Return false if you do not want the specified item to be editable.
// return true
// }
//
//
//
// // Override to support editing the table view.
// override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// if editingStyle == .Delete {
// // Delete the row from the data source
// tableView.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)
{
let datailsVC:DetailViewController = DetailViewController()
datailsVC.gitHubFriend = gitHubFriends[indexPath.row]
//presentViewController(datailsVC, animated: true, completion: nil)// it shows like a modal view
navigationController?.pushViewController(datailsVC, animated: true)
}
//MARK: - Handle Actions
func addButtonActionTapped(sender: UIButton)
{
print("Hay que rico!")
//MARK: this piece of code is fucking awesome !!!!
let searchTableVC = SearchTableViewController()
let navigationController = UINavigationController(rootViewController: searchTableVC)// THIS is fucking awesome!!!! this create a new navigation controller that allows the modal view animation !!!!!!!!!!!!!
searchTableVC.delegator = self // 3 nescessary to get the value from the popover
// navigationController?.pushViewController(searchTableVC, animated: true)
//presentViewController(searchTableVC, animated: true, completion: nil)// it shows like a modal view
presentViewController(navigationController, animated: true, completion: nil)
}
//MARK: - API Controller Protocl
func didReceiveAPIResults(results:NSArray)
{
print("didReceiveAPIResults got: \(results)")
dispatch_async(dispatch_get_main_queue(), {
//self.gitHubFriends = GitHubFriend.friendsWithJSON(results)
self.gitHubFriends.append( GitHubFriend.aFriendWithJSON(results))
self.tableView.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}
//MARK: - Search View Controller Protocl
func friendWasFound(friend:String)
{
if !friendRegister.contains(friend)
{
friendRegister.append(friend)
api.searchGitHubFor(friend, byCriteria: "user")
tableView.reloadData()
print("Friend was found!!!!!!!: "+friend)
dismissViewControllerAnimated(true, completion: nil) // this destroy the modal view like the popover
}
}
}
|
cc0-1.0
|
91e3e2aebee109b5021660c585adb259
| 35.25641 | 214 | 0.679986 | 5.179487 | false | false | false | false |
mr-v/NSErrorPointerWrapper
|
NSErrorPointerWrapperTests/NSErrorPointerWrapperTests.swift
|
1
|
5083
|
// NSErrorPointerWrapperTests.swift
//
// Copyright (c) 2014 Witold Skibniewski
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import NSErrorPointerWrapper
class NSErrorPointerWrapperTests: XCTestCase {
func test_tryWithErrorPointer_Success_CallsOnSuccess() {
let JSONData = properJSONData()
tryWithErrorPointer { NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: $0) }
.onError { _ in XCTFail() }
.onSuccess { _ in XCTAssert(true) }
}
func test_tryWithErrorPointer_FailureCreatesError_CallsOnErrorWithError() {
let malformedJSONData = "{\"a\":}".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
tryWithErrorPointer { NSJSONSerialization.JSONObjectWithData(malformedJSONData, options: nil, error: $0) }
.onSuccess { _ in XCTFail() }
.onError{ error in XCTAssertNotNil(error?) }
}
/**
some of the APIs return Bool to indicate whether the operation was successful
test example might be: NSManagedObjectContext().save($0) (returns false and doesn't set error)
*/
func test_tryWithErrorPointer_FailureReturnsFalseErrorNil_CallsOnError() {
let fake = Fake(result: false)
tryWithErrorPointer { fake.potentiallyErroneousAction($0) }
.onSuccess { _ in XCTFail() }
.onError { _ in XCTAssert(true) }
}
func test_tryWithErrorPointer_SuccessReturnsTrue_CallsOnSuccessWithData() {
let fake = Fake(result: true)
tryWithErrorPointer { fake.potentiallyErroneousAction($0) }
.onError { _ in XCTFail() }
.onSuccess { data in XCTAssertTrue(data) }
}
/**
some of the APIs to indicate error return nil value
*/
func test_tryWithErrorPointer_FailureReturnsNil_CallsOnError() {
let fake = Fake<AnyObject?>(result: nil)
tryWithErrorPointer { fake.potentiallyErroneousAction($0) }
.onSuccess { _ in XCTFail() }
.onError{ _ in XCTAssertTrue(true) }
}
/**
Note: use optional downcasting inside fun closure
(*to avoid crash, since we can't tell whether the cast will be successful)
tryWithError will call onError if the cast failed.
*/
func test_tryWithErrorPointer_SuccessFailedCast_CallsOnError() {
let JSONData = properJSONData()
tryWithErrorPointer { NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: $0) as? Int }
.onSuccess { _ in XCTFail() }
.onError { _ in XCTAssertTrue(true) }
}
func test_tryWithErrorPointer_SuccessSuccessfulCast_CallsOnSuccessWithData() {
let JSONData = properJSONData()
tryWithErrorPointer { NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: $0) as? NSDictionary }
.onError { _ in XCTFail() }
.onSuccess { data in XCTAssertNotNil(data) }
}
func test_tryWithErrorPointerCastResulTo_SuccessFailedCast_CallsOnErrorWithFailedCastError() {
let JSONData = properJSONData()
tryWithErrorPointer(castResultTo: Int.self, { NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: $0)} )
.onSuccess { _ in XCTFail() }
.onError { error in XCTAssertEqual(NSErrorPointerWrapperFailedDowncast, error!.code) }
}
func test_tryWithErrorPointerCastResultTo_SuccessSuccessfulCast_CallsOnSuccessWithData() {
let JSONData = properJSONData()
tryWithErrorPointer(castResultTo: NSDictionary.self) { NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: $0) }
.onError{ _ in XCTFail() }
.onSuccess{ XCTAssertNotNil($0); return }
}
}
// MARK: -
private struct Fake<T> {
let result: T
func potentiallyErroneousAction(error: NSErrorPointer) -> T {
return result
}
}
private func properJSONData() -> NSData {
return "{\"a\":\"b\"}".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
|
mit
|
0eb502baf6fb8c611023aa907321644e
| 39.34127 | 138 | 0.693095 | 4.710843 | false | true | false | false |
balitm/Sherpany
|
Sherpany/ListDataSource.swift
|
1
|
5783
|
//
// ListDataSource.swift
// Sherpany
//
// Created by Balázs Kilvády on 3/18/16.
// Copyright © 2016 kil-dev. All rights reserved.
//
import UIKit
import CoreData
class ListDataSource: NSObject, ListDataSourceProtocol {
var managedObjectContext: NSManagedObjectContext?
weak var tableView: UITableView!
var kReuseId: String
var kEntityName: String
var kSortKey: String
var kCacheName: String
var predicate: NSPredicate?
private var _fetchedResultsController: NSFetchedResultsController? = nil
weak var delegate: ListDataSourceDelegate? = nil
init(reuseId: String, entityName: String, sortKey: String) {
kReuseId = reuseId
kEntityName = entityName
kSortKey = sortKey
kCacheName = entityName
predicate = nil
super.init()
}
// MARK: - Table View Data Source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(kReuseId, forIndexPath: indexPath)
configureCell(cell, atIndexPath: indexPath)
return cell
}
// Configure a UITableViewCell.
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
delegate?.configureCell(cell, atIndexPath: indexPath)
}
func objectAtIndexPath(indexPath: NSIndexPath) -> AnyObject? {
return _fetchedResultsController?.objectAtIndexPath(indexPath)
}
}
// MARK: - Fetched results controller
extension ListDataSource: NSFetchedResultsControllerDelegate {
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
guard let moc = self.managedObjectContext else {
assert(false)
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName(kEntityName, inManagedObjectContext: moc)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: kSortKey, ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
// Use predicate if defined.
fetchRequest.predicate = self.predicate
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController.deleteCacheWithName(kCacheName)
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: kCacheName)
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
_performFetch()
return _fetchedResultsController!
}
func refetch() {
NSFetchedResultsController.deleteCacheWithName(kCacheName)
_performFetch()
tableView.reloadData()
}
private func _performFetch() {
do {
try self.fetchedResultsController.performFetch()
} catch let error as NSError {
print("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
}
class SearchableListDataSource: ListDataSource, SearchableListDataSourceProtocol {
func fetchWithPredicate(predicate: NSPredicate?) {
guard let fetchedResultsController = _fetchedResultsController else {
return
}
NSFetchedResultsController.deleteCacheWithName(kCacheName)
fetchedResultsController.fetchRequest.predicate = predicate == nil ? self.predicate : predicate;
_performFetch()
tableView.reloadData()
}
}
|
mit
|
5445f24b17614b50758ea88e2792ba12
| 34.243902 | 211 | 0.699135 | 5.903984 | false | false | false | false |
ocadaruma/museswift
|
MuseSwift/Source/Misc/String.swift
|
1
|
1034
|
import Foundation
public struct MatchResult {
public let match: String
public let range: Range<String.Index>
}
extension String {
public var range: NSRange {
return NSMakeRange(0, self.characters.count)
}
public func matchesWithPattern(pattern: String) -> [MatchResult] {
let regex = try? NSRegularExpression(pattern: pattern, options: .AnchorsMatchLines)
let match = regex?.firstMatchInString(self,
options: .Anchored,
range: self.range)
if let m = match {
let n = m.numberOfRanges
var matches: [MatchResult] = []
for i in 0..<n {
let r = m.rangeAtIndex(i)
if r.location != NSNotFound {
let start = self.startIndex.advancedBy(r.location)
let end = start.advancedBy(r.length)
let range = start..<end
let result = MatchResult(
match: self.substringWithRange(range),
range: range)
matches.append(result)
}
}
return matches
} else {
return []
}
}
}
|
mit
|
6381b5e7958d975e1084dd31a33c5b59
| 23.642857 | 87 | 0.612186 | 4.344538 | false | false | false | false |
shengyangyu/beauties
|
beauties/CHTCollectionViewWaterfallLayout.swift
|
13
|
15567
|
//
// CHTCollectionViewWaterfallLayout.swift
// PinterestSwift
//
// Created by Nicholas Tau on 6/30/14.
// Copyright (c) 2014 Nicholas Tau. All rights reserved.
//
import Foundation
import UIKit
@objc protocol CHTCollectionViewDelegateWaterfallLayout: UICollectionViewDelegate{
func collectionView (collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
optional func collectionView (collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
heightForHeaderInSection section: NSInteger) -> CGFloat
optional func collectionView (collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
heightForFooterInSection section: NSInteger) -> CGFloat
optional func collectionView (collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAtIndex section: NSInteger) -> UIEdgeInsets
optional func collectionView (collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAtIndex section: NSInteger) -> CGFloat
}
enum CHTCollectionViewWaterfallLayoutItemRenderDirection : NSInteger{
case CHTCollectionViewWaterfallLayoutItemRenderDirectionShortestFirst
case CHTCollectionViewWaterfallLayoutItemRenderDirectionLeftToRight
case CHTCollectionViewWaterfallLayoutItemRenderDirectionRightToLeft
}
class CHTCollectionViewWaterfallLayout : UICollectionViewLayout{
let CHTCollectionElementKindSectionHeader = "CHTCollectionElementKindSectionHeader"
let CHTCollectionElementKindSectionFooter = "CHTCollectionElementKindSectionFooter"
var columnCount : NSInteger{
didSet{
invalidateLayout()
}}
var minimumColumnSpacing : CGFloat{
didSet{
invalidateLayout()
}}
var minimumInteritemSpacing : CGFloat{
didSet{
invalidateLayout()
}}
var headerHeight : CGFloat{
didSet{
invalidateLayout()
}}
var footerHeight : CGFloat{
didSet{
invalidateLayout()
}}
var sectionInset : UIEdgeInsets{
didSet{
invalidateLayout()
}}
var itemRenderDirection : CHTCollectionViewWaterfallLayoutItemRenderDirection{
didSet{
invalidateLayout()
}}
// private property and method above.
weak var delegate : CHTCollectionViewDelegateWaterfallLayout?{
get{
return self.collectionView!.delegate as? CHTCollectionViewDelegateWaterfallLayout
}
}
var columnHeights : NSMutableArray
var sectionItemAttributes : NSMutableArray
var allItemAttributes : NSMutableArray
var headersAttributes : NSMutableDictionary
var footersAttributes : NSMutableDictionary
var unionRects : NSMutableArray
let unionSize = 20
override init(){
self.headerHeight = 0.0
self.footerHeight = 0.0
self.columnCount = 2
self.minimumInteritemSpacing = 10
self.minimumColumnSpacing = 10
self.sectionInset = UIEdgeInsetsZero
self.itemRenderDirection =
CHTCollectionViewWaterfallLayoutItemRenderDirection.CHTCollectionViewWaterfallLayoutItemRenderDirectionShortestFirst
headersAttributes = NSMutableDictionary()
footersAttributes = NSMutableDictionary()
unionRects = NSMutableArray()
columnHeights = NSMutableArray()
allItemAttributes = NSMutableArray()
sectionItemAttributes = NSMutableArray()
super.init()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func itemWidthInSectionAtIndex (section : NSInteger) -> CGFloat {
var insets : UIEdgeInsets
if let sectionInsets = self.delegate?.collectionView?(self.collectionView!, layout: self, insetForSectionAtIndex: section){
insets = sectionInsets
}else{
insets = self.sectionInset
}
let width:CGFloat = self.collectionView!.bounds.size.width - sectionInset.left-sectionInset.right
let spaceColumCount:CGFloat = CGFloat(self.columnCount-1)
return floor((width - (spaceColumCount*self.minimumColumnSpacing)) / CGFloat(self.columnCount))
}
override func prepareLayout(){
super.prepareLayout()
let numberOfSections = self.collectionView!.numberOfSections()
if numberOfSections == 0 {
return
}
self.headersAttributes.removeAllObjects()
self.footersAttributes.removeAllObjects()
self.unionRects.removeAllObjects()
self.columnHeights.removeAllObjects()
self.allItemAttributes.removeAllObjects()
self.sectionItemAttributes.removeAllObjects()
var idx = 0
while idx<self.columnCount{
self.columnHeights.addObject(0)
idx++
}
var top : CGFloat = 0.0
var attributes = UICollectionViewLayoutAttributes()
for var section = 0; section < numberOfSections; ++section{
/*
* 1. Get section-specific metrics (minimumInteritemSpacing, sectionInset)
*/
var minimumInteritemSpacing : CGFloat
if let miniumSpaceing = self.delegate?.collectionView?(self.collectionView!, layout: self, minimumInteritemSpacingForSectionAtIndex: section){
minimumInteritemSpacing = miniumSpaceing
}else{
minimumInteritemSpacing = self.minimumColumnSpacing
}
var sectionInsets : UIEdgeInsets
if let insets = self.delegate?.collectionView?(self.collectionView!, layout: self, insetForSectionAtIndex: section){
sectionInsets = insets
}else{
sectionInsets = self.sectionInset
}
let width = self.collectionView!.bounds.size.width - sectionInset.left - sectionInset.right
let spaceColumCount = CGFloat(self.columnCount-1)
let itemWidth = floor((width - (spaceColumCount*self.minimumColumnSpacing)) / CGFloat(self.columnCount))
/*
* 2. Section header
*/
var heightHeader : CGFloat
if let height = self.delegate?.collectionView?(self.collectionView!, layout: self, heightForHeaderInSection: section){
heightHeader = height
}else{
heightHeader = self.headerHeight
}
if heightHeader > 0 {
attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: CHTCollectionElementKindSectionHeader, withIndexPath: NSIndexPath(forRow: 0, inSection: section))
attributes.frame = CGRectMake(0, top, self.collectionView!.bounds.size.width, heightHeader)
self.headersAttributes.setObject(attributes, forKey: (section))
self.allItemAttributes.addObject(attributes)
top = CGRectGetMaxY(attributes.frame)
}
top += sectionInset.top
for var idx = 0; idx < self.columnCount; idx++ {
self.columnHeights[idx]=top;
}
/*
* 3. Section items
*/
let itemCount = self.collectionView!.numberOfItemsInSection(section)
let itemAttributes = NSMutableArray(capacity: itemCount)
// Item will be put into shortest column.
for var idx = 0; idx < itemCount; idx++ {
let indexPath = NSIndexPath(forItem: idx, inSection: section)
let columnIndex = self.nextColumnIndexForItem(idx)
let xOffset = sectionInset.left + (itemWidth + self.minimumColumnSpacing) * CGFloat(columnIndex)
let yOffset = self.columnHeights.objectAtIndex(columnIndex).doubleValue
let itemSize = self.delegate?.collectionView(self.collectionView!, layout: self, sizeForItemAtIndexPath: indexPath)
var itemHeight : CGFloat = 0.0
if itemSize?.height > 0 && itemSize?.width > 0 {
itemHeight = floor(itemSize!.height*itemWidth/itemSize!.width)
}
attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
attributes.frame = CGRectMake(xOffset, CGFloat(yOffset), itemWidth, itemHeight)
itemAttributes.addObject(attributes)
self.allItemAttributes.addObject(attributes)
self.columnHeights[columnIndex]=CGRectGetMaxY(attributes.frame) + minimumInteritemSpacing;
}
self.sectionItemAttributes.addObject(itemAttributes)
/*
* 4. Section footer
*/
var footerHeight : CGFloat = 0.0
let columnIndex = self.longestColumnIndex()
top = CGFloat(self.columnHeights.objectAtIndex(columnIndex).floatValue) - minimumInteritemSpacing + sectionInset.bottom
if let height = self.delegate?.collectionView?(self.collectionView!, layout: self, heightForFooterInSection: section){
footerHeight = height
}else{
footerHeight = self.footerHeight
}
if footerHeight > 0 {
attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: CHTCollectionElementKindSectionFooter, withIndexPath: NSIndexPath(forItem: 0, inSection: section))
attributes.frame = CGRectMake(0, top, self.collectionView!.bounds.size.width, footerHeight)
self.footersAttributes.setObject(attributes, forKey: section)
self.allItemAttributes.addObject(attributes)
top = CGRectGetMaxY(attributes.frame)
}
for var idx = 0; idx < self.columnCount; idx++ {
self.columnHeights[idx] = top
}
}
idx = 0;
let itemCounts = self.allItemAttributes.count
while(idx < itemCounts){
var rect1 = self.allItemAttributes.objectAtIndex(idx).frame as CGRect
idx = min(idx + unionSize, itemCounts) - 1
var rect2 = self.allItemAttributes.objectAtIndex(idx).frame as CGRect
self.unionRects.addObject(NSValue(CGRect:CGRectUnion(rect1,rect2)))
idx++
}
}
override func collectionViewContentSize() -> CGSize{
var numberOfSections = self.collectionView!.numberOfSections()
if numberOfSections == 0{
return CGSizeZero
}
var contentSize = self.collectionView!.bounds.size as CGSize
let height = self.columnHeights.objectAtIndex(0) as! NSNumber
contentSize.height = CGFloat(height.doubleValue)
return contentSize
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes!{
if indexPath.section >= self.sectionItemAttributes.count{
return nil
}
if indexPath.item >= self.sectionItemAttributes.objectAtIndex(indexPath.section).count{
return nil;
}
var list = self.sectionItemAttributes.objectAtIndex(indexPath.section) as! NSArray
return list.objectAtIndex(indexPath.item) as! UICollectionViewLayoutAttributes
}
override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes{
var attribute = UICollectionViewLayoutAttributes()
if elementKind == CHTCollectionElementKindSectionHeader{
attribute = self.headersAttributes.objectForKey(indexPath.section) as! UICollectionViewLayoutAttributes
}else if elementKind == CHTCollectionElementKindSectionFooter{
attribute = self.footersAttributes.objectForKey(indexPath.section) as! UICollectionViewLayoutAttributes
}
return attribute
}
override func layoutAttributesForElementsInRect (rect : CGRect) -> [AnyObject] {
var i = 0
var begin = 0, end = self.unionRects.count
var attrs = NSMutableArray()
for var i = 0; i < end; i++ {
if CGRectIntersectsRect(rect, self.unionRects.objectAtIndex(i).CGRectValue()){
begin = i * unionSize;
break
}
}
for var i = self.unionRects.count - 1; i>=0; i-- {
if CGRectIntersectsRect(rect, self.unionRects.objectAtIndex(i).CGRectValue()){
end = min((i+1)*unionSize,self.allItemAttributes.count)
break
}
}
for var i = begin; i < end; i++ {
var attr = self.allItemAttributes.objectAtIndex(i) as! UICollectionViewLayoutAttributes
if CGRectIntersectsRect(rect, attr.frame) {
attrs.addObject(attr)
}
}
return NSArray(array: attrs) as [AnyObject]
}
override func shouldInvalidateLayoutForBoundsChange (newBounds : CGRect) -> Bool {
var oldBounds = self.collectionView!.bounds
if CGRectGetWidth(newBounds) != CGRectGetWidth(oldBounds){
return true
}
return false
}
/**
* Find the shortest column.
*
* @return index for the shortest column
*/
func shortestColumnIndex () -> NSInteger {
var index = 0
var shorestHeight = MAXFLOAT
self.columnHeights.enumerateObjectsUsingBlock({(object : AnyObject!, idx : NSInteger,pointer :UnsafeMutablePointer<ObjCBool>) in
let height = object.floatValue
if (height<shorestHeight){
shorestHeight = height
index = idx
}
})
return index
}
/**
* Find the longest column.
*
* @return index for the longest column
*/
func longestColumnIndex () -> NSInteger {
var index = 0
var longestHeight:CGFloat = 0.0
self.columnHeights.enumerateObjectsUsingBlock({(object : AnyObject!, idx : NSInteger,pointer :UnsafeMutablePointer<ObjCBool>) in
let height = CGFloat(object.floatValue)
if (height > longestHeight){
longestHeight = height
index = idx
}
})
return index
}
/**
* Find the index for the next column.
*
* @return index for the next column
*/
func nextColumnIndexForItem (item : NSInteger) -> Int {
var index = 0
switch (self.itemRenderDirection){
case .CHTCollectionViewWaterfallLayoutItemRenderDirectionShortestFirst :
index = self.shortestColumnIndex()
case .CHTCollectionViewWaterfallLayoutItemRenderDirectionLeftToRight :
index = (item%self.columnCount)
case .CHTCollectionViewWaterfallLayoutItemRenderDirectionRightToLeft:
index = (self.columnCount - 1) - (item % self.columnCount);
default:
index = self.shortestColumnIndex()
}
return index
}
}
|
mit
|
3001cde95ee90a874b35db5bd62bdd1b
| 39.22739 | 188 | 0.637181 | 5.841276 | false | false | false | false |
johnno1962/eidolon
|
Kiosk/Bid Fulfillment/Models/BidDetails.swift
|
1
|
2725
|
import UIKit
import RxSwift
import Moya
@objc class BidDetails: NSObject {
typealias DownloadImageClosure = (url: NSURL, imageView: UIImageView) -> ()
let auctionID: String
var newUser: NewUser = NewUser()
var saleArtwork: SaleArtwork?
var paddleNumber = Variable<String?>(nil)
var bidderPIN = Variable<String?>(nil)
var bidAmountCents = Variable<NSNumber?>(nil)
var bidderID = Variable<String?>(nil)
var setImage: DownloadImageClosure = { (url, imageView) -> () in
imageView.sd_setImageWithURL(url)
}
init(saleArtwork: SaleArtwork?, paddleNumber: String?, bidderPIN: String?, bidAmountCents: Int?, auctionID: String) {
self.auctionID = auctionID
self.saleArtwork = saleArtwork
self.paddleNumber.value = paddleNumber
self.bidderPIN.value = bidderPIN
self.bidAmountCents.value = bidAmountCents
}
/// Creates a new authenticated networking provider based on either:
/// - User's paddle/phone # and PIN, or
/// - User's email and password
func authenticatedNetworking(provider: Networking) -> Observable<AuthorizedNetworking> {
let auctionID = saleArtwork?.auctionID ?? ""
if let number = paddleNumber.value, let pin = bidderPIN.value {
let newEndpointsClosure = { (target: ArtsyAuthenticatedAPI) -> Endpoint<ArtsyAuthenticatedAPI> in
// Grab existing endpoint to piggy-back off of any existing configurations being used by the sharedprovider.
let endpoint = Networking.endpointsClosure()(target)
return endpoint.endpointByAddingParameters(["auction_pin": pin, "number": number, "sale_id": auctionID])
}
let provider = OnlineProvider(endpointClosure: newEndpointsClosure, requestClosure: Networking.endpointResolver(), stubClosure: Networking.APIKeysBasedStubBehaviour, plugins: Networking.authenticatedPlugins)
return .just(AuthorizedNetworking(provider: provider))
} else {
let endpoint: ArtsyAPI = ArtsyAPI.XAuth(email: newUser.email.value ?? "", password: newUser.password.value ?? "")
return provider.request(endpoint)
.filterSuccessfulStatusCodes()
.mapJSON()
.flatMap { accessTokenDict -> Observable<AuthorizedNetworking> in
guard let accessToken = accessTokenDict["access_token"] as? String else {
return Observable.error(EidolonError.CouldNotParseJSON)
}
return .just(Networking.newAuthorizedNetworking(accessToken))
}
.logServerError("Getting Access Token failed.")
}
}
}
|
mit
|
976d4d7da5a95de5d47a731f26c484a9
| 40.938462 | 219 | 0.65945 | 5.200382 | false | false | false | false |
ubi-naist/SenStick
|
ios/SenStickViewer/SenStickViewer/SamplingDurationViewController.swift
|
1
|
8408
|
//
// File.swift
// SenStickViewer
//
// Created by AkihiroUehara on 2016/05/27.
// Copyright © 2016年 AkihiroUehara. All rights reserved.
//
import UIKit
import SenStickSDK
class SamplingDurationViewController : UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource
{
@IBOutlet var durationField: UITextField!
@IBOutlet var picker: UIPickerView!
@IBOutlet var rangeLabel: UILabel!
var target: AnyObject?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.durationField.delegate = self
self.picker.delegate = self
self.picker.dataSource = self
if let service = target as? AccelerationSensorService {
if let duration = service.settingData?.samplingDuration {
durationField.text = "\(Int(duration.duration * 1000))"
}
}
if let service = target as? GyroSensorService {
if let duration = service.settingData?.samplingDuration {
durationField.text = "\(Int(duration.duration * 1000))"
}
}
if let service = target as? MagneticFieldSensorService {
if let duration = service.settingData?.samplingDuration {
durationField.text = "\(Int(duration.duration * 1000))"
}
}
if let service = target as? BrightnessSensorService {
picker.isHidden = true
rangeLabel.isHidden = true
if let duration = service.settingData?.samplingDuration {
durationField.text = "\(Int(duration.duration * 1000))"
}
}
if let service = target as? UVSensorService {
picker.isHidden = true
rangeLabel.isHidden = true
if let duration = service.settingData?.samplingDuration {
durationField.text = "\(Int(duration.duration * 1000))"
}
}
if let service = target as? HumiditySensorService {
picker.isHidden = true
rangeLabel.isHidden = true
if let duration = service.settingData?.samplingDuration {
durationField.text = "\(Int(duration.duration * 1000))"
}
}
if let service = target as? PressureSensorService {
picker.isHidden = true
rangeLabel.isHidden = true
if let duration = service.settingData?.samplingDuration {
durationField.text = "\(Int(duration.duration * 1000))"
}
}
// キーボードのDoneツールバーを追加
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50))
toolBar.items = [UIBarButtonItem(barButtonSystemItem: .flexibleSpace , target: nil, action: nil),
UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneToolBarButton))]
self.durationField.inputAccessoryView = toolBar
toolBar .sizeToFit()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let service = target as? AccelerationSensorService {
if let value = Int(durationField.text!) {
let sd = SamplingDurationType(milliSeconds: UInt16(value))
let range = AccelerationRange(rawValue: UInt16(picker.selectedRow(inComponent: 0)))
let setting = SensorSettingData<AccelerationRange>(status: (service.settingData?.status)!, samplingDuration: sd, range: range!)
service.writeSetting(setting)
service.readSetting()
}
}
if let service = target as? GyroSensorService {
if let value = Int(durationField.text!) {
let sd = SamplingDurationType(milliSeconds: UInt16(value))
let range = RotationRange(rawValue: UInt16(picker.selectedRow(inComponent: 0)))
let setting = SensorSettingData<RotationRange>(status: (service.settingData?.status)!, samplingDuration: sd, range: range!)
service.writeSetting(setting)
service.readSetting()
}
}
if let service = target as? MagneticFieldSensorService {
if let value = Int(durationField.text!) {
let sd = SamplingDurationType(milliSeconds: UInt16(value))
let setting = SensorSettingData<MagneticFieldRange>(status: (service.settingData?.status)!, samplingDuration: sd, range: (service.settingData?.range)!)
service.writeSetting(setting)
service.readSetting()
}
}
if let service = target as? BrightnessSensorService {
if let value = Int(durationField.text!) {
let sd = SamplingDurationType(milliSeconds: UInt16(value))
let setting = SensorSettingData<BrightnessRange>(status: (service.settingData?.status)!, samplingDuration: sd, range: (service.settingData?.range)!)
service.writeSetting(setting)
service.readSetting()
}
}
if let service = target as? UVSensorService {
if let value = Int(durationField.text!) {
let sd = SamplingDurationType(milliSeconds: UInt16(value))
let setting = SensorSettingData<UVSensorRange>(status: (service.settingData?.status)!, samplingDuration: sd, range: (service.settingData?.range)!)
service.writeSetting(setting)
service.readSetting()
}
}
if let service = target as? HumiditySensorService {
if let value = Int(durationField.text!) {
let sd = SamplingDurationType(milliSeconds: UInt16(value))
let setting = SensorSettingData<HumiditySensorRange>(status: (service.settingData?.status)!, samplingDuration: sd, range: (service.settingData?.range)!)
service.writeSetting(setting)
service.readSetting()
}
}
if let service = target as? PressureSensorService {
if let value = Int(durationField.text!) {
let sd = SamplingDurationType(milliSeconds: UInt16(value))
let setting = SensorSettingData<PressureRange>(status: (service.settingData?.status)!, samplingDuration: sd, range: (service.settingData?.range)!)
service.writeSetting(setting)
service.readSetting()
}
}
}
// UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
durationField.resignFirstResponder()
return true
}
func doneToolBarButton() {
durationField.resignFirstResponder()
}
// UIPickerViewDataSource
func numberOfComponents(in pickerView: UIPickerView) -> Int
{
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
// FIXME クラスインスタンスを見てswitch構文を使うべき
if target is AccelerationSensorService {
return 4
}
if target is GyroSensorService {
return 4
}
// else
return 0
}
// UIPickerViewDataSource
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
// FIXME クラスインスタンスを見てswitch構文を使うべき
if self.target is AccelerationSensorService {
return ["2G", "4G", "8G", "16G"][row]
}
if target is GyroSensorService {
return ["250DPS", "500DPS", "1000DPS", "2000DPS"][row]
}
// else
return nil
}
}
/*
if let service = target as? AccelerationSensorService {
}
if let service = target as? GyroSensorService {
}
if let service = target as? MagneticFieldSensorService {
}
if let service = target as? BrightnessSensorService {
}
if let service = target as? UVSensorService {
}
if let service = target as? HumiditySensorService {
}
if let service = target as? PressureSensorService {
}*/
|
mit
|
07886b8ef00e7d59d6bb315b036fa3aa
| 36.058036 | 168 | 0.599205 | 4.973637 | false | false | false | false |
Acumen004/ConvertibleCollection
|
ConvertibleCollection/GridLayout.swift
|
1
|
1416
|
//
// GridLayout.swift
// TogglingLayouts
//
// Created by Appinventiv on 14/02/17.
// Copyright © 2017 Appinventiv. All rights reserved.
//
import Foundation
import UIKit
class GridLayout: UICollectionViewFlowLayout{
// define the height of each item cell
let itemHeight: CGFloat = 135
override init() {
super.init()
setupLayout()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayout()
}
// Sets up the layout for the collectionView. 1pt distance between each cell and 1pt distance between each row plus use a vertical layout
func setupLayout() {
minimumLineSpacing = 1
minimumInteritemSpacing = 1
scrollDirection = .vertical
}
/// here we define the width of each cell, creating a 2 column layout. In case you would create 3 columns, change the number 2 to 3
func itemWidth() -> CGFloat {
return (collectionView?.frame.width)!/2 - 1
}
override var itemSize: CGSize {
set {
self.itemSize = CGSize(width: itemWidth(),height: itemHeight)
}
get {
return CGSize(width: itemWidth(),height:itemHeight)
}
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
return collectionView!.contentOffset
}
}
|
mit
|
e7be16b76896e546dc2830239547a1d3
| 26.211538 | 141 | 0.638163 | 5.035587 | false | false | false | false |
BrianCorbin/SwiftRangeSlider
|
Examples/SwiftRangeSliderExample/Pods/RappleColorPicker/Pod/Classes/RappleColorPicker.swift
|
1
|
6799
|
/* **
RappleColorPicker.swift
Custom Activity Indicator with swift 2.0
Created by Rajeev Prasad on 28/11/15.
The MIT License (MIT)
Copyright (c) 2015 Rajeev Prasad <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
** */
import UIKit
/**
RappleColorPickerDelegate public delegate
*/
@objc
public protocol RappleColorPickerDelegate: NSObjectProtocol {
/**
Retrieve selected color from color picker
*/
@objc optional func colorSelected(_ color:UIColor)
@objc optional func colorSelected(_ color:UIColor, tag: Int)
}
/**
RappleColorPicker attribute keys
case Title Title text
case BGColor Background color
case Style Cell style (Square, Circle)
case TintColor Tint Color (Text color, cell border color)
*/
public enum RappleCPAttributeKey : String {
case Title = "Title"
case BGColor = "BGColor"
case Style = "Style"
case TintColor = "TintColor"
}
public let RappleCPStyleSquare = "Square"
public let RappleCPStyleCircle = "Circle"
/**
RappleColorPicker - Easy to use color pricker for iOS apps
*/
open class RappleColorPicker: NSObject {
fileprivate var colorVC : RappleColorPickerViewController?
fileprivate var background : UIView?
fileprivate var closeButton : UIButton?
fileprivate static let sharedInstance = RappleColorPicker()
/**
Open color picker with default look and feel
Color picker size - W(218) x H(352) fixed size for now
@param onViewController opening viewController
@param origin origin point of the color pallet
@param delegate RappleColorPickerDelegate
@param title color pallet name default "Color Picker"
@param tag
*/
open class func openColorPallet(onViewController vc: UIViewController, origin: CGPoint, delegate:RappleColorPickerDelegate, title:String?) {
RappleColorPicker.openColorPallet(onViewController: vc, origin: origin, delegate: delegate, title: title, tag: 0)
}
/**
Open color picker with default look and feel
Color picker size - W(218) x H(352) fixed size for now
*/
open class func openColorPallet(onViewController vc: UIViewController, origin: CGPoint, delegate:RappleColorPickerDelegate, title:String?, tag: Int) {
var attributes : [RappleCPAttributeKey : AnyObject]?
if title != nil {
attributes = [.Title : title! as AnyObject]
}
RappleColorPicker.openColorPallet(onViewController: vc, origin: origin, delegate: delegate, attributes: attributes, tag: tag)
}
/**
Open color picker with custom look and feel (optional)
Color picker size - W(218) x H(352) fixed size for now
@param onViewController opening viewController
@param origin origin point of the color pallet
@param delegate RappleColorPickerDelegate
@param attributes look and feel attribute (Title, BGColor, TintColor, Style)
@param tag
*/
open class func openColorPallet(onViewController vc: UIViewController, origin: CGPoint, delegate:RappleColorPickerDelegate, attributes:[RappleCPAttributeKey:AnyObject]?) {
RappleColorPicker.openColorPallet(onViewController: vc, origin: origin, delegate: delegate, attributes: attributes, tag: 0)
}
/**
Open color picker with custom look and feel (optional)
Color picker size - W(218) x H(352) fixed size for now
*/
open class func openColorPallet(onViewController vc: UIViewController, origin: CGPoint, delegate:RappleColorPickerDelegate, attributes:[RappleCPAttributeKey:AnyObject]?, tag: Int) {
let this = RappleColorPicker.sharedInstance
var title = attributes?[.Title] as? String; if title == nil { title = "Color Picker" }
var bgColor = attributes?[.BGColor] as? UIColor; if bgColor == nil { bgColor = UIColor.darkGray }
var tintColor = attributes?[.TintColor] as? UIColor; if tintColor == nil { tintColor = UIColor.white }
var style = attributes?[.Style] as? String; if style == nil { style = RappleCPStyleCircle }
let attrib : [RappleCPAttributeKey:AnyObject] = [
.Title : title! as AnyObject,
.BGColor : bgColor!,
.TintColor : tintColor!,
.Style : style! as AnyObject
]
this.background = UIView(frame: vc.view.bounds)
this.background?.backgroundColor = UIColor.clear
vc.view.addSubview(this.background!)
this.closeButton = UIButton(frame: this.background!.bounds)
this.closeButton?.addTarget(this, action: #selector(RappleColorPicker.closeTapped), for: .touchUpInside)
this.background?.addSubview(this.closeButton!)
var point = CGPoint(x: origin.x, y: origin.y)
if origin.x < 0 { point.x = 0 }
if origin.y < 0 { point.y = 0 }
if origin.x + 224 > vc.view.bounds.width { point.x = vc.view.bounds.width - 224 }
if origin.y + 354 > vc.view.bounds.height { point.y = vc.view.bounds.height - 354 }
this.colorVC = RappleColorPickerViewController()
this.colorVC?.delegate = delegate
this.colorVC?.attributes = attrib
this.colorVC?.tag = tag
this.colorVC!.view.frame = CGRect(x: point.x, y: point.y, width: 222, height: 352)
this.background!.addSubview(this.colorVC!.view)
}
/**
Close color picker Class func
*/
open class func close(){
let this = RappleColorPicker.sharedInstance
this.closeTapped()
}
/**
Close color picker
*/
internal func closeTapped(){
self.background?.removeFromSuperview()
self.colorVC = nil
self.closeButton = nil
self.background = nil
}
}
|
mit
|
32d206a2c660f832c067bf0eed27b200
| 38.52907 | 185 | 0.687307 | 4.688966 | false | false | false | false |
enums/Pjango
|
Source/Pjango/View/PCView.swift
|
1
|
2298
|
//
// PCView.swift
// Pjango
//
// Created by 郑宇琦 on 2017/6/15.
// Copyright © 2017年 郑宇琦. All rights reserved.
//
import Foundation
import PerfectHTTP
import PerfectHTTPServer
import PerfectMustache
public typealias PCViewParam = Dictionary<String, Any>
open class PCView: PCObject {
internal var _pjango_core_view_template_path: String {
return "\(PJANGO_TEMPLATES_DIR)/\(templateName ?? "")"
}
internal var _pjango_core_view_param: PCViewParam {
return viewParam ?? PCViewParam()
}
public static var meta: PCView {
return self.init()
}
open var templateName: String? {
return nil
}
open var viewParam: PCViewParam? {
return nil
}
required public override init() { }
open weak var currentRequest: HTTPRequest? = nil
public static func asHandle() -> PCUrlHandle {
let handle: RequestHandler = { req, res in
let view = self.init()
view.currentRequest = req
guard view.requestVaild(req) else {
guard let invaildHandle = view.requestInvaildHandle() else {
res._pjango_safe_setBody("Oops! Request is invaild but the `invaild handle` is nil!")
_pjango_core_log.error("Failed on rendering view when request is invaild!")
return
}
invaildHandle(req, res)
return
}
res._pjango_safe_setBody(view.getTemplate())
view.currentRequest = nil
}
return handle
}
open func requestVaild(_ req: HTTPRequest) -> Bool {
return req.method == .get
}
open func requestInvaildHandle() -> PCUrlHandle? {
return nil
}
open func getTemplate() -> String {
do {
let param = _pjango_core_view_param
_pjango_core_log.debug("Rendering [\(_pjango_core_class_name)]:\nTemplate: \(_pjango_core_view_template_path)")
return try PCMustacheUtility.getTemplate(path: _pjango_core_view_template_path, param: param)
} catch {
_pjango_core_log.error(error)
return "Oops! Something wrong when rendering view!"
}
}
}
|
apache-2.0
|
12582758a896cae09e3199af308709c5
| 27.5375 | 123 | 0.579501 | 4.143376 | false | false | false | false |
rsmoz/swift-package-manager
|
Sources/PackageDescription/Version.swift
|
1
|
11491
|
/*
This source file is part of the Swift.org open source project
Copyright 2015 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 Swift project authors
-------------------------------------------------------------------------
[A semantic version](http://semver.org).
*/
public struct Version {
public enum Component: String {
case Major, Minor, Patch
}
public let (major, minor, patch): (Int, Int, Int)
public let prereleaseIdentifiers: [String]
public let buildMetadataIdentifier: String?
public init(_ major: Int, _ minor: Int, _ patch: Int, prereleaseIdentifiers: [String] = [], buildMetadataIdentifier: String? = nil) {
self.major = Swift.max(major, 0)
self.minor = Swift.max(minor, 0)
self.patch = Swift.max(patch, 0)
self.prereleaseIdentifiers = prereleaseIdentifiers
self.buildMetadataIdentifier = buildMetadataIdentifier
}
public init?(_ characters: String.CharacterView) {
let prereleaseStartIndex = characters.indexOf("-")
let metadataStartIndex = characters.indexOf("+")
let requiredEndIndex = prereleaseStartIndex ?? metadataStartIndex ?? characters.endIndex
let requiredCharacters = characters.prefixUpTo(requiredEndIndex)
let requiredComponents = requiredCharacters.split(".", maxSplit: 2, allowEmptySlices: true).map{ String($0) }.flatMap{ Int($0) }.filter{ $0 >= 0 }
guard requiredComponents.count == 3 else {
return nil
}
self.major = requiredComponents[0]
self.minor = requiredComponents[1]
self.patch = requiredComponents[2]
if let prereleaseStartIndex = prereleaseStartIndex {
let prereleaseEndIndex = metadataStartIndex ?? characters.endIndex
let prereleaseCharacters = characters[prereleaseStartIndex.successor()..<prereleaseEndIndex]
prereleaseIdentifiers = prereleaseCharacters.split(".").map{ String($0) }
} else {
prereleaseIdentifiers = []
}
self.buildMetadataIdentifier = metadataStartIndex
.map { characters.suffixFrom($0.successor()) }
.flatMap { $0.isEmpty ? nil : $0 }
.map { String($0) }
}
public init?(_ versionString: String) {
self.init(versionString.characters)
}
public func value(forComponent component: Component) -> Int {
switch component {
case .Major: return major
case .Minor: return minor
case .Patch: return patch
}
}
}
// MARK: Equatable
extension Version: Equatable {}
public func ==(v1: Version, v2: Version) -> Bool {
guard v1.major == v2.major && v1.minor == v2.minor && v1.patch == v2.patch else {
return false
}
if v1.prereleaseIdentifiers != v2.prereleaseIdentifiers {
return false
}
return v1.buildMetadataIdentifier == v2.buildMetadataIdentifier
}
// MARK: Comparable
extension Version: Comparable {}
public func <(lhs: Version, rhs: Version) -> Bool {
let lhsComparators = [lhs.major, lhs.minor, lhs.patch]
let rhsComparators = [rhs.major, rhs.minor, rhs.patch]
if lhsComparators != rhsComparators {
return lhsComparators.lexicographicalCompare(rhsComparators)
}
guard lhs.prereleaseIdentifiers.count > 0 else {
return false // Non-prerelease lhs >= potentially prerelease rhs
}
guard rhs.prereleaseIdentifiers.count > 0 else {
return true // Prerelease lhs < non-prerelease rhs
}
for (lhsPrereleaseIdentifier, rhsPrereleaseIdentifier) in zip(lhs.prereleaseIdentifiers, rhs.prereleaseIdentifiers) {
if lhsPrereleaseIdentifier == rhsPrereleaseIdentifier {
continue
}
let typedLhsIdentifier: Any = Int(lhsPrereleaseIdentifier) ?? lhsPrereleaseIdentifier
let typedRhsIdentifier: Any = Int(rhsPrereleaseIdentifier) ?? rhsPrereleaseIdentifier
switch (typedLhsIdentifier, typedRhsIdentifier) {
case let (int1 as Int, int2 as Int): return int1 < int2
case let (string1 as String, string2 as String): return string1 < string2
case (is Int, is String): return true // Int prereleases < String prereleases
case (is String, is Int): return false
default:
return false
}
}
return lhs.prereleaseIdentifiers.count < rhs.prereleaseIdentifiers.count
}
// MARK: ForwardIndexType
extension Version: BidirectionalIndexType {
public func successor() -> Version {
return successor(.Patch)
}
public func successor(component: Version.Component) -> Version {
switch component {
case .Major:
return Version(major.successor(), 0, 0)
case .Minor:
return Version(major, minor.successor(), 0)
case .Patch:
return Version(major, minor, patch.successor())
}
}
public func predecessor() -> Version {
if patch == 0 {
if minor == 0 {
return Version(major - 1, Int.max, Int.max)
} else {
return Version(major, minor - 1, Int.max)
}
} else {
return Version(major, minor, patch - 1)
}
}
}
// MARK: CustomStringConvertible
extension Version: CustomStringConvertible {
public var description: String {
var base = "\(major).\(minor).\(patch)"
if prereleaseIdentifiers.count > 0 {
base += "-" + prereleaseIdentifiers.joinWithSeparator(".")
}
if let buildMetadataIdentifier = buildMetadataIdentifier {
base += "+" + buildMetadataIdentifier
}
return base
}
}
// MARK: StringLiteralConvertible
extension Version: StringLiteralConvertible {
public init(stringLiteral value: String) {
self.init(value.characters)!
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(stringLiteral: value)
}
public init(unicodeScalarLiteral value: String) {
self.init(stringLiteral: value)
}
}
// MARK: -
extension Version {
public static var max: Version {
return Version(Int.max, Int.max, Int.max)
}
public static var min: Version {
return Version(0, 0, 0)
}
public static var maxRange: Range<Version> {
return self.min..<self.max
}
}
// MARK: - Specifier
public struct Specifier {
public let major: Int?
public let minor: Int?
public let patch: Int?
public static var Any: Specifier {
return Specifier(nil, nil, nil)
}
private init(_ major: Int?, _ minor: Int?, _ patch: Int?) {
self.major = major.map{ Swift.max($0, 0) }
self.minor = minor.map{ Swift.max($0, 0) }
self.patch = patch.map{ Swift.max($0, 0) }
}
public init?(_ characters: String.CharacterView) {
let components = characters.split(".", maxSplit: 2).map(String.init).flatMap{ Int($0) }.filter{ $0 >= 0 }
self.major = components.count >= 1 ? components[0] : nil
self.minor = components.count >= 2 ? components[1] : nil
self.patch = components.count >= 3 ? components[2] : nil
}
public init(_ major: Int) {
self.init(major, nil, nil)
}
public init(_ major: Int, _ minor: Int) {
self.init(major, minor, nil)
}
public init(_ major: Int, _ minor: Int, _ patch: Int) {
self.init(major, minor, patch)
}
public func value(forComponent component: Version.Component) -> Int? {
switch component {
case .Major: return major
case .Minor: return minor
case .Patch: return patch
}
}
}
// MARK: StringLiteralConvertible
extension Specifier: StringLiteralConvertible {
public init(stringLiteral value: String) {
self.init(value.characters)!
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(stringLiteral: value)
}
public init(unicodeScalarLiteral value: String) {
self.init(stringLiteral: value)
}
}
// MARK: IntegerLiteralConvertible
extension Specifier: IntegerLiteralConvertible {
public init(integerLiteral value: Int) {
self.init(value)
}
}
// MARK: FloatLiteralConvertible
extension Specifier: FloatLiteralConvertible {
public init(floatLiteral value: Float) {
self.init(stringLiteral: "\(value)")
}
}
// MARK: -
extension Version {
private init(minimumForSpecifier specifier: Specifier) {
self.init(specifier.major ?? 0, specifier.minor ?? 0, specifier.patch ?? 0)
}
}
//
public typealias Requirement = (Version) -> Bool
prefix operator == {}
prefix operator != {}
prefix operator > {}
prefix operator >= {}
prefix operator ~> {}
prefix operator <= {}
//prefix operator < {}
prefix func ==(specifier: Specifier) -> Requirement {
return { $0 == specifier }
}
prefix func !=(specifier: Specifier) -> Requirement {
return { $0 != specifier }
}
prefix func >(specifier: Specifier) -> Requirement {
return { $0 > specifier }
}
prefix func >=(specifier: Specifier) -> Requirement {
return { $0 >= specifier }
}
prefix func ~>(specifier: Specifier) -> Requirement {
return { $0 ~> specifier }
}
prefix func <=(specifier: Specifier) -> Requirement {
return { $0 <= specifier }
}
//prefix func <(specifier: Specifier) -> Requirement {
// return { $0 < specifier }
//}
// MARK:
func ==(version: Version, specifier: Specifier) -> Bool {
return version == Version(minimumForSpecifier: specifier)
}
func !=(version: Version, specifier: Specifier) -> Bool {
return !(version == specifier)
}
func >(version: Version, specifier: Specifier) -> Bool {
return version >= specifier && version != specifier
}
func >=(version: Version, specifier: Specifier) -> Bool {
return !(version < specifier)
}
infix operator ~> { associativity left precedence 130 }
func ~>(version: Version, specifier: Specifier) -> Bool {
guard version >= specifier else { return false }
switch (specifier.major, specifier.minor, specifier.patch) {
case (let major?, _, nil):
return version.major < major.successor()
case (_, let minor?, _):
return version.minor < minor.successor()
default:
return true
}
}
func <=(version: Version, specifier: Specifier) -> Bool {
return version < specifier || version == specifier
}
func <(version: Version, specifier: Specifier) -> Bool {
return version < Version(minimumForSpecifier: specifier)
}
// MARK: Match Operators
func ~=(lhs: Version, rhs: Requirement) -> Bool {
return rhs(lhs)
}
func ~=(lhs: Version, rhs: [Requirement]) -> Bool {
for requirement in rhs {
guard lhs ~= requirement else { return false }
}
return true
}
// MARK: Interval Operators
public func ...(lhs: Specifier, rhs: Specifier) -> Requirement {
return { (Version(minimumForSpecifier: lhs)...Version(minimumForSpecifier: rhs)).contains($0) }
}
public func ..<(lhs: Specifier, rhs: Specifier) -> Requirement {
return { (Version(minimumForSpecifier: lhs)..<Version(minimumForSpecifier: rhs)).contains ($0) }
}
|
apache-2.0
|
1316119df050431d01245bd69167579b
| 27.513648 | 154 | 0.627274 | 4.399311 | false | false | false | false |
CaiMiao/CGSSGuide
|
DereGuide/Settings/Controller/LicenseViewController.swift
|
1
|
4152
|
//
// LicenseViewController.swift
// DereGuide
//
// Created by zzk on 2016/9/20.
// Copyright © 2016年 zzk. All rights reserved.
//
import UIKit
class LicenseViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
let path = Bundle.main.path(forResource: "ThirdPartyLibraries", ofType: ".plist")
var tableView: UITableView!
var headerTitles = [NSLocalizedString("Copyright of Game Data", comment: ""), NSLocalizedString("Copyright of \(Config.appName)", comment: "") , NSLocalizedString("Third-party Libraries", comment: "")]
lazy var thirdPartyLibraries: [[String: String]] = {
return NSArray.init(contentsOfFile: self.path!) as! [[String: String]]
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("版权声明", comment: "")
tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: view.fwidth, height: view.fheight), style: .grouped)
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
tableView.separatorInset = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 0)
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 50
tableView.register(LicenseTableViewCell.self, forCellReuseIdentifier: "LicenseCell")
tableView.cellLayoutMarginsFollowReadableWidth = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return headerTitles.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return headerTitles[section]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 || section == 1 {
return 1
} else {
return thirdPartyLibraries.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LicenseCell", for: indexPath) as! LicenseTableViewCell
if indexPath.section == 0 {
cell.setup(title: NSLocalizedString("本程序是非官方程序,与官方应用\"アイドルマスターシンデレラガールズ スターライトステージ\"没有任何关联。所有本程序中使用的游戏相关数据版权所属为:\nBANDAI NAMCO Entertainment Inc.\n\n本程序所使用的非官方数据来源于网络,其版权在不违反官方版权的前提下遵循数据提供者的版权声明。\n\n本程序不能保证所提供的数据真实可靠,由此带来的风险由使用者承担。", comment: ""), site: "")
} else if indexPath.section == 1 {
cell.setup(title: NSLocalizedString("本程序基于MIT协议,详情请访问:", comment: ""), site: "https://github.com/superk589/DereGuide")
} else {
cell.setup(title: thirdPartyLibraries[indexPath.row]["name"]!, site: thirdPartyLibraries[indexPath.row]["site"]!)
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
if let cell = tableView.cellForRow(at: indexPath) as? LicenseTableViewCell {
if let url = URL.init(string: cell.siteLabel.text ?? "") {
UIApplication.shared.openURL(url)
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
a7e50dfe6d13cf7aed206c6988c14ba1
| 39.178947 | 269 | 0.661252 | 4.407621 | false | false | false | false |
TrustWallet/trust-wallet-ios
|
Trust/Lock/Coordinators/AuthenticateUserCoordinator.swift
|
1
|
1283
|
// Copyright DApps Platform Inc. All rights reserved.
import Foundation
final class AuthenticateUserCoordinator: Coordinator {
var coordinators: [Coordinator] = []
let navigationController: NavigationController
private let model: LockEnterPasscodeViewModel
private let lock: LockInterface
private lazy var lockEnterPasscodeViewController: LockEnterPasscodeViewController = {
return LockEnterPasscodeViewController(model: model)
}()
init(
navigationController: NavigationController,
model: LockEnterPasscodeViewModel = LockEnterPasscodeViewModel(),
lock: LockInterface = Lock()
) {
self.navigationController = navigationController
self.model = model
self.lock = lock
lockEnterPasscodeViewController.unlockWithResult = { [weak self] (state, bioUnlock) in
if state {
self?.stop()
}
}
}
func start() {
guard lock.shouldShowProtection() else { return }
navigationController.present(lockEnterPasscodeViewController, animated: true)
}
func showAuthentication() {
lockEnterPasscodeViewController.cleanUserInput()
}
func stop() {
navigationController.dismiss(animated: true)
}
}
|
gpl-3.0
|
5cb12a1a2c862ae5f9174edfb37a2142
| 28.159091 | 94 | 0.682775 | 5.554113 | false | false | false | false |
ZhaoBingDong/CYPhotosLibrary
|
CYPhotoKit/Model/CYPhotosCollection.swift
|
1
|
1883
|
//
// CYPhotosCollection.swift
// CYPhotosKit
//
// Created by 董招兵 on 2017/8/6.
// Copyright © 2017年 大兵布莱恩特. All rights reserved.
//
import UIKit
import Photos
/**
* 代表一个集合可能是一个相册组也可能是所有 PHAsset 的集合
*/
public class CYPhotosCollection: NSObject {
/**
* 集合里边放的是 PHAsset 对象
*/
public var fetchResult : PHFetchResult<PHAsset>?
/**
* 相册名称
*/
public var localizedTitle : String?
/**
* 相册里照片/视频的数量
*/
public var count : String?
/**
* 相册封面取最新的一张照片作为封面
*/
public var thumbnail : UIImage?
/// 表示该相簿里选中照片的个数
func getSelectImageCount(close :@escaping ((_ count : Int)-> Void)) {
DispatchQueue.global().async { [weak self] in
let objects = self?.allObjects
func filter(asset : CYPhotosAsset) -> Bool {
if let _ = CYPhotosManager.default.selectImages[asset.localIdentifier] {
return true
}
return false
}
let selectAssets = objects!.filter(filter)
let fetchCount = selectAssets.count
DispatchQueue.main.async {
close(fetchCount)
}
}
}
/// 相册里所有 Asset 集合
public var allObjects : [PHAsset] {
get {
if let result = self.fetchResult {
var objects = [PHAsset]()
for index in 0..<result.count {
objects.append(result.object(at: index))
}
return objects
} else {
return [PHAsset]()
}
}
}
deinit {
// NSLog("self deaclloc")
}
}
|
apache-2.0
|
cb7bd23f8be03dd840f29f54ee33df2b
| 22.583333 | 88 | 0.508834 | 4.234414 | false | false | false | false |
disklessGames/cartel
|
Cartel/Cartel/CityData.swift
|
1
|
4770
|
import UIKit
class CityData: NSObject {
let identifier = "CardCell"
let width = 15
var city = [Int: [Card]]()
var agents = [Int: Int]()
var cardRotations = [CGAffineTransform]()
var pocket = [Int: [Card]]()
var playableLocation = [Bool]()
init(players: Int) {
super.init()
for i in 0..<players {
pocket[i] = [Card]()
}
for x in 0..<width*width {
city[x] = [Card(.none)]
agents[x] = 0
cardRotations.insert(.identity, at: x)
playableLocation.append(false)
}
play(card: Card(RoadCardType.straight), at: width*width/2, playerId: nil)
play(card: Card(RoadCardType.straight), at: width*width/2 + width, playerId: nil)
}
func setPlayableLocations(for card: Card) {
for y in 0..<width {
for x in 0..<width {
playableLocation[x*width + y] = canPlay(card: card, x: x, y: y)
}
}
}
func play(card: Card, at index: Int, playerId: Int?) {
switch card.type {
case .road:
city[index]?.append(card)
case .building:
switch card.building! {
case .anniewares :
agents[index]? += 1
case.topTech:
if city[index]!.count > 1 {
agents[index]? += 1
}
case .groundhogCoffees:
if city[index]!.count == 1 {
agents[index]? += 1
}
case .privateSecurity:
agents[index] = 0
case .mannedManagement:
if agents[index]! > 0 {
agents[index]? += 1
}
case .neueNewsNetwork:
if pocket[playerId!]!.count > 0 {
agents[index]? += 1
}
case .doubleDown:
agents[index]? += doubleDownBonus(index: index)
case
.lucyLaundromat,
.shelfCorp,
.skyline,
.efficientConsulting:
break
}
city[index]?.append(card)
case .pocket:
pocket[playerId!]!.append(card)
default:
break
}
}
func cards(at index: Int) -> [Card]? {
return city[index]
}
func getTopCard(at index: IndexPath) -> Card? {
if let block = cards(at: index.item),
let card = block.last,
card.type != .none {
city[index.item]!.remove(at: block.count - 1)
return card
} else {
return nil
}
}
func canPlay(card: Card, at index: Int) -> Bool {
switch card.type {
case .building:
if city[index]?.last?.type == .building {
return true
} else {
return city[index]!.last!.type == .none &&
canPlayBuilding(at: index)
}
case .road:
if city[index]!.last!.type == .none {
return city[index+1]?.last?.type == .road ||
city[index-1]?.last?.type == .road ||
city[index+width]?.last?.type == .road ||
city[index-width]?.last?.type == .road
} else {
return true
}
case .pocket:
return true
default:
return false
}
}
func canPlay(card: Card, x: Int, y: Int) -> Bool {
return canPlay(card: card, at: x*width + y)
}
private func canPlayBuilding(at index: Int) -> Bool {
return
city[index+1]?.last?.type == .road ||
city[index-1]?.last?.type == .road ||
city[index+width]?.last?.type == .road ||
city[index-width]?.last?.type == .road
}
private func doubleDownBonus(index: Int) -> Int {
if let under = city[index]?.last?.building {
if case .doubleDown = under {
return 1
}
} else if let left = city[index - 1]?.last?.building {
if case .doubleDown = left {
return 1
}
} else if let right = city[index + 1]?.last?.building {
if case .doubleDown = right {
return 1
}
} else if let top = city[index - width]?.last?.building {
if case .doubleDown = top {
return 1
}
} else if let bottom = city[index + width]?.last?.building {
if case .doubleDown = bottom {
return 1
}
}
return 0
}
func cardsToDraw(for player: Player) -> Int {
return 4
}
}
|
mit
|
033a604e1ab459a9d6fa1d486810e720
| 28.627329 | 89 | 0.455346 | 4.262735 | false | false | false | false |
beausmith/ios-tip-calculator
|
tips/ViewController.swift
|
1
|
1624
|
//
// ViewController.swift
// tips
//
// Created by Beau Smith on 1/9/16.
// Copyright © 2016 Beau Smith. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var denominatorField: UITextField!
@IBOutlet weak var perPersonLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tipLabel.text = "$0.00"
totalLabel.text = "$0.00"
denominatorField.text = "1"
perPersonLabel.text = "$0.00"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onEditingChanged(sender: AnyObject) {
var tipPercentages = [0.18, 0.2, 0.22]
let tipPercentage = tipPercentages[tipControl.selectedSegmentIndex]
let billAmount = NSString(string: billField.text!).doubleValue
let tip = billAmount * tipPercentage
let total = billAmount + tip
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
let denominatorAmount = NSString(string: denominatorField.text!).doubleValue
perPersonLabel.text = String(format: "$%.2f", total / denominatorAmount)
}
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
}
|
mit
|
2821caf22b75383541c20f99c56b5ed4
| 32.8125 | 84 | 0.666051 | 4.483425 | false | false | false | false |
practicalswift/swift
|
test/attr/Inputs/PackageDescription.swift
|
14
|
1397
|
public enum SwiftVersion {
// CHECK: @available(_PackageDescription, introduced: 3.0, deprecated: 4.2, obsoleted: 5.0)
@available(_PackageDescription, introduced: 3.0, deprecated: 4.2, obsoleted: 5.0)
case v3
case v4
// CHECK: @available(_PackageDescription 5.0)
// CHECK-NEXT: @available(OSX 10.1, *)
// CHECK-NEXT: v5
@available(_PackageDescription, introduced: 5.0)
@available(macOS, introduced: 10.1)
case v5
}
public class Package {
public var swiftVersion: [SwiftVersion]
@available(_PackageDescription 4.3)
public var buildSettings: [String: String] {
get {
return _buildSettings
}
set {
_buildSettings = newValue
}
}
private var _buildSettings: [String: String]
@available(_PackageDescription 5)
public init(
swiftVersion: [SwiftVersion] = [],
buildSettings: [String: String] = [:]
) {
self._buildSettings = buildSettings
self.swiftVersion = swiftVersion
}
@available(_PackageDescription, introduced: 3.0, obsoleted: 5.0)
public init(
swiftVersion: [SwiftVersion] = []
) {
self._buildSettings = [:]
self.swiftVersion = swiftVersion
}
public func serialize() {
for version in swiftVersion {
print(version)
}
print(_buildSettings)
}
}
|
apache-2.0
|
7566dee71ab9786354e5406cef19ef0a
| 24.87037 | 95 | 0.605583 | 4.325077 | false | false | false | false |
adamnemecek/AudioKit
|
Sources/AudioKit/Sequencing/Apple Sequencer/MusicTrack+Load.swift
|
1
|
3757
|
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
extension MusicTrackManager {
func loadMIDI(filePath: String) {
Log("loading file from exists @ \(filePath)")
let fileURL = URL(fileURLWithPath: filePath)
var tempSeq: MusicSequence?
NewMusicSequence(&tempSeq)
if let newSeq = tempSeq {
let status: OSStatus = MusicSequenceFileLoad(newSeq, fileURL as CFURL, .midiType, MusicSequenceLoadFlags())
if status != OSStatus(noErr) {
Log("error reading midi file url: \(fileURL), read status: \(status)")
}
var trackCount = UInt32(0)
MusicSequenceGetTrackCount(newSeq, &trackCount)
Log("Sequencer has \(trackCount) tracks")
var tempTrack: MusicTrack?
MusicSequenceGetIndTrack(newSeq, 0, &tempTrack)
if let sourceTrack = tempTrack, let destTrack = self.internalMusicTrack {
MusicTrackCopyInsert(sourceTrack, 0, self.length, destTrack, 0)
var tempIterator: MusicEventIterator?
NewMusicEventIterator(sourceTrack, &tempIterator)
if let iterator = tempIterator {
var hasEvent = DarwinBoolean(false)
MusicEventIteratorHasCurrentEvent(iterator, &hasEvent)
var i = 0
while hasEvent.boolValue {
MusicEventIteratorNextEvent(iterator)
var eventTime = MusicTimeStamp(0)
var eventType = MusicEventType(0)
var eventData: UnsafeRawPointer?
var eventDataSize: UInt32 = 0
MusicEventIteratorGetEventInfo(iterator, &eventTime, &eventType, &eventData, &eventDataSize)
if let event = MusicTrackManagerEventType(rawValue: eventType) {
Log("event \(i) at time \(eventTime) type is \(event.description)")
}
MusicEventIteratorHasCurrentEvent(iterator, &hasEvent)
i += 1
}
}
}
}
return
}
}
enum MusicTrackManagerEventType: UInt32 {
case kMusicEventType_NULL = 0
case kMusicEventType_ExtendedNote = 1
case undefined2 = 2
case kMusicEventType_ExtendedTempo = 3
case kMusicEventType_User = 4
case kMusicEventType_Meta = 5
case kMusicEventType_MIDINoteMessage = 6
case kMusicEventType_MIDIChannelMessage = 7
case kMusicEventType_MIDIRawData = 8
case kMusicEventType_Parameter = 9
case kMusicEventType_AUPreset = 10
var description: String {
switch self {
case .kMusicEventType_NULL:
return "kMusicEventType_NULL"
case .kMusicEventType_ExtendedNote:
return "kMusicEventType_ExtendedNote"
case .kMusicEventType_ExtendedTempo:
return "kMusicEventType_ExtendedTempo"
case .kMusicEventType_User:
return "kMusicEventType_User"
case .kMusicEventType_Meta:
return "kMusicEventType_Meta"
case .kMusicEventType_MIDINoteMessage:
return "kMusicEventType_MIDINoteMessage"
case .kMusicEventType_MIDIChannelMessage:
return "kMusicEventType_MIDIChannelMessage"
case .kMusicEventType_MIDIRawData:
return "kMusicEventType_MIDIRawData"
case .kMusicEventType_Parameter:
return "kMusicEventType_Parameter"
case .kMusicEventType_AUPreset:
return "kMusicEventType_AUPreset"
default:
return "undefined"
}
}
}
|
mit
|
84f5c5eedea8e1b1da9ae4aca17fb03e
| 41.693182 | 119 | 0.608198 | 5.063342 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformUIKit/WalletUpgrade/WalletUpgradePresenter.swift
|
1
|
1488
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import RxCocoa
import RxSwift
import WalletPayloadKit
public final class WalletUpgradePresenter {
// MARK: Properties
var viewModel: Driver<WalletUpgradeViewModel> {
viewModelRelay.asDriver()
}
// MARK: Private Properties
private let viewModelRelay = BehaviorRelay<WalletUpgradeViewModel>(value: .loading(version: nil))
private let interactor: WalletUpgradeInteractor
private let disposeBag = DisposeBag()
// MARK: Init
public init(interactor: WalletUpgradeInteractor) {
self.interactor = interactor
}
private lazy var viewDidAppearOnce: Void = interactor.upgradeWallet()
.subscribe(
onNext: { [weak self] version in
self?.viewModelRelay.accept(.loading(version: version))
},
onError: { [weak self] error in
let version: String
switch error {
case WalletUpgradeError.errorUpgrading(let errorVersion):
version = errorVersion
default:
version = ""
}
self?.viewModelRelay.accept(.error(version: version))
},
onCompleted: { [weak self] in
self?.viewModelRelay.accept(.success)
}
)
.disposed(by: disposeBag)
// MARK: Methods
func viewDidAppear() {
_ = viewDidAppearOnce
}
}
|
lgpl-3.0
|
52dce3a2d770106235b4e810b04fc971
| 27.056604 | 101 | 0.597176 | 5.310714 | false | false | false | false |
lzamudio/swift-book
|
Collection Types.playground/section-1.swift
|
2
|
2602
|
// Playground for Collection Types section
// Mutability of Collections
// Arrays
var shoppingList: [String] = ["Eggs", "Milk"]
println("The shopping list contains \(shoppingList.count) items.")
if shoppingList.isEmpty {
println("The shopping list is empty")
} else {
println("The shopping list is not empty")
}
shoppingList.append("Flour")
shoppingList += ["Baking Powder"]
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
var firstItem = shoppingList[0]
shoppingList[0] = "Six eggs"
shoppingList
shoppingList[4...6] = ["Bananas", "Apples"]
shoppingList
shoppingList.insert("Maple Syrup", atIndex: 0)
let mapleSyrup = shoppingList.removeAtIndex(0)
firstItem = shoppingList[0]
let apples = shoppingList.removeLast()
for item in shoppingList {
println(item)
}
for (index, value) in enumerate(shoppingList) {
println("Item \(index + 1): \(value)")
}
var someInts = [Int]()
println("someInts is of type [Int] with \(someInts.count) items.")
someInts.append(3)
someInts = []
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
var anotherThreeDoubles = [Double](count: 3, repeatedValue: 2.5)
var sixDoubles = threeDoubles + anotherThreeDoubles
// Dictionaries
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
println("The airports dictionary contains \(airports.count) items.")
if airports.isEmpty {
println("The airports dictionary is empty.")
} else {
println("The airports dictionary is not empty.")
}
airports["LHR"] = "London"
airports
airports["LHR"] = "London Heathrow"
airports
if let oldValue = airports.updateValue("Dublin Aiport", forKey: "DUB") {
println("The old value for DUB was \(oldValue).")
}
if let airportName = airports["DUB"] {
println("The name of the airport is \(airportName)")
} else {
println("The airport is not in the airports dictionary.")
}
airports["APL"] = "Apple International"
airports
airports["APL"] = nil
airports
if let removedValue = airports.removeValueForKey("DUB") {
println("The removed airport's name is \(removedValue).")
} else {
println("The airports dictionary does not contain a value for DUB.")
}
for (airportCode, airportName) in airports {
println("\(airportCode): \(airportName)")
}
for airportCode in airports.keys {
println("Airport code: \(airportCode)")
}
for airportName in airports.values {
println("Airport name: \(airportName)")
}
let airportCodes = [String](airports.keys)
let airportNames = [String](airports.values)
var namesOfIntegers = [Int: String]()
namesOfIntegers[16] = "sixteen"
namesOfIntegers = [:]
|
mit
|
66f60614cbefe667def420d0682ae26d
| 21.833333 | 76 | 0.707148 | 3.664789 | false | false | false | false |
ddgold/Cathedral
|
Cathedral/Views/PieceView.swift
|
1
|
8409
|
//
// PieceView.swift
// Cathedral
//
// Created by Doug Goldstein on 1/30/19.
// Copyright © 2019 Doug Goldstein. All rights reserved.
//
import UIKit
/// A building piece view.
class PieceView: UIImageView
{
//MARK: - Properties
/// The owner of the piece.
let owner: Owner
/// The building type of the piece.
let building: Building
/// The direction the piece is facing.
private(set) var direction: Direction?
/// The address of the piece.
private(set) var address: Address?
/// The state of the piece.
var state: State
{
didSet
{
switch state
{
case .standard:
colorFilter.isHidden = true
case .success:
colorFilter.backgroundColor = UIColor(displayP3Red: 0, green: 1, blue: 0, alpha: 0.3)
colorFilter.isHidden = false
case .failure:
colorFilter.backgroundColor = UIColor(displayP3Red: 1, green: 0, blue: 0, alpha: 0.3)
colorFilter.isHidden = false
case .disabled:
colorFilter.backgroundColor = UIColor(displayP3Red: 0, green: 0, blue: 0, alpha: 0.5)
colorFilter.isHidden = false
}
}
}
/// The color filter for highlighting the piece.
private var colorFilter: UIView
/// The current rotation of the piece.
private(set) var angle: CGFloat = 0
/// The size of a tile set by controller.
private var tileSize: CGFloat
{
didSet(newValue)
{
resetTileSize(newValue)
}
}
//MARK: - Initialization
/// Initialize a new piece view from a piece object with a direction and address.
///
/// - Parameters:
/// - piece: The piece object.
/// - tileSize: The tile size.
convenience init(_ piece: Piece, tileSize: CGFloat)
{
self.init(owner: piece.owner, building: piece.building, tileSize: tileSize)
// Rotate to direction
let angle = CGFloat(piece.direction.rawValue) * (CGFloat.pi / 2)
rotate(to: angle)
// Adjust address based on direction
var address = piece.address
let (width, height) = building.dimensions(direction: piece.direction)
switch piece.direction
{
case .north:
// Top-left corner (no need to change address)
break;
case .east:
// Top-right corner
address.col -= width - 1
case .south:
// Bottom-right corner
address.col -= width - 1
address.row -= height - 1
case .west:
// Bottom-left corner
address.row -= height - 1
}
// Move to adjusted address
let point = CGPoint(address, tileSize: tileSize)
move(to: point)
self.direction = piece.direction
self.address = piece.address
}
/// Initialize a new piece view without a direction or address.
///
/// - Parameters:
/// - owner: The owner.
/// - building: The building type.
/// - tileSize: The tile size.
init(owner: Owner, building: Building, tileSize: CGFloat)
{
self.tileSize = tileSize
self.owner = owner
self.building = building
self.state = .standard
let imageName = "\(owner.description)_\(building.description)"
guard let imageObject = UIImage(named: imageName) else
{
fatalError("Failed to find image: '\(imageName)'")
}
colorFilter = UIView()
super.init(image: imageObject)
self.isUserInteractionEnabled = true
// Set size
resetTileSize(tileSize)
// Add color filter
colorFilter.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
colorFilter.isHidden = true
let maskView = UIImageView(image: imageObject)
maskView.frame = colorFilter.frame
colorFilter.mask = maskView
addSubview(colorFilter)
}
/// Unsupported decoder initilizer.
///
/// - Parameter aDecoder: The decoder.
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
//MARK: - Functions
/// Determines if a point is within the bounds of this piece.
///
/// - Parameter point: The point.
/// - Returns: Whether or not the point is in the piece.
func contains(point: CGPoint) -> Bool
{
let col = Int8((point.x / tileSize).rounded(.down))
let row = Int8((point.y / tileSize).rounded(.down))
// Always get blueprint relateive to North because point is address inside view
return building.blueprint(owner: owner, facing: .north).contains(where: { address in
return (address.col == col) && (address.row == row)
})
}
/// Move the piece to a new position.
///
/// - Parameter newPosition: The new position.
func move(to newPosition: CGPoint)
{
self.frame.origin = newPosition
self.direction = nil
self.address = nil
}
/// Rotate the piece to a new angle.
///
/// - Parameter newAngle: The new angle.
func rotate(to newAngle: CGFloat)
{
self.angle = newAngle
self.direction = nil
self.address = nil
transform = CGAffineTransform(rotationAngle: newAngle)
}
/// Snap the piece to a point along the grid.
///
/// - Returns: The snapped address of the piece.
func snapToBoard()
{
// (1) Snap to the nearest half-pi
let halfPi = CGFloat.pi / 2
let angle = self.angle.snap(to: halfPi)
rotate(to: angle)
// Count the number of half-pis and add 4 until its positive
var halfPis = Int8((angle / halfPi).rounded())
while halfPis < 0
{
halfPis += 4
}
// Mod 4 to get the direction raw value
let direction = Direction(rawValue: UInt8(halfPis % 4))!
// (2) Snap to the nearest point
var point = self.frame.origin
point.x = point.x.snap(to: tileSize)
point.y = point.y.snap(to: tileSize)
var address = point.toAddress(tileSize: tileSize)
// (3) Snap onto board
let (width, height) = building.dimensions(direction: direction)
// Left
if address.col < 0
{
address.col = 0
}
// Top
if address.row < 0
{
address.row = 0
}
// Right
if (address.col + width) > 10
{
address.col = 10 - width
}
// Bottom
if (address.row + height) > 10
{
address.row = 10 - height
}
// Move frame to position
move(to: CGPoint(address, tileSize: tileSize))
// (4) Adjust address based on direction
switch direction
{
case .north:
// Top-left corner (no need to change address)
break;
case .east:
// Top-right corner
address.col += width - 1
case .south:
// Bottom-right corner
address.col += width - 1
address.row += height - 1
case .west:
// Bottom-left corner
address.row += height - 1
}
self.direction = direction
self.address = address
}
/// Reset the tile size to a new value.
///
/// - Parameter tileSize: The new tile size.
private func resetTileSize(_ tileSize: CGFloat)
{
let (width, height) = building.dimensions(direction: .north)
let size = CGSize(width: tileSize * CGFloat(width), height: tileSize * CGFloat(height))
self.frame = CGRect(origin: self.frame.origin, size: size)
}
//MARK: - State Enum
enum State: UInt8
{
/// Standard, unhighlighted.
case standard
/// Highlighted in green.
case success
/// Highlighted in red.
case failure
/// Disabled, aka darkened
case disabled
}
}
|
apache-2.0
|
c673ddb41d07edec3e40484d5978717d
| 27.696246 | 102 | 0.542578 | 4.609649 | false | false | false | false |
eofster/Telephone
|
Domain/SimpleUserAgentAudioDevice.swift
|
1
|
1067
|
//
// SimpleUserAgentAudioDevice.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
public struct SimpleUserAgentAudioDevice: UserAgentAudioDevice {
public let identifier: Int
public let name: String
public let inputs: Int
public let outputs: Int
public let isNil = false
public init(identifier: Int, name: String, inputs: Int, outputs: Int) {
self.identifier = identifier
self.name = name
self.inputs = inputs
self.outputs = outputs
}
}
|
gpl-3.0
|
2c23d3afeb38d1a4f84b03b93688b1e0
| 32.28125 | 75 | 0.710798 | 4.329268 | false | false | false | false |
keighl/Pathology
|
Pathology/Element.swift
|
1
|
1794
|
//
// Element.swift
// Pathology
//
// Created by Kyle Truscott on 3/2/16.
// Copyright © 2016 keighl. All rights reserved.
//
import Foundation
import QuartzCore
public enum ElementType : String {
case Invalid = ""
case MoveToPoint = "move"
case AddLineToPoint = "line"
case AddQuadCurveToPoint = "quad"
case AddCurveToPoint = "curve"
case CloseSubpath = "close"
}
public struct Element {
var type: ElementType = .Invalid
var points: [CGPoint] = []
public func toDictionary() -> [String: AnyObject] {
return [
"type": type.rawValue,
"pts": points.map({point in
return [point.x, point.y]
})
]
}
public func toJSON(options: NSJSONWritingOptions) throws -> NSData {
let data = try NSJSONSerialization.dataWithJSONObject(toDictionary(), options: options)
return data
}
public func endPoint() -> CGPoint {
if points.count >= 1 {
return points[0]
}
return CGPointZero
}
public func ctrlPoint1() -> CGPoint {
if points.count >= 2 {
return points[1]
}
return CGPointZero
}
public func ctrlPoint2() -> CGPoint {
if points.count >= 3 {
return points[2]
}
return CGPointZero
}
}
extension Element {
public init(dictionary: [String: AnyObject]) {
if let type = dictionary["type"] as? String {
if let ptype = ElementType(rawValue: type) {
self.type = ptype
}
}
if let points = dictionary["pts"] as? [[CGFloat]] {
self.points = points.map({pt in
return CGPointMake(pt[0], pt[1])
})
}
}
}
|
mit
|
50a7b7eb5ecde71879978e05273f57ef
| 22.906667 | 95 | 0.546012 | 4.405405 | false | false | false | false |
ChefZhang/weico
|
weico/weico/Classes/Home/HomeModel/CZStatusViewModel.swift
|
1
|
2343
|
//
// CZStatusViewModel.swift
// weico
//
// Created by JohnZhang on 16/4/10.
// Copyright © 2016年 JohnZhang. All rights reserved.
//
import UIKit
class CZStatusViewModel: NSObject {
var status: CZStatus?
// MARK: - 对数据处理的属性
/// 微博来源
var sourceText : String?
/// 创建时间
var createAtText : String?
/// 处理用户认证图标
var verifiedImage : UIImage?
/// 处理用户会员等级
var vipImage : UIImage?
/// 处理用户头像的地址
var profileURL : NSURL?
/// 处理微博配图的数据
var picURLs : [NSURL] = [NSURL]()
init(status: CZStatus) {
self.status = status
// 处理微博来源
if let source = status.source where source != "" {
let startIndex = (source as NSString).rangeOfString(">").location + 1
let length = (source as NSString).rangeOfString("</").location - startIndex
sourceText = (source as NSString).substringWithRange(NSRange(location: startIndex, length: length))
}
// 创建时间处理
if let createAt = status.created_at {
createAtText = NSDate.createDateString(createAt)
}
// 处理认证
let verifiedType = status.user?.verified_type ?? -1
switch verifiedType {
case 0:
verifiedImage = UIImage(named: "avatar_vip")
case 2, 3, 5:
verifiedImage = UIImage(named: "avatar_enterprise_vip")
case 220:
verifiedImage = UIImage(named: "avatar_grassroot")
default:
verifiedImage = nil
}
// 处理会员图标
let mbrank = status.user?.mbrank ?? 0
if mbrank > 0 && mbrank <= 6 {
vipImage = UIImage(named: "common_icon_membership_level\(mbrank)")
}
// 处理用户头像
let picURLDicts = status.pic_urls!.count != 0 ? status.pic_urls : status.retweeted_status?.pic_urls
if let picURLDicts = picURLDicts {
for picURLDict in picURLDicts {
guard let picURLString = picURLDict["thumbnail_pic"] else {
continue
}
picURLs.append(NSURL(string: picURLString)!)
}
}
}
}
|
apache-2.0
|
d883ad080eef3e99a40fdc591b0bceb7
| 27.736842 | 111 | 0.550824 | 4.439024 | false | false | false | false |
mortorqrobotics/MorTeam-ios
|
MorTeam/FilesVC.swift
|
1
|
3521
|
//
// FilesVC.swift
// MorTeam
//
// Created by Arvin Zadeh on 1/31/17.
// Copyright © 2017 MorTorq. All rights reserved.
//
import Foundation
import UIKit
import Foundation
class FilesVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
var folder: Folder? = nil
@IBOutlet weak var searchFilesSearchBar: UISearchBar!
@IBOutlet weak var filesTableView: UITableView!
var allFiles = [File]()
var showingFiles = [File]()
let morTeamURL = "http://www.morteam.com/api"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = folder!.name
self.loadFiles()
}
func loadFiles(){
httpRequest(self.morTeamURL+"/folders/id/"+(self.folder?._id)!+"/files", type: "GET"){responseText, responseCode in
self.showingFiles = []
self.allFiles = []
let filesJSON = parseJSON(responseText)
for(_, subJson):(String, JSON) in filesJSON {
self.allFiles += [File(fileJSON: subJson)]
}
self.showingFiles = self.allFiles
DispatchQueue.main.async(execute: {
self.filesTableView.reloadData()
})
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.showingFiles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.filesTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FileTableViewCell
cell.name.text = self.showingFiles[indexPath.row].name
cell.originalName.text = self.showingFiles[indexPath.row].originalName
cell.fileImage.image = UIImage(imageLiteralResourceName: self.showingFiles[indexPath.row].type)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
filesTableView.deselectRow(at: indexPath, animated: true)
UIApplication.shared.openURL(NSURL(string: "http://www.morteam.com/api/files/id/"+self.showingFiles[indexPath.row]._id)! as URL)
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar){
searchBar.showsCancelButton = false
searchBar.text = "";
searchBar.resignFirstResponder()
DispatchQueue.main.async(execute: {
self.showingFiles = self.allFiles
self.filesTableView.reloadData()
})
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String){
self.showingFiles = self.allFiles.filter() {$0.name.lowercased().contains(searchText.lowercased())}
DispatchQueue.main.async(execute: {
self.filesTableView.reloadData()
})
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.searchFilesSearchBar.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
d2944c9a2bd13b0045423d84e87820c7
| 29.877193 | 136 | 0.632386 | 5 | false | false | false | false |
Antondomashnev/Sourcery
|
SourceryTests/Stub/Performance-Code/Kiosk/Bid Fulfillment/LoadingViewController.swift
|
2
|
9449
|
import UIKit
import Artsy_UILabels
import ARAnalytics
import RxSwift
class LoadingViewController: UIViewController {
var provider: Networking!
@IBOutlet weak var titleLabel: ARSerifLabel!
@IBOutlet var bidDetailsPreviewView: BidDetailsPreviewView!
@IBOutlet weak var statusMessage: ARSerifLabel!
@IBOutlet weak var spinner: Spinner!
@IBOutlet weak var bidConfirmationImageView: UIImageView!
var placingBid = true
var animate = true
@IBOutlet weak var backToAuctionButton: SecondaryActionButton!
@IBOutlet weak var placeHigherBidButton: ActionButton!
fileprivate let _viewWillDisappear = PublishSubject<Void>()
var viewWillDisappear: Observable<Void> {
return self._viewWillDisappear.asObserver()
}
lazy var viewModel: LoadingViewModelType = {
return LoadingViewModel(
provider: self.provider,
bidNetworkModel: BidderNetworkModel(provider: self.provider, bidDetails: self.fulfillmentNav().bidDetails),
placingBid: self.placingBid,
actionsComplete: self.viewWillDisappear
)
}()
lazy var recognizer = UITapGestureRecognizer()
lazy var closeSelf: () -> Void = { [weak self] in
self?.fulfillmentContainer()?.closeFulfillmentModal()
return
}
override func viewDidLoad() {
super.viewDidLoad()
if placingBid {
bidDetailsPreviewView.bidDetails = viewModel.bidDetails
} else {
bidDetailsPreviewView.isHidden = true
}
statusMessage.isHidden = true
backToAuctionButton.isHidden = true
placeHigherBidButton.isHidden = true
spinner.animate(animate)
titleLabel.text = placingBid ? "Placing bid..." : "Registering..."
// Either finishUp() or bidderError() are responsible for providing a way back to the auction.
fulfillmentContainer()?.cancelButton.isHidden = true
// The view model will perform actions like registering a user if necessary,
// placing a bid if requested, and polling for results.
viewModel.performActions().subscribe(onNext: nil,
onError: { [weak self] error in
logger.log("Bidder error \(error)")
self?.bidderError(error as NSError)
},
onCompleted: { [weak self] in
logger.log("Bid placement and polling completed")
self?.finishUp()
},
onDisposed: { [weak self] in
// Regardless of error or completion. hide the spinner.
self?.spinner.isHidden = true
})
.addDisposableTo(rx_disposeBag)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
_viewWillDisappear.onNext()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue == .PushtoRegisterConfirmed {
let detailsVC = segue.destination as! YourBiddingDetailsViewController
detailsVC.confirmationImage = bidConfirmationImageView.image
detailsVC.provider = provider
}
if segue == .PlaceaHigherBidAfterNotBeingHighestBidder {
let placeBidVC = segue.destination as! PlaceBidViewController
placeBidVC.hasAlreadyPlacedABid = true
placeBidVC.provider = provider
}
}
}
extension LoadingViewController {
func finishUp() {
let reserveNotMet = viewModel.reserveNotMet.value
let isHighestBidder = viewModel.isHighestBidder.value
let bidIsResolved = viewModel.bidIsResolved.value
let createdNewBidder = viewModel.createdNewBidder.value
logger.log("Bidding process result: reserveNotMet \(reserveNotMet), isHighestBidder \(isHighestBidder), bidIsResolved \(bidIsResolved), createdNewbidder \(createdNewBidder)")
if placingBid {
ARAnalytics.event("Placed a bid", withProperties: ["top_bidder" : isHighestBidder, "sale_artwork": viewModel.bidDetails.saleArtwork?.artwork.id ?? ""])
if bidIsResolved {
if reserveNotMet {
handleReserveNotMet()
} else if isHighestBidder {
handleHighestBidder()
} else {
handleLowestBidder()
}
} else {
handleUnknownBidder()
}
} else { // Not placing bid
if createdNewBidder { // Creating new user
handleRegistered()
} else { // Updating existing user
handleUpdate()
}
}
let showPlaceHigherButton = placingBid && (!isHighestBidder || reserveNotMet)
placeHigherBidButton.isHidden = !showPlaceHigherButton
let showAuctionButton = showPlaceHigherButton || isHighestBidder || (!placingBid && !createdNewBidder)
backToAuctionButton.isHidden = !showAuctionButton
let title = reserveNotMet ? "NO, THANKS" : (createdNewBidder ? "CONTINUE" : "BACK TO AUCTION")
backToAuctionButton.setTitle(title, for: .normal)
fulfillmentContainer()?.cancelButton.isHidden = false
}
func handleRegistered() {
titleLabel.text = "Registration Complete"
bidConfirmationImageView.image = UIImage(named: "BidHighestBidder")
fulfillmentContainer()?.cancelButton.setTitle("DONE", for: .normal)
Observable<Int>.interval(1, scheduler: MainScheduler.instance)
.take(1)
.subscribe(onCompleted: { [weak self] in
self?.performSegue(.PushtoRegisterConfirmed)
})
.addDisposableTo(rx_disposeBag)
}
func handleUpdate() {
titleLabel.text = "Updated your Information"
bidConfirmationImageView.image = UIImage(named: "BidHighestBidder")
fulfillmentContainer()?.cancelButton.setTitle("DONE", for: .normal)
}
func handleUnknownBidder() {
titleLabel.text = "Bid Submitted"
bidConfirmationImageView.image = UIImage(named: "BidHighestBidder")
}
func handleReserveNotMet() {
titleLabel.text = "Reserve Not Met"
statusMessage.isHidden = false
statusMessage.text = "Your bid is still below this lot's reserve. Please place a higher bid."
bidConfirmationImageView.image = UIImage(named: "BidNotHighestBidder")
}
func handleHighestBidder() {
titleLabel.text = "High Bid!"
statusMessage.isHidden = false
statusMessage.text = "You are the high bidder for this lot."
bidConfirmationImageView.image = UIImage(named: "BidHighestBidder")
recognizer.rx.event.subscribe(onNext: { [weak self] _ in
self?.closeSelf()
}).addDisposableTo(rx_disposeBag)
bidConfirmationImageView.isUserInteractionEnabled = true
bidConfirmationImageView.addGestureRecognizer(recognizer)
fulfillmentContainer()?.cancelButton.setTitle("DONE", for: .normal)
}
func handleLowestBidder() {
titleLabel.text = "Higher bid needed"
titleLabel.textColor = .artsyRedRegular()
statusMessage.isHidden = false
statusMessage.text = "Another bidder has placed a higher maximum bid. Place a higher bid to secure the lot."
bidConfirmationImageView.image = UIImage(named: "BidNotHighestBidder")
placeHigherBidButton.isHidden = false
}
// MARK: - Error Handling
func bidderError(_ error: NSError) {
if placingBid {
// If you are bidding, we show a bidding error regardless of whether or not you're also registering.
if error.domain == OutbidDomain {
handleLowestBidder()
} else {
bidPlacementFailed(error: error)
}
} else {
// If you're not placing a bid, you're here because you're .just registering.
handleRegistrationFailed(error: error)
}
}
func handleRegistrationFailed(error: NSError) {
handleError(withTitle: "Registration Failed",
message: "There was a problem registering for the auction. Please speak to an Artsy representative.",
error: error)
}
func bidPlacementFailed(error: NSError) {
handleError(withTitle: "Bid Failed",
message: "There was a problem placing your bid. Please speak to an Artsy representative.",
error: error)
}
func handleError(withTitle title: String, message: String, error: NSError) {
titleLabel.textColor = .artsyRedRegular()
titleLabel.text = title
statusMessage.text = message
statusMessage.isHidden = false
backToAuctionButton.isHidden = false
statusMessage.presentOnLongPress("Error: \(error.localizedDescription). \n \(error.artsyServerError())", title: title) { [weak self] alertController in
self?.present(alertController, animated: true, completion: nil)
}
}
@IBAction func placeHigherBidTapped(_ sender: AnyObject) {
self.fulfillmentNav().bidDetails.bidAmountCents.value = 0
self.performSegue(.PlaceaHigherBidAfterNotBeingHighestBidder)
}
@IBAction func backToAuctionTapped(_ sender: AnyObject) {
if viewModel.createdNewBidder.value {
self.performSegue(.PushtoRegisterConfirmed)
} else {
closeSelf()
}
}
}
|
mit
|
3fffd6c92ecdefd61a6e5cb338615ca0
| 35.910156 | 182 | 0.646206 | 5.169037 | false | false | false | false |
nekrich/GlobalMessageService-iOS
|
Source/Core/GlobalMessageServiceHelper+Validation.swift
|
1
|
3243
|
//
// GlobalMessageServiceHelper+Validation.swift
// GlobalMessageService
//
// Created by Vitalii Budnik on 3/28/16.
// Copyright © 2016 Global Message Services Worldwide. All rights reserved.
//
import Foundation
internal extension GlobalMessageServiceHelper {
/**
Checks if there no mutually exclusive tasks
- parameter checkGMStoken: `Bool` indicates to check Global Message Services device token is set, or not
- parameter completion: closure to execute, if checks not passed
- returns: `true` if all checks passed, `false` otherwise
*/
internal func canPreformAction<T>(
checkGMStoken: Bool,
_ completion: ((GlobalMessageServiceResult<T>) -> Void)? = .None)
-> Bool // swiftlint:disable:this opening_brace
{
let errorCompletion: (GlobalMessageServiceError.AnotherTaskInProgress) -> Void = { error in
completion?(.Failure(.AnotherTaskInProgressError(error)))
return
}
if addSubscriberTask != nil {
errorCompletion(.AddSubscriber)
return false
}
if updateSubscriberInfoTask != nil {
errorCompletion(.UpdateSubscriber)
return false
}
if checkGMStoken && GlobalMessageService.registeredGMStoken <= 0 {
completion?(.Failure(.GMSTokenIsNotSet))
return false
}
return true
}
/**
Validates email and phone number
- parameter email: `String` containing subscriber's e-mail address
- parameter phone: `Int64?` containing subscriber's phone number. Can be `nil`
- returns: `true` if email or phone is setted and not empty, `false` otherwise.
Executes `completionHandler` on `false`
*/
func validateEmail(
email: String?,
phone: Int64?)
-> Bool // swiftlint:disable:this opening_brace
{
/// Email is empty
let emailIsEmpty: Bool
if let email = email {
if email.isEmpty {
emailIsEmpty = true
} else {
emailIsEmpty = false
}
} else {
emailIsEmpty = true
}
// Phone is not valid
let phoneNumberIsEmpty: Bool
if let phone = phone {
if phone < 1 {
phoneNumberIsEmpty = true
} else {
phoneNumberIsEmpty = false
}
} else {
phoneNumberIsEmpty = true
}
if emailIsEmpty && phoneNumberIsEmpty {
return false
}
return true
}
/**
Validates email and phone number
- parameter email: `String` containing subscriber's e-mail address
- parameter phone: `Int64?` containing subscriber's phone number. Can be `nil`
- parameter completionHandler: The code to be executed when validation failed. (optional).
This block takes no parameters. Returns `Result` `<T, GlobalMessageServiceError>`
- returns: `true` if email or phone is setted and not empty, `false` otherwise.
Executes `completionHandler` on `false`
*/
func validateEmail<T>(
email: String?,
phone: Int64?,
completionHandler completion: ((GlobalMessageServiceResult<T>) -> Void)?)
-> Bool // swiftlint:disable:this opening_brace
{
if !validateEmail(email, phone: phone) {
completion?(.Failure(.NoPhoneOrEmailPassed))
return false
}
return true
}
}
|
apache-2.0
|
1d1017e4f258e3751e5c2989225dbedd
| 25.57377 | 107 | 0.654226 | 4.592068 | false | false | false | false |
stripe/stripe-ios
|
Example/PaymentSheet Example/PaymentSheetLocalizationScreenshotGenerator/PaymentSheetLocalizationScreenshotGenerator.swift
|
1
|
8754
|
//
// PaymentSheetLocalizationScreenshotGenerator.swift
// PaymentSheetLocalizationScreenshotGenerator
//
// Created by Cameron Sabol on 7/28/21.
// Copyright © 2021 stripe-ios. All rights reserved.
//
import XCTest
@testable import PaymentSheet_Example
class PaymentSheetLocalizationScreenshotGenerator: XCTestCase {
var app: XCUIApplication!
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
app = XCUIApplication()
app.launchEnvironment = ["UITesting": "true"]
app.launch()
}
func waitToAppear(_ target: XCUIElement?) {
_ = target?.waitForExistence(timeout: 60)
}
func saveScreenshot(_ name: String) {
let attachment = XCTAttachment(screenshot: app.windows.firstMatch.screenshot())
attachment.lifetime = .keepAlways
attachment.name = name
add(attachment)
}
func scrollToPaymentMethodCell(_ cell: String) {
let paymentMethodTypeCollectionView = app.collectionViews["PaymentMethodTypeCollectionView"]
waitToAppear(paymentMethodTypeCollectionView)
let targetCell = paymentMethodTypeCollectionView.cells[cell]
// This is not particularly efficient or robust but it's working
// Unfortunately UICollectionViews are setup for KVO so we can't query
// contentOffset or contentSize here
let maxScrollPerDirection = 10
var scrollsLeft = 0
var scrollsRight = 0
while !targetCell.isHittable,
(scrollsLeft < maxScrollPerDirection ||
scrollsRight < maxScrollPerDirection) {
if scrollsLeft < maxScrollPerDirection {
paymentMethodTypeCollectionView.swipeLeft()
scrollsLeft += 1
} else if scrollsRight < maxScrollPerDirection {
paymentMethodTypeCollectionView.swipeRight()
scrollsRight += 1
}
}
waitToAppear(targetCell)
}
func testAllStrings() {
app.staticTexts["PaymentSheet (test playground)"].tap()
app.segmentedControls["customer_mode_selector"].buttons["new"].tap() // new customer
app.segmentedControls["apple_pay_selector"].buttons["off"].tap() // disable Apple Pay
app.segmentedControls["currency_selector"].buttons["EUR"].tap() // EUR currency
app.segmentedControls["mode_selector"].buttons["Pay"].tap() // PaymentIntent
app.segmentedControls["automatic_payment_methods_selector"].buttons["off"].tap() // disable automatic payment methods
app.buttons["Reload PaymentSheet"].tap()
let checkout = app.buttons["Checkout (Complete)"]
expectation(
for: NSPredicate(format: "enabled == true"),
evaluatedWith: checkout,
handler: nil
)
waitForExpectations(timeout: 60.0, handler: nil)
checkout.tap()
do {
let cardCell = app.cells["card"]
scrollToPaymentMethodCell("card")
cardCell.tap()
saveScreenshot("card_entry")
let numberField = app.textFields["Card number"]
let expField = app.textFields["expiration date"]
let cvcField = app.textFields["CVC"]
let postalField = app.textFields["Postal Code"]
numberField.tap()
numberField.typeText("1234")
expField.clearText()
cvcField.clearText()
if postalField.exists, postalField.isHittable {
postalField.clearText()
}
saveScreenshot("card_bad_number")
numberField.clearText()
numberField.tap()
numberField.typeText("4")
expField.clearText()
cvcField.clearText()
if postalField.exists, postalField.isHittable {
postalField.clearText()
}
cvcField.tap()
saveScreenshot("card_incomplete_number")
numberField.clearText()
expField.tap()
expField.typeText("1111")
cvcField.clearText()
if postalField.exists, postalField.isHittable {
postalField.clearText()
}
saveScreenshot("card_bad_exp_year")
numberField.clearText()
expField.clearText()
expField.tap()
expField.typeText("13")
cvcField.clearText()
if postalField.exists, postalField.isHittable {
postalField.clearText()
}
saveScreenshot("card_bad_exp_month")
numberField.clearText()
expField.clearText()
expField.tap()
expField.typeText("1311")
cvcField.clearText()
if postalField.exists, postalField.isHittable {
postalField.clearText()
}
saveScreenshot("card_bad_exp_date")
numberField.clearText()
expField.clearText()
expField.tap()
expField.typeText("1")
cvcField.clearText()
if postalField.exists, postalField.isHittable {
postalField.clearText()
}
cvcField.tap()
saveScreenshot("card_incomplete_exp_date")
numberField.clearText()
expField.clearText()
cvcField.tap()
cvcField.typeText("1")
if postalField.exists, postalField.isHittable {
postalField.clearText()
}
numberField.tap()
saveScreenshot("card_incomplete_cvc")
}
do {
let idealCell = app.cells["ideal"]
scrollToPaymentMethodCell("ideal")
idealCell.tap()
idealCell.tap() // hacky to double tap but fixes transition if software keyboard is enabled
saveScreenshot("ideal_entry")
}
do {
let bancontactCell = app.cells["bancontact"]
scrollToPaymentMethodCell("bancontact")
bancontactCell.tap()
bancontactCell.tap() // hacky to double tap but fixes transition if software keyboard is enabled
saveScreenshot("bancontact_entry")
}
app.buttons["UIButton.Close"].tap()
waitToAppear(app.buttons["Checkout (Complete)"])
app.segmentedControls["mode_selector"].buttons["Setup"].tap() // setup intent
app.buttons["Reload PaymentSheet"].tap()
expectation(
for: NSPredicate(format: "enabled == true"),
evaluatedWith: checkout,
handler: nil
)
waitForExpectations(timeout: 60.0, handler: nil)
checkout.tap()
do {
saveScreenshot("card_entry_setup")
}
app.buttons["UIButton.Close"].tap()
// This section commented out for CI since it depends on global state
// of the returning customer. Uncomment when generating screenshots
// waitToAppear(app.buttons["Checkout (Complete)"])
//
// app.segmentedControls["mode_selector"].buttons["Pay"].tap() // payment intent
// app.segmentedControls["customer_mode_selector"].buttons["returning"].tap() // returning customer
// app.buttons["Reload PaymentSheet"].tap()
//
// expectation(
// for: NSPredicate(format: "enabled == true"),
// evaluatedWith: checkout,
// handler: nil
// )
// waitForExpectations(timeout: 60.0, handler: nil)
// checkout.tap()
//
// do {
// let editButton = app.buttons["edit_saved_button"]
// waitToAppear(editButton)
// saveScreenshot("payment_selector")
//
// editButton.tap()
// saveScreenshot("payment_selector_editing")
//
// app.cells.containing(.button, identifier: "Remove").firstMatch.buttons["Remove"].tap()
// saveScreenshot("removing_payment_method_confirmation")
// }
}
}
extension XCUIElement {
func clearText() {
guard let stringValue = value as? String, !stringValue.isEmpty else {
return
}
// offset tap location a bit so cursor is at end of string
let offsetTapLocation = coordinate(withNormalizedOffset: CGVector(dx: 0.6, dy: 0.6))
offsetTapLocation.tap()
let deleteString = String(repeating: XCUIKeyboardKey.delete.rawValue, count: stringValue.count)
self.typeText(deleteString)
}
}
|
mit
|
8a2e1fab2fb29c5cf6cdb5e636cc1b10
| 34.15261 | 125 | 0.593854 | 5.02757 | false | false | false | false |
ins-wing/Apptoms
|
Example/Pods/SwiftMsgPack/Sources/SwiftMsgPack/Decoder.swift
|
1
|
11127
|
/*
* SwiftMsgPack
* Lightweight MsgPack for Swift
*
* Created by: Daniele Margutti
* Email: [email protected]
* Web: http://www.danielemargutti.com
* Twitter: @danielemargutti
*
* Copyright © 2017 Daniele Margutti
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import Foundation
// MARK: Helper Struct to read and decoded stream of `Data`
private struct StreamReader {
/// Pointer to `data` instance
private var data: Data
/// Current position on `data` instance
private var index: Int
/// Initialize a new stream with an input data
///
/// - Parameter data: data to read
public init(_ data: Data) {
self.data = data
self.index = 0
}
/// Read the next data type header of the structure (8 bit) and move the index by 1 position
///
/// - Returns: data type value
/// - Throws: throw an exception if data cannot be read or it's not available
mutating func readType() throws -> UInt8 {
guard index < data.count else {
throw MsgPackError.unexpectedData
}
let type: UInt8 = data[Data.Index(index)]
index += 1
return type
}
/// Read 8 bit value and return it and move the index by 1 position
///
/// - Returns: 8 bit value
/// - Throws: throw an exception if data cannot be read or it's not available
mutating func read8Bit() throws -> UInt8 {
return try readType()
}
/// Read next 16 bytes and return the value (index is moved according to the task)
///
/// - Returns: value read
/// - Throws: throw an exception if data cannot be read or it's not available
mutating func read16Bit() throws -> UInt16 {
guard index + 2 <= data.count else {
throw MsgPackError.unexpectedData
}
let value_int16 = UInt16(data[Data.Index(index)]) << 8 + UInt16(data[Data.Index(index + 1)])
index += 2
return value_int16
}
/// Read next 32 bytes and return the value (index is moved according to the task)
///
/// - Returns: value read
/// - Throws: throw an exception if data cannot be read or it's not available
mutating func read32Bit() throws -> UInt32 {
guard index + 4 <= data.count else {
throw MsgPackError.unexpectedData
}
var value_int32: UInt32 = 0
for idx in index...(index + 3) {
value_int32 = (value_int32 << 8) + UInt32(data[Data.Index(idx)])
}
index += 4
return value_int32
}
/// Read next 64 bytes and return the value (index is moved according to the task)
///
/// - Returns: value read
/// - Throws: throw an exception if data cannot be read or it's not available
mutating func read64Bit() throws -> UInt64 {
guard index + 8 <= data.count else {
throw MsgPackError.unexpectedData
}
var value_int64: UInt64 = 0
for idx in index...(index + 7) {
value_int64 = (value_int64 << 8) + UInt64(data[Data.Index(idx)])
}
index += 8
return value_int64
}
/// Read next `length` bytes of data and return it (index is moved according to it)
///
/// - Parameter length: length of data to read
/// - Returns: read value
/// - Throws: throw an exception if data cannot be read or it's not available
mutating func readData(length: Int) throws -> Data {
guard index + length <= data.count else {
throw MsgPackError.unexpectedData
}
let range = Range(index..<(index + length))
index += length
return data.subdata(in: range)
}
}
// MARK: Unpack of MsgPack Data
public extension Data {
// MARK - Unpack
/// This is the public function which can read a sequence of Data
/// and unpack all objects by returning decoded data.
///
/// - Returns: decoded data
/// - Throws: an error if decoding task cannot be finished correctly due to an error
public func unpack() throws -> Any? {
// Create a reader which has a point to the current position in data instance
// and several help functions to read data
var reader = StreamReader(self)
// try to unpack data
return try self.unpack(stream: &reader)
}
// MARK - Unpack Internal Functions
/// This is the unpack function which reader
///
/// - Parameter stream: stream object
/// - Returns: decoded data
/// - Throws: an error if decoding task cannot be finished correctly due to an error
private func unpack(stream: inout StreamReader) throws -> Any? {
let type = try stream.readType()
// Spec is defined here:
// https://github.com/msgpack/msgpack/blob/master/spec.md#formats-bool
switch type {
// POSITIVE FIX INT
// positive fixint 0xxxxxxx 0x00 - 0x7f
case 0x00...0x7f:
return Int8(type)
// FIX DICTIONARY (< 16 ITEMS)
// fixmap 1000xxxx 0x80 - 0x8f
case 0x80...0x8f:
let count_items = Int(type & 0xf)
return try self.unpack(dictionary: &stream, count: count_items)
// FIX ARRAY (< 16 ITEMS)
// fixarray 1001xxxx 0x90 - 0x9f
case 0x90...0x9f:
let count_items = Int(type & 0xf)
return try self.unpack(array: &stream, count: count_items)
// NEGATIVE FIX NUM
// negative fixint 111xxxxx 0xe0 - 0xff
case 0xe0...0xff:
return Int8( Int(type) - 256)
// FIX STRING (< 16 CHARS)
// fixstr 101xxxxx 0xa0 - 0xbf
case 0xa0...0xbf:
let str_length = Int(type - 0xa0)
return try self.unpack(string: &stream, length: str_length)
// NIL VALUE
// nil 11000000 0xc0
case 0xc0:
return nil
// BOOLEAN FALSE
// false 11000010 0xc2
case 0xc2:
return false
// BOOLEAN TRUE
// true 11000011 0xc3
case 0xc3:
return true
// BINARY DATA 8 BIT
// bin 8 11000100 0xc4
case 0xc4:
let len_data = Int(try stream.read8Bit())
return try stream.readData(length: len_data)
// BINARY DATA 16 BIT
// bin 16 11000101 0xc5
case 0xc5:
let len_data = Int(try stream.read16Bit())
return try stream.readData(length: len_data)
// BINARY DATA 32 BIT
// bin 32 11000110 0xc6
case 0xc6:
let len_data = Int(try stream.read32Bit())
return try stream.readData(length: len_data)
// FLOAT 32 BIT
// float 32 11001010 0xca
case 0xca:
return Float(bitPattern: try stream.read32Bit())
// DOUBLE
// float 64 11001011 0xcb
case 0xcb:
return Double(bitPattern: try stream.read64Bit())
// UNSIGNED INT 8 BIT
// uint 8 11001100 0xcc
case 0xcc:
return try stream.readType()
// UNSIGNED INT 16 BIT
// uint 16 11001101 0xcd
case 0xcd:
let h = UInt16(try stream.read8Bit())
let l = UInt16(try stream.read8Bit())
return (h << 8 + l)
// UNSIGNED INT 32 BIT
// uint 32 11001110 0xce
case 0xce:
return try stream.read32Bit()
// UNSIGNED INT 64 BIT
// uint 64 11001111 0xcf
case 0xcf:
return try stream.read64Bit()
// INT 8 BIT
// int 8 11010000 0xd0
case 0xd0:
let value = try stream.read8Bit()
return Int8(Int(value) - 256)
// INT 16 BIT
// int 16 11010001 0xd1
case 0xd1:
let h = UInt16(try stream.read8Bit())
let l = UInt16(try stream.read8Bit())
return Int16(bitPattern: h << 8 + l)
// INT 32 BIT
// int 32 11010010 0xd2
case 0xd2:
return try Int32(bitPattern: stream.read32Bit())
// INT 64 BIT
// int 64 11010011 0xd3
case 0xd3:
return try Int64(bitPattern: stream.read64Bit())
// STRING 8 BIT LENGTH
// str 8 11011001 0xd9
case 0xd9:
let len_data = Int(try stream.read8Bit())
return try unpack(string: &stream, length: len_data)
// STRING 16 BIT LENGTH
// str 16 11011010 0xda
case 0xda:
let len_data = Int(try stream.read8Bit()) << 8 + Int(try stream.read8Bit())
return try unpack(string: &stream, length: len_data)
// STRING 32 BIT LENGTH
// str 32 11011011 0xdb
case 0xdb:
let len_data = Int(try stream.read8Bit()) << 24 +
Int(try stream.read8Bit()) << 16 +
Int(try stream.read8Bit()) << 8 +
Int(try stream.read8Bit())
return try unpack(string: &stream, length: len_data)
// ARRAY 16 ITEMS LENGTH
// array 16 11011100 0xdc
case 0xdc:
let count_items = Int(try stream.read16Bit())
return try unpack(array: &stream, count: count_items)
// ARRAY 32 ITEMS LENGTH
// array 32 11011101 0xdd
case 0xdd:
let count_items = Int(try stream.read32Bit())
return try unpack(array: &stream, count: count_items)
// DICTIONARY 16 ITEMS LENGTH
// map 16 11011110 0xde
case 0xde:
let count_items = Int(try stream.read16Bit())
return try unpack(dictionary: &stream, count: count_items)
// DICTIONARY 32 ITEMS LENGTH
// map 32 11011111 0xdf
case 0xdf:
let count_items = Int(try stream.read32Bit())
return try unpack(dictionary: &stream, count: count_items)
default:
throw MsgPackError.unsupportedValue(String(format: "Type(%02x)", type))
}
}
/// Unpack a `dictionary` sequence
///
/// - Parameters:
/// - stream: input stream of data
/// - count: number of keys in dictionary
/// - Returns: decoded dictionary
/// - Throws: throw an exception if failed to decoded data
private func unpack(dictionary stream: inout StreamReader, count: Int) throws -> [AnyHashable: Any?] {
var dict: [AnyHashable: Any?] = [:]
for _ in 0..<count {
guard let key = try self.unpack(stream: &stream) as? AnyHashable else {
throw MsgPackError.unsupportedValue("Invalid dict key")
}
print(key)
let val = try self.unpack(stream: &stream)
dict[key] = val
}
return dict
}
/// Unpack an `array` sequence
///
/// - Parameters:
/// - stream: input stream of data
/// - count: number of keys in array
/// - Returns: decoded array
/// - Throws: throw an exception if failed to decoded data
private func unpack(array stream: inout StreamReader, count: Int) throws -> [Any?] {
var array: [Any?] = []
for _ in 0..<count {
array.append(try self.unpack(stream: &stream))
}
return array
}
/// Unpack a `string` sequence
///
/// - Parameters:
/// - stream: input stream of data
/// - length: length of data to read
/// - Returns: decoded string
/// - Throws: throw an exception if failed to decoded data
private func unpack(string stream: inout StreamReader, length: Int) throws -> String {
let data = try stream.readData(length: length)
guard let str = String(data: data, encoding: String.Encoding.utf8) else {
throw MsgPackError.invalidEncoding
}
return str
}
}
|
mit
|
790633de420380f671863336ccc8a0e3
| 27.749354 | 103 | 0.674007 | 3.247519 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/Map Detail/View Model/DefaultMapDetailViewModelFactory.swift
|
1
|
3453
|
import EurofurenceModel
import Foundation
public class DefaultMapDetailViewModelFactory: MapDetailViewModelFactory, MapsObserver {
private struct ViewModel: MapDetailViewModel {
let map: Map
var mapImagePNGData: Data
var mapName: String {
return map.location
}
func showContentsAtPosition(x: Float, y: Float, describingTo visitor: MapContentVisitor) {
let contentHandler = ContentHandler(x: x, y: y, visitor: visitor)
map.fetchContentAt(x: Int(x), y: Int(y), completionHandler: contentHandler.handle)
}
}
private struct ContentHandler {
var x: Float
var y: Float
var visitor: MapContentVisitor
func handle(_ content: MapContent) {
switch content {
case .location(let altX, let altY, let name):
let coordinate = MapCoordinate(x: altX, y: altY)
if let name = name {
let contextualInfo = MapInformationContextualContent(coordinate: coordinate, content: name)
visitor.visit(contextualInfo)
}
visitor.visit(coordinate)
case .room(let room):
let coordinate = MapCoordinate(x: x, y: y)
let contextualInfo = MapInformationContextualContent(coordinate: coordinate, content: room.name)
visitor.visit(contextualInfo)
case .dealer(let dealer):
visitor.visit(dealer.identifier)
case .multiple(let contents):
visitor.visit(OptionsViewModel(contents: contents, handler: self))
case .none:
break
}
}
}
private struct OptionsViewModel: MapContentOptionsViewModel {
private let contents: [MapContent]
private let handler: ContentHandler
init(contents: [MapContent], handler: ContentHandler) {
self.contents = contents
self.handler = handler
optionsHeading = .selectAnOption
options = contents.compactMap { (content) -> String? in
switch content {
case .room(let room):
return room.name
case .dealer(let dealer):
return dealer.preferredName
case .location(_, _, let name):
return name
default:
return nil
}
}
}
var optionsHeading: String
var options: [String]
func selectOption(at index: Int) {
let content = contents[index]
handler.handle(content)
}
}
private let mapsService: MapsService
private var maps = [Map]()
public init(mapsService: MapsService) {
self.mapsService = mapsService
mapsService.add(self)
}
public func makeViewModelForMap(
identifier: MapIdentifier,
completionHandler: @escaping (MapDetailViewModel) -> Void
) {
guard let map = maps.first(where: { $0.identifier == identifier }) else { return }
map.fetchImagePNGData { (mapGraphicData) in
let viewModel = ViewModel(map: map, mapImagePNGData: mapGraphicData)
completionHandler(viewModel)
}
}
public func mapsServiceDidChangeMaps(_ maps: [Map]) {
self.maps = maps
}
}
|
mit
|
e8ebb1cbb92f2e7b2a4574373d77779b
| 28.512821 | 112 | 0.571966 | 5.153731 | false | false | false | false |
sarahlee517/EasyTaipei-iOS
|
EasyTaipei/EasyTaipei/helper/HitTest.swift
|
2
|
2435
|
//
// HitTest.swift
// EasyTaipei
//
// Created by howard hsien on 2016/7/6.
// Copyright © 2016年 AppWorks School Hsien. All rights reserved.
//
import UIKit
extension UITabBar{
//for button out of bound of cell
override public func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
if(!self.clipsToBounds && !self.hidden && self.alpha > 0.0){
let subviews = self.subviews.reverse()
for member in subviews {
let subPoint = member.convertPoint(point, fromView: self)
if let result:UIView = member.hitTest(subPoint, withEvent:event) {
return result;
}
}
}
return nil
}
}
extension UICollectionView{
//for button out of bound of cell
override public func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
if(!self.clipsToBounds && !self.hidden && self.alpha > 0.0){
let subviews = self.subviews.reverse()
for member in subviews {
let subPoint = member.convertPoint(point, fromView: self)
if let result:UIView = member.hitTest(subPoint, withEvent:event) {
return result;
}
}
}
return nil
}
}
extension MenuBar{
//for button out of bound of cell
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
if(!self.clipsToBounds && !self.hidden && self.alpha > 0.0){
let subviews = self.subviews.reverse()
for member in subviews {
let subPoint = member.convertPoint(point, fromView: self)
if let result:UIView = member.hitTest(subPoint, withEvent:event) {
return result;
}
}
}
return nil
}
}
extension MenuCell{
//for button out of bound of cell
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
if(!self.clipsToBounds && !self.hidden && self.alpha > 0.0){
let subviews = self.subviews.reverse()
for member in subviews {
let subPoint = member.convertPoint(point, fromView: self)
if let result:UIView = member.hitTest(subPoint, withEvent:event) {
return result;
}
}
}
return nil
}
}
|
mit
|
405dfac082d5d7f9b2466b1fad2fb301
| 30.192308 | 88 | 0.560033 | 4.528864 | false | true | false | false |
MaartenBrijker/project
|
project/External/AudioKit-master/AudioKit/Common/Nodes/Mixing/Balancer/AKBalancer.swift
|
3
|
2797
|
//
// AKBalancer.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2015 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// This operation outputs a version of the audio source, amplitude-modified so
/// that its rms power is equal to that of the comparator audio source. Thus a
/// signal that has suffered loss of power (eg., in passing through a filter
/// bank) can be restored by matching it with, for instance, its own source. It
/// should be noted that this modifies amplitude only; output signal is not
/// altered in any other respect.
///
/// - parameter input: Input node to process
/// - parameter comparator: Audio to match power with
///
public class AKBalancer: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKBalancerAudioUnit?
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this balance node
///
/// - parameter input: Input node to process
/// - parameter comparator: Audio to match power with
///
public init( _ input: AKNode, comparator: AKNode) {
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Mixer
description.componentSubType = 0x626c6e63 /*'blnc'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKBalancerAudioUnit.self,
asComponentDescription: description,
name: "Local AKBalancer",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.avAudioNode = avAudioUnitEffect
self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKBalancerAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
comparator.connectionPoints.append(AVAudioConnectionPoint(node: self.avAudioNode, bus: 1))
AudioKit.engine.connect(comparator.avAudioNode, toConnectionPoints: comparator.connectionPoints, fromBus: 0, format: nil)
}
}
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
|
apache-2.0
|
f8226aa9be1d1c9eb6e5bfb099c87c6f
| 33.530864 | 133 | 0.666071 | 4.976868 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.