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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
calkinssean/TIY-Assignments | Day 11/starWarsApp/DetailViewController.swift | 1 | 2039 | //
// DetailViewController.swift
// starWarsApp
//
// Created by Sean Calkins on 2/15/16.
// Copyright © 2016 Sean Calkins. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
var newCharacter: StarWarsCharacter?
//MARK: - Variables
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var profileImageView: UIImageView!
//MARK: - View Will Appear
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
print(newCharacter?.description)
super.viewDidLoad()
self.nameLabel.text = newCharacter?.name
self.descriptionLabel.text = newCharacter?.description
self.profileImageView.image = UIImage(named: "\(newCharacter!.imageName)")
updateColors()
}
//MARK: - UI update
func updateColors() {
if newCharacter?.affiliations == "Sith" {
self.view.backgroundColor = UIColor.blackColor()
nameLabel.font = UIFont(name: "Pure evil 2", size: 45.0)
nameLabel.textColor = UIColor.redColor()
descriptionLabel.font = UIFont(name: "Pure evil 2", size: 20.0)
descriptionLabel.textColor = UIColor.redColor()
} else if newCharacter?.affiliations == "Jedi Order" {
self.view.backgroundColor = UIColor.whiteColor()
nameLabel.font = UIFont(name: "trench", size: 45.0)
nameLabel.textColor = UIColor.blackColor()
descriptionLabel.font = UIFont(name: "trench", size: 20.0)
descriptionLabel.textColor = UIColor.blackColor()
} else {
self.view.backgroundColor = UIColor.whiteColor()
nameLabel.font = UIFont(name: "Papyrus", size: 40.0)
nameLabel.textColor = UIColor.blueColor()
descriptionLabel.font = UIFont(name: "Papyrus", size: 15.0)
descriptionLabel.textColor = UIColor.blueColor()
}
}
}
| cc0-1.0 | d4e06790d54316a8623cbbcf8c172af3 | 29.878788 | 82 | 0.628067 | 4.761682 | false | false | false | false |
gouyz/GYZBaking | baking/Classes/Category/View/GYZGoodsConmentHeader.swift | 1 | 2629 | //
// GYZGoodsConmentHeader.swift
// baking
// 商家评论header
// Created by gouyz on 2017/4/17.
// Copyright © 2017年 gouyz. All rights reserved.
//
import UIKit
class GYZGoodsConmentHeader: UITableViewHeaderFooterView {
override init(reuseIdentifier: String?){
super.init(reuseIdentifier: reuseIdentifier)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI(){
bgView.backgroundColor = kWhiteColor
contentView.addSubview(bgView)
bgView.addSubview(nameLab)
bgView.addSubview(desLab)
bgView.addSubview(rightIconView)
bgView.addSubview(lineView)
rightIconView.isHidden = true
bgView.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(contentView)
make.top.equalTo(kMargin)
}
nameLab.snp.makeConstraints { (make) in
make.top.equalTo(bgView)
make.left.equalTo(kMargin)
make.bottom.equalTo(lineView.snp.top)
make.right.equalTo(desLab.snp.left).offset(-kMargin)
}
desLab.snp.makeConstraints { (make) in
make.right.equalTo(rightIconView.snp.left)
make.top.height.equalTo(nameLab)
make.width.equalTo(100)
}
rightIconView.snp.makeConstraints { (make) in
make.centerY.equalTo(bgView)
make.right.equalTo(-5)
make.size.equalTo(CGSize.init(width: 20, height: 20))
}
lineView.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(bgView)
make.height.equalTo(klineWidth)
}
}
fileprivate lazy var bgView: UIView = UIView()
/// 店铺名称
lazy var nameLab : UILabel = {
let lab = UILabel()
lab.font = k15Font
lab.textColor = kBlackFontColor
lab.text = "商品评价"
return lab
}()
/// 评论日期
lazy var desLab : UILabel = {
let lab = UILabel()
lab.font = k13Font
lab.textColor = kGaryFontColor
// lab.text = "查看全部评价"
lab.textAlignment = .right
return lab
}()
/// 右侧箭头图标
fileprivate lazy var rightIconView: UIImageView = UIImageView.init(image: UIImage.init(named: "icon_right_gray"))
fileprivate lazy var lineView : UIView = {
let line = UIView()
line.backgroundColor = kGrayLineColor
return line
}()
}
| mit | de2b4de7c935160566b7635a5d6686ce | 27.241758 | 117 | 0.585214 | 4.477352 | false | false | false | false |
GrupoGO/PGActionWidget | PGDActionWidgetView.swift | 1 | 14786 | //
// PGDActionWidgetView.swift
// ActionWidget
//
// Created by Emilio Cubo Ruiz on 13/7/17.
// Copyright © 2017 Grupo Go Optimizations, SL. All rights reserved.
//
import UIKit
import CoreLocation
struct Action {
var cms_url:String
var end_date:Date
var id:Int
var image:String
var isDo:Bool
var isTodo:Bool
var latitude:Double
var longitude:Double
var metric:String
var metric_quantity:Int
var platform:String
var pledges:Int
var review:Int
var start_date:Date
var text:String
var time:Int
var title:String
var type:String
var url:String
var categories:[Category]
var doUsers:[User]
var lists:[List]
var poll:[Answer]
var todoUsers:[User]
}
struct Category {
var id:Int
var image:String
var name:String
var valor:Int
var actions:[Action]
var usersWithCategory:[User]
}
struct User {
var address_1:String
var address_2:String
var alias:String
var birdthdate:String
var city:String
var co2:Int
var country:String
var dollars:Int
var email:String
var firstname:String
var gender:String
var id:Int
var image:String
var lasname:String
var latitude:Double
var lives:Int
var longitude:Double
var nationality:String
var official_document:String
var phone:String
var points:String
var postal_code:String
var region:String
var session:String
var time:Int
var categories:[Category]
var does:[Action]
var lists:[List]
var messages:[Message]
var todoes:[Action]
var types:[Type]
}
struct List {
var created:Date
var hashid:String
var id:Int
var isPrivate:Bool
var last_update:Date
var name:String
var actions:[Action]
var creator:User
}
struct Answer {
var id:Int
var poll_id:Int
var poll_title:String
var statValue:Int
var text:String
var action:Action
}
struct Message {
var date:Date
var ratting:Int
var text:String
var sender:User
}
struct Type {
var id:Int
var valor:Int
var userWithType:User
}
public class PGDActionWidgetView: UIView {
// MARK: Outlets
@IBOutlet fileprivate var contentView:UIView?
@IBOutlet fileprivate var container:UIView?
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var loader: UIActivityIndicatorView!
@IBOutlet weak var actionText: UILabel!
var downloadPGD:Bool = false
var actions: [Action]? {
didSet {
if let actions = actions {
let screenHeight = UIScreen.main.bounds.size.height
let height = screenHeight < 408 ? screenHeight - 108 : 300
var originX = 12.0
for action in actions {
let actionView = PGDActionView(frame: CGRect(x: originX, y: 0, width: 222.0, height: Double(height)))
actionView.action = action
actionView.downloadPGD = self.downloadPGD
originX += 234
scrollView.addSubview(actionView)
}
scrollView.layoutIfNeeded();
let width = 234 * actions.count + 12
scrollView.contentSize = CGSize(width: CGFloat(width), height: scrollView.contentSize.height);
loader.isHidden = true
}
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit();
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
public override func layoutSubviews() {
super.layoutSubviews()
guard let content = contentView else { return }
var frameSize = content.bounds
let screenHeight = UIScreen.main.bounds.size.height
let height = screenHeight < 408 ? screenHeight - 108 : 300
frameSize.size.height = screenHeight < 408 ? screenHeight : 408
content.frame = frameSize
for view in scrollView.subviews {
if view.isKind(of: PGDActionView.self) {
view.frame.size.height = height
}
}
}
public func searchActions(coordinates:CLLocationCoordinate2D, locationName:String, keywords:[String]?, numberOfAction:Int?) {
actionText.text = "Actions near \(locationName)"
let size = numberOfAction != nil ? numberOfAction! : 100
let urlCoordinates = "https://maps.googleapis.com/maps/api/geocode/json?language=en&sensor=false&latlng=\(coordinates.latitude),\(coordinates.longitude)&result_type=administrative_area_level_1&key=AIzaSyBxL5CwUDj15cnfFP0PbEr0k8nq6Po3gEw"
let requestCoordinates = NSMutableURLRequest(url: URL(string: urlCoordinates)!)
requestCoordinates.httpMethod = "GET"
let taskCoordinates = URLSession.shared.dataTask(with: requestCoordinates as URLRequest, completionHandler: { (data, response, error) in
if error != nil {
print(error!)
} else {
DispatchQueue.main.async(execute: {
do {
let json = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
if let results = json["results"] as? [Any] {
if results.count > 0 {
let geometry = (results[0] as! [String:Any])["geometry"] as! [String:Any]
let bounds = geometry["bounds"] as! [String:Any]
let max_lat = (bounds["northeast"] as! [String:Any])["lat"] as! Double
let max_lng = (bounds["northeast"] as! [String:Any])["lng"] as! Double
let min_lat = (bounds["southwest"] as! [String:Any])["lat"] as! Double
let min_lng = (bounds["southwest"] as! [String:Any])["lng"] as! Double
var text2Search = ""
if keywords != nil {
for i in 0..<keywords!.count {
if text2Search == "" {
text2Search = keywords![i]
} else {
text2Search = text2Search + "," + keywords![i]
}
}
}
let urlPHP = keywords != nil ? "https://webintra.net/api/Playground/search?keywords=\(text2Search)&size=\(size)&min_lat=\(min_lat)&max_lat=\(max_lat)&min_lng=\(min_lng)&max_lng=\(max_lng)" : "https://webintra.net/api/Playground/search?min_lat=\(min_lat)&max_lat=\(max_lat)&min_lng=\(min_lng)&max_lng=\(max_lng)&size=\(size)"
let request = NSMutableURLRequest(url: URL(string: urlPHP.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)!)
request.httpMethod = "GET"
request.addValue("59baef879d68f4af3c97c0269ed46200", forHTTPHeaderField: "Token")
request.addValue("b6cccc4e45422e84143cd6a8fa589eb4", forHTTPHeaderField: "Secret")
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
if error != nil {
print(error!)
} else {
DispatchQueue.main.async(execute: {
do {
let parsedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
self.parseActions(parsedData: parsedData)
} catch let error as NSError {
print(error)
}
});
}
})
task.resume()
}
}
} catch let error as NSError {
print(error)
}
});
}
})
taskCoordinates.resume()
}
public func searchActions(keywords:[String]?, numberOfAction:Int?) {
actionText.text = "Recommended actions"
var text2Search = ""
if keywords != nil {
for i in 0..<keywords!.count {
if text2Search == "" {
text2Search = keywords![i]
} else {
text2Search = text2Search + "," + keywords![i]
}
}
}
let size = numberOfAction != nil ? numberOfAction! : 10
let urlPHP = keywords != nil ? "https://webintra.net/api/Playground/search?keywords=\(text2Search)&size=\(size)" : "https://webintra.net/api/Playground/search?list=16758375"
let request = NSMutableURLRequest(url: URL(string: urlPHP.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)!)
request.httpMethod = "GET"
request.addValue("59baef879d68f4af3c97c0269ed46200", forHTTPHeaderField: "Token")
request.addValue("b6cccc4e45422e84143cd6a8fa589eb4", forHTTPHeaderField: "Secret")
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
if error != nil {
print(error!)
} else {
DispatchQueue.main.async(execute: {
do {
let parsedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
self.parseActions(parsedData: parsedData)
} catch let error as NSError {
print(error)
}
});
}
})
task.resume()
}
func parseActions(parsedData:[String:Any]) {
let info = parsedData["info"] as! [String:Any]
if let items = info["items"] as? [[String:Any]] {
var parseActions = [Action]()
for item in items {
var newAction = Action(
cms_url: item["cms_url"] as! String,
end_date: Date.dateFromString(item["end_date"] as! String, timeZone: false),
id: item["id"] as! Int,
image: item["image"] as! String,
isDo: false,
isTodo: false,
latitude: item["latitude"] as? Double != nil ? item["latitude"] as! Double : 0.0,
longitude: item["longitude"] as? Double != nil ? item["longitude"] as! Double : 0.0,
metric: item["metric"] as! String,
metric_quantity: item["metric_quantity"] as! Int,
platform: item["website"] as! String,
pledges: item["plegdes"] as? Int != nil ? item["plegdes"] as! Int : 0,
review: item["review"] as? Int != nil ? item["review"] as! Int : 0,
start_date: Date.dateFromString(item["start_date"] as! String, timeZone: false),
text: item["description"] as! String,
time: item["time"] as! Int,
title: item["title"] as! String,
type: item["type"] as! String,
url: item["url"] as! String,
categories: [],
doUsers: [],
lists: [],
poll: [],
todoUsers: []
)
if newAction.type.lowercased() == "poll" {
let poll = item["poll"] as! [String:Any]
let pollTitle = poll["title"] as! String
newAction.title = pollTitle
let pollAnswers = poll["answers"] as! [[String:Any]]
var answers = [Answer]()
for answer in pollAnswers {
let a = Answer(
id: answer["id"] as! Int,
poll_id: poll["id"] as! Int,
poll_title: newAction.title,
statValue: 0,
text: answer["text"] as! String,
action: newAction)
answers.append(a)
}
newAction.poll = answers
}
parseActions.append(newAction)
}
self.actions = parseActions
}
}
fileprivate func commonInit() {
let bundle = Bundle(for: PGDActionView.self)
bundle.loadNibNamed("PGDActionWidgetView", owner: self, options: nil)
guard let content = contentView else { return }
var frameSize = self.bounds
frameSize.size.height = 408
content.frame = frameSize
content.autoresizingMask = [.flexibleHeight, .flexibleWidth]
container?.layer.cornerRadius = 5
container?.layer.borderWidth = 1
container?.layer.borderColor = UIColor.black.cgColor
self.addSubview(content)
}
}
extension Date {
static func dateFromString(_ stringDate:String, timeZone:Bool) -> Date {
var dateToReturn:Date = Date();
let formatters = [
"dd-MM-yyyy HH:mm",
"yyyy-MM-dd"
].map { (format: String) -> DateFormatter in
let formatter = DateFormatter()
formatter.dateFormat = format
if timeZone {
formatter.timeZone = TimeZone(abbreviation: "UTC");
}
return formatter
}
for formatter in formatters {
if let date = formatter.date(from: stringDate) {
dateToReturn = date;
}
}
return dateToReturn;
}
}
| mit | 6a2e9d1a1a6edadc63e8e7bdc96d37ba | 35.9625 | 356 | 0.499966 | 5.022079 | false | false | false | false |
wrutkowski/Lucid-Weather-Clock | Pods/Charts/Charts/Classes/Renderers/ScatterChartRenderer.swift | 6 | 15980 | //
// ScatterChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class ScatterChartRenderer: LineScatterCandleRadarChartRenderer
{
open weak var dataProvider: ScatterChartDataProvider?
public init(dataProvider: ScatterChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
open override func drawData(context: CGContext)
{
guard let scatterData = dataProvider?.scatterData else { return }
for i in 0 ..< scatterData.dataSetCount
{
guard let set = scatterData.getDataSetByIndex(i) else { continue }
if set.visible
{
if !(set is IScatterChartDataSet)
{
fatalError("Datasets for ScatterChartRenderer must conform to IScatterChartDataSet")
}
drawDataSet(context: context, dataSet: set as! IScatterChartDataSet)
}
}
}
private var _lineSegments = [CGPoint](repeating: CGPoint(), count: 2)
open func drawDataSet(context: CGContext, dataSet: IScatterChartDataSet)
{
guard let dataProvider = dataProvider,
let animator = animator
else { return }
let trans = dataProvider.getTransformer(dataSet.axisDependency)
let phaseY = animator.phaseY
let entryCount = dataSet.entryCount
let shapeSize = dataSet.scatterShapeSize
let shapeHalf = shapeSize / 2.0
let shapeHoleSizeHalf = dataSet.scatterShapeHoleRadius
let shapeHoleSize = shapeHoleSizeHalf * 2.0
let shapeHoleColor = dataSet.scatterShapeHoleColor
let shapeStrokeSize = (shapeSize - shapeHoleSize) / 2.0
let shapeStrokeSizeHalf = shapeStrokeSize / 2.0
var point = CGPoint()
let valueToPixelMatrix = trans.valueToPixelMatrix
let shape = dataSet.scatterShape
context.saveGState()
for j in 0 ..< Int(min(ceil(CGFloat(entryCount) * animator.phaseX), CGFloat(entryCount)))
{
guard let e = dataSet.entryForIndex(j) else { continue }
point.x = CGFloat(e.xIndex)
point.y = CGFloat(e.value) * phaseY
point = point.applying(valueToPixelMatrix);
if (!viewPortHandler.isInBoundsRight(point.x))
{
break
}
if (!viewPortHandler.isInBoundsLeft(point.x) || !viewPortHandler.isInBoundsY(point.y))
{
continue
}
if (shape == .square)
{
if shapeHoleSize > 0.0
{
context.setStrokeColor(dataSet.colorAt(j).cgColor)
context.setLineWidth(shapeStrokeSize)
var rect = CGRect()
rect.origin.x = point.x - shapeHoleSizeHalf - shapeStrokeSizeHalf
rect.origin.y = point.y - shapeHoleSizeHalf - shapeStrokeSizeHalf
rect.size.width = shapeHoleSize + shapeStrokeSize
rect.size.height = shapeHoleSize + shapeStrokeSize
context.stroke(rect)
if let shapeHoleColor = shapeHoleColor
{
context.setFillColor(shapeHoleColor.cgColor)
rect.origin.x = point.x - shapeHoleSizeHalf
rect.origin.y = point.y - shapeHoleSizeHalf
rect.size.width = shapeHoleSize
rect.size.height = shapeHoleSize
context.fill(rect)
}
}
else
{
context.setFillColor(dataSet.colorAt(j).cgColor)
var rect = CGRect()
rect.origin.x = point.x - shapeHalf
rect.origin.y = point.y - shapeHalf
rect.size.width = shapeSize
rect.size.height = shapeSize
context.fill(rect)
}
}
else if (shape == .circle)
{
if shapeHoleSize > 0.0
{
context.setStrokeColor(dataSet.colorAt(j).cgColor)
context.setLineWidth(shapeStrokeSize)
var rect = CGRect()
rect.origin.x = point.x - shapeHoleSizeHalf - shapeStrokeSizeHalf
rect.origin.y = point.y - shapeHoleSizeHalf - shapeStrokeSizeHalf
rect.size.width = shapeHoleSize + shapeStrokeSize
rect.size.height = shapeHoleSize + shapeStrokeSize
context.strokeEllipse(in: rect)
if let shapeHoleColor = shapeHoleColor
{
context.setFillColor(shapeHoleColor.cgColor)
rect.origin.x = point.x - shapeHoleSizeHalf
rect.origin.y = point.y - shapeHoleSizeHalf
rect.size.width = shapeHoleSize
rect.size.height = shapeHoleSize
context.fillEllipse(in: rect)
}
}
else
{
context.setFillColor(dataSet.colorAt(j).cgColor)
var rect = CGRect()
rect.origin.x = point.x - shapeHalf
rect.origin.y = point.y - shapeHalf
rect.size.width = shapeSize
rect.size.height = shapeSize
context.fillEllipse(in: rect)
}
}
else if (shape == .triangle)
{
context.setFillColor(dataSet.colorAt(j).cgColor)
// create a triangle path
context.beginPath()
context.move(to: CGPoint(x: point.x, y: point.y - shapeHalf))
context.addLine(to: CGPoint(x: point.x + shapeHalf, y: point.y + shapeHalf))
context.addLine(to: CGPoint(x: point.x - shapeHalf, y: point.y + shapeHalf))
if shapeHoleSize > 0.0
{
context.addLine(to: CGPoint(x: point.x, y: point.y - shapeHalf))
context.move(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x + shapeHalf - shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x, y: point.y - shapeHalf + shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
}
context.closePath()
context.fillPath()
if shapeHoleSize > 0.0 && shapeHoleColor != nil
{
context.setFillColor(shapeHoleColor!.cgColor)
// create a triangle path
context.beginPath()
context.move(to: CGPoint(x: point.x, y: point.y - shapeHalf + shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x + shapeHalf - shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.closePath()
context.fillPath()
}
}
else if (shape == .cross)
{
context.setStrokeColor(dataSet.colorAt(j).cgColor)
_lineSegments[0].x = point.x - shapeHalf
_lineSegments[0].y = point.y
_lineSegments[1].x = point.x + shapeHalf
_lineSegments[1].y = point.y
context.strokeLineSegments(between: _lineSegments)
_lineSegments[0].x = point.x
_lineSegments[0].y = point.y - shapeHalf
_lineSegments[1].x = point.x
_lineSegments[1].y = point.y + shapeHalf
context.strokeLineSegments(between: _lineSegments)
}
else if (shape == .x)
{
context.setStrokeColor(dataSet.colorAt(j).cgColor)
_lineSegments[0].x = point.x - shapeHalf
_lineSegments[0].y = point.y - shapeHalf
_lineSegments[1].x = point.x + shapeHalf
_lineSegments[1].y = point.y + shapeHalf
context.strokeLineSegments(between: _lineSegments)
_lineSegments[0].x = point.x + shapeHalf
_lineSegments[0].y = point.y - shapeHalf
_lineSegments[1].x = point.x - shapeHalf
_lineSegments[1].y = point.y + shapeHalf
context.strokeLineSegments(between: _lineSegments)
}
else if (shape == .custom)
{
context.setFillColor(dataSet.colorAt(j).cgColor)
let customShape = dataSet.customScatterShape
if customShape == nil
{
return
}
// transform the provided custom path
context.saveGState()
context.translateBy(x: point.x, y: point.y)
context.beginPath()
context.addPath(customShape!)
context.fillPath()
context.restoreGState()
}
}
context.restoreGState()
}
open override func drawValues(context: CGContext)
{
guard let dataProvider = dataProvider,
let scatterData = dataProvider.scatterData,
let animator = animator
else { return }
// if values are drawn
if (scatterData.yValCount < Int(ceil(CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleX)))
{
guard let dataSets = scatterData.dataSets as? [IScatterChartDataSet] else { return }
let phaseX = max(0.0, min(1.0, animator.phaseX))
let phaseY = animator.phaseY
var pt = CGPoint()
for i in 0 ..< scatterData.dataSetCount
{
let dataSet = dataSets[i]
if !dataSet.drawValuesEnabled || dataSet.entryCount == 0
{
continue
}
let valueFont = dataSet.valueFont
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let entryCount = dataSet.entryCount
let shapeSize = dataSet.scatterShapeSize
let lineHeight = valueFont.lineHeight
for j in 0 ..< Int(ceil(CGFloat(entryCount) * phaseX))
{
guard let e = dataSet.entryForIndex(j) else { break }
pt.x = CGFloat(e.xIndex)
pt.y = CGFloat(e.value) * phaseY
pt = pt.applying(valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
// make sure the lines don't do shitty things outside bounds
if ((!viewPortHandler.isInBoundsLeft(pt.x)
|| !viewPortHandler.isInBoundsY(pt.y)))
{
continue
}
let text = formatter.string(from: e.value as NSNumber)
ChartUtils.drawText(
context: context,
text: text!,
point: CGPoint(
x: pt.x,
y: pt.y - shapeSize - lineHeight),
align: .center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
}
}
}
open override func drawExtras(context: CGContext)
{
}
private var _highlightPointBuffer = CGPoint()
open override func drawHighlighted(context: CGContext, indices: [ChartHighlight])
{
guard let dataProvider = dataProvider,
let scatterData = dataProvider.scatterData,
let animator = animator
else { return }
let chartXMax = dataProvider.chartXMax
context.saveGState()
for high in indices
{
let minDataSetIndex = high.dataSetIndex == -1 ? 0 : high.dataSetIndex
let maxDataSetIndex = high.dataSetIndex == -1 ? scatterData.dataSetCount : (high.dataSetIndex + 1)
if maxDataSetIndex - minDataSetIndex < 1 { continue }
for dataSetIndex in minDataSetIndex..<maxDataSetIndex
{
guard let set = scatterData.getDataSetByIndex(dataSetIndex) as? IScatterChartDataSet else { continue }
if !set.highlightEnabled
{
continue
}
context.setStrokeColor(set.highlightColor.cgColor)
context.setLineWidth(set.highlightLineWidth)
if (set.highlightLineDashLengths != nil)
{
context.setLineDash(phase: set.highlightLineDashPhase, lengths: set.highlightLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
let xIndex = high.xIndex; // get the x-position
if (CGFloat(xIndex) > CGFloat(chartXMax) * animator.phaseX)
{
continue
}
let yVal = set.yValForXIndex(xIndex)
if (yVal.isNaN)
{
continue
}
let y = CGFloat(yVal) * animator.phaseY; // get the y-position
_highlightPointBuffer.x = CGFloat(xIndex)
_highlightPointBuffer.y = y
let trans = dataProvider.getTransformer(set.axisDependency)
trans.pointValueToPixel(&_highlightPointBuffer)
// draw the lines
drawHighlightLines(context: context, point: _highlightPointBuffer, set: set)
}
}
context.restoreGState()
}
}
| mit | 9fe6c2bf5f7b6cc2cabb7805678cbf40 | 37.97561 | 132 | 0.494618 | 6.014302 | false | false | false | false |
uasys/swift | test/SILGen/objc_dealloc.swift | 1 | 5278 | // RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
class X { }
func onDestruct() { }
@requires_stored_property_inits
class SwiftGizmo : Gizmo {
var x = X()
// CHECK-LABEL: sil hidden [transparent] @_T012objc_dealloc10SwiftGizmoC1xAA1XCvpfi : $@convention(thin) () -> @owned X
// CHECK: [[FN:%.*]] = function_ref @_T012objc_dealloc1XCACycfC : $@convention(method) (@thick X.Type) -> @owned X
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick X.Type
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]([[METATYPE]]) : $@convention(method) (@thick X.Type) -> @owned X
// CHECK-NEXT: return [[RESULT]] : $X
// CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoC{{[_0-9a-zA-Z]*}}fc
// CHECK: bb0([[SELF_PARAM:%[0-9]+]] : @owned $SwiftGizmo):
override init() {
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var SwiftGizmo }, let, name "self"
// CHECK: [[SELF_UNINIT:%.*]] = mark_uninitialized [derivedselfonly] [[SELF_BOX]] : ${ var SwiftGizmo }
// CHECK: [[SELF_ADDR:%.*]] = project_box [[SELF_UNINIT]]
// CHECK-NOT: ref_element_addr
// CHECK: [[SELF:%.*]] = load [take] [[SELF_ADDR]]
// CHECK-NEXT: [[UPCAST_SELF:%.*]] = upcast [[SELF]] : $SwiftGizmo to $Gizmo
// CHECK-NEXT: [[BORROWED_UPCAST_SELF:%.*]] = begin_borrow [[UPCAST_SELF]]
// CHECK-NEXT: [[DOWNCAST_BORROWED_UPCAST_SELF:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_SELF]] : $Gizmo to $SwiftGizmo
// CHECK-NEXT: super_method [volatile] [[DOWNCAST_BORROWED_UPCAST_SELF]] : $SwiftGizmo
// CHECK-NEXT: end_borrow [[BORROWED_UPCAST_SELF]] from [[UPCAST_SELF]]
// CHECK: return
super.init()
}
// CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoCfD : $@convention(method) (@owned SwiftGizmo) -> ()
deinit {
// CHECK: bb0([[SELF:%[0-9]+]] : @owned $SwiftGizmo):
// Call onDestruct()
// CHECK: [[ONDESTRUCT_REF:%[0-9]+]] = function_ref @_T012objc_dealloc10onDestructyyF : $@convention(thin) () -> ()
// CHECK: [[ONDESTRUCT_RESULT:%[0-9]+]] = apply [[ONDESTRUCT_REF]]() : $@convention(thin) () -> ()
onDestruct()
// Note: don't destroy instance variables
// CHECK-NOT: ref_element_addr
// Call super -dealloc.
// CHECK: [[SUPER_DEALLOC:%[0-9]+]] = super_method [[SELF]] : $SwiftGizmo, #Gizmo.deinit!deallocator.foreign : (Gizmo) -> () -> (), $@convention(objc_method) (Gizmo) -> ()
// CHECK: [[SUPER:%[0-9]+]] = upcast [[SELF]] : $SwiftGizmo to $Gizmo
// CHECK: [[SUPER_DEALLOC_RESULT:%[0-9]+]] = apply [[SUPER_DEALLOC]]([[SUPER]]) : $@convention(objc_method) (Gizmo) -> ()
// CHECK: end_lifetime [[SUPER]]
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
}
// Objective-C deallocation deinit thunk (i.e., -dealloc).
// CHECK-LABEL: sil hidden [thunk] @_T012objc_dealloc10SwiftGizmoCfDTo : $@convention(objc_method) (SwiftGizmo) -> ()
// CHECK: bb0([[SELF:%[0-9]+]] : @unowned $SwiftGizmo):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[GIZMO_DTOR:%[0-9]+]] = function_ref @_T012objc_dealloc10SwiftGizmoCfD : $@convention(method) (@owned SwiftGizmo) -> ()
// CHECK: [[RESULT:%[0-9]+]] = apply [[GIZMO_DTOR]]([[SELF_COPY]]) : $@convention(method) (@owned SwiftGizmo) -> ()
// CHECK: return [[RESULT]] : $()
// Objective-C IVar initializer (i.e., -.cxx_construct)
// CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoCfeTo : $@convention(objc_method) (@owned SwiftGizmo) -> @owned SwiftGizmo
// CHECK: bb0([[SELF_PARAM:%[0-9]+]] : @owned $SwiftGizmo):
// CHECK-NEXT: debug_value [[SELF_PARAM]] : $SwiftGizmo, let, name "self"
// CHECK-NEXT: [[SELF:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_PARAM]] : $SwiftGizmo
// CHECK: [[XINIT:%[0-9]+]] = function_ref @_T012objc_dealloc10SwiftGizmoC1xAA1XCvpfi
// CHECK-NEXT: [[XOBJ:%[0-9]+]] = apply [[XINIT]]() : $@convention(thin) () -> @owned X
// CHECK-NEXT: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK-NEXT: [[X:%[0-9]+]] = ref_element_addr [[BORROWED_SELF]] : $SwiftGizmo, #SwiftGizmo.x
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X]] : $*X
// CHECK-NEXT: assign [[XOBJ]] to [[WRITE]] : $*X
// CHECK-NEXT: end_access [[WRITE]] : $*X
// CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]]
// CHECK-NEXT: return [[SELF]] : $SwiftGizmo
// Objective-C IVar destroyer (i.e., -.cxx_destruct)
// CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoCfETo : $@convention(objc_method) (SwiftGizmo) -> ()
// CHECK: bb0([[SELF:%[0-9]+]] : @unowned $SwiftGizmo):
// CHECK-NEXT: debug_value [[SELF]] : $SwiftGizmo, let, name "self"
// CHECK-NEXT: [[SELF_BORROW:%.*]] = begin_borrow [[SELF]]
// CHECK-NEXT: [[X:%[0-9]+]] = ref_element_addr [[SELF_BORROW]] : $SwiftGizmo, #SwiftGizmo.x
// CHECK-NEXT: destroy_addr [[X]] : $*X
// CHECK-NEXT: end_borrow [[SELF_BORROW]] from [[SELF]]
// CHECK-NEXT: [[RESULT:%[0-9]+]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
}
// CHECK-NOT: sil hidden [thunk] @_T0So11SwiftGizmo2CfETo : $@convention(objc_method) (SwiftGizmo2) -> ()
class SwiftGizmo2 : Gizmo {
}
| apache-2.0 | 871fde083f0a76293e217b1b4174d6a4 | 54.557895 | 177 | 0.601364 | 3.351111 | false | false | false | false |
alexruperez/ARFacebookShareKitActivity | Example/ARFacebookShareKitActivity/ViewController.swift | 1 | 1746 | //
// ViewController.swift
// ARFacebookShareKitActivity
//
// Created by alexruperez on 06/01/2016.
// Copyright (c) 2016 alexruperez. All rights reserved.
//
import UIKit
import ARFacebookShareKitActivity
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var linkField: UITextField!
@IBOutlet weak var shareButton: UIButton!
@IBAction func shareAction(sender: AnyObject) {
var items = [AnyObject]()
if let text = textField.text, text.characters.count > 0 {
items.append(text as AnyObject)
}
if let text = linkField.text, text.characters.count > 0 {
if let linkURL = NSURL(string: linkField.text!) {
items.append(linkURL)
}
}
let shareViewController = UIActivityViewController(activityItems: items, applicationActivities: [AppInviteActivity(), ShareLinkActivity()])
shareViewController.excludedActivityTypes = [.postToTwitter, .postToWeibo, .message, .mail, .print, .copyToPasteboard, .assignToContact, .saveToCameraRoll, .addToReadingList, .postToFlickr, .postToVimeo, .postToTencentWeibo, .airDrop]
if let popoverPresentationController = shareViewController.popoverPresentationController {
popoverPresentationController.sourceView = shareButton
popoverPresentationController.sourceRect = CGRect(x: shareButton.frame.width/2, y: 0, width: 0, height: 0)
}
self.present(shareViewController, animated: true, completion: nil)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | a5414b893aa1e758bc4f58b786f3d61a | 36.956522 | 242 | 0.690149 | 5.06087 | false | false | false | false |
rsyncOSX/RsyncOSX | RsyncOSX/DecodeConfiguration.swift | 1 | 6201 | //
// DecodeConfigJSON.swift
// RsyncOSX
//
// Created by Thomas Evensen on 17/10/2020.
// Copyright © 2020 Thomas Evensen. All rights reserved.
//
// Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport
import Foundation
struct DecodeConfiguration: Codable {
let backupID: String?
let dateRun: String?
let haltshelltasksonerror: Int?
let hiddenID: Int?
let localCatalog: String?
let offsiteCatalog: String?
let offsiteServer: String?
let offsiteUsername: String?
let parameter1: String?
let parameter10: String?
let parameter11: String?
let parameter12: String?
let parameter13: String?
let parameter14: String?
let parameter2: String?
let parameter3: String?
let parameter4: String?
let parameter5: String?
let parameter6: String?
let parameter8: String?
let parameter9: String?
let rsyncdaemon: Int?
let sshkeypathandidentityfile: String?
let sshport: Int?
let task: String?
let snapdayoffweek: String?
let snaplast: Int?
let executepretask: Int?
let pretask: String?
let executeposttask: Int?
let posttask: String?
let snapshotnum: Int?
enum CodingKeys: String, CodingKey {
case backupID
case dateRun
case haltshelltasksonerror
case hiddenID
case localCatalog
case offsiteCatalog
case offsiteServer
case offsiteUsername
case parameter1
case parameter10
case parameter11
case parameter12
case parameter13
case parameter14
case parameter2
case parameter3
case parameter4
case parameter5
case parameter6
case parameter8
case parameter9
case rsyncdaemon
case sshkeypathandidentityfile
case sshport
case task
case snapdayoffweek
case snaplast
case executepretask
case pretask
case executeposttask
case posttask
case snapshotnum
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
backupID = try values.decodeIfPresent(String.self, forKey: .backupID)
dateRun = try values.decodeIfPresent(String.self, forKey: .dateRun)
haltshelltasksonerror = try values.decodeIfPresent(Int.self, forKey: .haltshelltasksonerror)
hiddenID = try values.decodeIfPresent(Int.self, forKey: .hiddenID)
localCatalog = try values.decodeIfPresent(String.self, forKey: .localCatalog)
offsiteCatalog = try values.decodeIfPresent(String.self, forKey: .offsiteCatalog)
offsiteServer = try values.decodeIfPresent(String.self, forKey: .offsiteServer)
offsiteUsername = try values.decodeIfPresent(String.self, forKey: .offsiteUsername)
parameter1 = try values.decodeIfPresent(String.self, forKey: .parameter1)
parameter10 = try values.decodeIfPresent(String.self, forKey: .parameter10)
parameter11 = try values.decodeIfPresent(String.self, forKey: .parameter11)
parameter12 = try values.decodeIfPresent(String.self, forKey: .parameter12)
parameter13 = try values.decodeIfPresent(String.self, forKey: .parameter13)
parameter14 = try values.decodeIfPresent(String.self, forKey: .parameter14)
parameter2 = try values.decodeIfPresent(String.self, forKey: .parameter2)
parameter3 = try values.decodeIfPresent(String.self, forKey: .parameter3)
parameter4 = try values.decodeIfPresent(String.self, forKey: .parameter4)
parameter5 = try values.decodeIfPresent(String.self, forKey: .parameter5)
parameter6 = try values.decodeIfPresent(String.self, forKey: .parameter6)
parameter8 = try values.decodeIfPresent(String.self, forKey: .parameter8)
parameter9 = try values.decodeIfPresent(String.self, forKey: .parameter9)
rsyncdaemon = try values.decodeIfPresent(Int.self, forKey: .rsyncdaemon)
sshkeypathandidentityfile = try values.decodeIfPresent(String.self, forKey: .sshkeypathandidentityfile)
sshport = try values.decodeIfPresent(Int.self, forKey: .sshport)
task = try values.decodeIfPresent(String.self, forKey: .task)
snapdayoffweek = try values.decodeIfPresent(String.self, forKey: .snapdayoffweek)
snaplast = try values.decodeIfPresent(Int.self, forKey: .snaplast)
executepretask = try values.decodeIfPresent(Int.self, forKey: .executepretask)
pretask = try values.decodeIfPresent(String.self, forKey: .pretask)
executeposttask = try values.decodeIfPresent(Int.self, forKey: .executeposttask)
posttask = try values.decodeIfPresent(String.self, forKey: .posttask)
snapshotnum = try values.decodeIfPresent(Int.self, forKey: .snapshotnum)
}
// This init is used in WriteConfigurationJSON
init(_ data: Configuration) {
backupID = data.backupID
dateRun = data.dateRun
haltshelltasksonerror = data.haltshelltasksonerror
hiddenID = data.hiddenID
localCatalog = data.localCatalog
offsiteCatalog = data.offsiteCatalog
offsiteServer = data.offsiteServer
offsiteUsername = data.offsiteUsername
parameter1 = data.parameter1
parameter10 = data.parameter10
parameter11 = data.parameter11
parameter12 = data.parameter12
parameter13 = data.parameter13
parameter14 = data.parameter14
parameter2 = data.parameter2
parameter3 = data.parameter3
parameter4 = data.parameter4
parameter5 = data.parameter5
parameter6 = data.parameter6
parameter8 = data.parameter8
parameter9 = data.parameter9
rsyncdaemon = data.rsyncdaemon
sshkeypathandidentityfile = data.sshkeypathandidentityfile
sshport = data.sshport
task = data.task
snapdayoffweek = data.snapdayoffweek
snaplast = data.snaplast
executepretask = data.executepretask
pretask = data.pretask
executeposttask = data.executeposttask
posttask = data.posttask
snapshotnum = data.snapshotnum
}
}
| mit | d8f31f8a5174ed52181cf57f05c5b32f | 39.789474 | 111 | 0.693548 | 4.61653 | false | false | false | false |
martinverup/g2planner | g2planner/main.swift | 1 | 1389 | //
// main.swift
// g2planner
//
// Created by Martin Verup on 20/07/2017.
//
//
import Foundation
let args = CommandLine.arguments
if args.count < 3 {
print("Not enough parameters given")
exit(0)
}
let world = Map.createMap()
let dijkstra = Dijkstra(world)
let source: City
let destination: City
if let from = City(rawValue: args[1]) {
source = from
} else {
print("City \"\(args[1])\" not recognized")
exit(0)
}
if let to = City(rawValue: args[2]) {
destination = to
} else {
print("City \"\(args[2])\" not recognized")
exit(0)
}
let fastestPath = dijkstra.getRoute(from: source, to: destination, searchFor: Dijkstra.Parameter.fastest)
let fastestNoPlanePath = dijkstra.getRoute(from: source, to: destination, searchFor: Dijkstra.Parameter.fastest, exclude: Route.Method.Plane)
let cheapestPath = dijkstra.getRoute(from: source, to: destination, searchFor: Dijkstra.Parameter.cheapest)
let cheapestNoBusPath = dijkstra.getRoute(from: source, to: destination, searchFor: Dijkstra.Parameter.cheapest, exclude: Route.Method.Bus)
print("Routes from \(source.rawValue) to \(destination.rawValue):\n")
print("Fastest:")
Dijkstra.prettyPrint(fastestPath)
print("Cheapest:")
Dijkstra.prettyPrint(cheapestPath)
print("Cheapest (no bus):")
Dijkstra.prettyPrint(cheapestNoBusPath)
print("Fastest (no plane):")
Dijkstra.prettyPrint(fastestNoPlanePath)
| mit | ab1944afd6ea28f792ba250c9dce6f49 | 24.722222 | 141 | 0.725702 | 3.455224 | false | true | false | false |
IAskWind/IAWExtensionTool | IAWExtensionTool/IAWExtensionTool/Classes/Constant/IAW_Constant.swift | 1 | 3394 | //
// IAWConstant.swift
// CtkApp
//
// Created by winston on 16/12/9.
// Copyright © 2016年 winston. All rights reserved.
//
import UIKit
/// 第一次启动
public let IAW_FirstLaunch = "firstLaunch"
/// 是否登录open
public let IAW_IsLogin = "isLogin"
public let IAW_AccessToken = "accessToken"
public let IAW_NavigationH: CGFloat = 64
/// 间距
public let IAW_KMargin: CGFloat = 10.0
/// 圆角
// UITextField 高度
public let IAW_TextFieldH: CGFloat = 55
//左边距
public let IAW_LeftMargin: CGFloat = 10
// 屏幕的宽
public let IAW_ScreenW = UIScreen.main.bounds.size.width
// 屏幕的高
public let IAW_ScreenH = UIScreen.main.bounds.size.height
public let IAW_Window = UIApplication.shared.keyWindow!
///公用线条
//public var IAW_CommonLine:UIView = {
// let line = UIView()
// line.alpha = 0.2
// line.backgroundColor = UIColor.gray
// return line
//}()
//公用线条
public func IAW_CommonLine(lineColor:UIColor = UIColor.gray,alpha:CGFloat = 1)-> UIView{
let line = UIView()
line.alpha = alpha
line.backgroundColor = lineColor
return line
}
//全局NavBar的颜色
public var IAW_GlobalNavBarColor:UIColor {
return IAW_GlobalRedColor
}
/// 背景灰色
public var IAW_GlobalBgColor: UIColor {
return UIColor.iaw_Color(240, g: 240, b: 240, a: 1)
}
/// 红色
public var IAW_GlobalRedColor:UIColor {
return UIColor.iaw_Color(245, g: 80, b: 83, a: 1.0)
}
/// 蓝色
public var IAW_GlobalBlueColor:UIColor {
return UIColor.iaw_Color(84, g: 142, b: 252, a: 1.0)
}
// 颜色值如 #FFFFFF
public func IAW_HEXColor(_ hexColor:String,alpha:CGFloat = 1) -> UIColor {
var color = UIColor.red
var cStr : String = hexColor.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
if cStr.hasPrefix("#") {
let index = cStr.index(after: cStr.startIndex)
cStr = cStr.substring(from: index)
}
if cStr.count != 6 {
return UIColor.black
}
let rRange = cStr.startIndex ..< cStr.index(cStr.startIndex, offsetBy: 2)
let rStr = cStr.substring(with: rRange)
let gRange = cStr.index(cStr.startIndex, offsetBy: 2) ..< cStr.index(cStr.startIndex, offsetBy: 4)
let gStr = cStr.substring(with: gRange)
let bIndex = cStr.index(cStr.endIndex, offsetBy: -2)
let bStr = cStr.substring(from: bIndex)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
Scanner(string: rStr).scanHexInt32(&r)
Scanner(string: gStr).scanHexInt32(&g)
Scanner(string: bStr).scanHexInt32(&b)
color = UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
return color
}
//px处理 labelMapWidth 标注图用的屏幕宽 pt单位 默认6s为375
public func IAW_PX(px:CGFloat,labelMapWidth:CGFloat = 375)-> CGFloat{
return (IAW_ScreenW/labelMapWidth)*(px/2)
}
/**view设置点击事件封装方法
例:iaw_SetViewClick(dealView: leftView, target: self, viewClick: #selector(showPsd(_:)))
实现方法:func showPsd(_ sender:UITapGestureRecognizer){}
**/
public func iaw_SetViewClick(dealView:UIView,target:Any?,viewClick:Selector){
dealView.isUserInteractionEnabled = true
let tapGR = UITapGestureRecognizer(target: target, action: viewClick)
tapGR.numberOfTapsRequired = 1
dealView.addGestureRecognizer(tapGR)
}
| mit | 736d78c169c89e4e6773d2d335835237 | 26.330508 | 111 | 0.686512 | 3.338509 | false | false | false | false |
morizotter/KeyboardObserver | KeyboardObserver/KeyboardObserver.swift | 1 | 4224 | //
// Keyboard.swift
// Demo
//
// Created by MORITANAOKI on 2015/12/14.
// Copyright © 2015年 molabo. All rights reserved.
//
import UIKit
public enum KeyboardEventType: CaseIterable {
case willShow
case didShow
case willHide
case didHide
case willChangeFrame
case didChangeFrame
public var notificationName: NSNotification.Name {
switch self {
case .willShow:
return UIResponder.keyboardWillShowNotification
case .didShow:
return UIResponder.keyboardDidShowNotification
case .willHide:
return UIResponder.keyboardWillHideNotification
case .didHide:
return UIResponder.keyboardDidHideNotification
case .willChangeFrame:
return UIResponder.keyboardWillChangeFrameNotification
case .didChangeFrame:
return UIResponder.keyboardDidChangeFrameNotification
}
}
init?(name: NSNotification.Name) {
switch name {
case UIResponder.keyboardWillShowNotification:
self = .willShow
case UIResponder.keyboardDidShowNotification:
self = .didShow
case UIResponder.keyboardWillHideNotification:
self = .willHide
case UIResponder.keyboardDidHideNotification:
self = .didHide
case UIResponder.keyboardWillChangeFrameNotification:
self = .willChangeFrame
case UIResponder.keyboardDidChangeFrameNotification:
self = .didChangeFrame
default:
return nil
}
}
static func allEventNames() -> [NSNotification.Name] {
return allCases.map({ $0.notificationName })
}
}
public struct KeyboardEvent {
public let type: KeyboardEventType
public let keyboardFrameBegin: CGRect
public let keyboardFrameEnd: CGRect
public let curve: UIView.AnimationCurve
public let duration: TimeInterval
public var isLocal: Bool?
public var options: UIView.AnimationOptions {
return UIView.AnimationOptions(rawValue: UInt(curve.rawValue << 16))
}
init?(notification: Notification) {
guard let userInfo = (notification as NSNotification).userInfo else { return nil }
guard let type = KeyboardEventType(name: notification.name) else { return nil }
guard let begin = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue else { return nil }
guard let end = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return nil }
guard
let curveInt = (userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber)?.intValue,
let curve = UIView.AnimationCurve(rawValue: curveInt)
else { return nil }
guard
let durationDouble = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
else { return nil }
self.type = type
self.keyboardFrameBegin = begin
self.keyboardFrameEnd = end
self.curve = curve
self.duration = TimeInterval(durationDouble)
if #available(iOS 9, *) {
guard let isLocalInt = (userInfo[UIResponder.keyboardIsLocalUserInfoKey] as? NSNumber)?.intValue else { return nil }
self.isLocal = isLocalInt == 1
}
}
}
public enum KeyboardState {
case initial
case showing
case shown
case hiding
case hidden
case changing
}
public typealias KeyboardEventClosure = ((_ event: KeyboardEvent) -> Void)
open class KeyboardObserver {
open var state = KeyboardState.initial
open var isEnabled = true
fileprivate var eventClosures = [KeyboardEventClosure]()
deinit {
eventClosures.removeAll()
KeyboardEventType.allEventNames().forEach {
NotificationCenter.default.removeObserver(self, name: $0, object: nil)
}
}
public init() {
KeyboardEventType.allEventNames().forEach {
NotificationCenter.default.addObserver(self, selector: #selector(notified(_:)), name: $0, object: nil)
}
}
open func observe(_ event: @escaping KeyboardEventClosure) {
eventClosures.append(event)
}
}
internal extension KeyboardObserver {
@objc func notified(_ notification: Notification) {
guard let event = KeyboardEvent(notification: notification) else { return }
switch event.type {
case .willShow:
state = .showing
case .didShow:
state = .shown
case .willHide:
state = .hiding
case .didHide:
state = .hidden
case .willChangeFrame:
state = .changing
case .didChangeFrame:
state = .shown
}
if !isEnabled { return }
eventClosures.forEach { $0(event) }
}
}
| mit | c823b7cfa32dc547b5e72e2d234c6757 | 26.588235 | 119 | 0.751718 | 4.195825 | false | false | false | false |
fabiomassimo/eidolon | KioskTests/Models/SystemTimeTests.swift | 2 | 1440 | import Quick
import Nimble
import Kiosk
// Note, stubbed json contains a date in 2422
// If this is an issue ( hello future people! ) then move it along a few centuries.
class SystemTimeTests: QuickSpec {
override func spec() {
describe("in sync") {
setupProviderForSuite(Provider.StubbingProvider())
it("returns true") {
let time = SystemTime()
time.syncSignal().subscribeNext { (_) -> Void in
expect(time.inSync()) == true
return
}
}
it("returns a date in the future") {
let time = SystemTime()
time.syncSignal().subscribeNext { (_) -> Void in
let currentYear = yearFromDate(NSDate())
let timeYear = yearFromDate(time.date())
expect(timeYear) > currentYear
expect(timeYear) == 2422
}
}
}
describe("not in sync") {
it("returns false") {
let time = SystemTime()
expect(time.inSync()) == false
}
it("returns current time") {
let time = SystemTime()
let currentYear = yearFromDate(NSDate())
let timeYear = yearFromDate(time.date())
expect(timeYear) == currentYear
}
}
}
}
| mit | a9e3c48504a92e079acdbef660301c8a | 27.8 | 83 | 0.483333 | 5.255474 | false | false | false | false |
cdrage/kedge | vendor/github.com/openshift/origin/cmd/service-catalog/go/src/github.com/kubernetes-incubator/service-catalog/vendor/github.com/googleapis/gnostic/plugins/gnostic-swift-sample/Sources/main.swift | 89 | 2309 | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
func printDocument(document:Openapi_V2_Document,
name:String,
version:String) -> String {
var code = CodePrinter()
code.print("READING \(name) (\(version))\n")
code.print("Swagger: \(document.swagger)\n")
code.print("Host: \(document.host)\n")
code.print("BasePath: \(document.basePath)\n")
if document.hasInfo {
code.print("Info:\n")
code.indent()
if document.info.title != "" {
code.print("Title: \(document.info.title)\n")
}
if document.info.description_p != "" {
code.print("Description: \(document.info.description_p)\n")
}
if document.info.version != "" {
code.print("Version: \(document.info.version)\n")
}
code.outdent()
}
code.print("Paths:\n")
code.indent()
for pair in document.paths.path {
let v = pair.value
if v.hasGet {
code.print("GET \(pair.name)\n")
}
if v.hasPost {
code.print("POST \(pair.name)\n")
}
}
code.outdent()
return code.content
}
func main() throws {
var response = Openapi_Plugin_V1_Response()
let rawRequest = try Stdin.readall()
let request = try Openapi_Plugin_V1_Request(serializedData: rawRequest)
let wrapper = request.wrapper
let document = try Openapi_V2_Document(serializedData:wrapper.value)
let report = printDocument(document:document, name:wrapper.name, version:wrapper.version)
if let reportData = report.data(using:.utf8) {
var file = Openapi_Plugin_V1_File()
file.name = "report.txt"
file.data = reportData
response.files.append(file)
}
let serializedResponse = try response.serializedData()
Stdout.write(bytes: serializedResponse)
}
try main()
| apache-2.0 | 334317130ea0c8349ec36fe1b5f8ec8a | 31.521127 | 91 | 0.675617 | 3.6944 | false | false | false | false |
gurenupet/hah-auth-ios-swift | hah-auth-ios-swift/Pods/Mixpanel-swift/Mixpanel/DeviceInfoMessage.swift | 4 | 6111 | //
// DeviceInfoMessage.swift
// Mixpanel
//
// Created by Yarden Eitan on 8/26/16.
// Copyright © 2016 Mixpanel. All rights reserved.
//
import Foundation
import UIKit
class DeviceInfoRequest: BaseWebSocketMessage {
init() {
super.init(type: MessageType.deviceInfoRequest.rawValue)
}
override func responseCommand(connection: WebSocketWrapper) -> Operation? {
let operation = BlockOperation { [weak connection] in
guard let connection = connection else {
return
}
var response: DeviceInfoResponse? = nil
DispatchQueue.main.sync {
let currentDevice = UIDevice.current
let infoResponseInput = InfoResponseInput(systemName: currentDevice.systemName,
systemVersion: currentDevice.systemVersion,
appVersion: Bundle.main.infoDictionary?["CFBundleVersion"] as? String,
appRelease: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String,
deviceName: currentDevice.name,
deviceModel: currentDevice.model,
libLanguage: "Swift",
libVersion: "2.6", // workaround for a/b testing
availableFontFamilies: self.availableFontFamilies(),
mainBundleIdentifier: Bundle.main.bundleIdentifier,
tweaks: self.getTweaks())
response = DeviceInfoResponse(infoResponseInput)
}
connection.send(message: response)
}
return operation
}
func availableFontFamilies() -> [[String: AnyObject]] {
var fontFamilies = [[String: AnyObject]]()
let systemFonts = [UIFont.systemFont(ofSize: 17), UIFont.boldSystemFont(ofSize: 17), UIFont.italicSystemFont(ofSize: 17)]
var foundSystemFamily = false
for familyName in UIFont.familyNames {
var fontNames = UIFont.fontNames(forFamilyName: familyName)
if familyName == systemFonts.first!.familyName {
for systemFont in systemFonts {
if !fontNames.contains(systemFont.fontName) {
fontNames.append(systemFont.fontName)
}
}
foundSystemFamily = true
}
fontFamilies.append(["family": familyName as AnyObject,
"font_names": UIFont.fontNames(forFamilyName: familyName) as AnyObject])
}
if !foundSystemFamily {
fontFamilies.append(["family": systemFonts.first!.familyName as AnyObject,
"font_names": systemFonts.map { $0.fontName } as AnyObject])
}
return fontFamilies
}
func getTweaks() -> [[String: AnyObject]] {
var tweaks = [[String: AnyObject]]()
guard let allTweaks = MixpanelTweaks.defaultStore.tweakCollections["Mixpanel"]?.allTweaks else {
return tweaks
}
for tweak in allTweaks {
let (value, defaultValue, min, max) = MixpanelTweaks.defaultStore.currentViewDataForTweak(tweak).getValueDefaultMinMax()
let tweakDict = ["name": tweak.tweakName as AnyObject,
"encoding": getEncoding(value) as AnyObject,
"value": value as AnyObject,
"default": defaultValue as AnyObject,
"minimum": min as AnyObject? ?? defaultValue as AnyObject,
"maximum": max as AnyObject? ?? defaultValue as AnyObject] as [String : AnyObject]
tweaks.append(tweakDict)
}
return tweaks
}
func getEncoding(_ value: TweakableType) -> String {
if value is Double || value is CGFloat {
return "d"
} else if value is String {
return "@"
} else if value is Int {
return "i"
} else if value is UInt {
return "I"
}
return ""
}
}
struct InfoResponseInput {
let systemName: String
let systemVersion: String
let appVersion: String?
let appRelease: String?
let deviceName: String
let deviceModel: String
let libLanguage: String
let libVersion: String?
let availableFontFamilies: [[String: Any]]
let mainBundleIdentifier: String?
let tweaks: [[String: Any]]
}
class DeviceInfoResponse: BaseWebSocketMessage {
init(_ infoResponse: InfoResponseInput) {
var payload = [String: AnyObject]()
payload["system_name"] = infoResponse.systemName as AnyObject
payload["system_version"] = infoResponse.systemVersion as AnyObject
payload["device_name"] = infoResponse.deviceName as AnyObject
payload["device_model"] = infoResponse.deviceModel as AnyObject
payload["available_font_families"] = infoResponse.availableFontFamilies as AnyObject
payload["tweaks"] = infoResponse.tweaks as AnyObject
payload["lib_language"] = infoResponse.libLanguage as AnyObject
if let appVersion = infoResponse.appVersion {
payload["app_version"] = appVersion as AnyObject
}
if let appRelease = infoResponse.appRelease {
payload["app_release"] = appRelease as AnyObject
}
if let libVersion = infoResponse.libVersion {
payload["lib_version"] = libVersion as AnyObject
}
if let mainBundleIdentifier = infoResponse.mainBundleIdentifier {
payload["main_bundle_identifier"] = mainBundleIdentifier as AnyObject
}
super.init(type: MessageType.deviceInfoResponse.rawValue, payload: payload)
}
}
| mit | 15e77bd34676e52f5ab17276fc5eedc6 | 40.849315 | 139 | 0.568576 | 5.753296 | false | false | false | false |
howwayla/taipeiAttractions | taipeiAttractions/AppDataService/TAAppDataService.swift | 1 | 1316 | //
// TAAppDataService.swift
// taipeiAttractions
//
// Created by Hardy on 2016/6/28.
// Copyright © 2016年 Hardy. All rights reserved.
//
import Foundation
class TAAppDataService {
static let sharedInstance = TAAppDataService()
fileprivate init() {}
var categories: [String] = []
var attractions: [TAAttraction] = [] {
didSet {
setupCategories()
setupAttractionsByCategory()
}
}
var attractionsByCategory: [String: [TAAttraction]] = [:]
//MARK:- Setup methods
/**
Setup categories from attractions
*/
fileprivate func setupCategories() {
var newCategories: [String] = []
for category in (attractions.map{ $0.category }) {
guard let category = category else {
continue
}
if !newCategories.contains(category) {
newCategories.append(category)
}
}
self.categories = newCategories
}
fileprivate func setupAttractionsByCategory() {
for category in self.categories {
let attractions = self.attractions.filter{ $0.category == category }
self.attractionsByCategory[category] = attractions
}
}
}
| mit | 6584bf3115f484c81cbbf39a7b5e4053 | 23.314815 | 80 | 0.564356 | 4.899254 | false | false | false | false |
wwu-pi/md2-framework | de.wwu.md2.framework/res/resources/ios/lib/view/widget/MD2TextFieldWidget.swift | 1 | 7127 | //
// MD2TextFieldWidget.swift
// md2-ios-library
//
// Created by Christoph Rieger on 29.07.15.
// Copyright (c) 2015 Christoph Rieger. All rights reserved.
//
import UIKit
/// A regular text field widget.
class MD2TextFieldWidget: NSObject, MD2SingleWidget, MD2AssistedWidget, UITextFieldDelegate {
/// Unique widget identification.
let widgetId: MD2WidgetMapping
/// The view element value. Using a property observer, external changes trigger a UI control update.
var value: MD2Type {
didSet {
updateElement()
}
}
/// Inner dimensions of the screen occupied by the widget.
var dimensions: MD2Dimension?
/// Placeholder text for empty text fields.
var placeholder: MD2String?
/// The native UI control.
var widgetElement: UITextField
/// Text field caption.
var label: MD2String?
/// The tooltip text to display for assistance.
var tooltip: MD2String?
/// The tooltip UI control dimensions.
var tooltipDimensions: MD2Dimension?
/// Text field type, e.g. single-line, multi-line, ...
var type: TextField = TextField.Standard
/// Width of the widget as specified by the model (percentage of the availale width).
var width: Float?
/// The button widget that represents the tooltip control.
var infoButton: MD2ButtonWidget
/**
Default initializer.
:param: widgetId Widget identifier
*/
init(widgetId: MD2WidgetMapping) {
self.widgetId = widgetId
self.value = MD2String()
self.widgetElement = UITextField()
self.infoButton = MD2ButtonWidget(widgetId: self.widgetId)
}
/**
Render the view element, i.e. specifying the position and appearance of the widget.
:param: view The surrounding view element.
:param: controller The responsible view controller.
*/
func render(view: UIView, controller: UIViewController) {
if dimensions == nil {
// Element is not specified in layout. Maybe grid with not enough cells?!
return
}
// Set value
widgetElement.placeholder = placeholder?.platformValue
updateElement()
widgetElement.tag = widgetId.rawValue
widgetElement.addTarget(self, action: "onUpdate", forControlEvents: (UIControlEvents.EditingDidEnd | UIControlEvents.EditingDidEndOnExit))
// Set styling
widgetElement.backgroundColor = UIColor.whiteColor()
widgetElement.borderStyle = UITextBorderStyle.RoundedRect
widgetElement.font = UIFont(name: MD2ViewConfig.FONT_NAME.rawValue, size: CGFloat(MD2ViewConfig.FONT_SIZE))
// Add to surrounding view
widgetElement.delegate = self
view.addSubview(widgetElement)
// If tooltip info is available show info button
if tooltip != nil && tooltip!.isSet() && !tooltip!.equals(MD2String("")) {
infoButton.buttonType = UIButtonType.InfoLight
infoButton.dimensions = self.tooltipDimensions
infoButton.render(view, controller: controller)
}
}
/**
Calculate the dimensions of the widget based on the available bounds. The occupied space of the widget is returned.
*NOTICE* The occupied space may surpass the bounds (and thus the visible screen), if the height of the element is not sufficient. This is not a problem as the screen will scroll automatically.
*NOTICE* The occupied space usually differs from the dimensions property as it refers to the *outer* dimensions in contrast to the dimensions property referring to *inner* dimensions. The difference represents the gutter included in the widget positioning process.
:param: bounds The available screen space.
:returns: The occupied outer dimensions of the widget.
*/
func calculateDimensions(bounds: MD2Dimension) -> MD2Dimension {
var outerDimensions: MD2Dimension = bounds
// If tooltip info is available show info button
if tooltip != nil && tooltip!.isSet() && !tooltip!.equals(MD2String("")) {
outerDimensions = MD2Dimension(
x: bounds.x,
y: bounds.y,
width: bounds.width,
height: MD2ViewConfig.DIMENSION_TEXTFIELD_HEIGHT)
var textFieldDimensions = outerDimensions - MD2Dimension(
x: Float(0.0),
y: Float(0.0),
width: Float(MD2ViewConfig.TOOLTIP_WIDTH),
height: Float(0.0))
// Add gutter
self.dimensions = MD2UIUtil.innerDimensionsWithGutter(textFieldDimensions)
widgetElement.frame = MD2UIUtil.dimensionToCGRect(dimensions!)
self.tooltipDimensions = MD2Dimension(
x: (outerDimensions.x + outerDimensions.width) - Float(MD2ViewConfig.TOOLTIP_WIDTH) - MD2ViewConfig.GUTTER / 2,
// center vertically
y: textFieldDimensions.y + (textFieldDimensions.height - MD2ViewConfig.TOOLTIP_WIDTH) / 2,
width: MD2ViewConfig.TOOLTIP_WIDTH,
height: MD2ViewConfig.TOOLTIP_WIDTH)
infoButton.widgetElement?.frame = MD2UIUtil.dimensionToCGRect(tooltipDimensions!)
return outerDimensions
} else {
// Normal full-width field
outerDimensions = MD2Dimension(
x: bounds.x,
y: bounds.y,
width: bounds.width,
height: MD2ViewConfig.DIMENSION_TEXTFIELD_HEIGHT)
// Add gutter
self.dimensions = MD2UIUtil.innerDimensionsWithGutter(outerDimensions)
widgetElement.frame = MD2UIUtil.dimensionToCGRect(dimensions!)
return outerDimensions
}
}
/**
Enumeration for all possible text field types.
*TODO* Currently, only standard text field (single-line) are supported).
*/
enum TextField {
case Standard
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.widgetElement.resignFirstResponder()
return true
}
/// Enable the view element.
func enable() {
self.widgetElement.enabled = true
}
/// Disable the view element.
func disable() {
self.widgetElement.enabled = false
}
/**
Target for the value change event. Updates the stored value and passes it to the respective widget wrapper which will process the value, e.g. applying validators and firing further events.
*/
func onUpdate() {
self.value = MD2String(self.widgetElement.text)
MD2WidgetRegistry.instance.getWidget(widgetId)?.setValue(self.value)
}
/**
Update the view element after its value was changed externally.
*/
func updateElement() {
self.widgetElement.text = value.toString()
}
}
| apache-2.0 | 599a33ae0920445c8d3fe07bac45a2cb | 35.362245 | 272 | 0.629157 | 5.076211 | false | true | false | false |
kildevaeld/Sockets | Example/Sockets/ViewController.swift | 1 | 2396 | //
// ViewController.swift
// Sockets
//
// Created by Softshag & Me on 07/29/2015.
// Copyright (c) 2015 Softshag & Me. All rights reserved.
//
import UIKit
import Sockets
func after(delay: Double, _ fn: () -> Void) {
let delayTime = dispatch_time(DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
fn()
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var address: [SocketAddressInfo] = []
var s: SocketServer?
do {
address = try getAddressInfo(nil, port:3000, family: .Inet, type: .Stream, options: SocketAddressInfoOption.Passive)
s = try SocketServer(family: address.first!.family, type: .Stream)
} catch {
}
let server = s
//let server = Socket.listen(address)
server?.acceptQueue = dispatch_queue_create("something", DISPATCH_QUEUE_CONCURRENT)
server?.listen(address.first!.address, accept: { (client) -> Void in
let bytes = Bytes("Hello client \(client.remoteAddress)")
client.send(bytes)
let b = client.read()
print(CString(bytes:b.block))
client.send("Harry")
after(5, { () -> Void in
client.send("Somethin good")
client.close()
})
})
let client = Socket.connect(address)
client?.queue = dispatch_queue_create("read", DISPATCH_QUEUE_CONCURRENT)
client?.read({ (data, length) -> Void in
let str = CString(bytes:data)
print("Go from server \(str)")
})
client?.send("Rapper")
//let data = client?.read()
//let str = CString(bytes:data!.block)
//let dd = str.description.dataUsingEncoding(NSUTF8StringEncoding)
//var bytes = Bytes(void: dd!.bytes, length: dd!.length)
//print("Got from server \(str)")
//client?.send(bytes)
// 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.
}
}
| mit | c3f351d83c37e7ca7285f819dce5a6ad | 28.95 | 128 | 0.556344 | 4.428835 | false | false | false | false |
rugheid/Swift-MathEagle | MathEagle/Permutation/Cycle.swift | 1 | 2968 | //
// Cycle.swift
// MathEagle
//
// Created by Rugen Heidbuchel on 31/05/15.
// Copyright (c) 2015 Jorestha Solutions. All rights reserved.
//
/**
A class representing a cycle in a permutation.
*/
open class Cycle: ExpressibleByArrayLiteral, CustomStringConvertible, Hashable {
// MARK: Inner Structure
/**
Represents the cycle. Every element will be replaced by the next element.
The last element will be replaced by the first.
:example: `[0, 1, 2]`:
When this is applied to the array `[1, 2, 3]` this gives `[2, 3, 1]`.
*/
open var cycleRepresentation: [Int] = []
// MARK: Initialisers
/**
Creates an empty cycle.
*/
public init() {}
/**
Creates a cycle with the given cycle representation.
*/
public init(_ cycleRepresentation: [Int]) {
self.cycleRepresentation = cycleRepresentation
}
/**
Creates a cycle with the given cycle representation.
*/
public convenience required init(arrayLiteral elements: Int...) {
self.init(elements)
}
// MARK: Properties
/**
Returns a dictionary representation of the cycle.
:example: (3 4 7) gives [3: 4, 4: 7, 7: 3]
*/
open var dictionaryRepresentation: [Int: Int] {
get {
var dict = [Int: Int]()
for (index, element) in self.cycleRepresentation.enumerated() {
dict[element] = self.cycleRepresentation[index == self.length-1 ? 0 : index+1]
}
return dict
}
}
/**
Returns the length of the cycle.
*/
open var length: Int {
return self.cycleRepresentation.count
}
/**
Retursn the parity of the cycle. The cycle is even when it's length is odd.
*/
open var parity: Parity {
return self.length % 2 == 0 ? .odd : .even
}
/**
Returns a description of the cycle.
:example: (4 3 2)
*/
open var description: String {
let combine = { (a: String, b: Int) in a + (a == "" ? "" : " ") + "\(b)" }
return "(" + self.cycleRepresentation.reduce("", combine) + ")"
}
/**
Returns a hash value for the cycle.
*/
open var hashValue: Int {
//FIXME: This is a bad implementation
return sum(self.cycleRepresentation)
}
}
// MARK: Equatable
/**
Returns whether the two given cycles are equal. This means they have the same effect.
Note that the cycle representations may vary.
*/
public func == (left: Cycle, right: Cycle) -> Bool {
//TODO: This has to be more efficient
return left.dictionaryRepresentation == right.dictionaryRepresentation
}
| mit | add48afc245bb8b87d3e7a5de2629174 | 21.149254 | 94 | 0.534704 | 4.711111 | false | false | false | false |
berzerker-io/soothe | SoothingKit/Source/Commands/InterpolateCommand.swift | 1 | 1130 | import Foundation
import XcodeKit
public struct InterpolateCommand {
// MARK: - Initialization
public init() { }
// MARK: - Command
public func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) {
guard
let selection = invocation.buffer.selections.firstObject as? XCSourceTextRange,
var line = invocation.buffer.lines[selection.start.line] as? String
else { return completionHandler(SelectionError.none) }
guard selection.start.line == selection.end.line else {
return completionHandler(SelectionError.multi)
}
line.insert(")", at: line.index(line.startIndex, offsetBy: selection.end.column))
line.insert("(", at: line.index(line.startIndex, offsetBy: selection.start.column))
line.insert(#"\"#, at: line.index(line.startIndex, offsetBy: selection.start.column))
invocation.buffer.lines.replaceObject(at: selection.start.line, with: line)
selection.start.column += 2
selection.end.column += 2
completionHandler(nil)
}
}
| unlicense | 98c0e6ec4bc4164fa25fd39f261995f1 | 36.666667 | 123 | 0.673451 | 4.593496 | false | false | false | false |
nickplee/Aestheticam | Aestheticam/Vendor/RandomKit/Sources/RandomKit/Extensions/Swift/String+RandomKit.swift | 2 | 8919 | //
// String+RandomKit.swift
// RandomKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Nikolai Vazquez
//
// 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.
//
extension String: Random {
/// Generates a random `String`.
///
/// - returns: Random value in `UnicodeScalar.randomRange` with length of `10`.
public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> String {
return random(ofLength: 10, in: UnicodeScalar.randomRange, using: &randomGenerator)
}
/// Generates a random `String` with a length of `10` inside of the range.
///
/// - parameter range: The range in which the string will be generated.
/// - parameter randomGenerator: The random generator to use.
public static func random<R: RandomGenerator>(in range: Range<UnicodeScalar>,
using randomGenerator: inout R) -> String? {
return random(ofLength: 10, in: range, using: &randomGenerator)
}
/// Generates a random `String` of a given length inside of the range.
///
/// - parameter length: The length for the generated string.
/// - parameter range: The range in which the string will be generated.
/// - parameter randomGenerator: The random generator to use.
public static func random<I: ExpressibleByIntegerLiteral & Strideable, R: RandomGenerator>(ofLength length: I,
in range: Range<UnicodeScalar>,
using randomGenerator: inout R) -> String? where I.Stride: SignedInteger {
if range.isEmpty {
return nil
}
var result = UnicodeScalarView()
for _ in 0 ..< length {
result.append(UnicodeScalar.uncheckedRandom(in: range, using: &randomGenerator))
}
return String(result)
}
/// Generates a random `String` with a length of `10` inside of the closed range.
///
/// - parameter closedRange: The range in which the string will be generated.
/// - parameter randomGenerator: The random generator to use.
public static func random<R: RandomGenerator>(in closedRange: ClosedRange<UnicodeScalar>,
using randomGenerator: inout R) -> String {
return random(ofLength: 10, in: closedRange, using: &randomGenerator)
}
/// Generates a random `String` of a given length inside of the closed range.
///
/// - parameter length: The length for the generated string.
/// - parameter closedRange: The range in which the string will be generated. The default is `UnicodeScalar.randomRange`.
/// - parameter randomGenerator: The random generator to use.
public static func random<I: ExpressibleByIntegerLiteral & Strideable, R: RandomGenerator>(ofLength length: I,
in closedRange: ClosedRange<UnicodeScalar> = UnicodeScalar.randomRange,
using randomGenerator: inout R) -> String where I.Stride: SignedInteger {
var result = UnicodeScalarView()
for _ in 0 ..< length {
result.append(.random(in: closedRange, using: &randomGenerator))
}
return String(result)
}
#if swift(>=4.0)
// No character view for you
#else
/// Generates a random `String` with a length of `10` from `characters`.
///
/// - parameter characters: The characters from which the string will be generated.
/// - parameter randomGenerator: The random generator to use.
public static func random<R: RandomGenerator>(from characters: CharacterView,
using randomGenerator: inout R) -> String? {
return random(ofLength: 10, from: characters, using: &randomGenerator)
}
/// Generates a random `String` of a given length from `characters`.
///
/// - parameter length: The length for the generated string.
/// - parameter characters: The characters from which the string will be generated.
/// - parameter randomGenerator: The random generator to use.
public static func random<I: ExpressibleByIntegerLiteral & Strideable, R: RandomGenerator>(ofLength length: I,
from characters: CharacterView,
using randomGenerator: inout R) -> String? where I.Stride: SignedInteger {
var result = ""
for _ in 0 ..< length {
let random = self.random(using: &randomGenerator)
result.append(random)
}
return result
}
#endif
/// Generates a random `String` with a length of `10` from `scalars`.
///
/// - parameter scalars: The unicode scalars from which the string will be generated.
/// - parameter randomGenerator: The random generator to use.
public static func random<R: RandomGenerator>(from scalars: UnicodeScalarView,
using randomGenerator: inout R) -> String? {
return random(ofLength: 10, from: scalars, using: &randomGenerator)
}
/// Generates a random `String` of a given length from `scalars`.
///
/// - parameter length: The length for the generated string.
/// - parameter scalars: The unicode scalars from which the string will be generated.
/// - parameter randomGenerator: The random generator to use.
public static func random<I: ExpressibleByIntegerLiteral & Strideable, R: RandomGenerator>(ofLength length: I,
from scalars: UnicodeScalarView,
using randomGenerator: inout R) -> String? where I.Stride: SignedInteger {
var result = UnicodeScalarView()
for _ in 0 ..< length {
guard let random = scalars.random(using: &randomGenerator) else {
return nil
}
result.append(random)
}
return String(result)
}
/// Generates a random `String` with a length of `10` from characters in `string`.
///
/// - parameter string: The string whose characters from which the string will be generated.
/// - parameter randomGenerator: The random generator to use.
public static func random<R: RandomGenerator>(from string: String,
using randomGenerator: inout R) -> String? {
return random(ofLength: 10, from: string, using: &randomGenerator)
}
/// Generates a random `String` of a given length from characters in `string`.
///
/// - parameter length: The length for the generated string.
/// - parameter string: The string whose characters from which the string will be generated.
/// - parameter randomGenerator: The random generator to use.
public static func random<I: ExpressibleByIntegerLiteral & Strideable, R: RandomGenerator>(ofLength length: I,
from string: String,
using randomGenerator: inout R) -> String? where I.Stride: SignedInteger {
return random(ofLength: length, from: string.unicodeScalars, using: &randomGenerator)
}
}
#if swift(>=4.0)
extension String: RandomRetrievableInRange {}
#else
extension String.CharacterView: RandomRetrievableInRange {}
#endif
extension String.UnicodeScalarView: RandomRetrievableInRange {}
extension String.UTF8View: RandomRetrievableInRange {}
extension String.UTF16View: RandomRetrievableInRange {}
extension String: Shuffleable, UniqueShuffleable {
/// Shuffles the elements in `self` and returns the result.
public func shuffled<R: RandomGenerator>(using randomGenerator: inout R) -> String {
return String(self.shuffled(using: &randomGenerator))
}
/// Shuffles the elements in `self` in a unique order and returns the result.
public func shuffledUnique<R: RandomGenerator>(using randomGenerator: inout R) -> String {
return String(self.shuffledUnique(using: &randomGenerator))
}
}
| mit | 3b12aa4507730c4dc598f7bbdcde9916 | 46.441489 | 125 | 0.662182 | 4.971572 | false | false | false | false |
kylecrawshaw/ImagrAdmin | ImagrAdmin/WorkflowSupport/WorkflowComponents/IncludedWorkflowComponent/IncludedWorkflowComponent.swift | 1 | 1281 | //
// IncludedWorkflowComponent.swift
// ImagrManager
//
// Created by Kyle Crawshaw on 7/15/16.
// Copyright © 2016 Kyle Crawshaw. All rights reserved.
//
import Foundation
class IncludedWorkflowComponent: BaseComponent {
var includedWorkflow: String?
var script: String?
init(id: Int!, workflowName: String!, workflowId: Int!) {
super.init(id: id, type: "included_workflow", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = IncludedWorkflowViewController()
}
init(id: Int!, workflowName: String!, workflowId: Int!, dict: NSDictionary!) {
super.init(id: id, type: "included_workflow", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = IncludedWorkflowViewController()
self.includedWorkflow = dict.valueForKey("included_workflow") as? String
self.script = dict.valueForKey("script") as? String
}
override func asDict() -> NSDictionary? {
var dict: [String: AnyObject] = [
"type": type,
]
if includedWorkflow != nil {
dict["name"] = includedWorkflow!
}
if script != nil {
dict["script"] = script!
}
return dict
}
} | apache-2.0 | 94ee378a20e4cf96c14311b1f12b3b9b | 31.025 | 105 | 0.638281 | 4.507042 | false | false | false | false |
mownier/photostream | Photostream/UI/Photo Library/PhotoLibraryDelegate.swift | 1 | 1968 | //
// PhotoLibraryDelegate.swift
// Photostream
//
// Created by Mounir Ybanez on 11/11/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import UIKit
extension PhotoLibraryViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedIndex = indexPath.row
presenter.willShowSelectedPhoto(at: selectedIndex, size: selectedPhotoSize)
}
}
extension PhotoLibraryViewController {
var selectedPhotoSize: CGSize {
let scale = UIScreen.main.scale
return CGSize(width: cropView.bounds.width * scale,
height: cropView.bounds.height * scale)
}
}
extension PhotoLibraryViewController {
func scrollViewDidScroll(_ view: UIScrollView) {
guard let scrollView = scrollHandler.scrollView,
scrollView == view,
scrollHandler.isScrollable else {
return
}
if !dimView.isHidden {
dimView.alpha = min(scrollHandler.percentageOffsetY, 0.5)
}
switch scrollHandler.direction {
case .down:
didScrollDown(with: abs(scrollHandler.offsetDelta))
case .up, .none:
didScrollUp(with: abs(scrollHandler.offsetDelta), offsetY: view.contentOffset.y)
}
scrollHandler.update()
}
func didScrollUp(with delta: CGFloat, offsetY: CGFloat = 0) {
guard offsetY < -(48 + 2) else {
return
}
let sum = cropContentViewConstraintTop.constant + delta
let newDelta = min(sum, 0)
cropContentViewConstraintTop.constant = newDelta
}
func didScrollDown(with delta: CGFloat) {
let diff = cropContentViewConstraintTop.constant - delta
let newDelta = max(diff, -(collectionView.contentInset.top - 48))
cropContentViewConstraintTop.constant = newDelta
}
}
| mit | b12f9b450dd1aa9fb99b326eb7ac5b00 | 29.261538 | 99 | 0.644128 | 5.069588 | false | false | false | false |
moongift/NCMBiOSTodo | NCMBiOS_Todo/MasterViewController.swift | 1 | 7118 | //
// MasterViewController.swift
// NCMBiOS_Todo
//
// Created by naokits on 6/6/15.
//
import UIKit
class MasterViewController: UITableViewController {
/// TODOを格納する配列
var objects = [Todo]()
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.fetchAllTodos()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// ------------------------------------------------------------------------
// MARK: - Segues
// ------------------------------------------------------------------------
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "editTodo" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let todo = self.objects[indexPath.row]
if let dvc = segue.destinationViewController as? DetailViewController {
dvc.detailItem = todo
dvc.updateButton.title = "更新"
}
}
} else if segue.identifier == "addTodo" {
(segue.destinationViewController as! DetailViewController).updateButton.title = "追加"
} else {
// 遷移先が定義されていない
}
}
/// TODO登録/編集画面から戻ってきた時の処理を行います。
/// 今回はUnwind Identifierは必要ないので定義してません。
@IBAction func unwindromTodoEdit(segue:UIStoryboardSegue) {
let svc = segue.sourceViewController as! DetailViewController
if count(svc.todoTitle.text) < 3 {
return
}
if svc.detailItem == nil {
println("TODOオブジェクトが存在しないので、新規とみなします。")
self.addTodoWithTitle(svc.todoTitle.text)
} else {
println("更新処理")
svc.detailItem?.title = svc.todoTitle.text
svc.detailItem?.saveInBackgroundWithBlock({ (error: NSError!) -> Void in
self.tableView.reloadData()
})
}
}
// ------------------------------------------------------------------------
// MARK: - Table View
// ------------------------------------------------------------------------
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let todo = objects[indexPath.row]
cell.textLabel?.text = todo.title
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let todo = objects[indexPath.row] as NCMBObject
let objectID = todo.objectId
let query = Todo.query()
query.getObjectInBackgroundWithId(objectID, block: { (object: NCMBObject!, fetchError: NSError?) -> Void in
if fetchError == nil {
// NCMBから非同期で対象オブジェクトを削除します
object.deleteInBackgroundWithBlock({ (deleteError: NSError!) -> Void in
if (deleteError == nil) {
let deletedObject = self.objects.removeAtIndex(indexPath.row)
// データソースから削除
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else {
println("削除失敗: \(deleteError)")
}
})
} else {
println("オブジェクト取得失敗: \(fetchError)")
}
})
} 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.
}
}
// ------------------------------------------------------------------------
// MARK: Methods for Data Source
// ------------------------------------------------------------------------
/// 全てのTODO情報を取得し、プロパティに格納します
///
/// :param: None
/// :returns: None
func fetchAllTodos() {
let query = Todo.query()
// タイトルにデータが含まれないものは除外(空の文字列は除外されない)
query.whereKeyExists("title")
// 登録日の降順で取得
query.orderByDescending("createDate")
// 取得件数の指定
query.limit = 20
query.findObjectsInBackgroundWithBlock({(NSArray todos, NSError error) in
if (error == nil) {
println("登録件数: \(todos.count)")
for todo in todos {
let title = todo.title
println("--- \(todo.objectId): \(title)")
}
self.objects = todos as! [Todo] // NSArray -> Swift Array
self.tableView.reloadData()
} else {
println("Error: \(error)")
}
})
}
/// 新規にTODOを追加します
///
/// :param: title TODOのタイトル
/// :returns: None
func addTodoWithTitle(title: String) {
let todo = Todo.object() as! Todo
todo.setObject(title, forKey: "title")
// 非同期で保存
todo.saveInBackgroundWithBlock { (error: NSError!) -> Void in
if(error == nil){
println("新規TODOの保存成功。表示の更新などを行う。")
self.insertNewTodoObject(todo)
} else {
println("新規TODOの保存に失敗しました: \(error)")
}
}
}
/// TODOをDataSourceに追加して、表示を更新します
///
/// :param: todo TODOオブジェクト
/// :returns: None
func insertNewTodoObject(todo: Todo!) {
self.objects.insert(todo, atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
self.tableView.reloadData()
}
}
| mit | ebedc2485e3e30d39f398e29015a78e4 | 34.416216 | 157 | 0.528541 | 5.374897 | false | false | false | false |
johnsextro/cycschedule | cycschedule/ScheduleService.swift | 1 | 3714 | import Foundation
class ScheduleService {
func fetchTeamSchedule(teamId: String, callback: (Array< Game >) -> ()) {
var postEndpoint: String = "http://x8-avian-bricolage-r.appspot.com/games/GamesService.games"
let url = NSURL(string: postEndpoint)
var params = ["team_id": teamId] as Dictionary<String, String>
self.makeServiceCall(url!, params: params, callback: callback)
}
func fetchMultipleTeamSchedules(teamIds: String, callback: (Array< Game >) -> ()) {
var postEndpoint: String = "http://x8-avian-bricolage-r.appspot.com/multigames/GamesMultiTeamService.games"
let url = NSURL(string: postEndpoint)
var params = ["team_ids": teamIds] as Dictionary<String, String>
self.makeServiceCall(url!, params: params, callback: callback)
}
private func makeServiceCall(url: NSURL, params: Dictionary<String, String>, callback: (Array< Game >) -> ()) {
var err: NSError?
let timeout = 15
var urlRequest = NSMutableURLRequest(URL: url)
urlRequest.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
urlRequest.HTTPMethod = "POST"
let queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(
urlRequest,
queue: queue,
completionHandler: {(response: NSURLResponse!,
data: NSData!,
error: NSError!) in
if data.length > 0 && error == nil{
callback(self.parseJSONIntoArrayofGames(NSString(data: data, encoding: NSASCIIStringEncoding)!))
}else if data.length == 0 && error == nil{
println("Nothing was downloaded")
} else if error != nil{
println("Error happened = \(error)")
}
}
)
}
private func parseJSONIntoArrayofGames(data:NSString) -> Array< Game >{
var parseError: NSError?
var games:Array< Game > = Array < Game >()
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError)
if (parseError == nil)
{
if let schedule_obj = json as? NSDictionary
{
if let gamesArray = schedule_obj["games"] as? NSArray
{
for (var i = 0; i < gamesArray.count ; i++ )
{
if let game_obj = gamesArray[i] as? NSDictionary
{
if let gameId = game_obj["game_id"] as? String
{
var homeTeam: String = (game_obj["home"] as? String)!
var awayTeam: String = (game_obj["away"] as? String)!
var location: String = (game_obj["location"] as? String)!
var score: String = (game_obj["score"] as? String)!
var gameDate: String = (game_obj["game_date"] as? String)!
var gameTime: String = (game_obj["time"] as? String)!
games.append(Game(gameId: gameId, gameDate: gameDate, gameTime: gameTime, opponent: awayTeam, location: location, score: score, home: homeTeam))
}
}
}
}
}
}
return games
}
} | gpl-2.0 | 88681a3d3e7f4ab9b316bf1c70d8a546 | 47.246753 | 176 | 0.53608 | 4.925729 | false | false | false | false |
1170197998/SinaWeibo | SFWeiBo/SFWeiBo/Classes/HomeDetail/HomeDetailCommentTableViewCell.swift | 1 | 3936 | //
// HomeDetailCommentTableViewCell.swift
// SFWeiBo
//
// Created by ShaoFeng on 16/7/12.
// Copyright © 2016年 ShaoFeng. All rights reserved.
//
import UIKit
class HomeDetailCommentTableViewCell: UITableViewCell {
lazy var contentLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.font = UIFont.systemFontOfSize(15)
label.textColor = UIColor.darkTextColor()
return label
}()
var comment: Comments? {
didSet {
//名字赋值
nameLabel.text = comment?.user?.name
//用户头像赋值
if let url = comment?.user?.imageUrl {
headerIcon.sd_setImageWithURL(url)
}
//时间赋值
if let string = comment?.created_at {
dateLabel.text = string
}
//评论内容赋值
if let string = comment?.text {
let attributesString = NSMutableAttributedString.init(string: string)
let paraghStyle = NSMutableParagraphStyle()
paraghStyle.lineSpacing = 3
attributesString.addAttributes([NSParagraphStyleAttributeName : paraghStyle], range: NSMakeRange(0, string.characters.count))
contentLabel.attributedText = attributesString
contentLabel.lineBreakMode = NSLineBreakMode.ByTruncatingTail
contentLabel.contentMode = UIViewContentMode.Top
let attributes = [NSFontAttributeName:contentLabel.font,NSParagraphStyleAttributeName:paraghStyle]
let text: NSString = NSString(CString: string.cStringUsingEncoding(NSUTF8StringEncoding)!, encoding: NSUTF8StringEncoding)!
let size = text.boundingRectWithSize(CGSizeMake(UIScreen.mainScreen().bounds.width - 60, CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil).size
contentLabel.text = attributesString.string
contentLabel.frame = CGRectMake(50, 50, size.width, size.height)
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
}
private func setupUI() {
contentView.addSubview(headerIcon)
contentView.addSubview(nameLabel)
contentView.addSubview(dateLabel)
contentView.addSubview(contentLabel)
headerIcon.AlignInner(type: AlignType.TopLeft, referView: contentView, size: CGSizeMake(35, 35), offset: CGPointMake(5, 5))
nameLabel.AlignHorizontal(type: AlignType.TopRight, referView: headerIcon, size: CGSizeMake(200, 20), offset: CGPointMake(10, 0))
dateLabel.AlignVertical(type: AlignType.BottomLeft, referView: nameLabel, size: CGSizeMake(150, 15), offset: CGPointMake(0, 5))
// contentLabel.AlignVertical(type: AlignType.BottomLeft, referView: dateLabel, size: CGSizeMake(UIScreen.mainScreen().bounds.width - 50, 20), offset: CGPointMake(0, 5))
}
private lazy var headerIcon: UIImageView = {
let imageView = UIImageView()
imageView.layer.cornerRadius = 18
imageView.layer.masksToBounds = true
return imageView
}()
private lazy var nameLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFontOfSize(15)
label.textColor = UIColor.darkTextColor()
return label
}()
private lazy var dateLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFontOfSize(13)
label.textColor = UIColor.darkTextColor()
return label
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | a4e555390542de32e5cbc23558a709ba | 39.134021 | 223 | 0.631903 | 5.414465 | false | false | false | false |
sharath-cliqz/browser-ios | Client/Frontend/Browser/TabScrollController.swift | 2 | 8945 | /* 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 SnapKit
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
private let ToolbarBaseAnimationDuration: CGFloat = 0.2
class TabScrollingController: NSObject {
enum ScrollDirection {
case up
case down
}
enum ToolbarState {
case collapsed
case visible
case animating
}
weak var tab: Tab? {
willSet {
self.scrollView?.delegate = nil
self.scrollView?.removeGestureRecognizer(panGesture)
}
didSet {
self.scrollView?.addGestureRecognizer(panGesture)
scrollView?.delegate = self
}
}
weak var header: UIView?
weak var footer: UIView?
weak var urlBar: URLBarView?
weak var snackBars: UIView?
var footerBottomConstraint: Constraint?
var headerTopConstraint: Constraint?
var toolbarsShowing: Bool { return headerTopOffset == 0 }
fileprivate var headerTopOffset: CGFloat = 0 {
didSet {
headerTopConstraint?.update(offset: headerTopOffset)
header?.superview?.setNeedsLayout()
}
}
fileprivate var footerBottomOffset: CGFloat = 0 {
didSet {
footerBottomConstraint?.update(offset: footerBottomOffset)
footer?.superview?.setNeedsLayout()
}
}
fileprivate lazy var panGesture: UIPanGestureRecognizer = {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(TabScrollingController.handlePan(_:)))
panGesture.maximumNumberOfTouches = 1
panGesture.delegate = self
return panGesture
}()
fileprivate var scrollView: UIScrollView? { return tab?.webView?.scrollView }
fileprivate var contentOffset: CGPoint { return scrollView?.contentOffset ?? CGPoint.zero }
fileprivate var contentSize: CGSize { return scrollView?.contentSize ?? CGSize.zero }
fileprivate var scrollViewHeight: CGFloat { return scrollView?.frame.height ?? 0 }
fileprivate var topScrollHeight: CGFloat { return header?.frame.height ?? 0 }
fileprivate var bottomScrollHeight: CGFloat { return urlBar?.frame.height ?? 0 }
fileprivate var snackBarsFrame: CGRect { return snackBars?.frame ?? CGRect.zero }
fileprivate var lastContentOffset: CGFloat = 0
fileprivate var scrollDirection: ScrollDirection = .down
fileprivate var toolbarState: ToolbarState = .visible
override init() {
super.init()
}
func showToolbars(_ animated: Bool, completion: ((_ finished: Bool) -> Void)? = nil) {
if toolbarState == .visible {
completion?(true)
return
}
toolbarState = .visible
let durationRatio = abs(headerTopOffset / topScrollHeight)
let actualDuration = TimeInterval(ToolbarBaseAnimationDuration * durationRatio)
self.animateToolbarsWithOffsets(
animated,
duration: actualDuration,
headerOffset: 0,
footerOffset: 0,
alpha: 1,
completion: completion)
}
func hideToolbars(_ animated: Bool, completion: ((_ finished: Bool) -> Void)? = nil) {
if toolbarState == .collapsed {
completion?(true)
return
}
toolbarState = .collapsed
let durationRatio = abs((topScrollHeight + headerTopOffset) / topScrollHeight)
let actualDuration = TimeInterval(ToolbarBaseAnimationDuration * durationRatio)
self.animateToolbarsWithOffsets(
animated,
duration: actualDuration,
headerOffset: -topScrollHeight,
footerOffset: bottomScrollHeight,
alpha: 0,
completion: completion)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "contentSize" {
tab?.webView?.contentSizeChangeDetected()
if !checkScrollHeightIsLargeEnoughForScrolling() && !toolbarsShowing {
showToolbars(true, completion: nil)
}
}
}
}
private extension TabScrollingController {
func tabIsLoading() -> Bool {
return tab?.loading ?? true
}
@objc func handlePan(_ gesture: UIPanGestureRecognizer) {
if tabIsLoading() {
return
}
if let containerView = scrollView?.superview {
let translation = gesture.translation(in: containerView)
let delta = lastContentOffset - translation.y
if delta > 0 {
scrollDirection = .down
} else if delta < 0 {
scrollDirection = .up
}
lastContentOffset = translation.y
if checkRubberbandingForDelta(delta) && checkScrollHeightIsLargeEnoughForScrolling() {
if toolbarState != .collapsed || contentOffset.y <= 0 {
scrollWithDelta(delta)
}
if headerTopOffset == -topScrollHeight {
toolbarState = .collapsed
} else if headerTopOffset == 0 {
toolbarState = .visible
} else {
toolbarState = .animating
}
}
if gesture.state == .ended || gesture.state == .cancelled {
lastContentOffset = 0
}
}
}
func checkRubberbandingForDelta(_ delta: CGFloat) -> Bool {
return !((delta < 0 && contentOffset.y + scrollViewHeight > contentSize.height &&
scrollViewHeight < contentSize.height) ||
contentOffset.y < delta)
}
func scrollWithDelta(_ delta: CGFloat) {
if scrollViewHeight >= contentSize.height {
return
}
var updatedOffset = headerTopOffset - delta
headerTopOffset = clamp(updatedOffset, min: -topScrollHeight, max: 0)
if isHeaderDisplayedForGivenOffset(updatedOffset) {
scrollView?.contentOffset = CGPoint(x: contentOffset.x, y: contentOffset.y - delta)
}
updatedOffset = footerBottomOffset + delta
footerBottomOffset = clamp(updatedOffset, min: 0, max: bottomScrollHeight)
let alpha = 1 - abs(headerTopOffset / topScrollHeight)
urlBar?.updateAlphaForSubviews(alpha)
}
func isHeaderDisplayedForGivenOffset(_ offset: CGFloat) -> Bool {
return offset > -topScrollHeight && offset < 0
}
func clamp(_ y: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat {
if y >= max {
return max
} else if y <= min {
return min
}
return y
}
func animateToolbarsWithOffsets(_ animated: Bool, duration: TimeInterval, headerOffset: CGFloat,
footerOffset: CGFloat, alpha: CGFloat, completion: ((_ finished: Bool) -> Void)?) {
let animation: () -> Void = {
self.headerTopOffset = headerOffset
self.footerBottomOffset = footerOffset
self.urlBar?.updateAlphaForSubviews(alpha)
self.header?.superview?.layoutIfNeeded()
}
if animated {
UIView.animate(withDuration: duration, animations: animation, completion: completion)
} else {
animation()
completion?(true)
}
}
func checkScrollHeightIsLargeEnoughForScrolling() -> Bool {
return (UIScreen.main.bounds.size.height + 2 * UIConstants.ToolbarHeight) < scrollView?.contentSize.height
}
}
extension TabScrollingController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension TabScrollingController: UIScrollViewDelegate {
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if tabIsLoading() {
return
}
if (decelerate || (toolbarState == .animating && !decelerate)) && checkScrollHeightIsLargeEnoughForScrolling() {
if scrollDirection == .up {
showToolbars(true)
} else if scrollDirection == .down {
hideToolbars(true)
}
}
}
func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
showToolbars(true)
return true
}
}
| mpl-2.0 | d1cb5223f008d0ddd667d14bf8662aff | 32.882576 | 151 | 0.621465 | 5.427791 | false | false | false | false |
benlangmuir/swift | test/IRGen/prespecialized-metadata/struct-outmodule-frozen-1argument-1distinct_use-struct-outmodule-frozen-othermodule.swift | 16 | 3343 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-frozen-1argument.swift -emit-library -o %t/%target-library-name(Generic) -emit-module -module-name Generic -emit-module-path %t/Generic.swiftmodule -enable-library-evolution
// RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-frozen-0argument.swift -emit-library -o %t/%target-library-name(Argument) -emit-module -module-name Argument -emit-module-path %t/Argument.swiftmodule -enable-library-evolution
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s -L %t -I %t -lGeneric -lArgument | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s7Generic11OneArgumentVy0C07IntegerVGMN" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// : i8** getelementptr inbounds (
// : %swift.vwtable,
// : %swift.vwtable* @"
// CHECK-SAME: $s7Generic11OneArgumentVy0C07IntegerVGWV
// : ",
// : i32 0,
// : i32 0
// : ),
// CHECK-SAME: [[INT]] 512,
// : %swift.type_descriptor* @"
// CHECK-SAME: $s7Generic11OneArgumentVMn
// : ",
// CHECK-SAME: %swift.type* @"$s8Argument7IntegerVN",
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 {{4|8}},
// CHECK-SAME: i64 1
// CHECK-SAME: }>,
// CHECK-SAME: align [[ALIGNMENT]]
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
import Generic
import Argument
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: [[CANONICALIZED_METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @swift_getCanonicalSpecializedMetadata(
// CHECK-SAME: [[INT]] 0,
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s7Generic11OneArgumentVy0C07IntegerVGMN" to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ),
// CHECK-SAME: %swift.type** @"$s7Generic11OneArgumentVy0C07IntegerVGMJ"
// CHECK-SAME: )
// CHECK-NEXT: [[CANONICALIZED_METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[CANONICALIZED_METADATA_RESPONSE]], 0
// CHECK-NEXT: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}},
// CHECK-SAME: %swift.type* [[CANONICALIZED_METADATA]]
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( OneArgument(Integer(13)) )
}
doit()
| apache-2.0 | 21158343069d840815b186c83436761d | 40.271605 | 301 | 0.623691 | 3.18381 | false | false | false | false |
rechsteiner/Parchment | Parchment/Enums/PagingMenuItemSource.swift | 1 | 535 | import Foundation
import UIKit
public enum PagingMenuItemSource {
case `class`(type: PagingCell.Type)
case nib(nib: UINib)
}
extension PagingMenuItemSource: Equatable {
public static func == (lhs: PagingMenuItemSource, rhs: PagingMenuItemSource) -> Bool {
switch (lhs, rhs) {
case let (.class(lhsType), .class(rhsType)):
return lhsType == rhsType
case let (.nib(lhsNib), .nib(rhsNib)):
return lhsNib === rhsNib
default:
return false
}
}
}
| mit | 46bd7e02d1e61877e28706590717c1a9 | 23.318182 | 90 | 0.611215 | 4.115385 | false | false | false | false |
graphcool-examples/react-apollo-auth0-example | quickstart-with-apollo/Instagram/Carthage/Checkouts/apollo-ios/Sources/JSON.swift | 1 | 1990 | public typealias JSONValue = Any
public typealias JSONObject = [String: JSONValue]
public protocol JSONDecodable {
init(jsonValue value: JSONValue) throws
}
public protocol JSONEncodable {
var jsonValue: JSONValue { get }
}
public enum JSONDecodingError: Error, LocalizedError {
case missingValue
case nullValue
case couldNotConvert(value: Any, to: Any.Type)
public var errorDescription: String? {
switch self {
case .missingValue:
return "Missing value"
case .nullValue:
return "Unexpected null value"
case .couldNotConvert(let value, let expectedType):
return "Could not convert \"\(value)\" to \(expectedType)"
}
}
}
extension JSONDecodingError: Matchable {
public typealias Base = Error
public static func ~=(pattern: JSONDecodingError, value: Error) -> Bool {
guard let value = value as? JSONDecodingError else {
return false
}
switch (value, pattern) {
case (.missingValue, .missingValue), (.nullValue, .nullValue), (.couldNotConvert, .couldNotConvert):
return true
default:
return false
}
}
}
// MARK: Helpers
func optional(_ optionalValue: JSONValue?) throws -> JSONValue? {
guard let value = optionalValue else {
throw JSONDecodingError.missingValue
}
if value is NSNull { return nil }
return value
}
func required(_ optionalValue: JSONValue?) throws -> JSONValue {
guard let value = optionalValue else {
throw JSONDecodingError.missingValue
}
if value is NSNull {
throw JSONDecodingError.nullValue
}
return value
}
func cast<T>(_ value: JSONValue) throws -> T {
guard let castValue = value as? T else {
throw JSONDecodingError.couldNotConvert(value: value, to: T.self)
}
return castValue
}
func equals(_ lhs: Any, _ rhs: Any) -> Bool {
if let lhs = lhs as? Reference, let rhs = rhs as? Reference {
return lhs == rhs
}
let lhs = lhs as AnyObject, rhs = rhs as AnyObject
return lhs.isEqual(rhs)
}
| mit | 479e53d9d597adcf0a81fe981285a43a | 22.690476 | 104 | 0.685427 | 4.451902 | false | false | false | false |
ericdke/WithOrWithoutEmoji | Sources/WithOrWithoutEmoji.swift | 1 | 4437 | import Foundation
public extension NSString {
fileprivate func _containsAnEmoji() -> Bool {
// Original Objective-C code by Gabriel Massana https://github.com/GabrielMassana
// Adapted to Swift 3 by Eric Dejonckheere https://github.com/ericdke
let hs = self.character(at: 0)
// surrogate pair
if 0xd800 <= hs && hs <= 0xdbff {
if self.length > 1 {
let ls = self.character(at: 1)
let uc:Int = Int(((hs - 0xd800) * 0x400) + (ls - 0xdc00)) + 0x10000
if 0x1d000 <= uc && uc <= 0x1f9c0 {
return true
}
}
} else if self.length > 1 {
let ls = self.character(at: 1)
if ls == 0x20e3 || ls == 0xfe0f || ls == 0xd83c {
return true
}
} else {
// non surrogate
if (0x2100 <= hs && hs <= 0x27ff) ||
(0x2b05 <= hs && hs <= 0x2b07) ||
(0x2934 <= hs && hs <= 0x2935) ||
(0x3297 <= hs && hs <= 0x3299)
{
return true
} else if hs == 0xa9 ||
hs == 0xae ||
hs == 0x303d ||
hs == 0x3030 ||
hs == 0x2b55 ||
hs == 0x2b1c ||
hs == 0x2b1b ||
hs == 0x2b50
{
return true
}
}
return false
}
}
public extension String {
public var condensedWhitespace: String {
#if os(OSX)
let components = self.components(separatedBy: .whitespacesAndNewlines)
#else
let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines())
#endif
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
public var emojiRanges: [NSRange] {
var ranges = [NSRange]()
let s = NSString(string:self)
s.enumerateSubstrings(in: NSRange(location: 0, length: s.length),
options: .byComposedCharacterSequences) {
(substring, substringRange, _, _) in
if let substring = substring {
if NSString(string: substring)._containsAnEmoji() {
ranges.append(substringRange)
}
}
}
return ranges
}
public var containsEmoji: Bool {
var isEmoji = false
let s = NSString(string:self)
s.enumerateSubstrings(in:
NSRange(location: 0, length: s.length),
options: .byComposedCharacterSequences) {
(substring, substringRange, _, stop) in
if let substring = substring {
if NSString(string:substring)._containsAnEmoji() {
isEmoji = true
// Stops the enumeration by setting the unsafe pointer to ObjcBool memory value, false by default in the closure parameters, to true.
stop[0] = true
}
}
}
return isEmoji
}
public var emojisWithoutLetters: [String] {
let s = NSString(string:self)
return self.emojiRanges.map { s.substring(with: $0) }
}
public var lettersWithoutEmojis: [String] {
#if os(OSX)
var charSet = CharacterSet()
charSet.insert(charactersIn: self.emojisWithoutLetters.joined(separator: ""))
#else
let charSet = NSCharacterSet(charactersIn: self.emojisWithoutLetters.joined(separator: ""))
#endif
let wo = self.components(separatedBy: charSet).joined(separator: "")
return wo.characters.map { String($0) }.filter { $0 != "" }
}
public var condensedLettersWithoutEmojis: [String] {
return self.lettersWithoutEmojis.filter { !$0.isEmpty && $0 != " " }
}
public var withoutEmojis: String {
return self.lettersWithoutEmojis.joined(separator: "")
}
public var condensedStringWithoutEmojis: String {
return self.lettersWithoutEmojis.joined(separator: "").condensedWhitespace
}
public var onlyEmojis: String {
return self.emojisWithoutLetters.joined(separator: "")
}
public var emojiCount: Int {
return self.emojisWithoutLetters.count
}
} | mit | 5b0bfa27d4ded94670c92c2f343f71e9 | 33.671875 | 153 | 0.518368 | 4.646073 | false | false | false | false |
erlandranvinge/swift-mini-json | legacy/Json-2.0.swift | 1 | 1243 | import Foundation
class JsonGenerator: AnyGenerator<Json> {
init(data:AnyObject?) {
items = data as? [AnyObject]
length = items?.count ?? 0
}
private let items:[AnyObject]?
private let length:Int
private var current = 0
override func next() -> Json? {
return current < length ? Json(data: items?[current++]) : .None
}
}
class Json: SequenceType {
let data:AnyObject?
init(data:AnyObject?) {
if (data is NSData) {
self.data = try? NSJSONSerialization.JSONObjectWithData(
data as! NSData,
options: .AllowFragments)
} else {
self.data = data
}
}
func string() -> String { return data as? String ?? "" }
func int() -> Int { return data as? Int ?? 0 }
func float() -> Float { return data as? Float ?? 0.0 }
func double() -> Double { return data as? Double ?? 0.0 }
func bool() -> Bool { return data as? Bool ?? false }
subscript(name:String) -> Json {
let hash = data as? NSDictionary
return Json(data: hash?.valueForKey(name))
}
func generate() -> AnyGenerator<Json> {
return JsonGenerator(data: data)
}
}
| mit | fa33b697509ae5403bd2ded28e1a953d | 26.021739 | 71 | 0.555913 | 4.286207 | false | false | false | false |
jeevanRao7/Swift_Playgrounds | Swift Playgrounds/Challenges/LinkedIn Placements 2017/Consecutive 1's in Binary Numbers/Consecutive 1's in Binary Numbers .playground/Contents.swift | 1 | 520 | /*
Consecutive 1's in Binary Numbers
*/
import Foundation
let n = Int(readLine()!)!
let strN = String(n , radix:2);
var maxCount = 0;
var tempCount = 0;
//Loop each characters
for i in strN.characters.indices {
if (strN[i] == "1") {
//Increment count of '1'
tempCount = tempCount + 1;
}
else{
//Reset count
tempCount = 0;
}
//Track max count of '1's
if (tempCount > maxCount) {
maxCount = tempCount;
}
}
print(maxCount); | mit | 0a2e90a7347018a69c01f359f7574782 | 15.28125 | 35 | 0.544231 | 3.611111 | false | false | false | false |
anagac3/living-together-server | Sources/App/Controllers/HouseholdController.swift | 1 | 4667 | //
// HouseholdController.swift
// LivingTogetherServer
//
// Created by Andres Aguilar on 8/5/17.
//
//
import Vapor
import HTTP
final class HouseholdController {
/// it should return an index of all available posts
func index(_ req: Request) throws -> ResponseRepresentable {
return try Household.all().makeJSON()
}
/// When consumers call 'POST' on '/posts' with valid JSON
/// create and save the post
func create(_ req: Request) throws -> ResponseRepresentable {
var household : Household
var unique: Bool
//Keep generating a new household until we get a unique code name
repeat {
household = try req.household()
let queryResult = try Household.makeQuery().filter(Household.codeNameKey, .equals, household.codeName)
unique = (try queryResult.count() == 0) ? true: false
} while(!unique)
try household.save()
return household
}
/// When the consumer calls 'GET' on a specific resource, ie:
/// '/posts/13rd88' we should show that specific post
func show(_ req: Request) throws -> ResponseRepresentable {
guard let householdId = req.data[Household.idKey]?.int else {
throw Abort.badRequest
}
guard let household = try Household.find(householdId) else {
throw Abort.notFound
}
return household
}
/// When the consumer calls 'DELETE' on a specific resource, ie:
/// 'posts/l2jd9' we should remove that resource from the database
func delete(_ req: Request) throws -> ResponseRepresentable {
guard let householdId = req.data[Household.idKey]?.int else {
throw Abort.badRequest
}
guard let household = try Household.find(householdId) else {
throw Abort.notFound
}
try household.delete()
return Response(status: .ok)
}
/// When the consumer calls 'DELETE' on the entire table, ie:
/// '/posts' we should remove the entire table
func clear(_ req: Request) throws -> ResponseRepresentable {
try CompleteHistory.makeQuery().delete()
try BoardMessage.makeQuery().delete()
try ToDo.makeQuery().delete()
try Bill.makeQuery().delete()
try Resident.makeQuery().delete()
try Household.makeQuery().delete()
return Response(status: .ok)
}
/// When the user calls 'PATCH' on a specific resourcex, we should
/// update that resource to the new values.
func update(_ req: Request) throws -> ResponseRepresentable {
// See `extension Post: Updateable`
guard let householdId = req.data[Household.idKey]?.int else {
throw Abort.badRequest
}
guard let household = try Household.find(householdId) else {
throw Abort.notFound
}
try household.update(for: req)
// Save an return the updated post.
try household.save()
return household
}
func joinHousehold(_ req: Request) throws -> ResponseRepresentable {
guard let houseCodeName = req.data[Household.codeNameKey]?.string, let houseCode = req.data[Household.codeKey]?.int else {
throw Abort.badRequest
}
guard let household = try Household.makeQuery().filter(Household.codeNameKey, .equals, houseCodeName).filter(Household.codeKey, .equals, houseCode).first() else {
throw Abort.unauthorized
}
return household
}
func addRoutes(routeBuilder: RouteBuilder) {
let householdBuilder = routeBuilder.grouped("household")
householdBuilder.post("create", handler: create)
householdBuilder.post("show", handler: show)
householdBuilder.post("delete", handler: delete)
householdBuilder.post("update", handler: update)
householdBuilder.post("joinHousehold", handler: joinHousehold)
//To keep out of production
householdBuilder.get(handler: index)
householdBuilder.post("deleteAll", handler: clear)
}
}
extension Request {
/// Create a post from the JSON body
/// return BadRequest error if invalid
/// or no JSON
func household() throws -> Household {
guard let name = data[Household.nameKey]?.string else { throw Abort.badRequest }
return Household.init(name: name)
}
}
/// Since PostController doesn't require anything to
/// be initialized we can conform it to EmptyInitializable.
///
/// This will allow it to be passed by type.
extension HouseholdController: EmptyInitializable { }
| mit | 2f733e6ecf3c3f0fc86b447152a82134 | 34.356061 | 170 | 0.636383 | 4.776868 | false | false | false | false |
ZhangMingNan/MNMeiTuan | 15-MeiTuan/15-MeiTuan/View/EmptyPromptView.swift | 1 | 1729 | //
// EmptyPromptView.swift
// 15-MeiTuan
//
// Created by 张明楠 on 15/8/25.
// Copyright (c) 2015年 张明楠. All rights reserved.
//
import UIKit
class EmptyPromptView: UIView {
var imageView:UIImageView?
var textLabel:UILabel?
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
class func emptyPromptView()->EmptyPromptView{
var view = EmptyPromptView()
return view
}
override init(frame: CGRect) {
super.init(frame: frame)
var emptyInfoView = UIImageView(image: UIImage(named: "icon_deal_empty")!)
self.imageView = emptyInfoView
self.textLabel = UILabel()
self.textLabel?.text = "暂无此类团购"
self.textLabel?.textAlignment = NSTextAlignment.Center
self.textLabel?.frame.size = CGSizeMake(screenWidth, 20)
self.textLabel?.textColor = detailLabelColor
self.addSubview(self.imageView!)
self.addSubview(self.textLabel!)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.frame = self.superview!.bounds
println(self.superview?.center)
self.imageView?.frame.size = CGSizeMake(self.imageView!.image!.size.width * 0.5, self.imageView!.image!.size.height * 0.5)
self.imageView?.center = CGPointMake(screenWidth * 0.5, screenWidth * 0.5 - 44)
self.textLabel?.frame.origin = CGPointMake(0, CGRectGetMaxY(self.imageView!.frame))
}
}
| apache-2.0 | c8ac2db19e8b80936e7832b7ef79afcb | 29.963636 | 130 | 0.65825 | 4.184275 | false | false | false | false |
rudkx/swift | SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift | 1 | 2037 | //===--- PassRegistration.swift - Register optimzation passes -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SIL
import OptimizerBridging
#if canImport(ExperimentalRegex)
import ExperimentalRegex
#endif
@_cdecl("initializeSwiftModules")
public func initializeSwiftModules() {
registerSILClasses()
registerSwiftPasses()
#if canImport(ExperimentalRegex)
registerRegexParser()
#endif
}
private func registerPass(
_ pass: FunctionPass,
_ runFn: @escaping (@convention(c) (BridgedFunctionPassCtxt) -> ())) {
pass.name.withBridgedStringRef { nameStr in
SILPassManager_registerFunctionPass(nameStr, runFn)
}
}
private func registerPass<InstType: Instruction>(
_ pass: InstructionPass<InstType>,
_ runFn: @escaping (@convention(c) (BridgedInstructionPassCtxt) -> ())) {
pass.name.withBridgedStringRef { nameStr in
SILCombine_registerInstructionPass(nameStr, runFn)
}
}
private func registerSwiftPasses() {
registerPass(silPrinterPass, { silPrinterPass.run($0) })
registerPass(mergeCondFailsPass, { mergeCondFailsPass.run($0) })
registerPass(simplifyBeginCOWMutationPass, { simplifyBeginCOWMutationPass.run($0) })
registerPass(simplifyGlobalValuePass, { simplifyGlobalValuePass.run($0) })
registerPass(simplifyStrongRetainPass, { simplifyStrongRetainPass.run($0) })
registerPass(simplifyStrongReleasePass, { simplifyStrongReleasePass.run($0) })
registerPass(assumeSingleThreadedPass, { assumeSingleThreadedPass.run($0) })
registerPass(runUnitTests, { runUnitTests.run($0) })
registerPass(releaseDevirtualizerPass, { releaseDevirtualizerPass.run($0) })
}
| apache-2.0 | 516b0454d724b469e3e664410b3eec0f | 35.375 | 86 | 0.724595 | 4.27044 | false | false | false | false |
ChinaHackers/Alipay | Alipay/Alipay/Classes/Home/Controller/Search/View/HotSearchCollectionViewCell.swift | 1 | 3395 | //
// HotSearchCollectionViewCell.swift
// SimpleSugars
//
// Created by 苑伟 on 2016/10/19.
// Copyright © 2016年 苑伟. All rights reserved.
//
import UIKit
import SnapKit
// MARK: - 热门搜索cell
class HotSearchCollectionViewCell: UICollectionViewCell {
// MARK: - 懒加载
/// 排行榜数字
lazy var RankLabel: UILabel = {
let rankLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 25, height: 30))
rankLabel.textAlignment = .center
rankLabel.textColor = UIColor.white
return rankLabel
}()
/// 热门搜索中 按钮
lazy var hotButton: UIButton = {
let hotButton = UIButton(type: .custom)
// 设置按钮 边框\背景颜色
//hotButton.backgroundColor = UIColor(red:0.07, green:0.14, blue:0.19, alpha:1.00)
hotButton.backgroundColor = UIColor.groupTableViewBackground
// hotButton.layer.borderColor = UIColor.white.cgColor
// 边框宽度
// hotButton.layer.borderWidth = 0.5
// 设置按钮圆角
hotButton.layer.cornerRadius = 5
hotButton.layer.masksToBounds = true
// 开启按钮交互
hotButton.isUserInteractionEnabled = true
// 设置文字颜色\字体大小\对齐方式
hotButton.setTitleColor(UIColor.black, for: .normal)
hotButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
// 按钮文字对齐方式
hotButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
// 居左显示很难看,太靠边了。设置UIButton的文字边距
hotButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 0)
return hotButton
}()
/// 删除按钮
lazy var deleteButton: UIButton = {
let deleteButton = UIButton(type: .custom)
deleteButton.setImage(UIImage(named:"delete"), for: .normal)
deleteButton.isUserInteractionEnabled = true
return deleteButton
}()
/// 容器视图
private lazy var containerView:UIView = {
let containerView = UIView()
containerView.backgroundColor = UIColor.clear
containerView.isUserInteractionEnabled = true
return containerView
}()
// MARK: - 构造函数
private override init(frame: CGRect) {
super.init(frame: frame)
// MARK: -添加控件
//contentView: 自定义添加子视图的单元格的内容视图
contentView.addSubview(containerView)
containerView.frame = contentView.bounds
// 添加按钮到容器里
containerView.addSubview(hotButton)
containerView.addSubview(deleteButton)
hotButton.addSubview(RankLabel)
hotButton.frame = contentView.bounds
// 默认隐藏删除按钮
deleteButton.isHidden = true
//布局删除按钮
deleteButton.snp.makeConstraints { (make) in
make.width.height.equalTo(15)
make.top.equalTo(hotButton.snp.top).offset(-5)
make.right.equalTo(hotButton.snp.right).offset(5)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 1f8f84991881c6c240df839170112bed | 27.440367 | 90 | 0.602258 | 4.661654 | false | false | false | false |
moysklad/ios-remap-sdk | Sources/MoyskladiOSRemapSDK/Money/Shared/Decimal/Decimal.swift | 1 | 6021 | //
// Decimal.swift
// Money
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Daniel Thorpe
//
// 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 ValueCoding
/**
# Decimal
A value type which implements `DecimalNumberType` using `NSDecimalNumber` internally.
It is generic over the decimal number behavior type, which defines the rounding
and scale rules for base 10 decimal arithmetic.
*/
public struct _Decimal<Behavior: DecimalNumberBehaviorType>: DecimalNumberType, Comparable {
public typealias Magnitude = Double
public typealias DecimalNumberBehavior = Behavior
public var magnitude: Magnitude
public static func -=(lhs: inout _Decimal<Behavior>, rhs: _Decimal<Behavior>) {
lhs = lhs.subtract(rhs)
}
public static func +=(lhs: inout _Decimal<Behavior>, rhs: _Decimal<Behavior>) {
lhs = lhs.add(rhs)
}
public static func *=(lhs: inout _Decimal<Behavior>, rhs: _Decimal<Behavior>) {
lhs = lhs.multiply(by: rhs)
}
public static func *(lhs: _Decimal<Behavior>, rhs: _Decimal<Behavior>) -> _Decimal<Behavior> {
return lhs.multiply(by: rhs)
}
public static func +=(lhs: inout _Decimal<Behavior>, rhs: _Decimal<Behavior>) -> _Decimal<Behavior> {
return lhs.add(rhs)
}
public static func -=(lhs: inout _Decimal<Behavior>, rhs: _Decimal<Behavior>) -> _Decimal<Behavior> {
return lhs.subtract(rhs)
}
public static prefix func +(lhs: _Decimal<Behavior>) -> _Decimal<Behavior> {
return lhs
}
public static prefix func -(lhs: _Decimal<Behavior>) -> _Decimal<Behavior> {
return lhs.multiply(by: -1)
}
public static func ==(lhs: _Decimal<Behavior>, rhs: _Decimal<Behavior>) -> Bool {
return lhs.storage == rhs.storage
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than or equal to that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func <=(lhs: _Decimal<Behavior>, rhs: _Decimal<Behavior>) -> Bool {
return lhs.storage <= lhs.storage
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is greater than or equal to that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func >=(lhs: _Decimal<Behavior>, rhs: _Decimal<Behavior>) -> Bool {
return lhs.storage >= lhs.storage
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is greater than that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func >(lhs: _Decimal<Behavior>, rhs: _Decimal<Behavior>) -> Bool {
return lhs.storage > lhs.storage
}
/// Access the underlying decimal storage.
/// - returns: the `NSDecimalNumber`
public let storage: NSDecimalNumber
public init?<T>(exactly source: T) where T : BinaryInteger {
self.storage = NSDecimalNumber(integerLiteral: Int(source))
self.magnitude = Double(source.magnitude as? String ?? "0.0")!//NSDecimalNumber(string: source.magnitude as? String)
}
/**
Initialize a new value using the underlying decimal storage.
- parameter storage: a `NSDecimalNumber` defaults to zero.
*/
public init(storage: NSDecimalNumber = NSDecimalNumber.zero) {
self.storage = storage
self.magnitude = storage.doubleValue
}
}
// MARK: - Equality
public func ==<B>(lhs: _Decimal<B>, rhs: _Decimal<B>) -> Bool {
return lhs.storage == rhs.storage
}
// MARK: - Comparable
public func <<B>(lhs: _Decimal<B>, rhs: _Decimal<B>) -> Bool {
return lhs.storage < rhs.storage
}
/// `Decimal` with plain decimal number behavior
public typealias PlainDecimal = _Decimal<DecimalNumberBehavior.Plain>
/// `BankersDecimal` with banking decimal number behavior
public typealias BankersDecimal = _Decimal<DecimalNumberBehavior.Bankers>
// MARK: - Value Coding
extension _Decimal: ValueCoding {
public typealias Coder = _DecimalCoder<Behavior>
}
/**
Coding class to support `_Decimal` `ValueCoding` conformance.
*/
public final class _DecimalCoder<Behavior: DecimalNumberBehaviorType>: NSObject, NSCoding, CodedValue,
CodingProtocol{
public let value: _Decimal<Behavior>
public required init(_ v: _Decimal<Behavior>) {
value = v
}
public init?(coder aDecoder: NSCoder) {
let storage = aDecoder.decodeObject(forKey: "storage") as! NSDecimalNumber
value = _Decimal<Behavior>(storage: storage)
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(value.storage, forKey: "storage")
}
}
| mit | 198d8a37260e07b60392202c89593dea | 33.210227 | 125 | 0.668494 | 4.369376 | false | false | false | false |
salemoh/GoldenQuraniOS | GoldenQuranSwift/Pods/GRDB.swift/GRDB/QueryInterface/Support/SQLFunctions.swift | 2 | 6810 | // MARK: - Custom Functions
extension DatabaseFunction {
/// Returns an SQL expression that applies the function.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func apply(_ arguments: SQLExpressible...) -> SQLExpression {
return SQLExpressionFunction(SQLFunctionName(name), arguments: arguments.map { $0.sqlExpression })
}
}
// MARK: - ABS(...)
extension SQLFunctionName {
/// The `ABS` function name
public static let abs = SQLFunctionName("ABS")
}
/// Returns an expression that evaluates the `ABS` SQL function.
///
/// // ABS(amount)
/// abs(Column("amount"))
public func abs(_ value: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionFunction(.abs, arguments: value)
}
// MARK: - AVG(...)
extension SQLFunctionName {
/// The `AVG` function name
public static let avg = SQLFunctionName("AVG")
}
/// Returns an expression that evaluates the `AVG` SQL function.
///
/// // AVG(length)
/// average(Column("length"))
public func average(_ value: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionFunction(.avg, arguments: value)
}
// MARK: - COUNT(...)
/// Returns an expression that evaluates the `COUNT` SQL function.
///
/// // COUNT(email)
/// count(Column("email"))
public func count(_ counted: SQLSelectable) -> SQLExpression {
return SQLExpressionCount(counted)
}
// MARK: - COUNT(DISTINCT ...)
/// Returns an expression that evaluates the `COUNT(DISTINCT)` SQL function.
///
/// // COUNT(DISTINCT email)
/// count(distinct: Column("email"))
public func count(distinct value: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionCountDistinct(value.sqlExpression)
}
// MARK: - IFNULL(...)
extension SQLFunctionName {
/// The `IFNULL` function name
public static let ifNull = SQLFunctionName("IFNULL")
}
/// Returns an expression that evaluates the `IFNULL` SQL function.
///
/// // IFNULL(name, 'Anonymous')
/// Column("name") ?? "Anonymous"
public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
return SQLExpressionFunction(.ifNull, arguments: lhs, rhs)
}
// MARK: - LENGTH(...)
extension SQLFunctionName {
/// The `LENGTH` function name
public static let length = SQLFunctionName("LENGTH")
}
/// Returns an expression that evaluates the `LENGTH` SQL function.
///
/// // LENGTH(name)
/// length(Column("name"))
public func length(_ value: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionFunction(.length, arguments: value)
}
// MARK: - MAX(...)
extension SQLFunctionName {
/// The `MAX` function name
public static let max = SQLFunctionName("MAX")
}
/// Returns an expression that evaluates the `MAX` SQL function.
///
/// // MAX(score)
/// max(Column("score"))
public func max(_ value: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionFunction(.max, arguments: value)
}
// MARK: - MIN(...)
extension SQLFunctionName {
/// The `MIN` function name
public static let min = SQLFunctionName("MIN")
}
/// Returns an expression that evaluates the `MIN` SQL function.
///
/// // MIN(score)
/// min(Column("score"))
public func min(_ value: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionFunction(.min, arguments: value)
}
// MARK: - SUM(...)
extension SQLFunctionName {
/// The `SUM` function name
public static let sum = SQLFunctionName("SUM")
}
/// Returns an expression that evaluates the `SUM` SQL function.
///
/// // SUM(amount)
/// sum(Column("amount"))
public func sum(_ value: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionFunction(.sum, arguments: value)
}
// MARK: - Swift String functions
extension SQLSpecificExpressible {
/// Returns an SQL expression that applies the Swift's built-in
/// capitalized String property. It is NULL for non-String arguments.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn.capitalized)
/// let names = try String.fetchAll(dbQueue, request) // [String]
public var capitalized: SQLExpression {
return DatabaseFunction.capitalize.apply(sqlExpression)
}
/// Returns an SQL expression that applies the Swift's built-in
/// lowercased String property. It is NULL for non-String arguments.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn.lowercased())
/// let names = try String.fetchAll(dbQueue, request) // [String]
public var lowercased: SQLExpression {
return DatabaseFunction.lowercase.apply(sqlExpression)
}
/// Returns an SQL expression that applies the Swift's built-in
/// uppercased String property. It is NULL for non-String arguments.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn.uppercased())
/// let names = try String.fetchAll(dbQueue, request) // [String]
public var uppercased: SQLExpression {
return DatabaseFunction.uppercase.apply(sqlExpression)
}
}
extension SQLSpecificExpressible {
/// Returns an SQL expression that applies the Swift's built-in
/// localizedCapitalized String property. It is NULL for non-String arguments.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn.localizedCapitalized)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
public var localizedCapitalized: SQLExpression {
return DatabaseFunction.localizedCapitalize.apply(sqlExpression)
}
/// Returns an SQL expression that applies the Swift's built-in
/// localizedLowercased String property. It is NULL for non-String arguments.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn.localizedLowercased)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
public var localizedLowercased: SQLExpression {
return DatabaseFunction.localizedLowercase.apply(sqlExpression)
}
/// Returns an SQL expression that applies the Swift's built-in
/// localizedUppercased String property. It is NULL for non-String arguments.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn.localizedUppercased)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
public var localizedUppercased: SQLExpression {
return DatabaseFunction.localizedUppercase.apply(sqlExpression)
}
}
| mit | df38bbf32c35172ffefa5ca05365cd6a | 30.82243 | 106 | 0.670485 | 4.468504 | false | false | false | false |
ben-ng/swift | benchmark/single-source/Integrate.swift | 1 | 1923 | //===--- Integrate.swift --------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
// A micro-benchmark for recursive divide and conquer problems.
// The program performs integration via Gaussian Quadrature
class Integrate {
static let epsilon = 1.0e-9
let fun: (Double) -> Double
init (f: @escaping (Double) -> Double) {
fun = f
}
private func recEval(_ l: Double, fl: Double, r: Double, fr: Double, a: Double) -> Double {
let h = (r - l) / 2
let hh = h / 2
let c = l + h
let fc = fun(c)
let al = (fl + fc) * hh
let ar = (fr + fc) * hh
let alr = al + ar
let error = abs(alr-a)
if (error < Integrate.epsilon) {
return alr
} else {
let a1 = recEval(c, fl:fc, r:r, fr:fr, a:ar)
let a2 = recEval(l, fl:fl, r:c, fr:fc, a:al)
return a1 + a2
}
}
@inline(never)
func computeArea(_ left: Double, right: Double) -> Double {
return recEval(left, fl:fun(left), r:right, fr:fun(right), a:0)
}
}
@inline(never)
public func run_Integrate(_ N: Int) {
let obj = Integrate(f: { x in (x*x + 1.0) * x})
let left = 0.0
let right = 10.0
let ref_result = 2550.0
let bound = 0.0001
var result = 0.0
for _ in 1...N {
result = obj.computeArea(left, right:right)
if abs(result - ref_result) > bound {
break
}
}
CheckResults(abs(result - ref_result) < bound,
"Incorrect results in Integrate: abs(\(result) - \(ref_result)) > \(bound)")
}
| apache-2.0 | 09b1d8da0a309e6603985801d1ab6de5 | 27.279412 | 93 | 0.565783 | 3.415631 | false | false | false | false |
rockbruno/swiftshield | Sources/SwiftShieldCore/Log/Logger.swift | 1 | 1289 | import Foundation
public protocol LoggerProtocol {
func log(_ message: String, verbose: Bool, sourceKit: Bool)
func fatalError(forMessage message: String) -> NSError
}
extension LoggerProtocol {
func log(_ message: String) {
log(message, verbose: false, sourceKit: false)
}
func log(_ message: String, verbose: Bool) {
log(message, verbose: verbose, sourceKit: false)
}
func log(_ message: String, sourceKit: Bool) {
log(message, verbose: false, sourceKit: sourceKit)
}
}
public struct Logger: LoggerProtocol {
let verbose: Bool
let printSourceKit: Bool
public init(
verbose: Bool = false,
printSourceKit: Bool = false
) {
self.verbose = verbose
self.printSourceKit = printSourceKit
}
public func fatalError(forMessage message: String) -> NSError {
NSError(
domain: "com.rockbruno.swiftshield",
code: 0,
userInfo: [NSLocalizedDescriptionKey: message]
)
}
public func log(_ message: String, verbose: Bool, sourceKit: Bool) {
if sourceKit && !printSourceKit {
return
}
guard verbose == false || self.verbose else {
return
}
print(message)
}
}
| gpl-3.0 | 28b24bc64ad6ac1d6b155ef74c7af7f5 | 24.27451 | 72 | 0.605896 | 4.587189 | false | false | false | false |
iOS-mamu/SS | P/Library/Eureka/Source/Rows/ButtonRowWithPresent.swift | 1 | 3863 | // Rows.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class _ButtonRowWithPresent<T: Equatable, VCType: TypedRowControllerType>: Row<T, ButtonCellOf<T>>, PresenterRowType where VCType: UIViewController, VCType.RowValue == T {
open var presentationMode: PresentationMode<VCType>?
open var onPresentCallback : ((FormViewController, VCType)->())?
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = nil
cellStyle = .default
}
open override func customUpdateCell() {
super.customUpdateCell()
let leftAligmnment = presentationMode != nil
cell.textLabel?.textAlignment = leftAligmnment ? .left : .center
cell.accessoryType = !leftAligmnment || isDisabled ? .none : .disclosureIndicator
cell.editingAccessoryType = cell.accessoryType
if (!leftAligmnment){
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
cell.tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
cell.textLabel?.textColor = UIColor(red: red, green: green, blue: blue, alpha:isDisabled ? 0.3 : 1.0)
}
else{
cell.textLabel?.textColor = nil
}
}
open override func customDidSelect() {
super.customDidSelect()
if let presentationMode = presentationMode, !isDisabled {
if let controller = presentationMode.createController(){
controller.row = self
onPresentCallback?(cell.formViewController()!, controller)
presentationMode.presentViewController(controller, row: self, presentingViewController: cell.formViewController()!)
}
else{
presentationMode.presentViewController(nil, row: self, presentingViewController: cell.formViewController()!)
}
}
}
open override func prepareForSegue(_ segue: UIStoryboardSegue) {
super.prepareForSegue(segue)
guard let rowVC = segue.destination as? VCType else {
return
}
if let callback = self.presentationMode?.completionHandler{
rowVC.completionCallback = callback
}
rowVC.row = self
onPresentCallback?(cell.formViewController()!, rowVC)
}
}
//MARK: Rows
/// A generic row with a button that presents a view controller when tapped
public final class ButtonRowWithPresent<T: Equatable, VCType: TypedRowControllerType> : _ButtonRowWithPresent<T, VCType>, RowType where VCType: UIViewController, VCType.RowValue == T {
public required init(tag: String?) {
super.init(tag: tag)
}
}
| mit | 73e0177b942752579c6579fcf0cf3ca7 | 40.537634 | 184 | 0.6803 | 5.043081 | false | false | false | false |
Latyntsev/bumper | bumper/Parametres.swift | 1 | 1883 | //
// Parametres.swift
// bumper
//
// Created by Aleksandr Latyntsev on 1/12/16.
// Copyright © 2016 Aleksandr Latyntsev. All rights reserved.
//
import Foundation
class Parametres {
var imagesFolderPath: String?
var text = ""
var fontName = "Menlo Regular"
var help = false
var showVersion = false
private func parseArgument() {
var setParametersValueHandler: ((value: String) -> Void)?
let arguments = Process.arguments
for argument in arguments[1..<arguments.count] {
if setParametersValueHandler == nil {
switch argument.lowercaseString {
case "-path":
setParametersValueHandler = {(value) -> Void in
self.imagesFolderPath = value
}
case "-text":
setParametersValueHandler = {(value) -> Void in
self.text = value.stringByReplacingOccurrencesOfString("\\n", withString: "\n")
}
case "-fontName":
setParametersValueHandler = {(value) -> Void in
self.fontName = value
}
case "-help", "--h":
self.help = true
case "-version", "--v":
self.showVersion = true
default:
break
}
} else {
if (setParametersValueHandler != nil) {
setParametersValueHandler!(value: argument)
setParametersValueHandler = nil
}
}
}
}
init() {
self.parseArgument()
}
} | mit | 35f0f01e97a34a3d8091cade11685581 | 28.421875 | 103 | 0.443677 | 6.252492 | false | false | false | false |
mrdepth/Neocom | Neocom/Neocom/Fitting/Actions/DamagePatternsCustom.swift | 2 | 4278 | //
// DamagePatternsCustom.swift
// Neocom
//
// Created by Artem Shimanski on 3/19/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import Dgmpp
import Expressible
import CoreData
struct DamagePatternsCustom: View {
var onSelect: (DGMDamageVector) -> Void
@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \DamagePattern.name, ascending: true)])
private var damagePatterns: FetchedResults<DamagePattern>
var body: some View {
Section(header: Text("CUSTOM")) {
ForEach(damagePatterns, id: \.objectID) { row in
CustomDamagePatternCell(damagePattern: row, onSelect: self.onSelect)
}.onDelete { (indices) in
indices.map{self.damagePatterns[$0]}.forEach {$0.managedObjectContext?.delete($0)}
}
NewDamagePatternButton()
}
}
}
struct CustomDamagePatternCell: View {
var damagePattern: DamagePattern
var onSelect: (DGMDamageVector) -> Void
@Environment(\.editMode) private var editMode
@Environment(\.self) private var environment
@State private var selectedDamagePattern: DamagePattern?
@EnvironmentObject private var sharedState: SharedState
private func action() {
if editMode?.wrappedValue == .active {
self.selectedDamagePattern = damagePattern
}
else {
self.onSelect(damagePattern.damageVector)
}
}
var body: some View {
Button(action: action) {
VStack(alignment: .leading, spacing: 4) {
if damagePattern.name?.isEmpty == false {
Text(damagePattern.name!)
}
else {
Text("Unnamed").italic()
}
DamageVectorView(damage: damagePattern.damageVector)
}.contentShape(Rectangle())
}.buttonStyle(PlainButtonStyle())
.sheet(item: $selectedDamagePattern) { pattern in
NavigationView {
DamagePatternEditor(damagePattern: pattern) {
self.selectedDamagePattern = nil
}
}
.modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState))
.navigationViewStyle(StackNavigationViewStyle())
}
}
}
struct NewDamagePatternButton: View {
@State private var selectedDamagePattern: DamagePattern?
@Environment(\.self) private var environment
@Environment(\.managedObjectContext) private var managedObjectContext
@EnvironmentObject private var sharedState: SharedState
var body: some View {
Button(action: {
self.selectedDamagePattern = DamagePattern(entity: NSEntityDescription.entity(forEntityName: "DamagePattern", in: self.managedObjectContext)!, insertInto: nil)
self.selectedDamagePattern?.damageVector = .omni
}) {
Text("Add New Pattern").frame(maxWidth: .infinity, alignment: .center)
.frame(height: 30)
.contentShape(Rectangle())
}
.buttonStyle(BorderlessButtonStyle())
.sheet(item: $selectedDamagePattern) { pattern in
NavigationView {
DamagePatternEditor(damagePattern: pattern) {
self.selectedDamagePattern = nil
}
}
.modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState))
.navigationViewStyle(StackNavigationViewStyle())
}
}
}
#if DEBUG
struct DamagePatternsCustom_Previews: PreviewProvider {
static var previews: some View {
if (try? Storage.testStorage.persistentContainer.viewContext.from(DamagePattern.self).count()) == 0 {
let pattern = DamagePattern(context: Storage.testStorage.persistentContainer.viewContext)
pattern.name = "Pattern1"
pattern.em = 2
pattern.thermal = 1
}
return NavigationView {
List {
DamagePatternsCustom { _ in}
}.listStyle(GroupedListStyle())
.navigationBarItems(trailing: EditButton())
}
.modifier(ServicesViewModifier.testModifier())
}
}
#endif
| lgpl-2.1 | f15e0d2d0129d1c7d0cab41720afa2a9 | 34.347107 | 171 | 0.625205 | 5.313043 | false | false | false | false |
iDevelopper/PBRevealViewController | ExampleWithSwiftLibrary/ExampleWithSwiftLibrary/SettingsViewController.swift | 1 | 8634 | //
// SettingsViewController.swift
// ExampleWithSwiftLibrary
//
// Created by Patrick BODET on 19/08/2017.
// Copyright © 2017 iDevelopper. All rights reserved.
//
import UIKit
import PBRevealViewController
class SettingsViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var leftButton: UIBarButtonItem!
@IBOutlet weak var rightButton: UIBarButtonItem!
@IBOutlet weak var leftBlurSegmentedControl: UISegmentedControl!
@IBOutlet weak var rightBlurSegmentedControl: UISegmentedControl!
@IBOutlet weak var leftPresentOnTopSwitch: UISwitch!
@IBOutlet weak var rightPresentOnTopSwitch: UISwitch!
@IBOutlet weak var leftHierarchicallySwitch: UISwitch!
@IBOutlet weak var rightHierarchicallySwitch: UISwitch!
@IBOutlet weak var leftRevealWidthField: UITextField!
@IBOutlet weak var rightRevealWidthField: UITextField!
@IBOutlet weak var leftOverdrawField: UITextField!
@IBOutlet weak var rightOverdrawField: UITextField!
@IBOutlet weak var leftDisplacementField: UITextField!
@IBOutlet weak var rightDisplacementField: UITextField!
@IBOutlet weak var leftPanBoderWidthField: UITextField!
@IBOutlet weak var rightPanBoderWidthField: UITextField!
@IBOutlet weak var toolBar: UIToolbar!
var currentTextField: UITextField?
var isMainUserInteraction: Bool = true
let styles:[PBRevealBlurEffectStyle] = [.none, .extraLight, .light, .dark]
override func viewDidLoad() {
super.viewDidLoad()
leftButton.target = self.revealViewController()
leftButton.action = #selector(PBRevealViewController.revealLeftView)
rightButton.target = self.revealViewController()
rightButton.action = #selector(PBRevealViewController.revealRightView)
leftBlurSegmentedControl.selectedSegmentIndex = (revealViewController()?.leftViewBlurEffectStyle.rawValue)! + 1
rightBlurSegmentedControl.selectedSegmentIndex = (revealViewController()?.rightViewBlurEffectStyle.rawValue)! + 1
leftPresentOnTopSwitch.isOn = (revealViewController()?.isLeftPresentViewOnTop)!
rightPresentOnTopSwitch.isOn = (revealViewController()?.isRightPresentViewOnTop)!
leftHierarchicallySwitch.isOn = (revealViewController()?.isLeftPresentViewHierarchically)!
rightHierarchicallySwitch.isOn = (revealViewController()?.isRightPresentViewHierarchically)!
Bundle.main.loadNibNamed("KeyboardTool", owner: self, options: nil)
leftRevealWidthField.inputAccessoryView = toolBar
leftRevealWidthField.text = "\(Int((revealViewController()?.leftViewRevealWidth)!))"
rightRevealWidthField.inputAccessoryView = toolBar
rightRevealWidthField.text = "\(Int((revealViewController()?.rightViewRevealWidth)!))"
leftOverdrawField.inputAccessoryView = toolBar
leftOverdrawField.text = "\(Int((revealViewController()?.leftViewRevealOverdraw)!))"
rightOverdrawField.inputAccessoryView = toolBar
rightOverdrawField.text = "\(Int((revealViewController()?.rightViewRevealOverdraw)!))"
leftDisplacementField.inputAccessoryView = toolBar
leftDisplacementField.text = "\(Int((revealViewController()?.leftViewRevealDisplacement)!))"
rightDisplacementField.inputAccessoryView = toolBar
rightDisplacementField.text = "\(Int((revealViewController()?.rightViewRevealDisplacement)!))"
leftPanBoderWidthField.inputAccessoryView = toolBar
leftPanBoderWidthField.text = "\(Int((revealViewController()?.panFromLeftBorderWidth)!))"
rightPanBoderWidthField.inputAccessoryView = toolBar
rightPanBoderWidthField.text = "\(Int((revealViewController()?.panFromRightBorderWidth)!))"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func blurValueChanged(_ sender: UISegmentedControl) {
switch sender.tag {
case 100: // Left
revealViewController()?.leftViewBlurEffectStyle = styles[sender.selectedSegmentIndex]
let nc = revealViewController()?.leftViewController as! UINavigationController
let controller = nc.topViewController as! MenuTableViewController
if sender.selectedSegmentIndex == 0 {
controller.tableView.backgroundColor = UIColor.white
}
controller.tableView.reloadData()
case 200: // Right
revealViewController()?.rightViewBlurEffectStyle = styles[sender.selectedSegmentIndex]
let nc = revealViewController()?.rightViewController as! UINavigationController
let controller = nc.topViewController as! MenuTableViewController
if sender.selectedSegmentIndex == 0 {
controller.tableView.backgroundColor = UIColor.white
}
controller.tableView.reloadData()
default:
break
}
}
@IBAction func onTopValueChanged(_ sender: UISwitch) {
switch sender.tag {
case 100: // Left
revealViewController()?.isLeftPresentViewOnTop = sender.isOn
if !sender.isOn {
revealViewController()?.isLeftPresentViewHierarchically = false
leftHierarchicallySwitch.isOn = false
}
case 200: // Right
revealViewController()?.isRightPresentViewOnTop = sender.isOn
if !sender.isOn {
revealViewController()?.isRightPresentViewHierarchically = false
rightHierarchicallySwitch.isOn = false
}
default:
break
}
}
@IBAction func hierarchicallyValueChanged(_ sender: UISwitch) {
switch sender.tag {
case 100: // Left
revealViewController()?.isLeftPresentViewHierarchically = sender.isOn
if sender.isOn {
revealViewController()?.isLeftPresentViewOnTop = true
leftPresentOnTopSwitch.isOn = true
}
case 200: // Right
revealViewController()?.isRightPresentViewHierarchically = sender.isOn
if sender.isOn {
revealViewController()?.isRightPresentViewOnTop = true
rightPresentOnTopSwitch.isOn = true
}
default:
break
}
}
@IBAction func mainUserInteractionValueChanged(_ sender: UISwitch) {
isMainUserInteraction = sender.isOn
}
func textFieldDidBeginEditing(_ textField: UITextField) {
currentTextField = textField
let contentOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height)
scrollView.setContentOffset(contentOffset, animated: true)
}
@IBAction func clear(_ sender: UIBarButtonItem) {
currentTextField?.text = nil
}
@IBAction func done(_ sender: UIBarButtonItem) {
if currentTextField == leftRevealWidthField {
revealViewController()?.leftViewRevealWidth = CGFloat(Float(currentTextField!.text!)!)
}
if currentTextField == rightRevealWidthField {
revealViewController()?.rightViewRevealWidth = CGFloat(Float(currentTextField!.text!)!)
}
if currentTextField == leftOverdrawField {
revealViewController()?.leftViewRevealOverdraw = CGFloat(Float(currentTextField!.text!)!)
}
if currentTextField == rightOverdrawField {
revealViewController()?.rightViewRevealOverdraw = CGFloat(Float(currentTextField!.text!)!)
}
if currentTextField == leftDisplacementField {
revealViewController()?.leftViewRevealDisplacement = CGFloat(Float(currentTextField!.text!)!)
}
if currentTextField == rightDisplacementField {
revealViewController()?.rightViewRevealDisplacement = CGFloat(Float(currentTextField!.text!)!)
}
if currentTextField == leftPanBoderWidthField {
revealViewController()?.panFromLeftBorderWidth = CGFloat(Float(currentTextField!.text!)!)
}
if currentTextField == rightPanBoderWidthField {
revealViewController()?.panFromRightBorderWidth = CGFloat(Float(currentTextField!.text!)!)
}
currentTextField?.resignFirstResponder()
let contentOffset = CGPoint(x: 0, y: -scrollView.contentInset.top)
scrollView.setContentOffset(contentOffset, animated: true)
}
}
| mit | 569501d3d0cd9a2c5f68ba6fd619e19d | 43.271795 | 121 | 0.68632 | 6.481231 | false | false | false | false |
testpress/ios-app | ios-app/UI/TargetThreatViewController.swift | 1 | 4111 | //
// TargetThreatViewController.swift
// ios-app
//
// Copyright © 2017 Testpress. 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 ObjectMapper
import UIKit
import XLPagerTabStrip
class TargetThreatViewController: BaseTableViewController<Reputation>, BaseTableViewDelegate,
IndicatorInfoProvider {
var userReputation: Reputation?
var startingRank: Int = 1
override func viewDidLoad() {
super.viewDidLoad()
tableViewDelegate = self
tableView.register(
UINib(nibName: Constants.LEADERBOARD_TABLE_VIEW_CELL, bundle: Bundle.main),
forCellReuseIdentifier: Constants.LEADERBOARD_TABLE_VIEW_CELL
)
tableView.rowHeight = 80
tableView.allowsSelection = false
tableView.separatorStyle = .none
}
func loadItems() {
// Load targets
TPApiClient.getListItems(
endpointProvider: TPEndpointProvider(.getTargets),
completion: { response, error in
if let error = error {
debugPrint(error.message ?? "No error")
debugPrint(error.kind)
self.handleError(error)
return
}
let items = response!.results.reversed()
self.items.append(contentsOf: items)
if self.userReputation != nil {
self.items.append(self.userReputation!)
self.startingRank = self.userReputation!.rank - items.count
}
self.loadThreats()
},
type: Reputation.self
)
}
func loadThreats() {
TPApiClient.getListItems(
endpointProvider: TPEndpointProvider(.getThreats),
completion: { response, error in
if let error = error {
debugPrint(error.message ?? "No error")
debugPrint(error.kind)
self.handleError(error)
return
}
let items = response!.results.reversed()
self.items.append(contentsOf: items)
self.onLoadFinished(items: self.items)
},
type: Reputation.self
)
}
// MARK: - Table view data source
override func tableViewCell(cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: Constants.LEADERBOARD_TABLE_VIEW_CELL,
for: indexPath
) as! LeaderboardTableViewCell
cell.initCell(reputation: items[indexPath.row],
rank: startingRank + indexPath.row,
userId: userReputation?.user.id)
return cell
}
func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
return IndicatorInfo(title: Strings.TARGETS_AND_THREATS)
}
}
| mit | c64d22f742c8168f3e8015e3aed689ed | 36.027027 | 99 | 0.615572 | 5.18285 | false | false | false | false |
TalkingBibles/Talking-Bible-iOS | TalkingBible/Notification.swift | 1 | 2005 | //
// Copyright 2015 Talking Bibles International
//
// 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
class Box<T> {
let unbox: T
init(_ value: T) { self.unbox = value }
}
class Notification<A> {
let name: String
var observers: [String: NSObjectProtocol] = [:]
init(name: String) {
self.name = name
}
}
func postNotification<A>(note: Notification<A>, value: A) {
let userInfo = ["value": Box(value)]
NSNotificationCenter.defaultCenter().postNotificationName(note.name, object: nil, userInfo: userInfo)
}
class NotificationObserver {
let observer: NSObjectProtocol
init<A>(notification: Notification<A>, withName observerName: String, block aBlock: A -> ()) {
if let observer = notification.observers[observerName] {
NSNotificationCenter.defaultCenter().removeObserver(observer)
}
observer = NSNotificationCenter.defaultCenter().addObserverForName(notification.name, object: nil, queue: nil) { note in
if let value = (note.userInfo?["value"] as? Box<A>)?.unbox {
aBlock(value)
} else if let object = note.object as? A {
aBlock(object)
} else {
assert(false, "Couldn't understand user info")
}
}
notification.observers[observerName] = observer
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(observer)
}
} | apache-2.0 | 26377b76180a7a752371b0fa9e7391d0 | 31.354839 | 128 | 0.652369 | 4.445676 | false | false | false | false |
zerovagner/iOS-Studies | SwappingScreens/SwappingScreens/MusicListViewController.swift | 1 | 1202 | //
// MusicListViewController.swift
// SwappingScreens
//
// Created by Vagner Oliveira on 5/5/17.
// Copyright © 2017 Vagner Oliveira. All rights reserved.
//
import UIKit
class MusicListViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.blue
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backButtonPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func load3rdScreenButtonPressed(_ sender: Any) {
let songTitle = "Smells Like Teen Spirit"
performSegue(withIdentifier: "musicListPlaySongSegue", sender: songTitle)
}
// 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?) {
if let destination = segue.destination as? PlaySongViewController {
if let song = sender as? String {
destination.selectedSong = song
}
}
}
}
| gpl-3.0 | 135fe8c73c0d7f855f184897eb0a57a6 | 25.688889 | 106 | 0.706911 | 4.214035 | false | false | false | false |
Hodglim/hacking-with-swift | Project-09/Petitions/MasterViewController.swift | 1 | 3926 | //
// MasterViewController.swift
// Petitions
//
// Created by Darren Hodges on 13/10/2015.
// Copyright © 2015 Darren Hodges. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController
{
var detailViewController: DetailViewController? = nil
var objects = [[String: String]]()
override func viewDidLoad()
{
super.viewDidLoad()
let urlString: String
if navigationController?.tabBarItem.tag == 0
{
urlString = "https://api.whitehouse.gov/v1/petitions.json?limit=100"
}
else
{
urlString = "https://api.whitehouse.gov/v1/petitions.json?signatureCountFloor=10000&limit=100"
}
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0))
{
[unowned self] in
if let url = NSURL(string: urlString)
{
if let data = try? NSData(contentsOfURL: url, options: [])
{
let json = JSON(data: data)
if json["metadata"]["responseInfo"]["status"].intValue == 200
{
self.parseJSON(json)
}
else
{
self.showError()
}
}
else
{
self.showError()
}
}
else
{
self.showError()
}
}
}
func parseJSON(json: JSON)
{
for result in json["results"].arrayValue
{
let title = result["title"].stringValue
let body = result["body"].stringValue
let sigs = result["signatureCount"].stringValue
let obj = ["title": title, "body": body, "sigs": sigs]
objects.append(obj)
}
dispatch_async(dispatch_get_main_queue())
{
[unowned self] in
self.tableView.reloadData()
}
}
override func viewWillAppear(animated: Bool)
{
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
func showError()
{
dispatch_async(dispatch_get_main_queue())
{
[unowned self] in
let ac = UIAlertController(title: "Loading error", message: "There was a problem loading the feed; please check your connection and try again.", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(ac, animated: true, completion: nil)
}
}
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = objects[indexPath.row]
cell.textLabel!.text = object["title"]
cell.detailTextLabel!.text = object["body"]
return cell
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "showDetail"
{
if let indexPath = self.tableView.indexPathForSelectedRow
{
let object = objects[indexPath.row]
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
}
| mit | a115d2ab6b2bc23cd723b0a7457b6d86 | 27.860294 | 180 | 0.593885 | 4.937107 | false | false | false | false |
nikita-leonov/boss-client | BoSS/Models/Transformers/LocationTransform.swift | 1 | 1119 | //
// LocationTransform.swift
// BoSS
//
// Created by Emanuele Rudel on 28/02/15.
// Copyright (c) 2015 Bureau of Street Services. All rights reserved.
//
import Foundation
import CoreLocation
import ObjectMapper
class LocationTransform: TransformType {
typealias Object = CLLocation
typealias JSON = [String: Double]
private let latitudeKey = "lat"
private let longitudeKey = "lng"
required init() {
}
func transformFromJSON(value: AnyObject?) -> Object? {
var result: Object?
if let geopoint = value as? [String: Double] {
if let latitude = geopoint[latitudeKey], longitude = geopoint[longitudeKey] {
result = CLLocation(latitude: latitude, longitude: longitude)
}
}
return result
}
func transformToJSON(value: Object?) -> JSON? {
var result: JSON?
if let coordinate = value?.coordinate {
result = [latitudeKey: coordinate.latitude, longitudeKey: coordinate.longitude]
}
return result
}
} | mit | 92580e0188d9f8b4ea88916b2c8691db | 23.347826 | 91 | 0.60143 | 4.586066 | false | false | false | false |
lhc70000/iina | iina/FilterPresets.swift | 2 | 7539 | //
// FilterPresets.swift
// iina
//
// Created by lhc on 25/8/2017.
// Copyright © 2017 lhc. All rights reserved.
//
import Foundation
fileprivate typealias PM = FilterParameter
/**
A fliter preset or tamplate, which contains the filter name and definitions of all parameters.
*/
class FilterPreset {
typealias Transformer = (FilterPresetInstance) -> MPVFilter
private static let defaultTransformer: Transformer = { instance in
return MPVFilter(lavfiFilterFromPresetInstance: instance)
}
var name: String
var params: [String: FilterParameter]
var paramOrder: [String]?
/** Given an instance, create the corresponding `MPVFilter`. */
var transformer: Transformer
var localizedName: String {
return FilterPreset.l10nDic[name] ?? name
}
init(_ name: String,
params: [String: FilterParameter],
paramOrder: String? = nil,
transformer: @escaping Transformer = FilterPreset.defaultTransformer) {
self.name = name
self.params = params
self.paramOrder = paramOrder?.components(separatedBy: ":")
self.transformer = transformer
}
func localizedParamName(_ param: String) -> String {
return FilterPreset.l10nDic["\(name).\(param)"] ?? param
}
}
/**
An instance of a filter preset, with concrete values for each parameter.
*/
class FilterPresetInstance {
var preset: FilterPreset
var params: [String: FilterParameterValue] = [:]
init(from preset: FilterPreset) {
self.preset = preset
}
func value(for name: String) -> FilterParameterValue {
return params[name] ?? preset.params[name]!.defaultValue
}
}
/**
Definition of a filter parameter. It can be one of several types:
- `text`: A generic string value.
- `int`: An int value with range. It will be rendered as a slider.
- `float`: A float value with range. It will be rendered as a slider.
*/
class FilterParameter {
enum ParamType {
case text, int, float, choose
}
var type: ParamType
var defaultValue: FilterParameterValue
// for float
var min: Float?
var max: Float?
// for int
var minInt: Int?
var maxInt: Int?
var step: Int?
// for choose
var choices: [String] = []
static func text(defaultValue: String = "") -> FilterParameter {
return FilterParameter(.text, defaultValue: FilterParameterValue(string: defaultValue))
}
static func int(min: Int, max: Int, step: Int = 1, defaultValue: Int = 0) -> FilterParameter {
let pm = FilterParameter(.int, defaultValue: FilterParameterValue(int: defaultValue))
pm.minInt = min
pm.maxInt = max
pm.step = step
return pm
}
static func float(min: Float, max: Float, defaultValue: Float = 0) -> FilterParameter {
let pm = FilterParameter(.float, defaultValue: FilterParameterValue(float: defaultValue))
pm.min = min
pm.max = max
return pm
}
static func choose(from choices: [String], defaultChoiceIndex: Int = 0) -> FilterParameter {
guard !choices.isEmpty else { fatalError("FilterParameter: Choices cannot be empty") }
let pm = FilterParameter(.choose, defaultValue: FilterParameterValue(string: choices[defaultChoiceIndex]))
pm.choices = choices
return pm
}
private init(_ type: ParamType, defaultValue: FilterParameterValue) {
self.type = type
self.defaultValue = defaultValue
}
}
/**
The structure to store values of different param types.
*/
struct FilterParameterValue {
private var _stringValue: String?
private var _intValue: Int?
private var _floatValue: Float?
var stringValue: String {
return _stringValue ?? _intValue?.description ?? _floatValue?.description ?? ""
}
var intValue: Int {
return _intValue ?? 0
}
var floatValue: Float {
return _floatValue ?? 0
}
init(string: String) {
self._stringValue = string
}
init(int: Int) {
self._intValue = int
}
init(float: Float) {
self._floatValue = float
}
}
/** Related data. */
extension FilterPreset {
/** Preloaded localization. */
static let l10nDic: [String: String] = {
guard let filePath = Bundle.main.path(forResource: "FilterPresets", ofType: "strings"),
let dic = NSDictionary(contentsOfFile: filePath) as? [String : String] else {
return [:]
}
return dic
}()
static private let customMPVFilterPreset = FilterPreset("custom_mpv", params: ["name": PM.text(defaultValue: ""), "string": PM.text(defaultValue: "")]) { instance in
return MPVFilter(rawString: instance.value(for: "name").stringValue + "=" + instance.value(for: "string").stringValue)!
}
// custom ffmpeg
static private let customFFmpegFilterPreset = FilterPreset("custom_ffmpeg", params: [ "name": PM.text(defaultValue: ""), "string": PM.text(defaultValue: "") ]) { instance in
return MPVFilter(name: "lavfi", label: nil, paramString: "[\(instance.value(for: "name").stringValue)=\(instance.value(for: "string").stringValue)]")
}
/** All filter presets. */
static let vfPresets: [FilterPreset] = [
// crop
FilterPreset("crop", params: [
"x": PM.text(), "y": PM.text(),
"w": PM.text(), "h": PM.text()
], paramOrder: "w:h:x:y") { instance in
return MPVFilter(mpvFilterFromPresetInstance: instance)
},
// expand
FilterPreset("expand", params: [
"x": PM.text(), "y": PM.text(),
"w": PM.text(), "h": PM.text(),
"aspect": PM.text(defaultValue: "0"),
"round": PM.text(defaultValue: "1")
], paramOrder: "w:h:x:y:aspect:round") { instance in
return MPVFilter(mpvFilterFromPresetInstance: instance)
},
// sharpen
FilterPreset("sharpen", params: [
"amount": PM.float(min: 0, max: 1.5),
"msize": PM.int(min: 3, max: 23, step: 2, defaultValue: 5)
]) { instance in
return MPVFilter.unsharp(amount: instance.value(for: "amount").floatValue,
msize: instance.value(for: "msize").intValue)
},
// blur
FilterPreset("blur", params: [
"amount": PM.float(min: 0, max: 1.5),
"msize": PM.int(min: 3, max: 23, step: 2, defaultValue: 5)
]) { instance in
return MPVFilter.unsharp(amount: -instance.value(for: "amount").floatValue,
msize: instance.value(for: "msize").intValue)
},
// delogo
FilterPreset("delogo", params: [
"x": PM.text(defaultValue: "1"),
"y": PM.text(defaultValue: "1"),
"w": PM.text(defaultValue: "1"),
"h": PM.text(defaultValue: "1")
], paramOrder: "x:y:w:h"),
// invert color
FilterPreset("negative", params: [:]) { instance in
return MPVFilter(lavfiName: "lutrgb", label: nil, paramDict: [
"r": "negval", "g": "negval", "b": "negval"
])
},
// flip
FilterPreset("vflip", params: [:]) { instance in
return MPVFilter(mpvFilterFromPresetInstance: instance)
},
// mirror
FilterPreset("hflip", params: [:]) { instance in
return MPVFilter(mpvFilterFromPresetInstance: instance)
},
// 3d lut
FilterPreset("lut3d", params: [
"file": PM.text(),
"interp": PM.choose(from: ["nearest", "trilinear", "tetrahedral"], defaultChoiceIndex: 0)
]) { instance in
return MPVFilter(lavfiName: "lut3d", label: nil, paramDict: [
"file": instance.value(for: "file").stringValue,
"interp": instance.value(for: "interp").stringValue,
])
},
// custom
customMPVFilterPreset,
customFFmpegFilterPreset
]
static let afPresets: [FilterPreset] = [
customMPVFilterPreset,
customFFmpegFilterPreset
]
}
| gpl-3.0 | 5b13a38c19d8719d3fc3c22ed8f866c3 | 29.767347 | 175 | 0.648581 | 4.031016 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/User Profile Sheet/UserProfileUserInfoCell.swift | 2 | 1757 | class UserProfileUserInfoCell: UITableViewCell, NibReusable {
// MARK: - Properties
@IBOutlet weak var gravatarImageView: CircularImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var userBioLabel: UILabel!
static let estimatedRowHeight: CGFloat = 200
// MARK: - View
override func awakeFromNib() {
super.awakeFromNib()
configureCell()
}
// MARK: - Public Methods
func configure(withUser user: LikeUser) {
nameLabel.text = user.displayName
usernameLabel.text = String(format: Constants.usernameFormat, user.username)
userBioLabel.text = user.bio
userBioLabel.isHidden = user.bio.isEmpty
downloadGravatarWithURL(user.avatarUrl)
}
}
// MARK: - Private Extension
private extension UserProfileUserInfoCell {
func configureCell() {
nameLabel.textColor = .text
nameLabel.font = WPStyleGuide.serifFontForTextStyle(.title3, fontWeight: .semibold)
usernameLabel.textColor = .textSubtle
userBioLabel.textColor = .text
}
func downloadGravatarWithURL(_ url: String?) {
// Always reset gravatar
gravatarImageView.cancelImageDownload()
gravatarImageView.image = .gravatarPlaceholderImage
guard let url = url,
let gravatarURL = URL(string: url) else {
return
}
gravatarImageView.downloadImage(from: gravatarURL, placeholderImage: .gravatarPlaceholderImage)
}
struct Constants {
static let usernameFormat = NSLocalizedString("@%1$@", comment: "Label displaying the user's username preceeded by an '@' symbol. %1$@ is a placeholder for the username.")
}
}
| gpl-2.0 | a747b76080ee99aff6f321b286db2475 | 27.803279 | 179 | 0.677291 | 5.107558 | false | false | false | false |
winkelsdorf/SwiftWebViewProgress | SwiftWebViewProgress/SwiftWebViewProgress/SwiftWebViewProgress.swift | 1 | 6726 | //
// SwiftWebViewProgress.swift
// SwiftWebViewProgress
//
// Created by Daichi Ichihara on 2014/12/03.
// Copyright (c) 2014 MokuMokuCloud. All rights reserved.
//
import UIKit
protocol WebViewProgressDelegate {
func webViewProgress(webViewProgress: WebViewProgress, updateProgress progress: Float)
}
class WebViewProgress: NSObject, UIWebViewDelegate {
var progressDelegate: WebViewProgressDelegate?
var webViewProxyDelegate: UIWebViewDelegate?
var progress: Float = 0.0
private var loadingCount: Int!
private var maxLoadCount: Int!
private var currentUrl: NSURL?
private var interactive: Bool!
private let InitialProgressValue: Float = 0.1
private let InteractiveProgressValue: Float = 0.5
private let FinalProgressValue: Float = 0.9
private let completePRCURLPath = "/webviewprogressproxy/complete"
// MARK: Initializer
override init() {
super.init()
maxLoadCount = 0
loadingCount = 0
interactive = false
}
// MARK: Private Method
private func startProgress() {
if progress < InitialProgressValue {
setProgress(InitialProgressValue)
}
}
private func incrementProgress() {
var progress = self.progress
var maxProgress = interactive == true ? FinalProgressValue : InteractiveProgressValue
let remainPercent = Float(loadingCount / maxLoadCount)
let increment = (maxProgress - progress) / remainPercent
progress += increment
progress = fmin(progress, maxProgress)
setProgress(progress)
}
private func completeProgress() {
setProgress(1.0)
}
private func setProgress(progress: Float) {
if progress > self.progress || progress == 0 {
self.progress = progress
progressDelegate?.webViewProgress(self, updateProgress: progress)
}
}
// MARK: Public Method
func reset() {
maxLoadCount = 0
loadingCount = 0
interactive = false
setProgress(0.0)
}
// MARK: - UIWebViewDelegate
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.URL!.path == completePRCURLPath {
completeProgress()
return false
}
var ret = true
if webViewProxyDelegate!.respondsToSelector("webView:shouldStartLoadWithRequest:navigationType:") {
ret = webViewProxyDelegate!.webView!(webView, shouldStartLoadWithRequest: request, navigationType: navigationType)
}
var isFragmentJump = false
if let fragmentURL = request.URL?.fragment {
let nonFragmentURL = request.URL?.absoluteString?.stringByReplacingOccurrencesOfString("#"+fragmentURL, withString: "")
isFragmentJump = nonFragmentURL == webView.request!.URL?.absoluteString
}
var isTopLevelNavigation = request.mainDocumentURL! == request.URL
var isHTTP = request.URL?.scheme == "http" || request.URL?.scheme == "https"
if ret && !isFragmentJump && isHTTP && isTopLevelNavigation {
currentUrl = request.URL
reset()
}
return ret
}
func webViewDidStartLoad(webView: UIWebView) {
if webViewProxyDelegate!.respondsToSelector("webViewDidStartLoad:") {
webViewProxyDelegate!.webViewDidStartLoad!(webView)
}
loadingCount = loadingCount + 1
maxLoadCount = Int(fmax(Double(maxLoadCount), Double(loadingCount)))
startProgress()
}
func webViewDidFinishLoad(webView: UIWebView) {
if webViewProxyDelegate!.respondsToSelector("webViewDidFinishLoad:") {
webViewProxyDelegate!.webViewDidFinishLoad!(webView)
}
loadingCount = loadingCount - 1
// incrementProgress()
let readyState = webView.stringByEvaluatingJavaScriptFromString("document.readyState")
var interactive = readyState == "interactive"
if interactive {
self.interactive = true
let waitForCompleteJS = "window.addEventListener('load',function() { var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = '\(webView.request?.mainDocumentURL?.scheme)://\(webView.request?.mainDocumentURL?.host)\(completePRCURLPath)'; document.body.appendChild(iframe); }, false);"
webView.stringByEvaluatingJavaScriptFromString(waitForCompleteJS)
}
var isNotRedirect: Bool
if let _currentUrl = currentUrl {
if _currentUrl == webView.request?.mainDocumentURL {
isNotRedirect = true
} else {
isNotRedirect = false
}
} else {
isNotRedirect = false
}
var complete = readyState == "complete"
if complete && isNotRedirect {
completeProgress()
}
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
if webViewProxyDelegate!.respondsToSelector("webView:didFailLoadWithError:") {
webViewProxyDelegate!.webView!(webView, didFailLoadWithError: error)
}
loadingCount = loadingCount - 1
// incrementProgress()
let readyState = webView.stringByEvaluatingJavaScriptFromString("document.readyState")
var interactive = readyState == "interactive"
if interactive {
self.interactive = true
let waitForCompleteJS = "window.addEventListener('load',function() { var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = '\(webView.request?.mainDocumentURL?.scheme)://\(webView.request?.mainDocumentURL?.host)\(completePRCURLPath)'; document.body.appendChild(iframe); }, false);"
webView.stringByEvaluatingJavaScriptFromString(waitForCompleteJS)
}
var isNotRedirect: Bool
if let _currentUrl = currentUrl {
if _currentUrl == webView.request?.mainDocumentURL {
isNotRedirect = true
} else {
isNotRedirect = false
}
} else {
isNotRedirect = false
}
var complete = readyState == "complete"
if complete && isNotRedirect {
completeProgress()
}
}
}
| mit | 9df329aceef447509dbe206f04cde179 | 35.366667 | 331 | 0.615076 | 5.818339 | false | false | false | false |
narner/AudioKit | Playgrounds/AudioKitPlaygrounds/Playgrounds/Analysis.playground/Pages/FFT Analysis.xcplaygroundpage/Contents.swift | 1 | 480 | //: ## FFT Analysis
//:
import AudioKitPlaygrounds
import AudioKit
let file = try AKAudioFile(readFileName: "leadloop.wav")
var player = try AKAudioPlayer(file: file)
player.looping = true
AudioKit.output = player
AudioKit.start()
player.play()
let fft = AKFFTTap(player)
AKPlaygroundLoop(every: 0.1) {
if let max = fft.fftData.max() {
let index = fft.fftData.index(of: max)
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
| mit | 215f244c67ae026edb42ce00a249c070 | 19.869565 | 56 | 0.73125 | 3.692308 | false | false | false | false |
bsmith11/ScoreReporter | ScoreReporterCore/ScoreReporterCore/Services/TeamService.swift | 1 | 5678 | //
// TeamService.swift
// ScoreReporter
//
// Created by Bradley Smith on 11/6/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
import Foundation
public struct TeamService {
fileprivate let client: APIClient
public init(client: APIClient) {
self.client = client
}
}
// MARK: - Public
public extension TeamService {
func downloadTeamList(completion: DownloadCompletion?) {
let parameters: [String: Any] = [
APIConstants.Path.Keys.function: APIConstants.Path.Values.teams
]
client.request(.get, path: "", parameters: parameters) { result in
switch result {
case .success(let value):
self.parseTeamList(response: value, completion: completion)
case .failure(let error):
completion?(DownloadResult(error: error))
}
}
}
func downloadDetails(for team: Team, completion: DownloadCompletion?) {
let parameters: [String: Any] = [
APIConstants.Path.Keys.function: APIConstants.Path.Values.teamDetails,
APIConstants.Request.Keys.teamID: team.teamID.intValue
]
client.request(.get, path: "", parameters: parameters) { result in
switch result {
case .success(let value):
self.parseTeam(response: value, team: team, completion: completion)
case .failure(let error):
completion?(DownloadResult(error: error))
}
}
}
}
// MARK: - Private
private extension TeamService {
func parseTeamList(response: [String: Any], completion: DownloadCompletion?) {
guard let teamArray = response[APIConstants.Response.Keys.teams] as? [[String: AnyObject]] else {
let error = NSError(type: .invalidResponse)
completion?(DownloadResult(error: error))
return
}
Team.teams(from: teamArray) { error in
completion?(DownloadResult(error: error))
}
}
func parseTeam(response: [String: Any], team: Team, completion: DownloadCompletion?) {
guard let responseArray = response[APIConstants.Response.Keys.groups] as? [[String: AnyObject]] else {
let error = NSError(type: .invalidResponse)
completion?(DownloadResult(error: error))
return
}
let partialEventDictionaries = responseArray.flatMap { dictionary -> [String: AnyObject]? in
guard let eventID = dictionary[APIConstants.Response.Keys.eventID] as? NSNumber else {
return nil
}
var partial = [String: AnyObject]()
partial[APIConstants.Response.Keys.eventID] = eventID
partial[APIConstants.Response.Keys.eventName] = dictionary[APIConstants.Response.Keys.eventName]
return partial
}
let eventImportOperations = partialEventDictionaries.map { EventImportOperation(eventDictionary: $0) }
let groupEventTuples = responseArray.flatMap { dictionary -> (NSNumber, NSNumber)? in
guard let eventID = dictionary[APIConstants.Response.Keys.eventID] as? NSNumber,
let groupID = dictionary[APIConstants.Response.Keys.groupID] as? NSNumber else {
return nil
}
return (groupID, eventID)
}
let eventIDs = responseArray.flatMap { $0[APIConstants.Response.Keys.eventID] as? NSNumber }
let eventDetailsOperations = eventIDs.map { EventDetailsOperation(eventID: $0) }
let terminalOperation = BlockOperation {
Group.coreDataStack.performBlockUsingBackgroundContext({ context in
if let contextualTeam = context.object(with: team.objectID) as? Team {
groupEventTuples.forEach { (groupID, eventID) in
let group = Group.object(primaryKey: groupID, context: context)
let event = Event.object(primaryKey: eventID, context: context)
group?.add(team: contextualTeam)
group?.event = event
}
}
}, completion: { error in
completion?(DownloadResult(error: error))
})
}
eventImportOperations.forEach { operation in
eventDetailsOperations.forEach { $0.addDependency(operation) }
}
eventDetailsOperations.forEach { terminalOperation.addDependency($0) }
let queue = OperationQueue()
queue.addOperations(eventImportOperations, waitUntilFinished: false)
queue.addOperations(eventDetailsOperations, waitUntilFinished: false)
queue.addOperation(terminalOperation)
}
}
class EventImportOperation: AsyncOperation {
convenience init(eventDictionary: [String: AnyObject]) {
let block = { (completionHandler: @escaping AsyncOperationCompletionHandler) in
Event.events(from: [eventDictionary], completion: { _ in
print("Finished importing event")
completionHandler()
})
}
self.init(block: block)
}
}
class EventDetailsOperation: AsyncOperation {
convenience init(eventID: NSNumber) {
let block = { (completionHandler: @escaping AsyncOperationCompletionHandler) in
let eventService = EventService(client: APIClient.sharedInstance)
eventService.downloadDetails(for: eventID, completion: { error in
print("Finished downloading \(eventID) with error: \(error)")
completionHandler()
})
}
self.init(block: block)
}
}
| mit | 4a2eca64007e29baa72117772816bbca | 35.159236 | 110 | 0.619165 | 5.064228 | false | false | false | false |
fuzongjian/SwiftStudy | SwiftStudy/Advance/DetailController.swift | 1 | 11559 | //
// DetailController.swift
// SwiftStudy
//
// Created by 付宗建 on 16/8/15.
// Copyright © 2016年 youran. All rights reserved.
//
import UIKit
class DetailController: SuperViewController,UICollectionViewDelegate,UICollectionViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
chooseInit()
// Do any additional setup after loading the view.
}
func chooseInit(){
if self.title == "UILabel"{// Lable
let lable = UILabel(frame: self.view.bounds)
lable.text = "Hello,World"
lable.backgroundColor = UIColor.blueColor()
lable.textAlignment = NSTextAlignment.Center
lable.font = UIFont.boldSystemFontOfSize(25)
self.view.addSubview(lable)
}else if self.title == "UIButton"{// UIButton
let button = UIButton(type: .System)
button.frame = self.view.bounds
button.center = self.view.center
button.setTitle("点我", forState: .Normal)
button.setTitle("点我", forState: .Highlighted)
button.setTitleColor(UIColor.redColor(), forState: .Normal)
button.setTitleColor(UIColor.blueColor(), forState: .Highlighted)
button.addTarget(self, action: #selector(backButtonClicked(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}else if self.title == "UIImageView"{// UIImageView
let image = UIImage(named: "press-to-h")
let imageView = UIImageView(frame: CGRectMake(0, 0, 100, 100))
imageView.center = self.view.center
imageView.image = image
self.view.addSubview(imageView)
}else if self.title == "UISlider"{// UISlider
let slider = UISlider(frame: CGRectMake(0,0,300,30))
slider.center = self.view.center
slider.value = 0.5
self.view.addSubview(slider)
}else if self.title == "UIWebView"{
let webView = UIWebView(frame: self.view.bounds)
let url = NSURL(fileURLWithPath:"http://caipiao.m.taobao.com")
let request = NSURLRequest(URL: url)
webView.loadRequest(request)
self.view.addSubview(webView)
}else if self.title == "UISegmentedControl"{
let segment = UISegmentedControl(items: ["fu","zong","jian"])
segment.frame = CGRectMake(0, 0, 200, 30)
segment.center = self.view.center
self.view.addSubview(segment)
}else if self.title == "UISwitch"{
let swtch = UISwitch(frame: CGRectMake(0,0,100,30))
swtch.on = true
swtch.center = self.view.center
self.view.addSubview(swtch)
}else if self.title == "UITextField"{
let textField = UITextField(frame: CGRectMake(0,0,200,30))
textField.center = self.view.center
textField.borderStyle = .RoundedRect
textField.placeholder = "hello world"
self.view.addSubview(textField)
}else if self.title == "UIScrollView"{
let scroll = UIScrollView(frame: CGRectMake(0,0,200,200))
scroll.center = self.view.center
scroll.pagingEnabled = true
scroll.showsVerticalScrollIndicator = false
self.view.addSubview(scroll)
var fx: CGFloat = 0.0
for i in 1...3{
let view = UIView(frame:CGRectMake(fx,0.0,200,200))
if i == 1{
view.backgroundColor = UIColor.redColor()
}else{
view.backgroundColor = UIColor.blueColor()
}
fx += 200
scroll.addSubview(view)
}
scroll.contentSize = CGSizeMake(3 * 200, 200)
}else if self.title == "UISearchBar"{
let searchbar = UISearchBar(frame: CGRectMake(0,0,300,40))
searchbar.center = self.view.center
searchbar.showsCancelButton = true
searchbar.searchBarStyle = .Minimal
self.view.addSubview(searchbar)
}else if self.title == "UIPageControl"{
let pageControl = UIPageControl(frame: CGRectMake(0,0,200,200))
pageControl.center = self.view.center
pageControl.numberOfPages = 5;
pageControl.currentPage = 2
pageControl.currentPageIndicatorTintColor = UIColor.redColor()
pageControl.pageIndicatorTintColor = UIColor.blueColor()
self.view.addSubview(pageControl)
}else if self.title == "UIDatePicker"{
let datePicker = UIDatePicker(frame: CGRectMake(0,0,300,200))
datePicker.center = self.view.center
self.view.addSubview(datePicker)
}else if self.title == "UIPickerView"{
let pickerView = UIPickerView(frame: CGRectMake(0,0,300,200))
pickerView.center = self.view.center
self.view.addSubview(pickerView)
}else if self.title == "UIProgressView"{
let progress = UIProgressView(progressViewStyle: .Default)
progress.frame = CGRectMake(0, 0, 300, 30)
progress.center = self.view.center
progress.setProgress(0.5, animated: false)
self.view.addSubview(progress)
}else if self.title == "UITextView"{
let textView = UITextView(frame: CGRectMake(0, 0, 300, 200))
textView.center = self.view.center
textView.backgroundColor = UIColor.lightGrayColor()
textView.editable = false
textView.font = UIFont.boldSystemFontOfSize(20)
textView.text = "2012年,魏则西考入西安电子科技大学计算机专业。他成绩优异,排名在班级前5%。2014年4月,魏则西被查出得了滑膜肉瘤。这是一种恶性软组织肿瘤,目前没有有效的治疗手段,生存率极低。休学。2014年5月20日至2014年8月15日,魏则西接连做了4次化疗,25次放疗。2014年9月至2015年底,魏则西先后在武警二院进行了4次生物免疫疗法的治疗,花了二十多万元.治病的巨额花费将家里积蓄掏空,魏则西接受了4次化疗、25次放疗,吃了几百服中药,经历了3次手术。检查出滑膜肉瘤之后,学校曾经组织了募捐活动,在学校食堂放置了几处募捐箱,筹集了8万元钱,也有人进行义卖筹钱。所做的这一切都是希望能够帮助挽回年轻的生命,结果却是未能如愿。"
self.view.addSubview(textView)
}else if self.title == "UIToolbar"{
let toolBar = UIToolbar(frame: CGRectMake(0,0,200,30))
toolBar.center = self.view.center
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
let ItemA = UIBarButtonItem(title: "A", style: .Plain, target: nil, action: nil)
let ItemB = UIBarButtonItem(title: "B", style: .Plain, target: nil, action: nil)
let ItemC = UIBarButtonItem(title: "C", style: .Plain, target: nil, action: nil)
let ItemD = UIBarButtonItem(title: "D", style: .Plain, target: nil, action: nil)
toolBar.items = [flexibleSpace,ItemA,flexibleSpace,ItemB,flexibleSpace,ItemC,flexibleSpace,ItemD,flexibleSpace]
self.view.addSubview(toolBar)
}else if self.title == "UIActionSheet"{
let button = UIButton(type: .System)
button.frame = CGRectMake(0, 0, 100, 40)
button.center = self.view.center
button.setTitle("show", forState: .Normal)
button.setTitle("show", forState: .Highlighted)
button.setTitleColor(UIColor.redColor(), forState: .Normal)
button.setTitleColor(UIColor.blueColor(), forState: .Highlighted)
button.addTarget(self, action: #selector(shouActionSheet(_:)), forControlEvents: .TouchUpInside)
self.view .addSubview(button)
}else if self.title == "UIActivityIndicatorView"{
let activity = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
activity.frame = CGRectMake(0, 0, 40, 40)
activity.center = self.view.center
activity.startAnimating()
self.view.addSubview(activity)
}else if self.title == "UICollectionView"{
let flowlayout = UICollectionViewFlowLayout();
flowlayout.scrollDirection = UICollectionViewScrollDirection.Vertical
let collectionView = UICollectionView(frame: self.view.bounds,collectionViewLayout: flowlayout)
collectionView.backgroundColor = UIColor.whiteColor()
collectionView.delegate = self
collectionView.dataSource = self
self.view.addSubview(collectionView)
collectionView.registerClass(CustomCollectionViewCell.self, forCellWithReuseIdentifier: "ReuseIdentifier")
}
}
func ButtonClicked(sender: UIButton!) {
print("按钮点击事件处理")
}
func shouActionSheet(sender: UIButton){
/*
let alert = UIAlertController(title: "I'm title", message: "choose", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "YES", style: .Default, handler: nil))
alert.addAction(UIAlertAction(title: "NO", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
*/
let alertView = UIAlertView()
alertView.title = "I'm title"
alertView.message = "I'm message"
alertView.addButtonWithTitle("OK")
alertView.addButtonWithTitle("NO")
alertView.show()
}
// UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 30
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ReuseIdentifier", forIndexPath: indexPath) as! CustomCollectionViewCell
cell.imageView?.image = UIImage.init(named: "0.jpg")
// cell.imageView?.image = UIImage(named: String(format: "%ld.jpg", indexPath.row))
cell.imageView?.userInteractionEnabled = true
return cell
}
// UICollectionViewDelegateFlowLayout methods
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(90, 90);
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0);
}
// UICollectionViewDelegate method
func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
print("点击了第\(indexPath.row + 1)张")
}
}
| apache-2.0 | df161b900ce7ef525759a05d56308f73 | 49.805556 | 345 | 0.641243 | 4.47553 | false | false | false | false |
dsmelov/simsim | SimSim/Tools.swift | 1 | 8261 | //
// Tools.swift
// SimSim
//
// Created by Daniil Smelov on 16/04/2018.
// Copyright © 2018 Daniil Smelov. All rights reserved.
//
import Foundation
import Cocoa
//============================================================================
class Tools: NSObject
{
//----------------------------------------------------------------------------
struct Keys
{
static let fileName = "fileName"
static let fileDate = "modificationDate"
static let fileType = "fileType"
}
//----------------------------------------------------------------------------
class func homeDirectoryPath() -> String
{
return NSHomeDirectory()
}
//----------------------------------------------------------------------------
class func simulatorRootPath(byUUID uuid: String) -> String
{
return Tools.homeDirectoryPath() + "/" + Constants.Simulator.rootPath + "/" + uuid + "/"
}
//----------------------------------------------------------------------------
class func getSimulatorProperties() -> NSDictionary?
{
let path = Tools.homeDirectoryPath() + "/Library/Preferences/com.apple.iphonesimulator.plist"
return NSDictionary(contentsOfFile: path)
}
//----------------------------------------------------------------------------
class func simulatorPaths() -> Set<String>
{
let properties = getSimulatorProperties()
var simulatorPaths = Set<String>()
if let currentSimulatorUuid = properties?["CurrentDeviceUDID"] as? String
{
_ = simulatorPaths.insert(simulatorRootPath(byUUID: currentSimulatorUuid))
}
if let devicePreferences = properties?["DevicePreferences"] as? NSDictionary
{
// we're running on xcode 9
for uuid: NSString in devicePreferences.allKeys as! [NSString]
{
_ = simulatorPaths.insert(self.simulatorRootPath(byUUID: uuid as String))
}
}
return simulatorPaths
}
//----------------------------------------------------------------------------
class func activeSimulators() -> [Simulator]
{
let paths = self.simulatorPaths()
var simulators = [Simulator]()
for path in paths
{
let propertiesPath = path + Constants.Simulator.deviceProperties
guard let properties = NSDictionary(contentsOfFile: propertiesPath) as? [AnyHashable : Any] else
{
continue
}
let simulator = Simulator(dictionary: properties, path: path)
simulators.append(simulator)
}
return simulators
}
//----------------------------------------------------------------------------
class func validApplication(_ application: Application) -> Bool
{
guard application.bundleName != nil else
{
return false
}
guard application.version != nil else
{
return false
}
guard !application.isAppleApplication else
{
return false
}
return true
}
//----------------------------------------------------------------------------
class func installedApps(on simulator: Simulator) -> [Application]
{
let installedApplicationsDataPath = simulator.path + ("data/Containers/Data/Application/")
let installedApplications = Tools.getSortedFiles(fromFolder: installedApplicationsDataPath)
let userApplications = installedApplications
.compactMap
{
Application(dictionary: $0, simulator: simulator)
}
.filter
{
!$0.isAppleApplication
}
return userApplications
}
//----------------------------------------------------------------------------
class func sharedAppGroups(on simulator: Simulator) -> [AppGroup]
{
let appGroupsDataPath = simulator.path + ("data/Containers/Shared/AppGroup/")
let appGroups = Tools.getSortedFiles(fromFolder: appGroupsDataPath)
return appGroups
.compactMap
{
AppGroup(dictionary: $0 as! [AnyHashable: Any], simulator: simulator)
}
.filter
{
!$0.isAppleAppGroup
}
}
//----------------------------------------------------------------------------
class func appExtensions(on simulator: Simulator) -> [AppExtension]
{
let appExtensionsDataPath = simulator.path + ("data/Containers/Data/PluginKitPlugin/")
let appExtensions = Tools.getSortedFiles(fromFolder: appExtensionsDataPath)
return appExtensions
.compactMap
{
AppExtension(dictionary: $0 as! [AnyHashable: Any], simulator: simulator)
}
.filter
{
!$0.isAppleExtension
}
}
//----------------------------------------------------------------------------
class func commanderOneAvailable() -> Bool
{
let fileManager = FileManager.default
// Check for App Store version
let isApplicationExist: Bool = fileManager.fileExists(atPath: Constants.Paths.commanderOneApp)
let isApplicationProExist: Bool = fileManager.fileExists(atPath: Constants.Paths.commanderOneProApp)
if isApplicationExist || isApplicationProExist
{
return true
}
// Check for version from Web
let plistPath = NSHomeDirectory() + "/" + Constants.Other.commanderOnePlist
let isPlistExist: Bool = fileManager.fileExists(atPath: plistPath)
return isPlistExist
}
//----------------------------------------------------------------------------
class func allFilesAt(path: String) -> [String]
{
let files = try? FileManager.default.contentsOfDirectory(atPath: path)
return files ?? []
}
//----------------------------------------------------------------------------
class func getFiles(fromFolder folderPath: String) -> [NSDictionary]
{
let files = allFilesAt(path: folderPath)
var filesAndProperties: [NSDictionary] = []
for file in files
{
if !(file == Constants.Other.dsStore)
{
let filePath = folderPath + "/" + file
let properties = try? FileManager.default.attributesOfItem(atPath: filePath)
let modificationDate = properties![.modificationDate] as! Date
let fileType = properties![.type] as! String
filesAndProperties.append([
Keys.fileName : file,
Keys.fileDate : modificationDate,
Keys.fileType : fileType
])
}
}
return filesAndProperties
}
//----------------------------------------------------------------------------
class func getName(from file: NSDictionary) -> NSString
{
return file.object(forKey: Keys.fileName) as! NSString
}
//----------------------------------------------------------------------------
class func getSortedFiles(fromFolder folderPath: String) -> [NSDictionary]
{
let filesAndProperties = getFiles(fromFolder: folderPath)
let sortedFiles = filesAndProperties.sorted(by:
{
path1, path2 in
guard let date1 = path1[Keys.fileDate] as? Date,
let date2 = path2[Keys.fileDate] as? Date else
{
return false
}
return date1 < date2
})
return sortedFiles
}
//----------------------------------------------------------------------------
class func getApplicationFolder(fromPath folderPath: String) -> String
{
return allFilesAt(path: folderPath)
.first(where: { URL(fileURLWithPath: $0).pathExtension == "app" })!
}
}
| mit | 01ca02067aabd479bb80bebac310cb80 | 32.577236 | 108 | 0.474092 | 6.224567 | false | false | false | false |
shabib87/SHVideoPlayer | SHVideoPlayer/Classes/SHVideoPlayerOrientationHandler.swift | 1 | 2154 | //
// SHVideoPlayerOrientationHandler.swift
// Pods
//
// Created by shabib hossain on 2/11/17.
//
//
import Foundation
import UIKit
final class SHVideoPlayerOrientationHandler {
public var isLandscape: Bool {
get {
return UIApplication.shared.statusBarOrientation.isLandscape
}
}
private var playerControl: SHVideoPlayerControl!
init(playerControlView playerControl: SHVideoPlayerControl) {
self.playerControl = playerControl
self.addPlayerControlFullScreenButtonAction()
self.addOrientationChangedNotification()
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidChangeStatusBarOrientation, object: nil)
}
private func addPlayerControlFullScreenButtonAction() {
playerControl.fullScreenButton?.addTarget(self, action: #selector(self.fullScreenAction(_:)), for: .touchUpInside)
playerControl.updateUI(!isLandscape)
}
private func addOrientationChangedNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(self.onOrientationChanged), name: NSNotification.Name.UIApplicationDidChangeStatusBarOrientation, object: nil)
}
@objc private func onOrientationChanged() {
playerControl.updateUI(!isLandscape)
}
@objc private func fullScreenAction(_ button: Any?) {
playerControl.updateUI(!isLandscape)
if isLandscape {
rotatePortraitAction()
} else {
rotateLandscapeAction()
}
}
private func rotatePortraitAction() {
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
UIApplication.shared.isStatusBarHidden = false
UIApplication.shared.statusBarOrientation = .portrait
}
private func rotateLandscapeAction() {
UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
UIApplication.shared.isStatusBarHidden = false
UIApplication.shared.statusBarOrientation = .landscapeRight
}
}
| mit | cc42a6b5fd6aea16c35acf97bc799c55 | 32.138462 | 183 | 0.706592 | 5.537275 | false | false | false | false |
rumana1411/Giphying | SwappingCollectionView/BackTableViewController.swift | 1 | 6859 | //
// BackTableViewController.swift
// swRevealSlidingMenu
//
// Created by Rumana Nazmul on 20/6/17.
// Copyright © 2017 ALFA. All rights reserved.
//
import UIKit
class BackTableViewController: UITableViewController {
var menuArray = ["Home","Level","Album","Score","About", "Help"]
var controllers = ["ViewController","LvlViewController","AlbumViewController","ScrViewController","AboutViewController","HelpViewController"]
var menuIcon = ["iconsHome","iconsLevel","iconsAbout","iconsScore","iconsAbout","iconsHelp"]
var frontNVC: UINavigationController?
var frontVC: ViewController?
override func viewDidLoad() {
super.viewDidLoad()
let logo = UIImage(named: "Logo.png")
let logoImgView = UIImageView(image: logo)
logoImgView.frame = CGRect(x: 100, y: 10, width: 10, height: 40 )
self.navigationItem.titleView = logoImgView
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menuArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell
var imgName = menuIcon[indexPath.row] + ".png"
cell.myImgView.image = UIImage(named: imgName)
cell.myLbl.text = menuArray[indexPath.row]
return cell
}
// override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//
// let revealViewController: SWRevealViewController = self.revealViewController()
//
// let cell:CustomTableViewCell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
//
//
//
//
// if cell.myLbl.text == "Home"{
//
// let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
// let newFrontViewController = UINavigationController.init(rootViewController: destVC)
// revealViewController.pushFrontViewController(newFrontViewController, animated: true)
//
// }
//
// if cell.myLbl.text == "Level"{
//
// let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "LvlViewController") as! LvlViewController
// let newFrontViewController = UINavigationController.init(rootViewController: destVC)
// revealViewController.pushFrontViewController(newFrontViewController, animated: true)
//
// }
// if cell.myLbl.text == "Album"{
//
// let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "AlbumViewController") as! AlbumViewController
// let newFrontViewController = UINavigationController.init(rootViewController: destVC)
// revealViewController.pushFrontViewController(newFrontViewController, animated: true)
//
// }
//
// if cell.myLbl.text == "Score"{
//
// let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "ScrViewController") as! ScrViewController
// let newFrontViewController = UINavigationController.init(rootViewController: destVC)
// revealViewController.pushFrontViewController(newFrontViewController, animated: true)
//
// }
//
// if cell.myLbl.text == "About"{
//
// let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "AboutViewController") as! AboutViewController
// let newFrontViewController = UINavigationController.init(rootViewController: destVC)
// revealViewController.pushFrontViewController(newFrontViewController, animated: true)
// }
//
// }
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//tableView.deselectRow(at: indexPath, animated: true)
var controller: UIViewController? = nil
switch indexPath.row
{
case 0:
controller = frontVC
default:
// Instantiate the controller to present
let storyboard = UIStoryboard(name: "Main", bundle: nil)
controller = storyboard.instantiateViewController(withIdentifier: controllers[indexPath.row])
break
}
if controller != nil
{
// Prevent stacking the same controller multiple times
_ = frontNVC?.popViewController(animated: false)
// Prevent pushing twice FrontTableViewController
if !(controller is ViewController) {
// Show the controller with the front view controller's navigation controller
frontNVC!.pushViewController(controller!, animated: false)
}
// Set front view controller's position to left
revealViewController().setFrontViewPosition(.left, animated: true)
}
}
// override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
//
// var headerTitle: String!
// headerTitle = "Giphying"
// return headerTitle
// }
// override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//
//
// let headerView = UIView()
//
// // headerView.backgroundColor = UIColor.white
// let viewImg = UIImage(named: "Logo.png")
// let headerImgView = UIImageView(image: viewImg)
// headerImgView.frame = CGRect(x: 60, y: 10, width: 120, height: 100)
// headerView.addSubview(headerImgView)
//
// return headerView
//
//
// }
//
// override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//
//
// return 110
// }
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 112
}
}
| mit | 128342708edf08f934535971409faea2 | 36.271739 | 145 | 0.62438 | 5.291667 | false | false | false | false |
izotx/iTenWired-Swift | Conference App/ItenWiredBeacon.swift | 1 | 3116 | // Copyright (c) 2016, Izotx
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Izotx nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//
// ItenWiredBeacon.swift
// Conference App
//
// Created by Felipe on 7/7/16.
//
//
import Foundation
import JMCiBeaconManager
enum ItenWiredBeaconEnum : String {
case id
case udid
case minor
case major
case name
}
class ItenWiredBeacon : iBeacon {
/// Date the beacon was last ranged
internal var lastRanged : NSDate!
/**
Initializes the Beacon with the data provided in the dictionary
*/
init(dictionary: NSDictionary) {
var minor = 0
var major = 0
var id:String = ""
var uuid = ""
if let unwrapedMinor = dictionary.objectForKey(ItenWiredBeaconEnum.minor.rawValue) as? Int {
minor = unwrapedMinor
}
if let unwrapedMajor = dictionary.objectForKey(ItenWiredBeaconEnum.major.rawValue) as? Int {
major = unwrapedMajor
}
if let unwrapedID = dictionary.objectForKey(ItenWiredBeaconEnum.id.rawValue) as? String {
id = unwrapedID
}
if let unwrapedUdid = dictionary.objectForKey(ItenWiredBeaconEnum.udid.rawValue) as? String {
uuid = unwrapedUdid
}
super.init(minor: UInt16(minor), major: UInt16(major), proximityId:uuid, id:id)
}
init(with beacon: iBeacon){
super.init(minor: beacon.minor, major: beacon.major, proximityId: beacon.UUID, id: beacon.id)
self.proximity = beacon.proximity
}
}
| bsd-2-clause | e1145248fd4713f52e61fbd193352626 | 32.869565 | 102 | 0.673299 | 4.609467 | false | false | false | false |
to4iki/conference-app-2017-ios | conference-app-2017/data/repository/SessionRepository.swift | 1 | 1499 | import OctavKit
import RxSwift
struct SessionRepository: Repository {
private let localDataStore: SessionLocalDataStore
private let remoteDataStore: SessionRemoteDataStore
private let disposeBag = DisposeBag()
init(
localDataStore: SessionLocalDataStore = SessionLocalDataStore.shared,
remoteDataStore: SessionRemoteDataStore = SessionRemoteDataStore.shared)
{
self.localDataStore = localDataStore
self.remoteDataStore = remoteDataStore
}
func findAll() -> Single<[Session]> {
return localDataStore.findAll().catchError { _ in
self.remoteDataStore.findAll().map { sessions in
self.storeToLocalDataStore(sessions)
return sessions
}
}
}
func update() {
remoteDataStore.findAll().subscribe { observer in
switch observer {
case .success(let sessions):
self.storeToLocalDataStore(sessions)
case .error(let error):
log.error("remoteDataStore error: \(error.localizedDescription)")
}
}
.disposed(by: disposeBag)
}
private func storeToLocalDataStore(_ value: [Session]) {
self.localDataStore.store(value).subscribe(
onCompleted: { _ in log.debug("localDataStore store completed") },
onError: { error in log.error("localDataStore error: \(error.localizedDescription)") }
).disposed(by: self.disposeBag)
}
}
| apache-2.0 | c54673b22b41c13adffe0e028b7eebac | 33.068182 | 98 | 0.639093 | 5.168966 | false | false | false | false |
2345Team/Swifter-Tips | 5.Tuple/5.Tuple/ViewController.swift | 1 | 2272 | //
// ViewController.swift
// 5.Tuple
//
// Created by luzhiyong on 16/6/15.
// Copyright © 2016年 2345. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var a = 3
var b = 4
swapMe(&a, b: &b)
print(a)
print(b)
swapMe2(&a, b: &b)
print(a)
print(b)
// 利用元组同时返回多个值,从而解决了在Objective-C中返回值只能有一个而造成的一些问题
// var areaOne: CGRect = CGRectMake(0, 0, 0, 0)
// var areaTwo: CGRect = CGRectMake(0, 0, 0, 0)
//
// CGRectDivide(self.view.bounds, &areaOne, &areaTwo, self.view.bounds.size.width * 0.3, .MinXEdge)
//
// let viewOne = UIView()
// viewOne.frame = areaOne
// viewOne.backgroundColor = UIColor.redColor()
// self.view.addSubview(viewOne)
//
// let viewTwo = UIView()
// viewTwo.frame = areaTwo
// viewTwo.backgroundColor = UIColor.yellowColor()
// self.view.addSubview(viewTwo)
var (areaOne, areaTwo) = CGRectDivide(self.view.bounds, amount: self.view.bounds.size.width * 0.3, edge: .MinXEdge)
let viewOne = UIView()
viewOne.frame = areaOne
viewOne.backgroundColor = UIColor.redColor()
self.view.addSubview(viewOne)
let viewTwo = UIView()
viewTwo.frame = areaTwo
viewTwo.backgroundColor = UIColor.yellowColor()
self.view.addSubview(viewTwo)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*!
普通实现方法
- parameter a: 参数a
- parameter b: 参数b
*/
func swapMe<T>(inout a: T, inout b: T) {
let tmp = a
a = b
b = tmp
}
/*!
高级实现方法
- parameter a: 参数a
- parameter b: 参数b
*/
func swapMe2<T>(inout a: T, inout b: T) {
(a,b) = (b,a)
}
}
| mit | 945537f1cece3cb80fef6879316dbe5e | 23.258427 | 123 | 0.541918 | 3.821239 | false | false | false | false |
ahernandezlopez/Preacher | Preacher/Comparison/StringComparisonModifier.swift | 1 | 1778 | //
// StringComparisonModifier.swift
// Preacher
//
// Created by Albert Hernández López on 7/6/15.
// Copyright (c) 2015 Albert Hernández López. All rights reserved.
//
/**
Lists all string comparison modifier options.
- None: No modifiers.
- CaseInsensitivity: Case insensitive.
- DiacriticInsensitivity: Diacritic insensitive.
*/
public struct StringComparisonModifier: RawOptionSetType, BooleanType, Printable {
public static var None: StringComparisonModifier { return self(rawValue: 0b00) }
public static var CaseInsensitivity: StringComparisonModifier { return self(rawValue: 0b01) }
public static var DiacriticInsensitivity: StringComparisonModifier { return self(rawValue: 0b10) }
// MARK: - RawRepresentable
public var rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
// MARK: - NilLiteralConvertible
public init(nilLiteral: ()) {
self.rawValue = 0
}
// MARK: - BitwiseOperationsType
public static var allZeros: StringComparisonModifier {
return StringComparisonModifier.None
}
// MARK: - BooleanType
public var boolValue: Bool {
return rawValue != 0
}
// MARK: - Printable
public var description: String {
var modifiersStr = ""
if self & StringComparisonModifier.CaseInsensitivity {
modifiersStr += "c"
}
if self & StringComparisonModifier.DiacriticInsensitivity {
modifiersStr += "d"
}
if modifiersStr.isEmpty {
return ""
}
else {
return "[\(modifiersStr)]"
}
}
}
| mit | 3c1ef4eb8e67af31b295f1bc92cf81ac | 25.878788 | 102 | 0.606539 | 5.233038 | false | false | false | false |
lyimin/EyepetizerApp | EyepetizerApp/EyepetizerApp/Views/LoaderView/EYELoaderView.swift | 1 | 2257 | //
// EYELoaderView.swift
// EyepetizerApp
//
// Created by 梁亦明 on 16/3/17.
// Copyright © 2016年 xiaoming. All rights reserved.
//
import UIKit
class EYELoaderView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(eyeBackgroundLoaderView)
self.addSubview(eyeCenterLoaderView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func startLoadingAnimation() {
self.hidden = false
let animation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.fromValue = 0
animation.toValue = M_PI * 2
animation.duration = 2
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.repeatCount = HUGE
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
self.eyeCenterLoaderView.layer.addAnimation(animation, forKey: animation.keyPath)
}
func stopLoadingAnimation() {
// self.hidden = true
self.eyeCenterLoaderView.layer.removeAllAnimations()
}
/// 外面眼圈
private lazy var eyeBackgroundLoaderView : UIImageView = {
let eyeBackgroundLoaderView = UIImageView(image: UIImage(named: "ic_eye_black_outer"))
eyeBackgroundLoaderView.frame = CGRect(x: 0, y: 0, width: self.height,height: self.height)
eyeBackgroundLoaderView.center = self.center
eyeBackgroundLoaderView.contentMode = .ScaleAspectFit
eyeBackgroundLoaderView.layer.allowsEdgeAntialiasing = true
return eyeBackgroundLoaderView;
}()
/// 中间眼球
private lazy var eyeCenterLoaderView : UIImageView = {
let eyeCenterLoaderView = UIImageView(image: UIImage(named: "ic_eye_black_inner"))
eyeCenterLoaderView.frame = CGRect(x: 0, y: 0, width: self.height - UIConstant.UI_MARGIN_5, height: self.height - UIConstant.UI_MARGIN_5)
eyeCenterLoaderView.center = self.center
eyeCenterLoaderView.contentMode = .ScaleAspectFit
eyeCenterLoaderView.layer.allowsEdgeAntialiasing = true
return eyeCenterLoaderView;
}()
}
| mit | cf15ecace6235aab56eba9dda9f3ad7b | 36.2 | 145 | 0.685036 | 4.938053 | false | false | false | false |
ashfurrow/RxSwift | RxTests/RxSwiftTests/Tests/Observable+BlockingTest.swift | 2 | 7599 | //
// Observable+BlockingTest.swift
// RxTests
//
// Created by Krunoslav Zaher on 7/12/15.
//
//
import Foundation
import RxSwift
import RxBlocking
import XCTest
class ObservableBlockingTest : RxTest {
}
// toArray
extension ObservableBlockingTest {
func testToArray_empty() {
XCTAssert(try! (empty() as Observable<Int>).toBlocking().toArray() == [])
}
func testToArray_return() {
XCTAssert(try! just(42).toBlocking().toArray() == [42])
}
func testToArray_fail() {
do {
try (failWith(testError) as Observable<Int>).toBlocking().toArray()
XCTFail("It should fail")
}
catch let e {
XCTAssertTrue(e as NSError === testError)
}
}
func testToArray_someData() {
XCTAssert(try! sequenceOf(42, 43, 44, 45).toBlocking().toArray() == [42, 43, 44, 45])
}
func testToArray_withRealScheduler() {
let scheduler = ConcurrentDispatchQueueScheduler(globalConcurrentQueuePriority: .Default)
let array = try! interval(0.001, scheduler)
.take(10)
.toBlocking()
.toArray()
XCTAssert(array == Array(0..<10))
}
}
// first
extension ObservableBlockingTest {
func testFirst_empty() {
XCTAssert(try! (empty() as Observable<Int>).toBlocking().first() == nil)
}
func testFirst_return() {
XCTAssert(try! just(42).toBlocking().first() == 42)
}
func testFirst_fail() {
do {
try (failWith(testError) as Observable<Int>).toBlocking().first()
XCTFail()
}
catch let e {
XCTAssertTrue(e as NSError === testError)
}
}
func testFirst_someData() {
XCTAssert(try! sequenceOf(42, 43, 44, 45).toBlocking().first() == 42)
}
func testFirst_withRealScheduler() {
let scheduler = ConcurrentDispatchQueueScheduler(globalConcurrentQueuePriority: .Default)
let array = try! interval(0.001, scheduler)
.take(10)
.toBlocking()
.first()
XCTAssert(array == 0)
}
}
// last
extension ObservableBlockingTest {
func testLast_empty() {
XCTAssert(try! (empty() as Observable<Int>).toBlocking().last() == nil)
}
func testLast_return() {
XCTAssert(try! just(42).toBlocking().last() == 42)
}
func testLast_fail() {
do {
try (failWith(testError) as Observable<Int>).toBlocking().last()
XCTFail()
}
catch let e {
XCTAssertTrue(e as NSError === testError)
}
}
func testLast_someData() {
XCTAssert(try! sequenceOf(42, 43, 44, 45).toBlocking().last() == 45)
}
func testLast_withRealScheduler() {
let scheduler = ConcurrentDispatchQueueScheduler(globalConcurrentQueuePriority: .Default)
let array = try! interval(0.001, scheduler)
.take(10)
.toBlocking()
.last()
XCTAssert(array == 9)
}
}
// single
extension ObservableBlockingTest {
func testSingle_empty() {
do {
try (empty() as Observable<Int>).toBlocking().single()
XCTFail()
}
catch let e {
XCTAssertTrue((e as! RxError)._code == RxError.NoElements._code)
}
}
func testSingle_return() {
XCTAssert(try! just(42).toBlocking().single() == 42)
}
func testSingle_two() {
do {
try (sequenceOf(42, 43) as Observable<Int>).toBlocking().single()
XCTFail()
}
catch let e {
XCTAssertTrue((e as! RxError)._code == RxError.MoreThanOneElement._code)
}
}
func testSingle_someData() {
do {
try (sequenceOf(42, 43, 44, 45) as Observable<Int>).toBlocking().single()
XCTFail()
}
catch let e {
XCTAssertTrue((e as! RxError)._code == RxError.MoreThanOneElement._code)
}
}
func testSingle_fail() {
do {
try (failWith(testError) as Observable<Int>).toBlocking().single()
XCTFail()
}
catch let e {
XCTAssertTrue(e as NSError === testError)
}
}
func testSingle_withRealScheduler() {
let scheduler = ConcurrentDispatchQueueScheduler(globalConcurrentQueuePriority: .Default)
let array = try! interval(0.001, scheduler)
.take(1)
.toBlocking()
.single()
XCTAssert(array == 0)
}
func testSingle_predicate_empty() {
do {
try (empty() as Observable<Int>).toBlocking().single { _ in true }
XCTFail()
}
catch let e {
XCTAssertTrue((e as! RxError)._code == RxError.NoElements._code)
}
}
func testSingle_predicate_return() {
XCTAssert(try! just(42).toBlocking().single( { _ in true } ) == 42)
}
func testSingle_predicate_someData_one_match() {
var predicateVals = [Int]()
do {
try (sequenceOf(42, 43, 44, 45) as Observable<Int>).toBlocking().single( { e in
predicateVals.append(e)
return e == 44
} )
}
catch _ {
XCTFail()
}
XCTAssertEqual(predicateVals, [42, 43, 44, 45])
}
func testSingle_predicate_someData_two_match() {
var predicateVals = [Int]()
do {
try (sequenceOf(42, 43, 44, 45) as Observable<Int>).toBlocking().single( { e in
predicateVals.append(e)
return e >= 43
} )
XCTFail()
}
catch let e {
XCTAssertTrue((e as! RxError)._code == RxError.MoreThanOneElement._code)
}
XCTAssertEqual(predicateVals, [42, 43, 44])
}
func testSingle_predicate_none() {
var predicateVals = [Int]()
do {
try (sequenceOf(42, 43, 44, 45) as Observable<Int>).toBlocking().single( { e in
predicateVals.append(e)
return e > 50
} )
XCTFail()
}
catch let e {
XCTAssertTrue((e as! RxError)._code == RxError.NoElements._code)
}
XCTAssertEqual(predicateVals, [42, 43, 44, 45])
}
func testSingle_predicate_throws() {
var predicateVals = [Int]()
do {
try (sequenceOf(42, 43, 44, 45, scheduler: CurrentThreadScheduler.instance) as Observable<Int>).toBlocking().single( { e in
predicateVals.append(e)
if e < 43 { return false }
throw testError
} )
XCTFail()
}
catch let e {
XCTAssertTrue(e as NSError === testError)
}
XCTAssertEqual(predicateVals, [42, 43])
}
func testSingle_predicate_fail() {
do {
try (failWith(testError) as Observable<Int>).toBlocking().single( { _ in true } )
XCTFail()
}
catch let e {
XCTAssertTrue(e as NSError === testError)
}
}
func testSingle_predicate_withRealScheduler() {
let scheduler = ConcurrentDispatchQueueScheduler(globalConcurrentQueuePriority: .Default)
let array = try! interval(0.001, scheduler)
.take(4)
.toBlocking()
.single( { $0 == 3 } )
XCTAssert(array == 3)
}
}
| mit | 73c3551e0cf4003ddfd56caac4f616f3 | 25.85159 | 135 | 0.530333 | 4.699443 | false | true | false | false |
arrrnas/vinted-ab-ios | Carthage/Checkouts/BigInt/sources/BigUInt.swift | 1 | 11407 | //
// BigUInt.swift
// BigInt
//
// Created by Károly Lőrentey on 2015-12-26.
// Copyright © 2016 Károly Lőrentey.
//
/// An arbitary precision unsigned integer type, also known as a "big integer".
///
/// Operations on big integers never overflow, but they might take a long time to execute.
/// The amount of memory (and address space) available is the only constraint to the magnitude of these numbers.
///
/// This particular big integer type uses base-2^64 digits to represent integers; you can think of it as a wrapper
/// around `Array<UInt64>`. In fact, `BigUInt` implements a mutable collection of its `UInt64` digits, with the
/// digit at index 0 being the least significant.
///
/// To make memory management simple, `BigUInt` allows you to subscript it with out-of-bounds indexes:
/// the subscript getter zero-extends the digit sequence, while the subscript setter automatically extends the
/// underlying storage when necessary:
///
/// ```Swift
/// var number = BigUInt(1)
/// number[42] // Not an error, returns 0
/// number[23] = 1 // Not an error, number is now 2^1472 + 1.
/// ```
///
/// Note that it is rarely a good idea to use big integers as collections; in the vast majority of cases it is much
/// easier to work with the provided high-level methods and operators rather than with raw big digits.
public struct BigUInt {
/// The type representing a digit in `BigUInt`'s underlying number system.
public typealias Digit = UIntMax
internal var _digits: [Digit]
internal var _start: Int
internal var _end: Int
internal init(digits: [Digit], start: Int, end: Int) {
precondition(start >= 0 && start <= end)
let start = Swift.min(start, digits.count)
var end = Swift.min(end, digits.count)
while end > start && digits[end - 1] == 0 { end -= 1 }
self._digits = digits
self._start = start
self._end = end
}
/// Initializes a new BigUInt with value 0.
public init() {
self.init([])
}
/// Initializes a new BigUInt with the specified digits. The digits are ordered from least to most significant.
public init(_ digits: [Digit]) {
self.init(digits: digits, start: 0, end: digits.count)
}
/// Initializes a new BigUInt that has the supplied value.
public init<I: UnsignedInteger>(_ integer: I) {
self.init(Digit.digitsFromUIntMax(integer.toUIntMax()))
}
/// Initializes a new BigUInt that has the supplied value.
///
/// - Requires: integer >= 0
public init<I: SignedInteger>(_ integer: I) {
precondition(integer >= 0)
self.init(UIntMax(integer.toIntMax()))
}
}
extension BigUInt: ExpressibleByIntegerLiteral {
//MARK: Init from Integer literals
/// Initialize a new big integer from an integer literal.
public init(integerLiteral value: UInt64) {
self.init(value.toUIntMax())
}
}
extension BigUInt: ExpressibleByStringLiteral {
//MARK: Init from String literals
/// Initialize a new big integer from a Unicode scalar.
/// The scalar must represent a decimal digit.
public init(unicodeScalarLiteral value: UnicodeScalar) {
self = BigUInt(String(value), radix: 10)!
}
/// Initialize a new big integer from an extended grapheme cluster.
/// The cluster must consist of a decimal digit.
public init(extendedGraphemeClusterLiteral value: String) {
self = BigUInt(value, radix: 10)!
}
/// Initialize a new big integer from a decimal number represented by a string literal of arbitrary length.
/// The string must contain only decimal digits.
public init(stringLiteral value: StringLiteralType) {
self = BigUInt(value, radix: 10)!
}
}
extension BigUInt: IntegerArithmetic {
/// Explicitly convert to `IntMax`, trapping on overflow.
public func toIntMax() -> IntMax {
precondition(count <= 1)
return IntMax(self[0])
}
}
extension BigUInt {
//MARK: Lift and shrink
/// True iff this integer is not a slice.
internal var isTop: Bool { return _start == 0 && _end == _digits.count }
/// Ensures that this integer is not a slice, allocating a new digit array if necessary.
internal mutating func lift() {
guard !isTop else { return }
_digits = Array(self)
_start = 0
_end = _digits.count
}
/// Gets rid of leading zero digits in the digit array.
internal mutating func shrink() {
assert(isTop)
while _digits.last == 0 {
_digits.removeLast()
}
_end = _digits.count
}
}
extension BigUInt: RandomAccessCollection {
//MARK: Collection
/// Big integers implement `Collection` to provide access to their big digits, indexed by integers; a zero index refers to the least significant digit.
public typealias Index = Int
/// The type representing the number of steps between two indices.
public typealias IndexDistance = Int
/// The type representing valid indices for subscripting the collection.
public typealias Indices = CountableRange<Int>
/// The type representing the iteration interface for the digits in a big integer.
public typealias Iterator = DigitIterator<Digit>
/// Big integers can be contiguous digit subranges of another big integer.
public typealias SubSequence = BigUInt
public var indices: Indices { return startIndex ..< endIndex }
/// The index of the first digit, starting from the least significant. (This is always zero.)
public var startIndex: Int { return 0 }
/// The index of the digit after the most significant digit in this integer.
public var endIndex: Int { return count }
/// The number of digits in this integer, excluding leading zero digits.
public var count: Int { return _end - _start }
/// Return a generator over the digits of this integer, starting at the least significant digit.
public func makeIterator() -> DigitIterator<Digit> {
return DigitIterator(digits: _digits, end: _end, index: _start)
}
/// Returns the position immediately after the given index.
public func index(after i: Int) -> Int {
return i + 1
}
/// Returns the position immediately before the given index.
public func index(before i: Int) -> Int {
return i - 1
}
/// Replaces the given index with its successor.
public func formIndex(after i: inout Int) {
i += 1
}
/// Replaces the given index with its predecessor.
public func formIndex(before i: inout Int) {
i -= 1
}
/// Returns an index that is the specified distance from the given index.
public func index(_ i: Int, offsetBy n: Int) -> Int {
return i + n
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
public func index(_ i: Int, offsetBy n: Int, limitedBy limit: Int) -> Int? {
let r = i + n
if n >= 0 {
return r <= limit ? r : nil
}
return r >= limit ? r : nil
}
/// Returns the number of steps between two indices.
public func distance(from start: Int, to end: Int) -> Int {
return end - start
}
/// Get or set a digit at a given index.
///
/// - Note: Unlike a normal collection, it is OK for the index to be greater than or equal to `endIndex`.
/// The subscripting getter returns zero for indexes beyond the most significant digit.
/// Setting these extended digits automatically appends new elements to the underlying digit array.
/// - Requires: index >= 0
/// - Complexity: The getter is O(1). The setter is O(1) if the conditions below are true; otherwise it's O(count).
/// - The integer's storage is not shared with another integer
/// - The integer wasn't created as a slice of another integer
/// - `index < count`
public subscript(index: Int) -> Digit {
get {
precondition(index >= 0)
let i = _start + index
return (i < Swift.min(_end, _digits.count) ? _digits[i] : 0)
}
set(digit) {
precondition(index >= 0)
lift()
let i = _start + index
if i < _end {
_digits[i] = digit
if digit == 0 && i == _end - 1 {
shrink()
}
}
else {
guard digit != 0 else { return }
while _digits.count < i { _digits.append(0) }
_digits.append(digit)
_end = i + 1
}
}
}
/// Returns an integer built from the digits of this integer in the given range.
public subscript(bounds: Range<Int>) -> BigUInt {
get {
return BigUInt(digits: _digits, start: _start + bounds.lowerBound, end: _start + bounds.upperBound)
}
}
}
/// State for iterating through the digits of a big integer.
public struct DigitIterator<Digit>: IteratorProtocol {
internal let digits: [Digit]
internal let end: Int
internal var index: Int
/// Return the next digit in the integer, or nil if there are no more digits.
/// Returned digits range from least to most significant.
public mutating func next() -> Digit? {
guard index < end else { return nil }
let v = digits[index]
index += 1
return v
}
}
extension BigUInt: Strideable {
/// A type that can represent the distance between two values of `BigUInt`.
public typealias Stride = BigInt
/// Adds `n` to `self` and returns the result. Traps if the result would be less than zero.
public func advanced(by n: BigInt) -> BigUInt {
return n < 0 ? self - n.abs : self + n.abs
}
/// Returns the (potentially negative) difference between `self` and `other` as a `BigInt`. Never traps.
public func distance(to other: BigUInt) -> BigInt {
return BigInt(other) - BigInt(self)
}
}
extension BigUInt {
//MARK: Low and High
/// Split this integer into a high-order and a low-order part.
///
/// - Requires: count > 1
/// - Returns: `(low, high)` such that
/// - `self == low.add(high, atPosition: middleIndex)`
/// - `high.width <= floor(width / 2)`
/// - `low.width <= ceil(width / 2)`
/// - Complexity: Typically O(1), but O(count) in the worst case, because high-order zero digits need to be removed after the split.
internal var split: (high: BigUInt, low: BigUInt) {
precondition(count > 1)
let mid = middleIndex
return (self[mid ..< count], self[0 ..< mid])
}
/// Index of the digit at the middle of this integer.
///
/// - Returns: The index of the digit that is least significant in `self.high`.
internal var middleIndex: Int {
return (count + 1) / 2
}
/// The low-order half of this BigUInt.
///
/// - Returns: `self[0 ..< middleIndex]`
/// - Requires: count > 1
internal var low: BigUInt {
return self[0 ..< middleIndex]
}
/// The high-order half of this BigUInt.
///
/// - Returns: `self[middleIndex ..< count]`
/// - Requires: count > 1
internal var high: BigUInt {
return self[middleIndex ..< count]
}
}
| mit | 17c35ac7e7fb2769d2dba74dbde7a141 | 34.855346 | 155 | 0.625943 | 4.388761 | false | false | false | false |
toshiapp/toshi-ios-client | Toshi/Extensions/Codable+Parsing.swift | 1 | 1966 | // Copyright (c) 2018 Token Browser, Inc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import Foundation
extension Decodable {
static func fromJSONData(_ data: Data,
with decoder: JSONDecoder = JSONDecoder(),
successCompletion: (Self) -> Void,
errorCompletion: ((ToshiError) -> Void)?) {
do {
let decoded = try decoder.decode(Self.self, from: data)
successCompletion(decoded)
} catch let error {
DLog("Parsing error: \(error)")
errorCompletion?(.invalidResponseJSON)
}
}
static func optionalFromJSONData(_ data: Data,
with decoder: JSONDecoder = JSONDecoder()) -> Self? {
return try? decoder.decode(Self.self, from: data)
}
}
extension Encodable {
func toJSONData(with encoder: JSONEncoder = JSONEncoder(),
successCompletion: (Data) -> Void,
errorCompletion: (Error) -> Void) {
do {
let encoded = try encoder.encode(self)
successCompletion(encoded)
} catch let error {
errorCompletion(error)
}
}
func toOptionalJSONData(with encoder: JSONEncoder = JSONEncoder()) -> Data? {
return try? encoder.encode(self)
}
}
| gpl-3.0 | 9b650b4213a073b7132c22d46c3ad0b5 | 34.107143 | 90 | 0.611902 | 4.783455 | false | false | false | false |
eofster/Telephone | UseCases/CallHistoryRecord.swift | 1 | 2169 | //
// CallHistoryRecord.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.
//
import Foundation
public struct CallHistoryRecord {
public let identifier: String
public let uri: URI
public let date: Date
public let duration: Int
public let isIncoming: Bool
public let isMissed: Bool
public init(uri: URI, date: Date, duration: Int, isIncoming: Bool, isMissed: Bool) {
identifier = "\(uri.user)@\(uri.host)|\(date.timeIntervalSinceReferenceDate)|\(duration)|\(isIncoming ? 1 : 0)"
self.uri = uri
self.date = date
self.duration = duration
self.isIncoming = isIncoming
self.isMissed = isMissed
}
public func removingHost() -> CallHistoryRecord {
return CallHistoryRecord(
uri: URI(user: uri.user, host: "", displayName: uri.displayName),
date: date,
duration: duration,
isIncoming: isIncoming,
isMissed: isMissed
)
}
}
extension CallHistoryRecord: Equatable {
public static func ==(lhs: CallHistoryRecord, rhs: CallHistoryRecord) -> Bool {
return
lhs.uri == rhs.uri &&
lhs.date == rhs.date &&
lhs.duration == rhs.duration &&
lhs.isIncoming == rhs.isIncoming &&
lhs.isMissed == rhs.isMissed
}
}
extension CallHistoryRecord {
public init(call: Call) {
self.init(
uri: call.remote,
date: call.date,
duration: call.duration,
isIncoming: call.isIncoming,
isMissed: call.isMissed
)
}
}
| gpl-3.0 | c9284590fb9221f4ee3520f1b8f47c9b | 29.957143 | 119 | 0.631287 | 4.562105 | false | false | false | false |
ldt25290/MyInstaMap | ThirdParty/AlamofireImage/Tests/AFError+AlamofireImageTests.swift | 4 | 4133 | //
// AFError+AlamofireImageTests.swift
//
// Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Alamofire
extension AFError {
// ResponseSerializationFailureReason
var isInputDataNil: Bool {
if case let .responseSerializationFailed(reason) = self, reason.isInputDataNil { return true }
return false
}
var isInputDataNilOrZeroLength: Bool {
if case let .responseSerializationFailed(reason) = self, reason.isInputDataNilOrZeroLength { return true }
return false
}
var isInputFileNil: Bool {
if case let .responseSerializationFailed(reason) = self, reason.isInputFileNil { return true }
return false
}
var isInputFileReadFailed: Bool {
if case let .responseSerializationFailed(reason) = self, reason.isInputFileReadFailed { return true }
return false
}
// ResponseValidationFailureReason
var isDataFileNil: Bool {
if case let .responseValidationFailed(reason) = self, reason.isDataFileNil { return true }
return false
}
var isDataFileReadFailed: Bool {
if case let .responseValidationFailed(reason) = self, reason.isDataFileReadFailed { return true }
return false
}
var isMissingContentType: Bool {
if case let .responseValidationFailed(reason) = self, reason.isMissingContentType { return true }
return false
}
var isUnacceptableContentType: Bool {
if case let .responseValidationFailed(reason) = self, reason.isUnacceptableContentType { return true }
return false
}
var isUnacceptableStatusCode: Bool {
if case let .responseValidationFailed(reason) = self, reason.isUnacceptableStatusCode { return true }
return false
}
}
// MARK: -
extension AFError.ResponseSerializationFailureReason {
var isInputDataNil: Bool {
if case .inputDataNil = self { return true }
return false
}
var isInputDataNilOrZeroLength: Bool {
if case .inputDataNilOrZeroLength = self { return true }
return false
}
var isInputFileNil: Bool {
if case .inputFileNil = self { return true }
return false
}
var isInputFileReadFailed: Bool {
if case .inputFileReadFailed = self { return true }
return false
}
}
// MARK: -
extension AFError.ResponseValidationFailureReason {
var isDataFileNil: Bool {
if case .dataFileNil = self { return true }
return false
}
var isDataFileReadFailed: Bool {
if case .dataFileReadFailed = self { return true }
return false
}
var isMissingContentType: Bool {
if case .missingContentType = self { return true }
return false
}
var isUnacceptableContentType: Bool {
if case .unacceptableContentType = self { return true }
return false
}
var isUnacceptableStatusCode: Bool {
if case .unacceptableStatusCode = self { return true }
return false
}
}
| mit | 665d4257dce108126716d9c5c097ea12 | 30.792308 | 114 | 0.691023 | 4.902728 | false | false | false | false |
coach-plus/ios | Pods/Eureka/Source/Validations/RuleLength.swift | 3 | 3030 | // RuleLength.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct RuleMinLength: RuleType {
let min: UInt
public var id: String?
public var validationError: ValidationError
public init(minLength: UInt, msg: String? = nil, id: String? = nil) {
let ruleMsg = msg ?? "Field value must have at least \(minLength) characters"
min = minLength
validationError = ValidationError(msg: ruleMsg)
self.id = id
}
public func isValid(value: String?) -> ValidationError? {
guard let value = value else { return nil }
return value.count < Int(min) ? validationError : nil
}
}
public struct RuleMaxLength: RuleType {
let max: UInt
public var id: String?
public var validationError: ValidationError
public init(maxLength: UInt, msg: String? = nil, id: String? = nil) {
let ruleMsg = msg ?? "Field value must have less than \(maxLength) characters"
max = maxLength
validationError = ValidationError(msg: ruleMsg)
self.id = id
}
public func isValid(value: String?) -> ValidationError? {
guard let value = value else { return nil }
return value.count > Int(max) ? validationError : nil
}
}
public struct RuleExactLength: RuleType {
let length: UInt
public var id: String?
public var validationError: ValidationError
public init(exactLength: UInt, msg: String? = nil, id: String? = nil) {
let ruleMsg = msg ?? "Field value must have exactly \(exactLength) characters"
length = exactLength
validationError = ValidationError(msg: ruleMsg)
self.id = id
}
public func isValid(value: String?) -> ValidationError? {
guard let value = value else { return nil }
return value.count != Int(length) ? validationError : nil
}
}
| mit | c3d2300f72dfba140fd98caf43de333a | 35.071429 | 86 | 0.686469 | 4.508929 | false | false | false | false |
DanielTomlinson/Persist | Persist/NSManagedObject+Helpers.swift | 1 | 2330 | //
// NSManagedObject+Helpers.swift
// Persist
//
// Created by Daniel Tomlinson on 13/09/2015.
// Copyright © 2015 Daniel Tomlinson. All rights reserved.
//
import Foundation
import CoreData
/**
ManagedObjectType is a protocol that exposes convenience methods for NSManagedObjects.
Default implementations are provided, but they can be overriden by individual classes as needeed.
To opt into these methods, add the ManagedObjectType protocol to your NSManagedObject subclass.
*/
public protocol ManagedObjectType : class {
typealias T = Self
/**
The name of the class in the managed object model.
*/
static func entityName() -> String
/**
Create a new instance of the model object in the given context.
- parameter context: The NSManagedObjectContext in which to create the object.
- returns: A new instance of the model.
*/
static func create(inContext context: NSManagedObjectContext) -> T
/**
Create a new fetch request for the entity.
*/
static func fetchRequest() -> NSFetchRequest
/**
Create and execute a fetch request with the given predicate to return all
matching records of the entity.
*/
static func findAllMatchingPredicate(predicate: NSPredicate, inContext: NSManagedObjectContext) throws -> [T]
}
extension ManagedObjectType where Self: NSManagedObject {
public static func entityName() -> String {
return NSStringFromClass(self)
}
public static func create(inContext context: NSManagedObjectContext) -> Self {
guard let object = NSEntityDescription.insertNewObjectForEntityForName(entityName(), inManagedObjectContext: context) as? Self else {
preconditionFailure("Could not find entity named \(entityName()) in context \(context)")
}
return object
}
public static func fetchRequest() -> NSFetchRequest {
return NSFetchRequest(entityName: entityName())
}
public static func findAllMatchingPredicate(predicate: NSPredicate, inContext context: NSManagedObjectContext) throws -> [Self] {
let fetchRequest = self.fetchRequest()
fetchRequest.predicate = predicate
let result = try context.executeFetchRequest(fetchRequest)
return result as? [Self] ?? []
}
}
| mit | e6a37607f2cb1ce7d55a03fdb4ce5a33 | 31.802817 | 141 | 0.70073 | 5.403712 | false | false | false | false |
mspvirajpatel/SwiftyBase | Example/SwiftyBase/Controller/SideMenu/SideMenuView.swift | 1 | 12766 | //
// SideMenuView.swift
// SwiftyBase
//
// Created by MacMini-2 on 06/09/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import SwiftyBase
import UIKit
class SideMenuView: BaseView {
// MARK: - Attribute -
internal var userProfileView : UIView!
private var imgUser : BaseImageView!
var lblUserRealName : BaseLabel!
var lblUserName: BaseLabel!
private var seperatorView : UIView!
private var tblMenu : UITableView!
private var btnlogin : BaseButton!
internal var arrMenuData : NSMutableArray! = NSMutableArray()
internal var selectedCell : IndexPath = IndexPath(item: 0, section: 0)
internal var selectedMenu : Int = Menu.api.rawValue
fileprivate var cellSelecteEvent : TableCellSelectEvent!
// MARK: - Lifecycle -
init(){
super.init(frame: .zero)
self.loadViewControls()
self.setViewlayout()
self.loadMenuData()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
if imgUser != nil{
imgUser.clipsToBounds = true
imgUser.layer.cornerRadius = imgUser.frame.size.width / 2
}
}
deinit{
print("side menu deinit called")
self.releaseObject()
}
override func releaseObject() {
super.releaseObject()
}
// MARK: - Layout -
override func loadViewControls()
{
super.loadViewControls()
self.backgroundColor = AppColor.appPrimaryBG.value
userProfileView = UIView()
userProfileView.layer .setValue("userProfileView", forKey: ControlConstant.name)
userProfileView.translatesAutoresizingMaskIntoConstraints = false
userProfileView.backgroundColor = UIColor.clear
self.addSubview(userProfileView)
btnlogin = BaseButton(ibuttonType: .transparent, iSuperView: userProfileView)
btnlogin.backgroundColor = UIColor.clear
btnlogin.isHidden = false
btnlogin.setButtonTouchUpInsideEvent { [weak self] (sendor, object) in
if self == nil{
return
}
if self!.cellSelecteEvent != nil{
self!.cellSelecteEvent(nil,Menu.api.rawValue as AnyObject)
}
}
imgUser = BaseImageView(type: .defaultImg, superView: userProfileView)
imgUser.layer .setValue("imgUser", forKey: ControlConstant.name)
imgUser.backgroundColor = UIColor.white
imgUser.isHidden = true
seperatorView = UIView()
seperatorView.layer .setValue("seperatorView", forKey: ControlConstant.name)
seperatorView.backgroundColor = AppColor.appSecondaryBG.value
seperatorView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(seperatorView)
lblUserName = BaseLabel(labelType: .small, superView: userProfileView)
lblUserName.layer .setValue("lblUserName", forKey: ControlConstant.name)
lblUserName.text = ""
lblUserName.textColor = AppColor.appSecondaryBG.value
lblUserName.isHidden = true
lblUserName.textAlignment = .left
lblUserRealName = BaseLabel(labelType: .large, superView: userProfileView)
lblUserRealName.layer .setValue("lblUserRealName", forKey: ControlConstant.name)
lblUserRealName.text = ""
lblUserRealName.textColor = AppColor.appSecondaryBG.value
lblUserRealName.isHidden = true
tblMenu = UITableView(frame: .zero, style: .grouped)
tblMenu.layer .setValue("tblMenu", forKey: ControlConstant.name)
tblMenu.translatesAutoresizingMaskIntoConstraints = false
tblMenu.backgroundColor = UIColor.clear
tblMenu.separatorStyle = .none
tblMenu.cellLayoutMarginsFollowReadableWidth = false
tblMenu.alwaysBounceVertical = false
tblMenu.delegate = self
tblMenu.dataSource = self
tblMenu.tableFooterView = UIView(frame: .zero)
tblMenu.register(LeftMenuCell.self, forCellReuseIdentifier: CellIdentifire.leftMenu)
self.addSubview(tblMenu)
}
override func setViewlayout() {
super.setViewlayout()
baseLayout.viewDictionary = self.getDictionaryOfVariableBindings(superView: self, viewDic: NSDictionary()) as? [String : AnyObject]
baseLayout.metrics = ["hSpace" : ControlConstant.horizontalPadding, "vSpace" : ControlConstant.verticalPadding / 2]
baseLayout.control_H = NSLayoutConstraint.constraints(withVisualFormat: "H:|[userProfileView]|", options: NSLayoutConstraint.FormatOptions(rawValue : 0), metrics: baseLayout.metrics, views: baseLayout.viewDictionary)
baseLayout.control_V = NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[userProfileView]-[seperatorView(==1)][tblMenu]|", options: [.alignAllLeading,.alignAllTrailing], metrics: baseLayout.metrics, views: baseLayout.viewDictionary)
self.addConstraints(baseLayout.control_H)
self.addConstraints(baseLayout.control_V)
baseLayout.expandView(btnlogin, insideView: userProfileView)
// UserProfile View Constraint
baseLayout.control_V = NSLayoutConstraint.constraints(withVisualFormat: "V:|-vSpace-[imgUser]-vSpace-|", options: NSLayoutConstraint.FormatOptions(rawValue : 0), metrics: baseLayout.metrics, views: baseLayout.viewDictionary)
baseLayout.control_H = NSLayoutConstraint.constraints(withVisualFormat: "H:|-hSpace-[imgUser]-hSpace-[lblUserName]-hSpace-|", options: NSLayoutConstraint.FormatOptions(rawValue : 0), metrics: baseLayout.metrics, views: baseLayout.viewDictionary)
userProfileView.addConstraints(baseLayout.control_H)
userProfileView.addConstraints(baseLayout.control_V)
lblUserRealName.bottomAnchor.constraint(equalTo: imgUser.centerYAnchor, constant: ControlConstant.verticalPadding / 2).isActive = true
lblUserName.topAnchor.constraint(equalTo: imgUser.centerYAnchor, constant: ControlConstant.verticalPadding / 2).isActive = true
lblUserRealName.leadingAnchor.constraint(equalTo: lblUserName.leadingAnchor).isActive = true
lblUserRealName.trailingAnchor.constraint(equalTo: lblUserName.trailingAnchor).isActive = true
imgUser.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.size.width * 0.20).isActive = true
imgUser.heightAnchor.constraint(equalTo: imgUser.widthAnchor).isActive = true
self.layoutIfNeeded()
self.layoutSubviews()
}
// MARK: - Public Interface -
open func updateUI(){
// imgUser.layer.cornerRadius = (UIScreen.main.bounds.size.width * 0.15) / 2
// imgUser.clipsToBounds = true
}
open func cellSelectedEvent( event : @escaping TableCellSelectEvent) -> Void{
cellSelecteEvent = event
}
open func setSelectedMenu(type : Int) -> Void{
selectedCell = IndexPath.init()
for (section,item) in arrMenuData.enumerated(){
for (index,menu) in ((item as! NSDictionary)["item"] as! NSArray).enumerated(){
if (menu as! NSDictionary)["type"] as! Int == type{
selectedCell = IndexPath(row: index, section: section)
}
}
}
tblMenu.reloadData()
}
open func showLoginView(){
self.btnlogin.isHidden = false
self.imgUser.isHidden = false
self.lblUserName.isHidden = false
self.lblUserRealName.isHidden = false
self.imgUser.image = UIImage(named: "App_icon")!
self.lblUserName.text = "Login with Instagram"
self.lblUserRealName.text = "LargeDp"
}
open func showProfileView(){
self.btnlogin.isHidden = true
self.imgUser.isHidden = false
self.lblUserName.isHidden = false
self.lblUserRealName.isHidden = false
}
open func loadMenuData(){
arrMenuData.removeAllObjects()
for menuData in AppPlistManager().readFromPlist("Menu") as! NSMutableArray
{
let dicMenu : NSMutableDictionary = menuData as! NSMutableDictionary
var arrItem : [NSDictionary] = []
for item in dicMenu["item"] as! NSArray
{
arrItem.append(item as! NSDictionary)
}
dicMenu .setObject(arrItem, forKey: "item" as NSCopying)
arrMenuData.add(dicMenu)
}
tblMenu.reloadData()
}
// MARK: - User Interaction -
// MARK: - Internal Helpers -
fileprivate func getDataForCell(indexPath : IndexPath) -> NSDictionary{
var dicMenu : NSDictionary! = arrMenuData[indexPath.section] as? NSDictionary
var arrItem : NSArray! = dicMenu["item"] as? NSArray
defer {
dicMenu = nil
arrItem = nil
}
return arrItem[indexPath.row] as! NSDictionary
}
// MARK: - Delegate Method -
// MARK: - Server Request -
}
// MARK : Extension
// TODO : UITableView Delegate
extension SideMenuView : UITableViewDelegate{
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cellData : NSDictionary = self.getDataForCell(indexPath: indexPath)
if self.cellSelecteEvent != nil{
self.cellSelecteEvent(nil,cellData["type"] as AnyObject)
}
}
}
// TODO : UITableView DataSource
extension SideMenuView : UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return self.arrMenuData.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let dicMenu : NSDictionary = arrMenuData[section] as! NSDictionary
let arrItem : NSArray = dicMenu["item"] as! NSArray
return arrItem.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
var cell : LeftMenuCell!
cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifire.leftMenu) as? LeftMenuCell
if cell == nil
{
cell = LeftMenuCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: CellIdentifire.leftMenu)
}
let cellData : NSDictionary = self.getDataForCell(indexPath: indexPath)
cell.selectionStyle = .none
cell.backgroundColor = UIColor.clear
cell.imageView?.image = UIImage(named:"ic_file")?.withRenderingMode(.alwaysTemplate)
cell.imageView?.tintColor = UIColor.green
cell.backgroundColor = UIColor.blue
if indexPath == selectedCell
{
cell.lblMenuText.textColor = AppColor.navigationBottomBorder.value
if let image = UIImage(named: cellData["icon"] as! String) {
cell.imgIcon.image = image.maskWithColor(AppColor.navigationBottomBorder.value)
cell.backgroundColor = AppColor.navigationTitle.value
}
}
else
{
cell.lblMenuText?.textColor = AppColor.navigationBottomBorder.value
if let image = UIImage(named: cellData["icon"] as! String) {
cell.imgIcon.image = image.maskWithColor(AppColor.navigationBottomBorder.value)
cell.backgroundColor = UIColor.clear
}
}
cell.lblMenuText?.text = (cellData["title"] as? String)?.localize()
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30.0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30))
headerView.backgroundColor = UIColor.clear
let lbltext : UILabel = UILabel(frame: CGRect(x: 10, y:5, width: headerView.bounds.size.width, height: 20))
lbltext.textColor = AppColor.navigationBottomBorder.value
lbltext.text = ((arrMenuData[section] as! NSDictionary)["title"] as? String)?.localize()
headerView.addSubview(lbltext)
return headerView
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 45.0
}
}
| mit | 2c80a8d785f8a8c5f3c63be19a7f26f9 | 36.878338 | 253 | 0.64622 | 5.305486 | false | false | false | false |
qmathe/Confetti | Event/Operator/MapIndexesToElements.swift | 1 | 926 | /**s
Date: November 2017
License: MIT
*/
import Foundation
import RxSwift
public extension Observable where Element == IndexSet {
/// Returns elements matching selection indexes in collection presented by the given viewpoint.
public func mapToElements<E, S>(in viewpoint: CollectionViewpoint<S>) -> Observable<[E]> where E == CollectionViewpoint<S>.E {
return withLatestFrom(viewpoint.collection) { (indexes: IndexSet, collection: [E]) -> [E] in
return collection[indexes]
}
}
/// Returns the element matching first selection index in collection presented by the given viewpoint.
public func mapToFirstElement<E, S>(in viewpoint: CollectionViewpoint<S>) -> Observable<E?> where E == CollectionViewpoint<S>.E {
return mapToElements(in: viewpoint).flatMap { (elements: [E]) -> Observable<E?> in
return .just(elements.first)
}
}
}
| mit | 5fe787e6ee079376f3a7c322daaf8728 | 36.04 | 133 | 0.679266 | 4.47343 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/RightSide/Topic/ViewModel/ZSFilterThemeViewModel.swift | 1 | 1148 | //
// ZSFilterThemeViewModel.swift
// zhuishushenqi
//
// Created by caony on 2019/3/22.
// Copyright © 2019年 QS. All rights reserved.
//
import Foundation
import ZSAPI
class ZSFilterThemeViewModel {
var items:[ZSFilterThemeModel] = []
func request(_ handler:ZSBaseCallback<Void>?) {
let api = ZSAPI.tagType("" as AnyObject)
zs_get(api.path, parameters: nil) { (response) in
guard let books = response?["data"] as? [Any] else {
handler?(nil)
return
}
if let items = [ZSFilterThemeModel].deserialize(from: books) as? [ZSFilterThemeModel] {
self.items = []
var item = ZSFilterThemeModel()
item.name = ""
item.tags = ["全部书单"]
self.items.append(item)
var itemGender = ZSFilterThemeModel()
itemGender.name = "性别"
itemGender.tags = ["男","女"]
self.items.append(itemGender)
self.items.append(contentsOf: items)
}
handler?(nil)
}
}
}
| mit | 730cf2a28ac201e7ff429251ac93e3c7 | 28.710526 | 99 | 0.527015 | 4.30916 | false | false | false | false |
steamclock/internetmap | Theme.swift | 1 | 743 | //
// Theme.swift
// Internet Map
//
// Created by Nigel Brooke on 2017-11-08.
// Copyright © 2017 Peer1. All rights reserved.
//
import UIKit
// Note: these definitions are duplocates of the one in HelperMethods.h (since it's two hard to share them given how they are set up)
// if changes are made, will need to be changed in both places
enum Theme {
static let blue = UIColor(red: 68.0 / 255.0, green: 144.0 / 255.0, blue: 206.0 / 255.0, alpha: 1.0)
static let primary = Theme.blue
static let fontNameLight = "NexaLight"
static func settingsItemBackgroundImage() -> UIImage {
return UIDevice.current.userInterfaceIdiom == .phone ? UIImage(named: "iphone-bg.png")! : UIImage(named: "ipad-bg.png")!
}
}
| mit | e54061100dd0d60a1269fcec657e114f | 29.916667 | 133 | 0.681941 | 3.435185 | false | false | false | false |
christophhagen/Signal-iOS | SignalMessaging/views/CommonStrings.swift | 1 | 3592 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
/**
* Strings re-used in multiple places should be added here.
*/
@objc public class CommonStrings: NSObject {
@objc
static public let dismissButton = NSLocalizedString("DISMISS_BUTTON_TEXT", comment: "Short text to dismiss current modal / actionsheet / screen")
@objc
static public let cancelButton = NSLocalizedString("TXT_CANCEL_TITLE", comment:"Label for the cancel button in an alert or action sheet.")
@objc
static public let retryButton = NSLocalizedString("RETRY_BUTTON_TEXT", comment:"Generic text for button that retries whatever the last action was.")
}
@objc public class MessageStrings: NSObject {
@objc
static public let newGroupDefaultTitle = NSLocalizedString("NEW_GROUP_DEFAULT_TITLE", comment: "Used in place of the group name when a group has not yet been named.")
}
@objc public class CallStrings: NSObject {
@objc
static public let callStatusFormat = NSLocalizedString("CALL_STATUS_FORMAT", comment: "embeds {{Call Status}} in call screen label. For ongoing calls, {{Call Status}} is a seconds timer like 01:23, otherwise {{Call Status}} is a short text like 'Ringing', 'Busy', or 'Failed Call'")
@objc
static public let confirmAndCallButtonTitle = NSLocalizedString("SAFETY_NUMBER_CHANGED_CONFIRM_CALL_ACTION", comment: "alert button text to confirm placing an outgoing call after the recipients Safety Number has changed.")
@objc
static public let callBackAlertTitle = NSLocalizedString("CALL_USER_ALERT_TITLE", comment: "Title for alert offering to call a user.")
@objc
static public let callBackAlertMessageFormat = NSLocalizedString("CALL_USER_ALERT_MESSAGE_FORMAT", comment: "Message format for alert offering to call a user. Embeds {{the user's display name or phone number}}.")
@objc
static public let callBackAlertCallButton = NSLocalizedString("CALL_USER_ALERT_CALL_BUTTON", comment: "Label for call button for alert offering to call a user.")
// MARK: Notification actions
@objc
static public let callBackButtonTitle = NSLocalizedString("CALLBACK_BUTTON_TITLE", comment: "notification action")
@objc
static public let showThreadButtonTitle = NSLocalizedString("SHOW_THREAD_BUTTON_TITLE", comment: "notification action")
// MARK: Missed Call Notification
@objc
static public let missedCallNotificationBodyWithoutCallerName = NSLocalizedString("MISSED_CALL", comment: "notification title")
@objc
static public let missedCallNotificationBodyWithCallerName = NSLocalizedString("MSGVIEW_MISSED_CALL_WITH_NAME", comment: "notification title. Embeds {{caller's name or phone number}}")
// MARK: Missed with changed identity notification (for not previously verified identity)
@objc
static public let missedCallWithIdentityChangeNotificationBodyWithoutCallerName = NSLocalizedString("MISSED_CALL_WITH_CHANGED_IDENTITY_BODY_WITHOUT_CALLER_NAME", comment: "notification title")
@objc
static public let missedCallWithIdentityChangeNotificationBodyWithCallerName = NSLocalizedString("MISSED_CALL_WITH_CHANGED_IDENTITY_BODY_WITH_CALLER_NAME", comment: "notification title. Embeds {{caller's name or phone number}}")
}
@objc public class SafetyNumberStrings: NSObject {
@objc
static public let confirmSendButton = NSLocalizedString("SAFETY_NUMBER_CHANGED_CONFIRM_SEND_ACTION",
comment: "button title to confirm sending to a recipient whose safety number recently changed")
}
| gpl-3.0 | eec72e7c71a5feb788ea682db052ecc9 | 56.935484 | 286 | 0.75167 | 4.713911 | false | false | false | false |
gmoral/SwiftTraining2016 | Training_Swift/SearchPeople.swift | 1 | 1716 | //
// SearchPeople.swift
// Training_Swift
//
// Created by Guillermo Moral on 3/8/16.
// Copyright © 2016 Guillermo Moral. All rights reserved.
//
import UIKit
import SwiftyJSON
enum ParseError: ErrorType {
case Empty
}
class SearchPeople
{
var id: String?
var firstname: String?
var lastname: String?
var title:String?
var avatar: UIImage?
var avatarBase64EncodedString: String?
required init?(json: JSON)
{
id = json["_id"].string!
firstname = json["firstname"].string!
lastname = json["lastname"].string!
title = json["title"].string!
do
{
avatarBase64EncodedString = try parseAvatar(json)
} catch
{
avatarBase64EncodedString = ""
}
if !avatarBase64EncodedString!.isEmpty
{
let decodedData = NSData(base64EncodedString: avatarBase64EncodedString!, options: NSDataBase64DecodingOptions(rawValue: 0))
let decodedimage = UIImage(data: decodedData!)
avatar = decodedimage! as UIImage
} else
{
avatar = UIImage(named: "Avatar.png")
}
}
lazy var fullName: String = {
guard let tmpFirstName = self.firstname,
let tmpLastName = self.lastname
where !tmpFirstName.isEmpty && !tmpLastName.isEmpty
else
{
return ""
}
return (tmpFirstName + " " + tmpLastName)
}()
private func parseAvatar(json: JSON) throws -> String
{
guard let anAvatar = json["thumb"].string else { throw ParseError.Empty }
return anAvatar
}
}
| mit | 15d19764c72fcae57b6eddf90c6b9f3d | 23.855072 | 136 | 0.571429 | 4.610215 | false | false | false | false |
hanhailong/practice-swift | Courses/stanford/stanford/cs193p/2015/Cassini/Cassini/ImageViewController.swift | 3 | 2909 | //
// ImageViewController.swift
// Cassini
//
// Created by Domenico on 11.04.15.
// License: MIT
//
import UIKit
class ImageViewController: UIViewController, UIScrollViewDelegate {
var imageURL: NSURL?{
didSet{
image = nil
// Fetch the image if I am onscreen
if view.window != nil{
fetchImage()
}
}
}
private func fetchImage(){
if let url = imageURL{
// Start animating the spinner
spinner?.startAnimating()
// Get the QUEUE identifier
let qos = Int(QOS_CLASS_USER_INITIATED.value)
// Dispatch the queue
dispatch_async(dispatch_get_global_queue(qos, 0)){ () -> Void in
let imageData = NSData(contentsOfURL: url)
// Need to dispatch the result to the main queue because we are modifying the UI
dispatch_async(dispatch_get_main_queue()) { () -> Void in
// Checking if this url is the last requested url
if url == self.imageURL{
if imageData != nil{
self.image = UIImage(data: imageData!)
}else{
self.image = nil
}
}
}
}
}
}
@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var scrollView: UIScrollView!{
didSet{
// Need to set the content size of the scroll view
scrollView.contentSize = imageView.frame.size
// Set the delegate for the scrollView
scrollView.delegate = self
// Set the zoom
scrollView.minimumZoomScale = 0.3
scrollView.maximumZoomScale = 1
}
}
// ScrollView function from UIScrollViewDelegate
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
private var imageView = UIImageView()
private var image: UIImage?{
get{
return imageView.image
}
set{
imageView.image = newValue
// Expand the frame to fit
imageView.sizeToFit()
// Set the content size of the scroll view
scrollView?.contentSize = imageView.frame.size
// Stop animating
spinner?.stopAnimating()
}
}
override func viewDidLoad(){
super.viewDidLoad()
view.addSubview(imageView)
}
override func viewWillAppear(animated:Bool){
super.viewWillAppear(animated)
// If I was offscreen and the image has not been fetched before
if image == nil{
fetchImage()
}
}
}
| mit | 323b0356b0f0fde5b941253d67132bf8 | 28.09 | 96 | 0.515985 | 5.715128 | false | false | false | false |
mobilabsolutions/jenkins-ios | JenkinsiOS/Model/JenkinsAPI/Computer/MonitorData.swift | 1 | 1358 | //
// MonitorData.swift
// JenkinsiOS
//
// Created by Robert on 12.10.16.
// Copyright © 2016 MobiLab Solutions. All rights reserved.
//
import Foundation
class MonitorData {
/// The number of avaible bytes of physical memory
var availablePhysicalMemory: Double?
/// The number of available bytes of swap space
var availableSwapSpace: Double?
/// The total number of bytes of physical memory
var totalPhysicalMemory: Double?
/// The total number of bytes of swap space
var totalSwapSpace: Double?
/// Initialize a MonitorData object
///
/// - parameter json: The json from which to initialize the monitor data
///
/// - returns: An initialized MonitorData object
init(json: [String: AnyObject]) {
for partJson in json {
if let dataJson = partJson.value as? [String: AnyObject] {
availablePhysicalMemory = dataJson[Constants.JSON.availablePhysicalMemory] as? Double ?? availablePhysicalMemory
availableSwapSpace = dataJson[Constants.JSON.availableSwapSpace] as? Double ?? availableSwapSpace
totalPhysicalMemory = dataJson[Constants.JSON.totalPhysicalMemory] as? Double ?? totalPhysicalMemory
totalSwapSpace = dataJson[Constants.JSON.totalSwapSpace] as? Double ?? totalSwapSpace
}
}
}
}
| mit | 2598ee9b61e648c6b40703b6aacdea6e | 36.694444 | 128 | 0.67944 | 4.863799 | false | false | false | false |
tardieu/swift | test/DebugInfo/closure.swift | 4 | 824 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests %s -emit-ir -g -o - | %FileCheck %s
func markUsed<T>(_ t: T) {}
func foldl1<T>(_ list: [T], _ function: (_ a: T, _ b: T) -> T) -> T {
assert(list.count > 1)
var accumulator = list[0]
for i in 1 ..< list.count {
accumulator = function(accumulator, list[i])
}
return accumulator
}
var a = [Int64](repeating: 0, count: 10)
for i in 0..<10 { a[i] = Int64(i) }
// A closure is not an artificial function (the last i32 0).
// CHECK: !DISubprogram({{.*}}linkageName: "_T07closures5Int64VAC_ACtcfU_",{{.*}} line: 20,{{.*}} scopeLine: 20,
// CHECK: !DILocalVariable(name: "$0", arg: 1{{.*}} line: [[@LINE+2]],
// CHECK: !DILocalVariable(name: "$1", arg: 2{{.*}} line: [[@LINE+1]],
var sum:Int64 = foldl1(a, { $0 + $1 })
markUsed(sum)
| apache-2.0 | 87566f4c1dc84999465d5c8f82df0298 | 38.238095 | 112 | 0.580097 | 2.953405 | false | false | false | false |
googlemaps/last-mile-fleet-solution-samples | ios_driverapp_samples/LMFSDriverSampleAppTests/ModelTests.swift | 1 | 3036 | /*
* Copyright 2022 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import XCTest
@testable import LMFSDriverSampleApp
class ModelsTests: XCTestCase {
private var modelData = ModelData()
override func setUpWithError() throws {
modelData = ModelData(filename: "test_manifest")
}
func testSetTaskStatus() throws {
let stop1 = modelData.stops[0]
let tasks = modelData.tasks(stop: stop1)
XCTAssertEqual(tasks.count, 3)
XCTAssertEqual(tasks[0].outcome, .pending)
XCTAssertEqual(tasks[1].outcome, .pending)
XCTAssertEqual(tasks[2].outcome, .pending)
XCTAssertEqual(stop1.taskStatus, .pending)
let navigationState1 = try XCTUnwrap(modelData.navigationState)
XCTAssertEqual(stop1, navigationState1.upcomingStop)
modelData.setTaskStatus(task: tasks[0], newStatus: .completed)
XCTAssertEqual(tasks[0].outcome, .completed)
modelData.setTaskStatus(task: tasks[1], newStatus: .completed)
XCTAssertEqual(tasks[1].outcome, .completed)
modelData.setTaskStatus(task: tasks[2], newStatus: .completed)
XCTAssertEqual(tasks[2].outcome, .completed)
XCTAssertEqual(stop1.taskStatus, .completed)
let navigationState2 = try XCTUnwrap(modelData.navigationState)
XCTAssertNotEqual(navigationState2.upcomingStop, stop1)
modelData.setTaskStatus(task: tasks[1], newStatus: .couldNotComplete)
XCTAssertEqual(tasks[1].outcome, .couldNotComplete)
XCTAssertEqual(stop1.taskStatus, .couldNotComplete)
}
/// Flip the first 2 stops.
func testMoveStops() throws {
let stopBeforeMove = modelData.stops[0]
let indexSet = IndexSet(integer: 0)
modelData.moveStops(source: indexSet, destination: 2)
let stopAfterMove = modelData.stops[1]
XCTAssertEqual(stopBeforeMove, stopAfterMove)
XCTAssertEqual(stopBeforeMove.order, 2)
let navigationState = try XCTUnwrap(modelData.navigationState)
XCTAssertNotEqual(stopBeforeMove, navigationState.upcomingStop)
}
// Tests the bug that caused b/221304932: Make sure the `id` property of a ModelData.Stop is
// globally unique, not just unique within the Manifest/vehicle.
func testGloballyUniqueStopId() throws {
let firstStops = Set(modelData.stops.map { $0.id })
// test_manifest_2.json is identical to test_manifest.json except for vehicle id.
let modelData2 = ModelData(filename: "test_manifest_2")
let secondStops = Set(modelData2.stops.map { $0.id })
XCTAssertTrue(firstStops.intersection(secondStops).isEmpty)
}
}
| apache-2.0 | 9f07c70d49dafd03ffaa8327e1748ea0 | 38.947368 | 94 | 0.746706 | 4.176066 | false | true | false | false |
lorentey/swift | test/SILGen/keypaths.swift | 3 | 28399 | // RUN: %target-swift-emit-silgen -parse-stdlib -module-name keypaths %s | %FileCheck %s
import Swift
struct S<T> {
var x: T
let y: String
var z: C<T>
var computed: C<T> { fatalError() }
var observed: C<T> { didSet { fatalError() } }
var reabstracted: () -> ()
}
class C<T> {
final var x: T
final let y: String
final var z: S<T>
var nonfinal: S<T>
var computed: S<T> { fatalError() }
var observed: S<T> { didSet { fatalError() } }
final var reabstracted: () -> ()
init() { fatalError() }
}
extension C {
var `extension`: S<T> { fatalError() }
}
protocol P {
var x: Int { get }
var y: String { get set }
}
extension P {
var z: String {
return y
}
var w: String {
get { return "" }
nonmutating set { }
}
}
struct T {
var a: (Int, String)
let b: (f: String, g: Int)
let c: (x: C<Int>, y: C<String>)
}
/* TODO: When we support superclass requirements on protocols, we should test
* this case as well.
protocol PoC : C<Int> {}
*/
// CHECK-LABEL: sil hidden [ossa] @{{.*}}storedProperties
func storedProperties<T>(_: T) {
// CHECK: keypath $WritableKeyPath<S<T>, T>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.x : $τ_0_0) <T>
_ = \S<T>.x
// CHECK: keypath $KeyPath<S<T>, String>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.y : $String) <T>
_ = \S<T>.y
// CHECK: keypath $ReferenceWritableKeyPath<S<T>, T>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.z : $C<τ_0_0>; stored_property #C.x : $τ_0_0) <T>
_ = \S<T>.z.x
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, T>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.x : $τ_0_0) <T>
_ = \C<T>.x
// CHECK: keypath $KeyPath<C<T>, String>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.y : $String) <T>
_ = \C<T>.y
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, T>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.z : $S<τ_0_0>; stored_property #S.x : $τ_0_0) <T>
_ = \C<T>.z.x
// CHECK: keypath $KeyPath<C<T>, String>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.z : $S<τ_0_0>; stored_property #S.z : $C<τ_0_0>; stored_property #C.y : $String) <T>
_ = \C<T>.z.z.y
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}computedProperties
func computedProperties<T: P>(_: T) {
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: settable_property $S<τ_0_0>,
// CHECK-SAME: id #C.nonfinal!getter.1 : <T> (C<T>) -> () -> S<T>,
// CHECK-SAME: getter @$s8keypaths1CC8nonfinalAA1SVyxGvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed C<τ_0_0>) -> @out S<τ_0_0>,
// CHECK-SAME: setter @$s8keypaths1CC8nonfinalAA1SVyxGvpAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed S<τ_0_0>, @in_guaranteed C<τ_0_0>) -> ()
// CHECK-SAME: ) <T>
_ = \C<T>.nonfinal
// CHECK: keypath $KeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: gettable_property $S<τ_0_0>,
// CHECK-SAME: id #C.computed!getter.1 : <T> (C<T>) -> () -> S<T>,
// CHECK-SAME: getter @$s8keypaths1CC8computedAA1SVyxGvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed C<τ_0_0>) -> @out S<τ_0_0>
// CHECK-SAME: ) <T>
_ = \C<T>.computed
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: settable_property $S<τ_0_0>,
// CHECK-SAME: id #C.observed!getter.1 : <T> (C<T>) -> () -> S<T>,
// CHECK-SAME: getter @$s8keypaths1CC8observedAA1SVyxGvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed C<τ_0_0>) -> @out S<τ_0_0>,
// CHECK-SAME: setter @$s8keypaths1CC8observedAA1SVyxGvpAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed S<τ_0_0>, @in_guaranteed C<τ_0_0>) -> ()
// CHECK-SAME: ) <T>
_ = \C<T>.observed
_ = \C<T>.nonfinal.x
_ = \C<T>.computed.x
_ = \C<T>.observed.x
_ = \C<T>.z.computed
_ = \C<T>.z.observed
_ = \C<T>.observed.x
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, () -> ()>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: settable_property $() -> (),
// CHECK-SAME: id ##C.reabstracted,
// CHECK-SAME: getter @$s8keypaths1CC12reabstractedyycvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed C<τ_0_0>) -> @out @callee_guaranteed () -> @out (),
// CHECK-SAME: setter @$s8keypaths1CC12reabstractedyycvpAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed @callee_guaranteed () -> @out (), @in_guaranteed C<τ_0_0>) -> ()
// CHECK-SAME: ) <T>
_ = \C<T>.reabstracted
// CHECK: keypath $KeyPath<S<T>, C<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $S<τ_0_0>; gettable_property $C<τ_0_0>,
// CHECK-SAME: id @$s8keypaths1SV8computedAA1CCyxGvg : $@convention(method) <τ_0_0> (@in_guaranteed S<τ_0_0>) -> @owned C<τ_0_0>,
// CHECK-SAME: getter @$s8keypaths1SV8computedAA1CCyxGvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed S<τ_0_0>) -> @out C<τ_0_0>
// CHECK-SAME: ) <T>
_ = \S<T>.computed
// CHECK: keypath $WritableKeyPath<S<T>, C<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $S<τ_0_0>;
// CHECK-SAME: settable_property $C<τ_0_0>,
// CHECK-SAME: id @$s8keypaths1SV8observedAA1CCyxGvg : $@convention(method) <τ_0_0> (@in_guaranteed S<τ_0_0>) -> @owned C<τ_0_0>,
// CHECK-SAME: getter @$s8keypaths1SV8observedAA1CCyxGvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed S<τ_0_0>) -> @out C<τ_0_0>,
// CHECK-SAME: setter @$s8keypaths1SV8observedAA1CCyxGvpAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed C<τ_0_0>, @inout S<τ_0_0>) -> ()
// CHECK-SAME: ) <T>
_ = \S<T>.observed
_ = \S<T>.z.nonfinal
_ = \S<T>.z.computed
_ = \S<T>.z.observed
_ = \S<T>.computed.x
_ = \S<T>.computed.y
// CHECK: keypath $WritableKeyPath<S<T>, () -> ()>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $S<τ_0_0>;
// CHECK-SAME: settable_property $() -> (),
// CHECK-SAME: id ##S.reabstracted,
// CHECK-SAME: getter @$s8keypaths1SV12reabstractedyycvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed S<τ_0_0>) -> @out @callee_guaranteed () -> @out (),
// CHECK-SAME: setter @$s8keypaths1SV12reabstractedyycvpAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed @callee_guaranteed () -> @out (), @inout S<τ_0_0>) -> ()
// CHECK-SAME: ) <T>
_ = \S<T>.reabstracted
// CHECK: keypath $KeyPath<T, Int>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $τ_0_0;
// CHECK-SAME: gettable_property $Int,
// CHECK-SAME: id #P.x!getter.1 : <Self where Self : P> (Self) -> () -> Int,
// CHECK-SAME: getter @$s8keypaths1PP1xSivpAaBRzlxTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out Int
// CHECK-SAME: ) <T>
_ = \T.x
// CHECK: keypath $WritableKeyPath<T, String>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $τ_0_0;
// CHECK-SAME: settable_property $String,
// CHECK-SAME: id #P.y!getter.1 : <Self where Self : P> (Self) -> () -> String,
// CHECK-SAME: getter @$s8keypaths1PP1ySSvpAaBRzlxTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out String,
// CHECK-SAME: setter @$s8keypaths1PP1ySSvpAaBRzlxTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in_guaranteed String, @inout τ_0_0) -> ()
// CHECK-SAME: ) <T>
_ = \T.y
// CHECK: keypath $KeyPath<T, String>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $τ_0_0;
// CHECK-SAME: gettable_property $String,
// CHECK-SAME: id @$s8keypaths1PPAAE1zSSvg
_ = \T.z
}
struct Concrete: P {
var x: Int
var y: String
}
// CHECK-LABEL: sil hidden [ossa] @$s8keypaths35keyPathsWithSpecificGenericInstanceyyF
func keyPathsWithSpecificGenericInstance() {
// CHECK: keypath $KeyPath<Concrete, String>, (
// CHECK-SAME: gettable_property $String,
// CHECK-SAME: id @$s8keypaths1PPAAE1zSSvg
// CHECK-SAME: getter @$s8keypaths1PPAAE1zSSvpAA8ConcreteVTK : $@convention(thin) (@in_guaranteed Concrete) -> @out String
_ = \Concrete.z
_ = \S<Concrete>.computed
}
class AA<T> {
var a: Int { get { return 0 } set { } }
}
class BB<U, V>: AA<V> {
}
func keyPathForInheritedMember() {
_ = \BB<Int, String>.a
}
func keyPathForExistentialMember() {
_ = \P.x
_ = \P.y
_ = \P.z
_ = \P.w
}
struct OptionalFields {
var x: S<Int>?
}
struct OptionalFields2 {
var y: OptionalFields?
}
// CHECK-LABEL: sil hidden [ossa] @$s8keypaths18keyPathForOptionalyyF
func keyPathForOptional() {
// CHECK: keypath $WritableKeyPath<OptionalFields, S<Int>>, (
// CHECK-SAME: stored_property #OptionalFields.x : $Optional<S<Int>>;
// CHECK-SAME: optional_force : $S<Int>)
_ = \OptionalFields.x!
// CHECK: keypath $KeyPath<OptionalFields, Optional<String>>, (
// CHECK-SAME: stored_property #OptionalFields.x : $Optional<S<Int>>;
// CHECK-SAME: optional_chain : $S<Int>;
// CHECK-SAME: stored_property #S.y : $String;
// CHECK-SAME: optional_wrap : $Optional<String>)
_ = \OptionalFields.x?.y
// CHECK: keypath $KeyPath<OptionalFields2, Optional<S<Int>>>, (
// CHECK-SAME: root $OptionalFields2;
// CHECK-SAME: stored_property #OptionalFields2.y : $Optional<OptionalFields>;
// CHECK-SAME: optional_chain : $OptionalFields;
// CHECK-SAME: stored_property #OptionalFields.x : $Optional<S<Int>>)
_ = \OptionalFields2.y?.x
}
class StorageQualified {
weak var tooWeak: StorageQualified?
unowned var disowned: StorageQualified
init() { fatalError() }
}
final class FinalStorageQualified {
weak var tooWeak: StorageQualified?
unowned var disowned: StorageQualified
init() { fatalError() }
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}keyPathForStorageQualified
func keyPathForStorageQualified() {
// CHECK: = keypath $ReferenceWritableKeyPath<StorageQualified, Optional<StorageQualified>>,
// CHECK-SAME: settable_property $Optional<StorageQualified>, id #StorageQualified.tooWeak!getter.1
_ = \StorageQualified.tooWeak
// CHECK: = keypath $ReferenceWritableKeyPath<StorageQualified, StorageQualified>,
// CHECK-SAME: settable_property $StorageQualified, id #StorageQualified.disowned!getter.1
_ = \StorageQualified.disowned
// CHECK: = keypath $ReferenceWritableKeyPath<FinalStorageQualified, Optional<StorageQualified>>,
// CHECK-SAME: settable_property $Optional<StorageQualified>, id ##FinalStorageQualified.tooWeak
_ = \FinalStorageQualified.tooWeak
// CHECK: = keypath $ReferenceWritableKeyPath<FinalStorageQualified, StorageQualified>,
// CHECK-SAME: settable_property $StorageQualified, id ##FinalStorageQualified.disowned
_ = \FinalStorageQualified.disowned
}
struct IUOProperty {
var iuo: IUOBlob!
}
struct IUOBlob {
var x: Int
subscript(y: String) -> String {
get { return y }
set {}
}
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}11iuoKeyPaths
func iuoKeyPaths() {
// CHECK: = keypath $WritableKeyPath<IUOProperty, Int>,
// CHECK-SAME: stored_property #IUOProperty.iuo
// CHECK-SAME: optional_force
// CHECK-SAME: stored_property #IUOBlob.x
_ = \IUOProperty.iuo.x
// CHECK: = keypath $WritableKeyPath<IUOProperty, Int>,
// CHECK-SAME: stored_property #IUOProperty.iuo
// CHECK-SAME: optional_force
// CHECK-SAME: stored_property #IUOBlob.x
_ = \IUOProperty.iuo!.x
}
class Bass: Hashable {
static func ==(_: Bass, _: Bass) -> Bool { return false }
func hash(into hasher: inout Hasher) {}
}
class Treble: Bass { }
struct Subscripts<T> {
subscript() -> T {
get { fatalError() }
set { fatalError() }
}
subscript(generic x: T) -> T {
get { fatalError() }
set { fatalError() }
}
subscript(concrete x: String) -> String {
get { fatalError() }
set { fatalError() }
}
subscript(x: String, y: String) -> String {
get { fatalError() }
set { fatalError() }
}
subscript<U>(subGeneric z: U) -> U {
get { fatalError() }
set { fatalError() }
}
subscript(mutable x: T) -> T {
get { fatalError() }
set { fatalError() }
}
subscript(bass: Bass) -> Bass {
get { return bass }
set { }
}
}
struct SubscriptDefaults1 {
subscript(x: Int = 0) -> Int {
get { fatalError() }
set { fatalError() }
}
subscript(x: Int, y: Int, z: Int = 0) -> Int {
get { fatalError() }
set { fatalError() }
}
subscript(x: Bool, bool y: Bool = false) -> Bool {
get { fatalError() }
set { fatalError() }
}
subscript(bool x: Bool, y: Int, z: Int = 0) -> Int {
get { fatalError() }
set { fatalError() }
}
}
struct SubscriptDefaults2 {
subscript(x: Int? = nil) -> Int {
get { fatalError() }
set { fatalError() }
}
}
struct SubscriptDefaults3 {
subscript(x: Int = #line) -> Int {
get { fatalError() }
set { fatalError() }
}
}
struct SubscriptDefaults4 {
subscript<T : Numeric>(x x: T, y y: T = 0) -> T {
get { fatalError() }
set { fatalError() }
}
}
struct SubscriptDefaults5 {
subscript<T : ExpressibleByStringLiteral>(x x: T, y y: T = #function) -> T {
get { fatalError() }
set { fatalError() }
}
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}10subscripts1x1y1syx_q_SStSHRzSHR_r0_lF
func subscripts<T: Hashable, U: Hashable>(x: T, y: U, s: String) {
_ = \Subscripts<T>.[]
_ = \Subscripts<T>.[generic: x]
_ = \Subscripts<T>.[concrete: s]
_ = \Subscripts<T>.[s, s]
_ = \Subscripts<T>.[subGeneric: s]
_ = \Subscripts<T>.[subGeneric: x]
_ = \Subscripts<T>.[subGeneric: y]
_ = \Subscripts<U>.[]
_ = \Subscripts<U>.[generic: y]
_ = \Subscripts<U>.[concrete: s]
_ = \Subscripts<U>.[s, s]
_ = \Subscripts<U>.[subGeneric: s]
_ = \Subscripts<U>.[subGeneric: x]
_ = \Subscripts<U>.[subGeneric: y]
_ = \Subscripts<String>.[]
_ = \Subscripts<String>.[generic: s]
_ = \Subscripts<String>.[concrete: s]
_ = \Subscripts<String>.[s, s]
_ = \Subscripts<String>.[subGeneric: s]
_ = \Subscripts<String>.[subGeneric: x]
_ = \Subscripts<String>.[subGeneric: y]
_ = \Subscripts<T>.[s, s].count
_ = \Subscripts<T>.[Bass()]
_ = \Subscripts<T>.[Treble()]
_ = \SubscriptDefaults1.[]
_ = \SubscriptDefaults1.[0]
_ = \SubscriptDefaults1.[0, 0]
_ = \SubscriptDefaults1.[0, 0, 0]
_ = \SubscriptDefaults1.[false]
_ = \SubscriptDefaults1.[false, bool: false]
_ = \SubscriptDefaults1.[bool: false, 0]
_ = \SubscriptDefaults1.[bool: false, 0, 0]
_ = \SubscriptDefaults2.[]
_ = \SubscriptDefaults2.[0]
_ = \SubscriptDefaults3.[]
_ = \SubscriptDefaults3.[0]
_ = \SubscriptDefaults4.[x: 0]
_ = \SubscriptDefaults4.[x: 0, y: 0]
_ = \SubscriptDefaults5.[x: ""]
_ = \SubscriptDefaults5.[x: "", y: ""]
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}check_default_subscripts
func check_default_subscripts() {
// CHECK: [[INTX:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 0
// CHECK: [[IX:%[0-9]+]] = apply %{{[0-9]+}}([[INTX]], {{.*}}
// CHECK: [[INTY:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 0
// CHECK: [[IY:%[0-9]+]] = apply %{{[0-9]+}}([[INTY]], {{.*}}
// CHECK: [[KEYPATH:%[0-9]+]] = keypath $WritableKeyPath<SubscriptDefaults4, Int>, (root $SubscriptDefaults4; settable_property $Int, id @$s8keypaths18SubscriptDefaults4V1x1yxx_xtcSjRzluig : $@convention(method) <τ_0_0 where τ_0_0 : Numeric> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0, SubscriptDefaults4) -> @out τ_0_0, getter @$s8keypaths18SubscriptDefaults4V1x1yxx_xtcSjRzluipACSiTK : $@convention(thin) (@in_guaranteed SubscriptDefaults4, UnsafeRawPointer) -> @out Int, setter @$s8keypaths18SubscriptDefaults4V1x1yxx_xtcSjRzluipACSiTk : $@convention(thin) (@in_guaranteed Int, @inout SubscriptDefaults4, UnsafeRawPointer) -> (), indices [%$0 : $Int : $Int, %$1 : $Int : $Int], indices_equals @$sS2iTH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sS2iTh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[IX]], [[IY]])
_ = \SubscriptDefaults4.[x: 0, y: 0]
// CHECK: [[INTINIT:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 0
// CHECK: [[I:%[0-9]+]] = apply %{{[0-9]+}}([[INTINIT]], {{.*}}
// CHECK: [[DFN:%[0-9]+]] = function_ref @$s8keypaths18SubscriptDefaults4V1x1yxx_xtcSjRzluipfA0_ : $@convention(thin) <τ_0_0 where τ_0_0 : Numeric> () -> @out τ_0_0
// CHECK: [[ALLOC:%[0-9]+]] = alloc_stack $Int
// CHECK: apply [[DFN]]<Int>([[ALLOC]]) : $@convention(thin) <τ_0_0 where τ_0_0 : Numeric> () -> @out τ_0_0
// CHECK: [[LOAD:%[0-9]+]] = load [trivial] [[ALLOC]] : $*Int
// CHECK: [[KEYPATH:%[0-9]+]] = keypath $WritableKeyPath<SubscriptDefaults4, Int>, (root $SubscriptDefaults4; settable_property $Int, id @$s8keypaths18SubscriptDefaults4V1x1yxx_xtcSjRzluig : $@convention(method) <τ_0_0 where τ_0_0 : Numeric> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0, SubscriptDefaults4) -> @out τ_0_0, getter @$s8keypaths18SubscriptDefaults4V1x1yxx_xtcSjRzluipACSiTK : $@convention(thin) (@in_guaranteed SubscriptDefaults4, UnsafeRawPointer) -> @out Int, setter @$s8keypaths18SubscriptDefaults4V1x1yxx_xtcSjRzluipACSiTk : $@convention(thin) (@in_guaranteed Int, @inout SubscriptDefaults4, UnsafeRawPointer) -> (), indices [%$0 : $Int : $Int, %$1 : $Int : $Int], indices_equals @$sS2iTH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sS2iTh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[I]], [[LOAD]])
_ = \SubscriptDefaults4.[x: 0]
// CHECK: [[STRX_LIT:%[0-9]+]] = string_literal utf8 ""
// CHECK: [[STRX:%[0-9]+]] = apply %{{[0-9]+}}([[STRX_LIT]], {{.*}}
// CHECK: [[STRY_LIT:%[0-9]+]] = string_literal utf8 "check_default_subscripts()"
// CHECK: [[DEF_ARG:%[0-9]+]] = apply %{{[0-9]+}}([[STRY_LIT]], {{.*}}
// CHECK: keypath $WritableKeyPath<SubscriptDefaults5, String>, (root $SubscriptDefaults5; settable_property $String, id @$s8keypaths18SubscriptDefaults5V1x1yxx_xtcs26ExpressibleByStringLiteralRzluig : $@convention(method) <τ_0_0 where τ_0_0 : ExpressibleByStringLiteral> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0, SubscriptDefaults5) -> @out τ_0_0, getter @$s8keypaths18SubscriptDefaults5V1x1yxx_xtcs26ExpressibleByStringLiteralRzluipACSSTK : $@convention(thin) (@in_guaranteed SubscriptDefaults5, UnsafeRawPointer) -> @out String, setter @$s8keypaths18SubscriptDefaults5V1x1yxx_xtcs26ExpressibleByStringLiteralRzluipACSSTk : $@convention(thin) (@in_guaranteed String, @inout SubscriptDefaults5, UnsafeRawPointer) -> (), indices [%$0 : $String : $String, %$1 : $String : $String], indices_equals @$sS2STH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sS2STh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[STRX]], [[DEF_ARG]])
_ = \SubscriptDefaults5.[x: ""]
// CHECK: [[STRX_LIT:%[0-9]+]] = string_literal utf8 ""
// CHECK: [[STRX:%[0-9]+]] = apply %{{[0-9]+}}([[STRX_LIT]], {{.*}}
// CHECK: [[STRY_LIT:%[0-9]+]] = string_literal utf8 ""
// CHECK: [[STRY:%[0-9]+]] = apply %{{[0-9]+}}([[STRY_LIT]], {{.*}}
// CHECK: keypath $WritableKeyPath<SubscriptDefaults5, String>, (root $SubscriptDefaults5; settable_property $String, id @$s8keypaths18SubscriptDefaults5V1x1yxx_xtcs26ExpressibleByStringLiteralRzluig : $@convention(method) <τ_0_0 where τ_0_0 : ExpressibleByStringLiteral> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0, SubscriptDefaults5) -> @out τ_0_0, getter @$s8keypaths18SubscriptDefaults5V1x1yxx_xtcs26ExpressibleByStringLiteralRzluipACSSTK : $@convention(thin) (@in_guaranteed SubscriptDefaults5, UnsafeRawPointer) -> @out String, setter @$s8keypaths18SubscriptDefaults5V1x1yxx_xtcs26ExpressibleByStringLiteralRzluipACSSTk : $@convention(thin) (@in_guaranteed String, @inout SubscriptDefaults5, UnsafeRawPointer) -> (), indices [%$0 : $String : $String, %$1 : $String : $String], indices_equals @$sS2STH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sS2STh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[STRX]], [[STRY]])
_ = \SubscriptDefaults5.[x: "", y: ""]
}
struct SubscriptVariadic1 {
subscript(x: Int...) -> Int { x[0] }
}
struct SubscriptVariadic2 {
subscript<T : ExpressibleByStringLiteral>(x: T...) -> T { x[0] }
}
struct SubscriptVariadic3<T : ExpressibleByStringLiteral> {
subscript(x: T...) -> T { x[0] }
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}test_variadics
func test_variadics() {
// CHECK: [[ARR_COUNT:%[0-9]+]] = integer_literal $Builtin.Word, 3
// CHECK: [[FN_REF:%[0-9]+]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK: [[MAKE_ARR:%[0-9]+]] = apply [[FN_REF]]<Int>([[ARR_COUNT]])
// CHECK: ([[ARR:%[0-9]+]], %{{[0-9]+}}) = destructure_tuple [[MAKE_ARR]] : $(Array<Int>, Builtin.RawPointer)
// CHECK: keypath $KeyPath<SubscriptVariadic1, Int>, (root $SubscriptVariadic1; gettable_property $Int, id @$s8keypaths18SubscriptVariadic1VyS2id_tcig : $@convention(method) (@guaranteed Array<Int>, SubscriptVariadic1) -> Int, getter @$s8keypaths18SubscriptVariadic1VyS2id_tcipACTK : $@convention(thin) (@in_guaranteed SubscriptVariadic1, UnsafeRawPointer) -> @out Int, indices [%$0 : $Array<Int> : $Array<Int>], indices_equals @$sSaySiGTH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sSaySiGTh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[ARR]])
_ = \SubscriptVariadic1.[1, 2, 3]
// CHECK: [[ARR_COUNT:%[0-9]+]] = integer_literal $Builtin.Word, 1
// CHECK: [[FN_REF:%[0-9]+]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK: [[MAKE_ARR:%[0-9]+]] = apply [[FN_REF]]<Int>([[ARR_COUNT]])
// CHECK: ([[ARR:%[0-9]+]], %{{[0-9]+}}) = destructure_tuple [[MAKE_ARR]] : $(Array<Int>, Builtin.RawPointer)
// CHECK: keypath $KeyPath<SubscriptVariadic1, Int>, (root $SubscriptVariadic1; gettable_property $Int, id @$s8keypaths18SubscriptVariadic1VyS2id_tcig : $@convention(method) (@guaranteed Array<Int>, SubscriptVariadic1) -> Int, getter @$s8keypaths18SubscriptVariadic1VyS2id_tcipACTK : $@convention(thin) (@in_guaranteed SubscriptVariadic1, UnsafeRawPointer) -> @out Int, indices [%$0 : $Array<Int> : $Array<Int>], indices_equals @$sSaySiGTH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sSaySiGTh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[ARR]])
_ = \SubscriptVariadic1.[1]
// CHECK: [[ARR_COUNT:%[0-9]+]] = integer_literal $Builtin.Word, 0
// CHECK: [[FN_REF:%[0-9]+]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK: [[MAKE_ARR:%[0-9]+]] = apply [[FN_REF]]<Int>([[ARR_COUNT]])
// CHECK: ([[ARR:%[0-9]+]], %{{[0-9]+}}) = destructure_tuple [[MAKE_ARR]] : $(Array<Int>, Builtin.RawPointer)
// CHECK: keypath $KeyPath<SubscriptVariadic1, Int>, (root $SubscriptVariadic1; gettable_property $Int, id @$s8keypaths18SubscriptVariadic1VyS2id_tcig : $@convention(method) (@guaranteed Array<Int>, SubscriptVariadic1) -> Int, getter @$s8keypaths18SubscriptVariadic1VyS2id_tcipACTK : $@convention(thin) (@in_guaranteed SubscriptVariadic1, UnsafeRawPointer) -> @out Int, indices [%$0 : $Array<Int> : $Array<Int>], indices_equals @$sSaySiGTH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sSaySiGTh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[ARR]])
_ = \SubscriptVariadic1.[]
_ = \SubscriptVariadic2.["", "1"]
_ = \SubscriptVariadic2.[""]
// CHECK: [[ARR_COUNT:%[0-9]+]] = integer_literal $Builtin.Word, 2
// CHECK: [[FN_REF:%[0-9]+]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK: [[MAKE_ARR:%[0-9]+]] = apply [[FN_REF]]<String>([[ARR_COUNT]])
// CHECK: ([[ARR:%[0-9]+]], %{{[0-9]+}}) = destructure_tuple [[MAKE_ARR]] : $(Array<String>, Builtin.RawPointer)
// CHECK: keypath $KeyPath<SubscriptVariadic2, String>, (root $SubscriptVariadic2; gettable_property $String, id @$s8keypaths18SubscriptVariadic2Vyxxd_tcs26ExpressibleByStringLiteralRzluig : $@convention(method) <τ_0_0 where τ_0_0 : ExpressibleByStringLiteral> (@guaranteed Array<τ_0_0>, SubscriptVariadic2) -> @out τ_0_0, getter @$s8keypaths18SubscriptVariadic2Vyxxd_tcs26ExpressibleByStringLiteralRzluipACSSTK : $@convention(thin) (@in_guaranteed SubscriptVariadic2, UnsafeRawPointer) -> @out String, indices [%$0 : $Array<String> : $Array<String>], indices_equals @$sSaySSGTH : $@convention(thin) (UnsafeRawPointer, UnsafeRawPointer) -> Bool, indices_hash @$sSaySSGTh : $@convention(thin) (UnsafeRawPointer) -> Int) ([[ARR]])
_ = \SubscriptVariadic2.["", #function]
_ = \SubscriptVariadic3<String>.[""]
_ = \SubscriptVariadic3<String>.["", "1"]
_ = \SubscriptVariadic3<String>.[]
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}subclass_generics
func subclass_generics<T: C<Int>, U: C<V>, V/*: PoC*/>(_: T, _: U, _: V) {
_ = \T.x
_ = \T.z
_ = \T.computed
_ = \T.extension
_ = \U.x
_ = \U.z
_ = \U.computed
_ = \U.extension
/*
_ = \V.x
_ = \V.z
_ = \V.computed
_ = \V.extension
*/
_ = \(C<Int> & P).x
_ = \(C<Int> & P).z
_ = \(C<Int> & P).computed
_ = \(C<Int> & P).extension
_ = \(C<V> & P).x
_ = \(C<V> & P).z
_ = \(C<V> & P).computed
_ = \(C<V> & P).extension
/* TODO: When we support superclass requirements on protocols, we should test
* this case as well.
_ = \PoC.x
_ = \PoC.z
_ = \PoC.computed
_ = \PoC.extension
*/
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}identity
func identity<T>(_: T) {
// CHECK: keypath $WritableKeyPath<T, T>, <τ_0_0> ({{.*}}root $τ_0_0) <T>
let _: WritableKeyPath<T, T> = \T.self
// CHECK: keypath $WritableKeyPath<Array<T>, Array<T>>, <τ_0_0> ({{.*}}root $Array<τ_0_0>) <T>
let _: WritableKeyPath<[T], [T]> = \[T].self
// CHECK: keypath $WritableKeyPath<String, String>, ({{.*}}root $String)
let _: WritableKeyPath<String, String> = \String.self
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}tuples
func tuples(_: T) {
// CHECK: keypath $WritableKeyPath<T, Int>, (root $T; stored_property #T.a : $(Int, String); tuple_element #0 : $Int)
let _: WritableKeyPath<T, Int> = \T.a.0
// CHECK: keypath $WritableKeyPath<T, String>, (root $T; stored_property #T.a : $(Int, String); tuple_element #1 : $String)
let _: WritableKeyPath<T, String> = \T.a.1
// CHECK: keypath $KeyPath<T, String>, (root $T; stored_property #T.b : $(f: String, g: Int); tuple_element #0 : $String)
let _: KeyPath<T, String> = \T.b.f
// CHECK: keypath $KeyPath<T, Int>, (root $T; stored_property #T.b : $(f: String, g: Int); tuple_element #1 : $Int)
let _: KeyPath<T, Int> = \T.b.g
// CHECK: keypath $KeyPath<T, C<Int>>, (root $T; stored_property #T.c : $(x: C<Int>, y: C<String>); tuple_element #0 : $C<Int>)
let _: KeyPath<T, C<Int>> = \T.c.x
// CHECK: keypath $KeyPath<T, C<String>>, (root $T; stored_property #T.c : $(x: C<Int>, y: C<String>); tuple_element #1 : $C<String>)
let _: KeyPath<T, C<String>> = \T.c.y
// CHECK: keypath $ReferenceWritableKeyPath<T, Int>, (root $T; stored_property #T.c : $(x: C<Int>, y: C<String>); tuple_element #0 : $C<Int>; stored_property #C.x : $Int)
let _: ReferenceWritableKeyPath<T, Int> = \T.c.x.x
// CHECK: keypath $KeyPath<T, String>, (root $T; stored_property #T.c : $(x: C<Int>, y: C<String>); tuple_element #0 : $C<Int>; stored_property #C.y : $String)
let _: KeyPath<T, String> = \T.c.x.y
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}tuples_generic
func tuples_generic<T, U, V>(_: T, _: U, _: V) {
typealias TUC = (T, U, C<V>)
// CHECK: keypath $WritableKeyPath<(T, U, C<V>), T>, <τ_0_0, τ_0_1, τ_0_2> (root $(τ_0_0, τ_0_1, C<τ_0_2>); tuple_element #0 : $τ_0_0) <T, U, V>
let _: WritableKeyPath<TUC, T> = \TUC.0
// CHECK: keypath $WritableKeyPath<(T, U, C<V>), U>, <τ_0_0, τ_0_1, τ_0_2> (root $(τ_0_0, τ_0_1, C<τ_0_2>); tuple_element #1 : $τ_0_1) <T, U, V>
let _: WritableKeyPath<TUC, U> = \TUC.1
// CHECK: keypath $ReferenceWritableKeyPath<(T, U, C<V>), V>, <τ_0_0, τ_0_1, τ_0_2> (root $(τ_0_0, τ_0_1, C<τ_0_2>); tuple_element #2 : $C<τ_0_2>; stored_property #C.x : $τ_0_2) <T, U, V>
let _: ReferenceWritableKeyPath<TUC, V> = \TUC.2.x
// CHECK: keypath $KeyPath<(T, U, C<V>), String>, <τ_0_0, τ_0_1, τ_0_2> (root $(τ_0_0, τ_0_1, C<τ_0_2>); tuple_element #2 : $C<τ_0_2>; stored_property #C.y : $String) <T, U, V>
let _: KeyPath<TUC, String> = \TUC.2.y
}
| apache-2.0 | e0b38bc07f9531e1dc961b0352fc17bc | 47.404803 | 970 | 0.63253 | 3.039311 | false | false | false | false |
cotkjaer/SilverbackFramework | SilverbackFramework/UIColor.swift | 1 | 3491 | //
// UIColor.swift
// SilverbackFramework
//
// Created by Christian Otkjær on 20/04/15.
// Copyright (c) 2015 Christian Otkjær. All rights reserved.
//
import UIKit
//MARK: - Random
extension UIColor
{
public static func lightestGrayColor() -> UIColor
{
return UIColor(white: 0.9, alpha: 1.0)
}
}
//MARK: - Random
extension UIColor
{
public static func randomOpaqueColor() -> UIColor
{
return UIColor(
red: CGFloat.random(lower: 0, upper: 1),
green: CGFloat.random(lower: 0, upper: 1),
blue: CGFloat.random(lower: 0, upper: 1),
alpha: 1
)
}
public static func randomColor() -> UIColor
{
return UIColor(
red: CGFloat.random(lower: 0, upper: 1),
green: CGFloat.random(lower: 0, upper: 1),
blue: CGFloat.random(lower: 0, upper: 1),
alpha: CGFloat.random(lower: 0, upper: 1)
)
}
}
//MARK: - Alpha
public extension UIColor
{
var alpha : CGFloat
{
var alpha : CGFloat = 0
getWhite(nil, alpha: &alpha)
return alpha
}
var opaque : Bool
{ return alpha > 0.999 }
}
//MARK: - HSB
public extension UIColor
{
private var hsbComponents : (CGFloat, CGFloat, CGFloat, CGFloat)
{
var h : CGFloat = 0
var s : CGFloat = 0
var b : CGFloat = 0
var a : CGFloat = 0
getHue(&h, saturation: &s, brightness: &b, alpha: &a)
return (h,s,b,a)
}
var hue: CGFloat
{
return hsbComponents.0
}
func withHue(hue: CGFloat) -> UIColor
{
let hsba = hsbComponents
return UIColor(hue: hue, saturation: hsba.1, brightness: hsba.2, alpha: hsba.3)
}
var saturation: CGFloat
{
return hsbComponents.1
}
func withSaturation(saturation: CGFloat) -> UIColor
{
let hsba = hsbComponents
return UIColor(hue: hsba.0, saturation: saturation, brightness: hsba.2, alpha: hsba.3)
}
var brightness: CGFloat
{
return hsbComponents.2
}
func withBrightness(brightness: CGFloat) -> UIColor
{
let hsba = hsbComponents
return UIColor(hue: hsba.0, saturation: hsba.1, brightness: brightness, alpha: hsba.3)
}
}
//MARK: - Brightness
public extension UIColor
{
var isBright: Bool
{ return brightness > 0.75 }
var isDark: Bool
{ return brightness < 0.25 }
func brighterColor(factor: CGFloat = 0.2) -> UIColor
{
return withBrightness(brightness + (1 - brightness) * factor)
}
func darkerColor(factor: CGFloat = 0.2) -> UIColor
{
return withBrightness(brightness - (brightness) * factor)
}
}
//MARK: - Image
public extension UIColor
{
public var image: UIImage
{
let rect = CGRectMake(0, 0, 1, 1)
UIGraphicsBeginImageContextWithOptions(rect.size, opaque, 0)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, self.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
} | mit | 47c68cc635cd747540ba6c2a82c673ec | 21.371795 | 94 | 0.548868 | 4.444586 | false | false | false | false |
vermont42/Conjugar | Conjugar/RatingsFetcher.swift | 1 | 2262 | //
// RatingsFetcher.swift
// Conjugar
//
// Created by Joshua Adams on 3/1/19.
// Copyright © 2019 Josh Adams. All rights reserved.
//
import Foundation
struct RatingsFetcher {
static let iTunesID = "1236500467"
static let errorMessage = "Fetching failed."
private static let urlInitializationMessage = " URL could not be initializaed."
static var iTunesURL: URL {
guard let iTunesURL = URL(string: "https://itunes.apple.com/lookup?id=\(iTunesID)") else {
fatalError("iTunes" + urlInitializationMessage)
}
return iTunesURL
}
static var reviewURL: URL {
guard let reviewURL = URL(string: "https://itunes.apple.com/app/conjugar/id\(iTunesID)?action=write-review") else {
fatalError("Rate/review" + urlInitializationMessage)
}
return reviewURL
}
static func fetchRatingsDescription(completion: @escaping (String) -> ()) {
let request = URLRequest(url: RatingsFetcher.iTunesURL)
let task = Current.session.dataTask(with: request) { (responseData, _, error) in
if error != nil {
completion(errorMessage)
return
} else if let responseData = responseData {
guard
let json = try? JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any],
let results = json["results"] as? [[String: Any]],
results.count == 1
else {
completion(errorMessage)
return
}
let ratingsCount = (results[0])["userRatingCountForCurrentVersion"] as? Int ?? 0
let description: String
let exhortation = " ¡Sé la primera o el primero!"
switch ratingsCount {
case 0:
description = Localizations.Settings.noRating + exhortation
case 1:
description = Localizations.Settings.oneRating + " " + Localizations.Settings.addYours
default:
description = String(format: Localizations.Settings.multipleRatings, ratingsCount) + " " + Localizations.Settings.addYours
}
completion(description)
}
}
task.resume()
}
static func stubData(ratingsCount: Int) -> Data {
return Data("{ \"resultCount\":1, \"results\": [ { \"userRatingCountForCurrentVersion\": \(ratingsCount) } ] }".utf8)
}
}
| agpl-3.0 | 6067690b22625684ad8aab21943b16da | 30.816901 | 132 | 0.64896 | 4.270321 | false | false | false | false |
jdanthinne/PIImageCache | PIImageCache/PIImageCache/PIImageCacheExtensions.swift | 2 | 998 |
// https://github.com/pixel-ink/PIImageCache
import UIKit
public extension NSURL {
public func getImageWithCache() -> UIImage? {
return PIImageCache.shared.get(self)
}
public func getImageWithCache(cache: PIImageCache) -> UIImage? {
return cache.get(self)
}
}
public extension UIImageView {
public func imageOfURL(url: NSURL) {
PIImageCache.shared.get(url) {
[weak self] img in
self?.image = img
}
}
public func imageOfURL(url: NSURL, cache: PIImageCache) {
cache.get(url) {
[weak self] img in
self?.image = img
}
}
public func imageOfURL(url: NSURL, then:(Bool)->Void) {
PIImageCache.shared.get(url) {
[weak self] img in
let isOK = img != nil
self?.image = img
then(isOK)
}
}
public func imageOfURL(url: NSURL, cache: PIImageCache, then:(Bool)->Void) {
cache.get(url) {
[weak self] img in
let isOK = img != nil
self?.image = img
then(isOK)
}
}
} | mit | ca29eb4eb1eda9ae07725b5fa9abe219 | 19.8125 | 78 | 0.608216 | 3.589928 | false | false | false | false |
arsonik/AKYamahaAV | Source/YamahaAV.swift | 1 | 3934 | //
// YamahaAV.swift
// Pods
//
// Created by Florian Morello on 11/11/15.
//
//
import Foundation
import Alamofire
import HTMLReader
public class YamahaAV : NSObject {
private let baseURL: URL
public private(set) var mainZonePower:Bool!
public private(set) var mainZoneSleep:Bool!
public private(set) var mainZoneVolume:Int!
public private(set) var mainZoneInput:String!
private var timer:Timer?
private let updateNotificationName = "YamahaUpdated"
private var listeners:Int = 0 {
didSet{
listeners = max(0, listeners)
if listeners == 0 {
// stop auto update
timer?.invalidate()
}
else if listeners == 1 && (timer == nil || timer?.isValid == false) {
timer = Timer(timeInterval: 2, target: self, selector: Selector(("poll:")), userInfo: nil, repeats: true)
RunLoop.main.add(timer!, forMode: RunLoopMode.commonModes)
}
}
}
public init(host:String) {
baseURL = URL(string: "http://\(host)/YamahaRemoteControl/ctrl")!
super.init()
}
public func startListening(_ observer: NSObject, selector: Selector) {
NotificationCenter.default.addObserver(observer, selector: selector, name: NSNotification.Name(rawValue: updateNotificationName), object: self)
listeners += 1
timer?.fire()
}
public func stopListening(observer: NSObject){
listeners -= 1
NotificationCenter.default.removeObserver(observer, name: NSNotification.Name(rawValue: updateNotificationName), object: self)
}
internal func poll(timer: Timer) {
let payload = "<YAMAHA_AV cmd=\"GET\"><Main_Zone><Basic_Status>GetParam</Basic_Status></Main_Zone></YAMAHA_AV>"
post(payload: payload) { [weak self] (result, error) -> Void in
if let str = result, let ss = self {
let xml = HTMLDocument(string: str)
if let vol = (xml.nodes(matchingSelector: "Volume Lvl Val").first)?.textContent {
ss.mainZoneVolume = Int(vol)
}
if let value = (xml.nodes(matchingSelector: "Power_Control Power").first)?.textContent {
ss.mainZonePower = value == "On"
}
if let value = (xml.nodes(matchingSelector: "Power_Control Sleep").first)?.textContent {
ss.mainZoneSleep = value == "On"
}
if let value = (xml.nodes(matchingSelector: "Input_Sel").first)?.textContent {
ss.mainZoneInput = value
}
NotificationCenter.default.post(name: NSNotification.Name(rawValue: ss.updateNotificationName), object: self)
} else {
print(error)
}
}
}
public func setMainZonePower(on: Bool) -> Request {
return post(payload: "<YAMAHA_AV cmd=\"PUT\"><Main_Zone><Power_Control><Power>\(on ? "On" : "Standby")</Power></Power_Control></Main_Zone></YAMAHA_AV>")
}
public func setMainZoneInput(input: String) -> Request {
return post(payload: "<YAMAHA_AV cmd=\"PUT\"><Main_Zone><Input><Input_Sel>\(input)</Input_Sel></Input></Main_Zone></YAMAHA_AV>")
}
public func setMainZoneVolume(value:Int) -> Request {
let vol = Int((round((Float(value) / 10) * 2) / 2) * 10)
mainZoneVolume = vol
//<YAMAHA_AV cmd="PUT"><Main_Zone><Volume><Lvl><Val>-300</Val><Exp>1</Exp><Unit>dB</Unit></Lvl></Volume></Main_Zone></YAMAHA_AV>
let payload = "<YAMAHA_AV cmd=\"PUT\"><Main_Zone><Volume><Lvl><Val>\(vol)</Val><Exp>1</Exp><Unit>dB</Unit></Lvl></Volume></Main_Zone></YAMAHA_AV>"
return post(payload: payload)
}
private func post(payload:String, completion:((String?, Error?) -> Void)! = nil) -> Request {
var request = URLRequest(url: baseURL as URL)
request.setValue("text/xml", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = payload.data(using: String.Encoding.utf8)
return Alamofire.request(request).responseString { (response) -> Void in
completion?(response.result.value, response.result.error)
}
}
}
| mit | ec743166fb419e287ca40115ba56b1c9 | 36.113208 | 160 | 0.651246 | 3.732448 | false | false | false | false |
sharath-cliqz/browser-ios | Client/Frontend/Browser/SwipeAnimator.swift | 2 | 5568 | /* 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
struct SwipeAnimationParameters {
let totalRotationInDegrees: Double
let deleteThreshold: CGFloat
let totalScale: CGFloat
let totalAlpha: CGFloat
let minExitVelocity: CGFloat
let recenterAnimationDuration: TimeInterval
}
private let DefaultParameters =
SwipeAnimationParameters(
totalRotationInDegrees: 10,
deleteThreshold: 80,
totalScale: 0.9,
totalAlpha: 0,
minExitVelocity: 800,
recenterAnimationDuration: 0.15)
protocol SwipeAnimatorDelegate: class {
func swipeAnimator(_ animator: SwipeAnimator, viewWillExitContainerBounds: UIView)
}
class SwipeAnimator: NSObject {
weak var delegate: SwipeAnimatorDelegate?
weak var container: UIView!
weak var animatingView: UIView!
fileprivate var prevOffset: CGPoint!
fileprivate let params: SwipeAnimationParameters
var containerCenter: CGPoint {
return CGPoint(x: container.frame.width / 2, y: container.frame.height / 2)
}
init(animatingView: UIView, container: UIView, params: SwipeAnimationParameters = DefaultParameters) {
self.animatingView = animatingView
self.container = container
self.params = params
super.init()
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(SwipeAnimator.SELdidPan(_:)))
container.addGestureRecognizer(panGesture)
panGesture.delegate = self
}
}
//MARK: Private Helpers
extension SwipeAnimator {
fileprivate func animateBackToCenter() {
UIView.animate(withDuration: params.recenterAnimationDuration, animations: {
self.animatingView.transform = CGAffineTransform.identity
self.animatingView.alpha = 1
})
}
fileprivate func animateAwayWithVelocity(_ velocity: CGPoint, speed: CGFloat) {
// Calculate the edge to calculate distance from
let translation = velocity.x >= 0 ? container.frame.width : -container.frame.width
let timeStep = TimeInterval(abs(translation) / speed)
self.delegate?.swipeAnimator(self, viewWillExitContainerBounds: self.animatingView)
UIView.animate(withDuration: timeStep, animations: {
self.animatingView.transform = self.transformForTranslation(translation)
self.animatingView.alpha = self.alphaForDistanceFromCenter(abs(translation))
}, completion: { finished in
if finished {
self.animatingView.alpha = 0
}
})
}
fileprivate func transformForTranslation(_ translation: CGFloat) -> CGAffineTransform {
let swipeWidth = container.frame.size.width
let totalRotationInRadians = CGFloat(params.totalRotationInDegrees / 180.0 * M_PI)
// Determine rotation / scaling amounts by the distance to the edge
let rotation = (translation / swipeWidth) * totalRotationInRadians
let scale = 1 - (abs(translation) / swipeWidth) * (1 - params.totalScale)
let rotationTransform = CGAffineTransform(rotationAngle: rotation)
let scaleTransform = CGAffineTransform(scaleX: scale, y: scale)
let translateTransform = CGAffineTransform(translationX: translation, y: 0)
return rotationTransform.concatenating(scaleTransform).concatenating(translateTransform)
}
fileprivate func alphaForDistanceFromCenter(_ distance: CGFloat) -> CGFloat {
let swipeWidth = container.frame.size.width
return 1 - (distance / swipeWidth) * (1 - params.totalAlpha)
}
}
//MARK: Selectors
extension SwipeAnimator {
@objc func SELdidPan(_ recognizer: UIPanGestureRecognizer!) {
let translation = recognizer.translation(in: container)
switch (recognizer.state) {
case .began:
prevOffset = containerCenter
case .changed:
animatingView.transform = transformForTranslation(translation.x)
animatingView.alpha = alphaForDistanceFromCenter(abs(translation.x))
prevOffset = CGPoint(x: translation.x, y: 0)
case .cancelled:
animateBackToCenter()
case .ended:
let velocity = recognizer.velocity(in: container)
// Bounce back if the velocity is too low or if we have not reached the threshold yet
let speed = max(abs(velocity.x), params.minExitVelocity)
if (speed < params.minExitVelocity || abs(prevOffset.x) < params.deleteThreshold) {
animateBackToCenter()
} else {
animateAwayWithVelocity(velocity, speed: speed)
}
default:
break
}
}
func close(_ right: Bool) {
let direction = CGFloat(right ? -1 : 1)
animateAwayWithVelocity(CGPoint(x: -direction * params.minExitVelocity, y: 0), speed: direction * params.minExitVelocity)
}
@objc func SELcloseWithoutGesture() -> Bool {
close(false)
return true
}
}
extension SwipeAnimator: UIGestureRecognizerDelegate {
@objc func gestureRecognizerShouldBegin(_ recognizer: UIGestureRecognizer) -> Bool {
let cellView = recognizer.view as UIView!
let panGesture = recognizer as! UIPanGestureRecognizer
let translation = panGesture.translation(in: cellView?.superview!)
return fabs(translation.x) > fabs(translation.y)
}
}
| mpl-2.0 | 936546a1b8cd66fefb9ef6d386d211dc | 37.666667 | 129 | 0.681753 | 5.19403 | false | false | false | false |
naokuro/sticker | Carthage/Checkouts/RapidFire/RapidFire/RapidFire.Setting.swift | 1 | 1465 | //
// RapidFire.Setting.swift
// RapidFire
//
// Created by keygx on 2016/11/19.
// Copyright © 2016年 keygx. All rights reserved.
//
import Foundation
extension RapidFire {
public enum HTTPMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
}
public struct PartData {
public var name: String
public var filename: String
public var value: Data
public var mimeType: String
public init(name: String, filename: String, value: Data, mimeType: String) {
self.name = name
self.filename = filename
self.value = value
self.mimeType = mimeType
}
}
class RequestSetting {
var method: HTTPMethod?
var baseUrl: String?
var path: String?
var headers: [String: String]?
var query: [String: String]?
var bodyParams: [String: String]?
var bodyData: Data?
var json: [String: Any]?
var partDataParams: [String: String]?
var partDataBinary: [PartData]?
var timeoutInterval: TimeInterval?
var retryCount: Int = 0
var retryInterval: Int = 15
var completionHandler: ((RapidFire.Response) -> Void)?
}
}
| mit | bf253c6919d756b7ba64d2b0a485f698 | 27.666667 | 84 | 0.52394 | 4.554517 | false | false | false | false |
Darshanptl7500/DPParallaxCell | DPParallaxCell/DPParallaxCell.swift | 1 | 2357 | //
// DPParallaxCell.swift
// DPParallaxCell
//
// Created by Darshan Patel on 7/29/15.
// Copyright (c) 2015 Darshan Patel. All rights reserved.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Darshan Patel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class DPParallaxCell: UITableViewCell {
@IBOutlet weak var imgParallax: UIImageView!
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
}
func cellParallax(tableView: UITableView!,view: UIView!)
{
let rect = tableView.convertRect(self.frame, toView: view)
let distanceFromCenter = (CGRectGetHeight(view.frame)/2) - CGRectGetMinY(rect)
let difference = CGRectGetHeight(self.imgParallax.frame) - CGRectGetHeight(self.frame)
let move = (distanceFromCenter / CGRectGetHeight(view.frame)) * difference
var imageRect = self.imgParallax.frame
imageRect.origin.y = -(difference/2) + move
self.imgParallax.frame = imageRect
}
}
| mit | 118610d6b288ee662054028a0cb9357f | 33.661765 | 94 | 0.684345 | 4.594542 | false | false | false | false |
arnaudbenard/my-npm | my-npm/ModuleDetailViewController.swift | 2 | 6448 | //
// ModuleDetailViewController.swift
// my-npm
//
// Created by Arnaud Benard on 28/07/2015.
// Copyright (c) 2015 Arnaud Benard. All rights reserved.
//
import UIKit
import Charts
class ModuleDetailViewController: UIViewController, ChartViewDelegate {
@IBOutlet var ModuleDetailView: UIView!
@IBOutlet weak var chartView: LineChartView!
@IBOutlet weak var monthCountLabel: UILabel!
@IBOutlet weak var weekCountLabel: UILabel!
@IBOutlet weak var dayCountLabel: UILabel!
let npm = npmAPI()
let blueColor = UIColor(red:0.34, green:0.72, blue:1.00, alpha:1.0)
var moduleName: String = ""
var days: [String] = [String]()
var downloads: [Double] = [Double]()
var dataEntries: [ChartDataEntry] = []
override func viewDidLoad() {
super.viewDidLoad()
// Invalid module name
if count(moduleName) == 0 {
return
}
self.fetchGraphData(moduleName)
self.fetchGlobalStat(moduleName)
chartView.delegate = self;
chartView.descriptionText = "";
chartView.noDataTextDescription = "Data will be loaded soon."
chartView.noDataText = ""
chartView.infoTextColor = UIColor.whiteColor()
chartView.drawGridBackgroundEnabled = false // remove gray bg
// lagging when there're a lot of data points
chartView.pinchZoomEnabled = false
chartView.doubleTapToZoomEnabled = false
chartView.scaleXEnabled = false
chartView.scaleYEnabled = false
}
override func viewDidAppear(animated: Bool) {
self.navigationController?.navigationBar.topItem?.title = moduleName
}
private func setData(xAxis: [String], yAxis: [Double]) {
var chartDataY = yAxis
for i in 0..<chartDataY.count {
let dataEntry = ChartDataEntry(value: chartDataY[i], xIndex: i)
dataEntries.append(dataEntry)
}
let chartDataSet = LineChartDataSet(yVals: dataEntries, label: "Downloads per day")
// line graph style
chartDataSet.cubicIntensity = 0.05
chartDataSet.drawCubicEnabled = true
chartDataSet.drawCircleHoleEnabled = false
chartDataSet.circleRadius = CGFloat(0.0)
chartDataSet.setColor(UIColor.whiteColor())
chartDataSet.highlightEnabled = false
chartDataSet.lineWidth = 1
chartDataSet.drawValuesEnabled = false
let chartData = LineChartData(xVals: xAxis, dataSet: chartDataSet)
chartView.data = chartData
// Hide label on the right
let yAxisRight = chartView.getAxis(ChartYAxis.AxisDependency.Right)
yAxisRight.drawLabelsEnabled = false
yAxisRight.drawGridLinesEnabled = false
yAxisRight.drawAxisLineEnabled = false
// Format Y axis labels
let yAxisLeft = chartView.getAxis(ChartYAxis.AxisDependency.Left)
yAxisLeft.valueFormatter = BigNumberFormatter()
yAxisLeft.drawGridLinesEnabled = false
chartView.drawBordersEnabled = false
chartView.leftAxis.customAxisMin = max(0.0, chartView.data!.yMin - 1.0)
chartView.leftAxis.customAxisMax = chartView.data!.yMax + 1.0
chartView.leftAxis.labelCount = 6
chartView.leftAxis.startAtZeroEnabled = false
chartView.leftAxis.drawGridLinesEnabled = true
chartView.leftAxis.gridColor = UIColor.whiteColor()
let smallFont = UIFont(name: "HelveticaNeue-Light" , size: 10)!
chartView.leftAxis.labelFont = smallFont
chartView.leftAxis.labelTextColor = UIColor.whiteColor()
chartView.leftAxis.drawAxisLineEnabled = false
chartView.xAxis.labelFont = smallFont
chartView.xAxis.labelPosition = .Bottom
chartView.xAxis.gridColor = UIColor.whiteColor()
chartView.xAxis.labelTextColor = UIColor.whiteColor()
chartView.xAxis.avoidFirstLastClippingEnabled = true
chartView.xAxis.drawAxisLineEnabled = false
}
private func formatDayLabel(day: String) -> String {
// Format from npm api: YYYY-MM-DD
let toDateFormatter = NSDateFormatter()
toDateFormatter.dateFormat = "YYYY-MM-dd"
// String to date
let dayDate = toDateFormatter.dateFromString(day)!
let labelFormatter = NSDateFormatter()
labelFormatter.dateFormat = "d MMM yyyy"
let dateFormatted = labelFormatter.stringFromDate(dayDate)
return dateFormatted
}
private func getCurrentDateAsString() -> String {
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let toStringFormatter = NSDateFormatter()
toStringFormatter.dateFormat = "YYYY-MM-dd"
let dateFormatted = toStringFormatter.stringFromDate(date)
return dateFormatted
}
private func fetchGraphData(name: String) {
let today = getCurrentDateAsString()
npm.fetchRange(name, start: "2013-01-04", end: today) { response, _ in
if let range = response {
for data in range {
if let dls = data["downloads"] as? Double, let day = data["day"] as? String {
self.downloads.append(dls)
self.days.append(self.formatDayLabel(day))
}
}
self.setData(self.days, yAxis: self.downloads)
self.chartView.setNeedsDisplay()
}
}
}
private func fetchGlobalStat(name: String) {
// Get ready for the worst code I wrote. Yolo async -> Needs to be refactored with promises ASAP
npm.fetchModule(name, period: .LastMonth) { response, _ in
if let downloads = response!["downloads"] as? Double {
self.monthCountLabel.text = downloads.toDecimalStyle
}
}
npm.fetchModule(name, period: .LastWeek) { response, _ in
if let downloads = response!["downloads"] as? Double {
self.weekCountLabel.text = downloads.toDecimalStyle
}
}
npm.fetchModule(name, period: .LastDay) { response, _ in
if let downloads = response!["downloads"] as? Double {
self.dayCountLabel.text = downloads.toDecimalStyle
}
}
}
}
| mit | 8566b10f53d858b9ca3aa331c757d94b | 34.234973 | 104 | 0.628567 | 5.133758 | false | false | false | false |
joerocca/GitHawk | Pods/Tabman/Sources/Tabman/TabmanBar/Components/Indicator/Styles/TabmanLineIndicator.swift | 1 | 2228 | //
// TabmanLineIndicator.swift
// Tabman
//
// Created by Merrick Sapsford on 20/02/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import UIKit
public extension TabmanIndicator {
/// Weight of the indicator line.
///
/// - thin: Thin - 1pt
/// - normal: Normal - 2pt
/// - thick: Thick - 4pt
public enum LineWeight: CGFloat {
case thin = 1.0
case normal = 2.0
case thick = 4.0
}
}
internal class TabmanLineIndicator: TabmanIndicator {
//
// MARK: Properties
//
/// The thickness of the indicator line.
///
/// Default is .normal
public var weight: LineWeight = TabmanBar.Appearance.defaultAppearance.indicator.lineWeight ?? .normal {
didSet {
guard weight != oldValue else {
return
}
self.invalidateIntrinsicContentSize()
self.superview?.setNeedsLayout()
self.superview?.layoutIfNeeded()
self.delegate?.indicator(requiresLayoutInvalidation: self)
}
}
/// Whether to use rounded corners for the indicator line.
///
/// Default is false
public var useRoundedCorners: Bool = TabmanBar.Appearance.defaultAppearance.indicator.useRoundedCorners ?? false {
didSet {
self.setNeedsLayout()
}
}
/// The color of the indicator line.
override public var tintColor: UIColor! {
didSet {
self.backgroundColor = tintColor
}
}
override public var intrinsicContentSize: CGSize {
return CGSize(width: 0.0, height: self.weight.rawValue)
}
//
// MARK: Lifecycle
//
public override func constructIndicator() {
self.tintColor = TabmanBar.Appearance.defaultAppearance.indicator.color
}
override public func layoutSubviews() {
super.layoutSubviews()
self.layoutIfNeeded()
self.layer.cornerRadius = useRoundedCorners ? self.bounds.size.height / 2.0 : 0.0
}
override func itemTransitionType() -> TabmanItemTransition.Type? {
return TabmanItemColorCrossfadeTransition.self
}
}
| mit | 5548cfb5aad86d507fc4a58180373f51 | 24.895349 | 118 | 0.601257 | 4.916115 | false | false | false | false |
psobot/hangover | Hangover/Dictionary+Swifter.swift | 1 | 3111 | //
// Dictionary+Swifter.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension String {
func urlEncodedStringWithEncoding(encoding: NSStringEncoding) -> String {
let charactersToBeEscaped = ":/?&=;+!@#$()',*" as CFStringRef
let charactersToLeaveUnescaped = "[]." as CFStringRef
let str = self as NSString
let result = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, str as CFString, charactersToLeaveUnescaped, charactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding)) as NSString
return result as String
}
}
extension Dictionary {
func filter(predicate: Element -> Bool) -> Dictionary {
var filteredDictionary = Dictionary()
for (key, value) in self {
if predicate(key, value) {
filteredDictionary[key] = value
}
}
return filteredDictionary
}
func queryStringWithEncoding() -> String {
var parts = [String]()
for (key, value) in self {
let keyString: String = "\(key)"
let valueString: String = "\(value)"
let query: String = "\(keyString)=\(valueString)"
parts.append(query)
}
return "&".join(parts)
}
func urlEncodedQueryStringWithEncoding(encoding: NSStringEncoding) -> String {
var parts = [String]()
for (key, value) in self {
let keyString: String = "\(key)".urlEncodedStringWithEncoding(encoding)
let valueString: String = "\(value)".urlEncodedStringWithEncoding(encoding)
let query: String = "\(keyString)=\(valueString)"
parts.append(query)
}
return "&".join(parts)
}
}
infix operator +| {}
func +| <K,V>(left: Dictionary<K,V>, right: Dictionary<K,V>) -> Dictionary<K,V> {
var map = Dictionary<K,V>()
for (k, v) in left {
map[k] = v
}
for (k, v) in right {
map[k] = v
}
return map
} | mit | c01ee057fa3f3cf7dd708a736a8bc0d5 | 32.462366 | 214 | 0.654131 | 4.671171 | false | false | false | false |
mmrmmlrr/ExamMaster | Pods/ModelsTreeKit/ModelsTreeKit/Classes/Lists/UnorderedListDataAdapter.swift | 1 | 7015 | //
// UnorderedListDataAdapter.swift
// SessionSwift
//
// Created by aleksey on 16.10.15.
// Copyright © 2015 aleksey chernish. All rights reserved.
//
import Foundation
public class UnorderedListDataAdapter<ObjectType, GroupKeyType where
ObjectType: Hashable, ObjectType: Equatable,
GroupKeyType: Hashable, GroupKeyType: Comparable>: ObjectsDataSource<ObjectType> {
typealias Section = (objects: [ObjectType], key: GroupKeyType?)
typealias Sections = [Section]
public var groupingCriteria: (ObjectType -> GroupKeyType)?
public var groupsSortingCriteria: (GroupKeyType, GroupKeyType) -> Bool = { return $0 < $1 }
public var groupContentsSortingCriteria: ((ObjectType, ObjectType) -> Bool)?
private var sections = Sections()
private let pool = AutodisposePool()
public init(list: UnorderedList<ObjectType>) {
super.init()
list.beginUpdatesSignal.subscribeNext { [weak self] in self?.beginUpdates() }.putInto(pool)
list.endUpdatesSignal.subscribeNext { [weak self] in self?.endUpdates() }.putInto(pool)
list.didReplaceContentSignal.subscribeNext() { [weak self] objects in
guard let strongSelf = self else { return }
strongSelf.sections = strongSelf.arrangedSectionsFrom(objects)
}.putInto(pool)
list.didChangeContentSignal.subscribeNext { [weak self] insertions, deletions, updates in
guard let strongSelf = self else { return }
let oldSections = strongSelf.sections
strongSelf.applyInsertions(insertions, deletions: deletions, updates: updates)
strongSelf.pushInsertions(
insertions,
deletions: deletions,
updates: updates,
oldSections: oldSections)
}.putInto(pool)
}
//Helpers
public func fetchAllFrom(list: UnorderedList<ObjectType>) {
sections = arrangedSectionsFrom(list.objects)
}
public func indexPathFor(object: ObjectType) -> NSIndexPath? {
return indexPathFor(object, inSections: sections)
}
public func allObjects() -> [[ObjectType]] {
if sections.isEmpty { return [] }
return sections.map {return $0.objects}
}
public override func numberOfSections() -> Int {
return sections.count
}
public override func numberOfObjectsInSection(section: Int) -> Int {
return sections[section].objects.count
}
public override func objectAtIndexPath(indexPath: NSIndexPath) -> ObjectType? {
return objectAtIndexPath(indexPath, inSections: sections)
}
func objectAtIndexPath(indexPath: NSIndexPath, inSections sections: Sections) -> ObjectType? {
return sections[indexPath.section].objects[indexPath.row]
}
override func titleForSection(atIndex sectionIndex: Int) -> String? {
return sections[sectionIndex].key as? String
}
//Private
private func arrangedSectionsFrom(objects: Set<ObjectType>) -> Sections {
if objects.isEmpty { return [] }
guard let groupingBlock = groupingCriteria else {
if let sortingCriteria = groupContentsSortingCriteria {
return [(objects: objects.sort(sortingCriteria), key: nil)]
} else {
return [(objects: Array(objects), key: nil)]
}
}
var groupsDictionary = [GroupKeyType: [ObjectType]]()
for object in objects {
let key = groupingBlock(object)
if groupsDictionary[key] == nil {
groupsDictionary[key] = []
}
groupsDictionary[key]!.append(object)
}
let sortedKeys = groupsDictionary.keys.sort(groupsSortingCriteria)
var result = Sections()
for key in sortedKeys {
var objects = groupsDictionary[key]!
if let sortingCriteria = groupContentsSortingCriteria {
objects = objects.sort(sortingCriteria)
}
result.append((objects, key))
}
return result
}
private func applyInsertions(insertions: Set<ObjectType>, deletions: Set<ObjectType>, updates: Set<ObjectType>) {
var objects = allObjectsSet()
objects.unionInPlace(insertions.union(updates))
objects.subtractInPlace(deletions)
sections = arrangedSectionsFrom(objects)
}
private func pushInsertions(
insertions: Set<ObjectType>,
deletions: Set<ObjectType>,
updates: Set<ObjectType>,
oldSections: Sections) {
//Objects
for object in insertions {
didChangeObjectSignal.sendNext((
object: object,
changeType: .Insertion,
fromIndexPath: nil,
toIndexPath: indexPathFor(object, inSections: sections))
)
}
for object in deletions {
didChangeObjectSignal.sendNext((
object: object,
changeType: .Deletion,
fromIndexPath: indexPathFor(object, inSections: oldSections),
toIndexPath: nil)
)
}
for object in updates {
guard
let oldIndexPath = indexPathFor(object, inSections: oldSections),
let newIndexPath = indexPathFor(object, inSections: sections)
else {
continue
}
let changeType: ListChangeType = oldIndexPath == newIndexPath ? .Update : .Move
didChangeObjectSignal.sendNext((
object: object,
changeType: changeType,
fromIndexPath: oldIndexPath,
toIndexPath: newIndexPath)
)
}
//Sections
for (index, section) in oldSections.enumerate() {
if sections.filter({ return $0.key == section.key }).isEmpty {
didChangeSectionSignal.sendNext((
changeType: .Deletion,
fromIndex: index,
toIndex: nil)
)
}
}
for (index, section) in sections.enumerate() {
if oldSections.filter({ return $0.key == section.key }).isEmpty {
didChangeSectionSignal.sendNext((
changeType: .Insertion,
fromIndex: nil,
toIndex: index)
)
}
}
}
private func indexPathFor(object: ObjectType, inSections sections: Sections) -> NSIndexPath? {
var allObjects: [ObjectType] = []
for section in sections {
allObjects.appendContentsOf(section.objects)
}
if !allObjects.contains(object) { return nil }
var row = 0
var section = 0
var objectFound = false
for (index, sectionInfo) in sections.enumerate() {
if sectionInfo.objects.contains(object) {
objectFound = true
section = index
row = sectionInfo.objects.indexOf(object)!
break
}
}
return objectFound ? NSIndexPath(forRow: row, inSection: section) : nil
}
private func allObjectsSet() -> Set<ObjectType> {
var result: Set<ObjectType> = []
for section in sections {
result.unionInPlace(section.objects)
}
return result
}
private func beginUpdates() {
beginUpdatesSignal.sendNext()
}
private func endUpdates() {
endUpdatesSignal.sendNext()
}
private func rearrangeAndPushReload() {
sections = arrangedSectionsFrom(allObjectsSet())
reloadDataSignal.sendNext()
}
} | mit | d20d0d5ea8513c3c571af8ac1e45e997 | 27.868313 | 115 | 0.659966 | 4.939437 | false | false | false | false |
lukevanin/OCRAI | CardScanner/EditFieldViewController.swift | 1 | 3254 | //
// EditFieldViewController.swift
// CardScanner
//
// Created by Luke Van In on 2017/03/27.
// Copyright © 2017 Luke Van In. All rights reserved.
//
import UIKit
private let pickerIndexPath = IndexPath(row: 2, section: 0)
extension EditFieldViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return FieldType.all.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return String(describing: FieldType.all[row])
}
}
extension EditFieldViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
updateTypeLabel()
}
}
extension EditFieldViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
class EditFieldViewController: UITableViewController {
var field: Field!
private var isTypePickerVisible = false
@IBOutlet weak var valueTextField: UITextField!
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var typePickerView: UIPickerView!
@IBAction func onTypeDropdownAction(_ sender: UIButton) {
valueTextField.resignFirstResponder()
setTypePickerVisible(!isTypePickerVisible, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setTypePickerVisible(false, animated: false)
updateView()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
commitChanges()
}
private func commitChanges() {
let row = typePickerView.selectedRow(inComponent: 0)
field.type = FieldType.all[row]
field.value = valueTextField.text
coreData.saveNow()
}
private func setTypePickerVisible(_ visible: Bool, animated: Bool) {
tableView.beginUpdates()
isTypePickerVisible = visible
tableView.endUpdates()
}
private func updateView() {
valueTextField.text = field.value
let row = FieldType.all.index(of: field.type) ?? 0
typePickerView.selectRow(row, inComponent: 0, animated: false)
updateTypeLabel()
}
fileprivate func updateTypeLabel() {
let row = typePickerView.selectedRow(inComponent: 0)
let fieldName = String(describing: FieldType.all[row])
typeLabel.text = fieldName
valueTextField.placeholder = fieldName
}
// MARK: Table view
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath == pickerIndexPath, !isTypePickerVisible {
return 0
}
else {
return super.tableView(tableView, heightForRowAt: indexPath)
}
}
}
| mit | 29ea0a04ca9349413c8e7d2dccf9bd96 | 28.306306 | 111 | 0.662465 | 5.306688 | false | false | false | false |
vnu/vTweetz | vTweetz/TweetDataSource.swift | 1 | 863 | //
// TweetDataSource.swift
// vTweetz
//
// Created by Vinu Charanya on 2/27/16.
// Copyright © 2016 vnu. All rights reserved.
//
import UIKit
class TweetDataSource: NSObject, UITableViewDataSource, UITableViewDelegate {
//CELL Identifiers
let tweetCellId = "com.vnu.tweetcell"
//Model Vars
var user: User!
var tweets = [Tweet]()
var cellDelegate:TweetCellDelegate?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(tweetCellId) as! TweetCell
cell.tweet = tweets[indexPath.row]
cell.delegate = cellDelegate
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
}
| apache-2.0 | 2f3d9210530335a67bc892db0e2ca4ab | 24.352941 | 109 | 0.675174 | 4.684783 | false | false | false | false |
ifabijanovic/firebase-messages-swift | Social/UI/Message/BBSMessageCollectionViewCell.swift | 2 | 4366 | //
// BBSMessageCollectionViewCell.swift
// Social
//
// Created by Ivan Fabijanović on 24/11/15.
// Copyright © 2015 Bellabeat. All rights reserved.
//
import UIKit
internal let CellIdentifierMessage = "messageCell"
internal class BBSMessageCollectionViewCell: BBSBaseCollectionViewCell {
// MARK: - Outlets
@IBOutlet weak var messageTextLabel: UILabel!
@IBOutlet weak var messageTimestampLabel: UILabel!
@IBOutlet weak var upvoteButton: UIButton!
@IBOutlet weak var messagePointsLabel: UILabel!
@IBOutlet weak var downvoteButton: UIButton!
@IBOutlet weak var clockImageView: UIImageView!
@IBOutlet weak var separatorView: UIView!
// MARK: - Properties
internal var message: BBSMessageModel? {
didSet {
self.observerContainer.dispose()
if let message = self.message {
weak var weakSelf = self
self.observerContainer.add(message.message.bindTo(self.messageTextLabel.rx_text))
self.observerContainer.add(message.timestamp.map {
let seconds = $0 - NSDate().timeIntervalSince1970
return BBSMessageCollectionViewCell.timeFormatter.stringForTimeInterval(seconds)
}.bindTo(self.messageTimestampLabel.rx_text))
self.observerContainer.add(message.points.map { "\($0)" }.bindTo(self.messagePointsLabel.rx_text))
self.observerContainer.add(message.points.bindNext { _ in
weakSelf!.updateAppearance()
})
self.observerContainer.add(self.upvoteButton.rx_controlEvents(.TouchUpInside).bindNext {
weakSelf!.message!.upvoteForUser(weakSelf!.userId)
})
self.observerContainer.add(self.downvoteButton.rx_controlEvents(.TouchUpInside).bindNext {
weakSelf!.message!.downvoteForUser(weakSelf!.userId)
})
}
}
}
internal var userId: String = ""
// MARK: - Private members
private static let timeFormatter = TTTTimeIntervalFormatter()
private static let clockImage = UIImage(named: "Clock")?.imageWithRenderingMode(.AlwaysTemplate)
private static let upvoteImage = UIImage(named: "Upvote")?.imageWithRenderingMode(.AlwaysTemplate)
private static let downvoteImage = UIImage(named: "Downvote")?.imageWithRenderingMode(.AlwaysTemplate)
private var textColor = UIColor.blackColor()
private var highlightColor = SystemTintColor
private var dimmedColor = UIColor.lightGrayColor()
// MARK: - Init
override func awakeFromNib() {
super.awakeFromNib()
self.updateAppearance()
}
// MARK: - Methods
internal override func applyTheme(theme: BBSUITheme) {
self.messageTextLabel.font = UIFont(name: theme.contentFontName, size: 18.0)
self.messageTimestampLabel.font = UIFont(name: theme.contentFontName, size: 16.0)
self.messagePointsLabel.font = UIFont(name: theme.contentFontName, size: 30.0)
self.textColor = theme.contentTextColor
self.highlightColor = theme.contentHighlightColor
self.dimmedColor = theme.contentDimmedColor
}
// MARK: - Private methods
private func updateAppearance() {
self.messageTextLabel.textColor = self.textColor
self.clockImageView.image = BBSMessageCollectionViewCell.clockImage
self.clockImageView.tintColor = self.dimmedColor
self.messageTimestampLabel.textColor = self.dimmedColor
self.messagePointsLabel.textColor = self.highlightColor
self.separatorView.backgroundColor = self.dimmedColor
self.upvoteButton.tintColor = self.dimmedColor
self.downvoteButton.tintColor = self.dimmedColor
self.upvoteButton.setImage(BBSMessageCollectionViewCell.upvoteImage, forState: .Normal)
self.downvoteButton.setImage(BBSMessageCollectionViewCell.downvoteImage, forState: .Normal)
if let message = self.message {
self.upvoteButton.tintColor = message.didUpvoteForUser(self.userId) ? self.highlightColor : self.dimmedColor
self.downvoteButton.tintColor = message.didDownvoteForUser(self.userId) ? self.highlightColor : self.dimmedColor
}
}
}
| mit | 4b3ff88e554a830970526fba397e8a28 | 40.561905 | 124 | 0.676214 | 5.20143 | false | false | false | false |
kousun12/RxSwift | RxSwift/Schedulers/MainScheduler.swift | 9 | 2103 | //
// MainScheduler.swift
// Rx
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Abstracts work that needs to be performed on `MainThread`. In case `schedule` methods are called from main thread, it will perform action immediately without scheduling.
This scheduler is usually used to perform UI work.
Main scheduler is a specialization of `SerialDispatchQueueScheduler`.
This scheduler is optimized for `observeOn` operator. To ensure observable sequence is subscribed on main thread using `subscribeOn`
operator please use `ConcurrentMainScheduler` because it is more optimized for that purpose.
*/
public final class MainScheduler : SerialDispatchQueueScheduler {
private let _mainQueue: dispatch_queue_t
var numberEnqueued: Int32 = 0
private init() {
_mainQueue = dispatch_get_main_queue()
super.init(serialQueue: _mainQueue)
}
/**
Singleton instance of `MainScheduler`
*/
public static let sharedInstance = MainScheduler()
/**
In case this method is called on a background thread it will throw an exception.
*/
public class func ensureExecutingOnScheduler() {
if !NSThread.currentThread().isMainThread {
rxFatalError("Executing on backgound thread. Please use `MainScheduler.sharedInstance.schedule` to schedule work on main thread.")
}
}
override func scheduleInternal<StateType>(state: StateType, action: StateType -> Disposable) -> Disposable {
let currentNumberEnqueued = OSAtomicIncrement32(&numberEnqueued)
if NSThread.currentThread().isMainThread && currentNumberEnqueued == 1 {
let disposable = action(state)
OSAtomicDecrement32(&numberEnqueued)
return disposable
}
let cancel = SingleAssignmentDisposable()
dispatch_async(_mainQueue) {
if !cancel.disposed {
action(state)
}
OSAtomicDecrement32(&self.numberEnqueued)
}
return cancel
}
}
| mit | 3479cb05ee1c97ca63664a08da3cd34d | 29.926471 | 169 | 0.68854 | 5.205446 | false | false | false | false |
victoraliss0n/FireRecord | FireRecord/Source/Extensions/Database/Filterable+FirebaseModel.swift | 2 | 3630 | //
// Filterable+Extension.swift
// FireRecord
//
// Created by Victor Alisson on 18/08/17.
//
import Foundation
import FirebaseCommunity
public extension Filterable where Self: FirebaseModel {
static func findFirst(when propertyEventType: PropertyEventType, completion: @escaping (_ object: Self) -> Void) {
if let fireRecordQuery = Self.fireRecordQuery?.queryLimited(toFirst: 1) {
Self.executeGenericFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModel in
completion(firebaseModel)
})
} else {
let fireRecordQuery = Self.classPath.queryLimited(toFirst: 1)
Self.executeGenericFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModel in
completion(firebaseModel)
})
}
}
fileprivate static func executeGenericFind(with reference: DatabaseQuery, and propertyEventType: PropertyEventType, completion: @escaping (_ object: Self) -> Void) {
reference.observeSingleEvent(of: propertyEventType.rawValue) { snapshot in
if let firebaseModel = Self.getFirebaseModels(snapshot).first {
completion(firebaseModel)
}
}
}
fileprivate static func executeFind(with databaseQuery: DatabaseQuery, and propertyEventType: PropertyEventType, completion: @escaping (_ objects: [Self]) -> Void) {
databaseQuery.observeSingleEvent(of: propertyEventType.rawValue) { snapshot in
let firebaseModels = Self.getFirebaseModels(snapshot)
completion(firebaseModels)
}
}
static func findLast(when propertyEventType: PropertyEventType, completion: @escaping (_ object: Self) -> Void) {
if let fireRecordQuery = Self.fireRecordQuery?.queryLimited(toLast: 1) {
Self.executeGenericFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModel in
completion(firebaseModel)
})
} else {
let fireRecordQuery = Self.classPath.queryLimited(toLast: 1)
Self.executeGenericFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModel in
completion(firebaseModel)
})
}
}
static func findFirst(when propertyEventType: PropertyEventType, _ toFirst: UInt, completion: @escaping (_ object: [Self]) -> Void) {
if let fireRecordQuery = Self.fireRecordQuery?.queryLimited(toFirst: toFirst) {
Self.executeFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModels in
completion(firebaseModels)
})
} else {
let fireRecordQuery = Self.classPath.queryLimited(toFirst: toFirst)
Self.executeFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModels in
completion(firebaseModels)
})
}
}
static func findLast(when propertyEventType: PropertyEventType, _ toLast: UInt, completion: @escaping (_ object: [Self]) -> Void) {
if let fireRecordQuery = Self.fireRecordQuery?.queryLimited(toLast: toLast) {
Self.executeFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModels in
completion(firebaseModels)
})
} else {
let fireRecordQuery = Self.classPath.queryLimited(toLast: toLast)
Self.executeFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModels in
completion(firebaseModels)
})
}
}
}
| mit | 14b7c81faacfce84928a03c554545679 | 46.142857 | 169 | 0.659504 | 5.253256 | false | false | false | false |
kaneshin/ActiveRecord | Tests/TestCoreDataStack.swift | 1 | 4294 | // TestCoreDataStack.swift
//
// Copyright (c) 2014 Kenji Tayama
// Copyright (c) 2014 Shintaro Kaneko
//
// 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 CoreData
import ActiveRecord
class ___TestCoreDataStack : NSObject, Context {
override init() {
super.init()
}
private lazy var lazyDefaultManagedObjectContext: NSManagedObjectContext? = {
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.parentContext = self.writerManagedObjectContext
managedObjectContext.mergePolicy = NSOverwriteMergePolicy
return managedObjectContext
}()
/// Main queue context
var defaultManagedObjectContext: NSManagedObjectContext? {
get {
return self.lazyDefaultManagedObjectContext
}
set {}
}
private lazy var lazyWriterManagedObjectContext: NSManagedObjectContext? = {
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
managedObjectContext.mergePolicy = NSOverwriteMergePolicy
return managedObjectContext
}()
/// Context for writing to the PersistentStore
var writerManagedObjectContext: NSManagedObjectContext? {
get {
return self.lazyWriterManagedObjectContext
}
set { }
}
lazy var lazyPersistentStoreCoordinator: NSPersistentStoreCoordinator? = {
if let managedObjectModel = self.managedObjectModel {
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
var error: NSError? = nil
if coordinator?.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil, error: &error) == true {
println("could not add persistent store : \(error?.localizedDescription)")
}
return coordinator
}
return nil;
}()
/// PersistentStoreCoordinator
var persistentStoreCoordinator: NSPersistentStoreCoordinator? {
get {
return self.lazyPersistentStoreCoordinator
}
set { }
}
lazy var lazyManagedObjectModel: NSManagedObjectModel? = {
let testsBundle: NSBundle = NSBundle(forClass: self.dynamicType)
let modelURL: NSURL? = testsBundle.URLForResource("ActiveRecordTests", withExtension: "momd")
if let managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL!) {
return managedObjectModel
}
return nil
}()
/// ManagedObjectModel
var managedObjectModel: NSManagedObjectModel? {
get {
return self.lazyManagedObjectModel
}
set { }
}
/// Store URL
var storeURL: NSURL? {
return nil
}
} | mit | ced9b5e3eb390a5f30a5d57d19683d60 | 35.092437 | 144 | 0.691197 | 5.980501 | false | false | false | false |
bromas/ActivityViewController | ApplicationVCSample/AuthenticationVC.swift | 1 | 2424 | //
// AuthenticationVC.swift
// ApplicationVCSample
//
// Created by Brian Thomas on 11/23/14.
// Copyright (c) 2014 Brian Thomas. All rights reserved.
//
import Foundation
import UIKit
import ActivityViewController
class AuthenticationVC : UIViewController {
@IBOutlet var activities: ActivityViewController!
var timesPresented = -1
@IBAction func buttonTap() { actionOnButtonTap() }
var actionOnButtonTap : () -> Void = {
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "activities" {
self.activities = segue.destination as? ActivityViewController
self.activities.registerGenerator("Generator") { () -> UIViewController in
return NoXibController()
}
}
}
override func viewDidLoad() {
self.navigationController?.isNavigationBarHidden = true
self.actionOnButtonTap = {
var operation = ActivityOperation(rule: .new, identifier: "Launch", animator: ShrinkAnimator())
operation.completionBlock = {
print("ohhhh yea")
}
self.activities.performActivityOperation(operation)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
timesPresented += 1
}
@IBAction func backButtonTapped() {
switch timesPresented % 5 {
case 0:
let operation = ActivityOperation(identifier: "Launch", animator: CircleTransitionAnimator(direction: .outward, duration: 0.5))
ActivityViewController.rootController?.performActivityOperation(operation)
case 1:
let operation = ActivityOperation(identifier: "Launch", animator: CinematicWipeTransitionAnimator())
ActivityViewController.rootController?.performActivityOperation(operation)
case 2:
let operation = ActivityOperation(identifier: "Launch", animator: ShrinkAnimator())
ActivityViewController.rootController?.performActivityOperation(operation)
case 3:
let operation = ActivityOperation(identifier: "Launch", animationType: UIViewAnimationOptions.transitionCurlUp, duration: 0.5)
ActivityViewController.rootController?.performActivityOperation(operation)
default:
let operation = ActivityOperation(identifier: "Launch", animationType: UIViewAnimationOptions.transitionFlipFromLeft, duration: 0.5)
ActivityViewController.rootController?.performActivityOperation(operation)
}
}
}
| mit | f2b590965ed71e493becdb02e1232bf1 | 33.628571 | 138 | 0.726073 | 5.281046 | false | false | false | false |
rmannion/RMCore | RMCore/Extensions/UIView+Extensions.swift | 1 | 1570 | //
// UIView+Extensions.swift
// RMCore
//
// Created by Ryan Mannion on 4/29/16.
// Copyright © 2016 Ryan Mannion. All rights reserved.
//
import UIKit
public extension UIView {
public var x: CGFloat {
get {
return frame.origin.x
}
set (newX) {
frame = CGRect(origin: CGPoint(x: newX, y: y), size: frame.size)
}
}
public var y: CGFloat {
get {
return frame.origin.y
}
set (newY) {
frame = CGRect(origin: CGPoint(x: x, y: newY), size: frame.size)
}
}
public var width: CGFloat {
get {
return frame.size.width
}
set (newWidth) {
frame = CGRect(origin: frame.origin, size: CGSize(width: newWidth, height: height))
}
}
public var height: CGFloat {
get {
return frame.size.height
}
set (newHeight) {
frame = CGRect(origin: frame.origin, size: CGSize(width: width, height: newHeight))
}
}
public var bottomY: CGFloat {
get {
return frame.maxY
}
}
public var rightX: CGFloat {
get{
return frame.maxX
}
}
@objc
public func removeAllSubviews() {
for subview in subviews {
subview.removeFromSuperview()
}
}
public func optionalSnapshotViewAfterScreenUpdates(afterUpdates: Bool = false) -> UIView? {
return snapshotView(afterScreenUpdates: afterUpdates)
}
}
| mit | aadc7ab891f17f9d51ad5d316b10c955 | 21.414286 | 95 | 0.525813 | 4.370474 | false | false | false | false |
Shivam0911/IOS-Training-Projects | SliderDemo/SliderDemo/MainVC.swift | 1 | 2956 | //
// MainVC.swift
// SliderDemo
//
// Created by MAC on 23/02/17.
// Copyright © 2017 Appinventiv. All rights reserved.
//
import UIKit
class MainVC: UIViewController {
@IBOutlet weak var sliderButtonOutlet: UIButton!
var leftSliderController = LeftSliderVC()
override func viewDidLoad() {
super.viewDidLoad()
doSubViewLoad()
}
//MARK: doSubViewLoad Method
//=======================
fileprivate func doSubViewLoad() {
let storyBoardScene = UIStoryboard(name: "Main", bundle: Bundle.main)
leftSliderController = storyBoardScene.instantiateViewController(withIdentifier : "LeftSliderVCID") as! LeftSliderVC
view.addSubview(leftSliderController.view)
addChildViewController(leftSliderController)
leftSliderController.didMove(toParentViewController: self)
leftSliderController.view.frame = CGRect(x: -(self.view.frame.width - 100)
, y: 0, width: self.view.frame.width - 100, height: self.view.frame.height )
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension MainVC {
//MARK: chnageSubView Method
//=======================
func changeSubView( _ subViewController : UIViewController ) {
leftSliderController.removeFromParentViewController()
subViewController.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width , height: self.view.frame.height )
view.addSubview(subViewController.view)
addChildViewController(subViewController)
sliderButtonOutlet.isSelected = false
doSubViewLoad()
subViewController.view.frame = CGRect(x: 0 , y: 0, width: self.view.frame.width , height: self.view.frame.height )
}
//MARK: sliderButtonTapped Method
//==========================
@IBAction func sliderButtonTapped(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected {
UIView.animate(withDuration: 1, delay: 0.1, options: .curveEaseOut, animations: {
self.leftSliderController.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width - 150, height: self.view.frame.height)
})
}
else {
UIView.animate(withDuration: 1, delay: 0.1, options: .curveEaseOut, animations: {
self.leftSliderController.view.frame = CGRect(x: -(self.view.frame.width - 150), y: 0, width: self.view.frame.width - 150, height: self.view.frame.height)
})
}
}
}
| mit | 6c1bcf5def037abf3f923834a38bea4c | 28.257426 | 174 | 0.569882 | 4.991554 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.