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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aatalyk/swift-algorithm-club | Strassen Matrix Multiplication/StrassensMatrixMultiplication.playground/Contents.swift | 2 | 485 | //: Playground - noun: a place where people can play
import Foundation
var A = Matrix(rows: 2, columns: 4, initialValue: 0)
A[.row, 0] = [2, 3, -1, 0]
A[.row, 1] = [-7, 2, 1, 10]
var B = Matrix(rows: 4, columns: 2, initialValue: 0)
print(B)
B[.column, 0] = [3, 2, -1, 2]
B[.column, 1] = [4, 1, 2, 7]
let C = A.matrixMultiply(by: B)
let D = A.strassenMatrixMultiply(by: B)
let E = B.matrixMultiply(by: A)
let F = B.strassenMatrixMultiply(by: A)
print(C)
print(D)
print(E)
print(F)
| mit | 4a7b20c6bb714eb073329ebe3f2c32b7 | 21.045455 | 52 | 0.624742 | 2.377451 | false | false | false | false |
microlimbic/Matrix | Matrix/Sources/Supporting Type/Status.swift | 1 | 3181 | //
// Status.swift
// TWMLMatrix
//
// Created by Grady Zhuo on 2015/9/8.
// Copyright © 2015年 Limbic. All rights reserved.
//
import Accelerate
//MARK: Status Type Redefined
public struct Status: RawRepresentable, CustomStringConvertible, CustomDebugStringConvertible {
public typealias RawValue = la_status_t
internal var value:RawValue
internal static func check(status status: Status) throws{
guard status >= 0 else {
throw LAError.ErrorWithStatus(status: status)
}
if status > 0 {
print("[Warn] status description:\(status)")
}
}
/// Convert from a value of `RawValue`, succeeding unconditionally.
public init(rawValue: RawValue){
self.value = rawValue
}
public var rawValue: RawValue { return value }
public static let Success = Status(rawValue: la_status_t(LA_SUCCESS))
public static let WarningPoorlyConditioned = Status(rawValue: la_status_t(LA_WARNING_POORLY_CONDITIONED))
public static let Internal = Status(rawValue: la_status_t(LA_INTERNAL_ERROR))
public static let InvalidParameterError = Status(rawValue: la_status_t(LA_INVALID_PARAMETER_ERROR))
public static let DimensionMismatchError = Status(rawValue: la_status_t(LA_DIMENSION_MISMATCH_ERROR))
public static let PrecisionMismatchError = Status(rawValue: la_status_t(LA_PRECISION_MISMATCH_ERROR))
public static let SingularError = Status(rawValue: la_status_t(LA_SINGULAR_ERROR))
public static let SliceOutOfBoundsError = Status(rawValue: la_status_t(LA_SLICE_OUT_OF_BOUNDS_ERROR))
public var description : String {
let represent:String
switch self {
case Status.Success :
represent = "Success"
case Status.WarningPoorlyConditioned:
represent = "WarningPoorlyConditioned"
case Status.Internal:
represent = "Internal"
case Status.InvalidParameterError:
represent = "InvalidParameterError"
case Status.DimensionMismatchError:
represent = "DimensionMismatchError"
case Status.PrecisionMismatchError:
represent = "PrecisionMismatchError"
case Status.SingularError:
represent = "SingularError"
case Status.SliceOutOfBoundsError:
represent = "SliceOutOfBoundsError"
default:
represent = "Undefined"
}
return represent
}
public var debugDescription: String {
return "Status : \(self)"
}
}
func ~=(lhs: Status, rhs: Status)->Bool{
return lhs.rawValue == rhs.rawValue
}
public func >(lhs: Status, rhs: Status.RawValue)->Bool{
return lhs.rawValue > rhs
}
public func >=(lhs: Status, rhs: Status.RawValue)->Bool{
return lhs.rawValue >= rhs
}
public func <(lhs: Status, rhs: Status.RawValue)->Bool{
return lhs.rawValue < rhs
}
public func <=(lhs: Status, rhs: Status.RawValue)->Bool{
return lhs.rawValue <= rhs
}
public func !=(lhs: Status, rhs: Status.RawValue)->Bool{
return lhs.rawValue != rhs
}
| mit | 5d4ce4e4621e05367b870223192717e5 | 28.981132 | 109 | 0.648836 | 4.476056 | false | false | false | false |
sarahspins/Loop | WatchApp Extension/ComplicationController.swift | 1 | 4634 | //
// ComplicationController.swift
// WatchApp Extension
//
// Created by Nathan Racklyeft on 8/29/15.
// Copyright © 2015 Nathan Racklyeft. All rights reserved.
//
import ClockKit
final class ComplicationController: NSObject, CLKComplicationDataSource {
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) {
handler([.Backward])
}
func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
if let date = DeviceDataManager.sharedManager.lastContextData?.glucoseDate {
handler(date)
} else {
handler(nil)
}
}
func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
if let date = DeviceDataManager.sharedManager.lastContextData?.glucoseDate {
handler(date)
} else {
handler(nil)
}
}
func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) {
handler(.HideOnLockScreen)
}
// MARK: - Timeline Population
private lazy var formatter = NSNumberFormatter()
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
switch complication.family {
case .ModularSmall:
if let context = DeviceDataManager.sharedManager.lastContextData,
glucose = context.glucose,
unit = context.preferredGlucoseUnit,
glucoseString = formatter.stringFromNumber(glucose.doubleValueForUnit(unit)),
date = context.glucoseDate where date.timeIntervalSinceNow.minutes >= -15,
let template = CLKComplicationTemplateModularSmallStackText(line1: glucoseString, date: date)
{
handler(CLKComplicationTimelineEntry(date: date, complicationTemplate: template))
} else {
handler(nil)
}
default:
handler(nil)
}
}
func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// Call the handler with the timeline entries prior to the given date
handler(nil)
}
func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// Call the handler with the timeline entries after to the given date
if let context = DeviceDataManager.sharedManager.lastContextData,
glucose = context.glucose,
unit = context.preferredGlucoseUnit,
glucoseString = formatter.stringFromNumber(glucose.doubleValueForUnit(unit)),
glucoseDate = context.glucoseDate where glucoseDate.timeIntervalSinceDate(date) > 0,
let template = CLKComplicationTemplateModularSmallStackText(line1: glucoseString, date: glucoseDate)
{
handler([CLKComplicationTimelineEntry(date: glucoseDate, complicationTemplate: template)])
} else {
handler(nil)
}
}
func requestedUpdateDidBegin() {
DeviceDataManager.sharedManager.updateComplicationDataIfNeeded()
}
func requestedUpdateBudgetExhausted() {
// TODO: os_log_info in iOS 10
}
// MARK: - Update Scheduling
func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) {
// Call the handler with the date when you would next like to be given the opportunity to update your complication content
handler(NSDate(timeIntervalSinceNow: NSTimeInterval(2 * 60 * 60)))
}
// MARK: - Placeholder Templates
func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) {
switch complication.family {
case .ModularSmall:
let template = CLKComplicationTemplateModularSmallStackText()
template.line1TextProvider = CLKSimpleTextProvider(text: "--", shortText: "--", accessibilityLabel: "No glucose value available")
template.line2TextProvider = CLKSimpleTextProvider(text: "mg/dL")
handler(template)
default:
handler(nil)
}
}
}
| apache-2.0 | 2471762f1307e1561b1662e715bebbd6 | 39.286957 | 178 | 0.677099 | 5.916986 | false | false | false | false |
cruisediary/Diving | Diving/Scenes/ExpenseDetail/ExpenseDetailRouter.swift | 1 | 2161 | //
// ExpenseDetailRouter.swift
// Diving
//
// Created by CruzDiary on 5/23/16.
// Copyright (c) 2016 DigitalNomad. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
protocol ExpenseDetailRouterInput {
func navigateToSomewhere()
}
class ExpenseDetailRouter {
weak var viewController: ExpenseDetailViewController!
// MARK: Navigation
func navigateToSomewhere() {
// NOTE: Teach the router how to navigate to another scene. Some examples follow:
// 1. Trigger a storyboard segue
// viewController.performSegueWithIdentifier("ShowSomewhereScene", sender: nil)
// 2. Present another view controller programmatically
// viewController.presentViewController(someWhereViewController, animated: true, completion: nil)
// 3. Ask the navigation controller to push another view controller onto the stack
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
// 4. Present a view controller from a different storyboard
// let storyboard = UIStoryboard(name: "OtherThanMain", bundle: nil)
// let someWhereViewController = storyboard.instantiateInitialViewController() as! SomeWhereViewController
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
}
// MARK: Communication
func passDataToNextScene(segue: UIStoryboardSegue) {
// NOTE: Teach the router which scenes it can communicate with
if segue.identifier == "ShowSomewhereScene" {
passDataToSomewhereScene(segue)
}
}
func passDataToSomewhereScene(segue: UIStoryboardSegue) {
// NOTE: Teach the router how to pass data to the next scene
// let someWhereViewController = segue.destinationViewController as! SomeWhereViewController
// someWhereViewController.output.name = viewController.output.name
}
}
| mit | 5140fa81c2e5ad1a11e539f21cc6e7c4 | 36.912281 | 114 | 0.701527 | 5.762667 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKitTests/Core/BoundingSphereTests.swift | 1 | 26538 | //
// BoundingSphereTests.swift
// CesiumKit
//
// Created by Ryan Walklin on 27/10/14.
// Copyright (c) 2014 Test Toast. All rights reserved.
//
import XCTest
class BoundingSphereTests: XCTestCase {
override func setUp() {
}
/*
/*global defineSuite*/
defineSuite([
'Core/BoundingSphere',
'Core/Cartesian3',
'Core/Cartesian4',
'Core/Cartographic',
'Core/Ellipsoid',
'Core/GeographicProjection',
'Core/Intersect',
'Core/Interval',
'Core/Math',
'Core/Matrix4',
'Core/Rectangle'
], function(
BoundingSphere,
Cartesian3,
Cartesian4,
Cartographic,
Ellipsoid,
GeographicProjection,
Intersect,
Interval,
CesiumMath,
Matrix4,
Rectangle) {
"use strict";
/*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/
var positionsRadius = 1.0;
var positionsCenter = new Cartesian3(10000001.0, 0.0, 0.0);
var center = new Cartesian3(10000000.0, 0.0, 0.0);
function getPositions() {
return [
Cartesian3.add(center, new Cartesian3(1, 0, 0), new Cartesian3()),
Cartesian3.add(center, new Cartesian3(2, 0, 0), new Cartesian3()),
Cartesian3.add(center, new Cartesian3(0, 0, 0), new Cartesian3()),
Cartesian3.add(center, new Cartesian3(1, 1, 0), new Cartesian3()),
Cartesian3.add(center, new Cartesian3(1, -1, 0), new Cartesian3()),
Cartesian3.add(center, new Cartesian3(1, 0, 1), new Cartesian3()),
Cartesian3.add(center, new Cartesian3(1, 0, -1), new Cartesian3())
];
}
function getPositionsAsFlatArray() {
var positions = getPositions();
var result = [];
for (var i = 0; i < positions.length; ++i) {
result.push(positions[i].x);
result.push(positions[i].y);
result.push(positions[i].z);
}
return result;
}
function getPositionsAsFlatArrayWithStride5() {
var positions = getPositions();
var result = [];
for (var i = 0; i < positions.length; ++i) {
result.push(positions[i].x);
result.push(positions[i].y);
result.push(positions[i].z);
result.push(1.23);
result.push(4.56);
}
return result;
}
it('default constructing produces expected values', function() {
var sphere = new BoundingSphere();
expect(sphere.center).toEqual(Cartesian3.ZERO);
expect(sphere.radius).toEqual(0.0);
});
it('constructor sets expected values', function() {
var expectedCenter = new Cartesian3(1.0, 2.0, 3.0);
var expectedRadius = 1.0;
var sphere = new BoundingSphere(expectedCenter, expectedRadius);
expect(sphere.center).toEqual(expectedCenter);
expect(sphere.radius).toEqual(expectedRadius);
});
it('clone without a result parameter', function() {
var sphere = new BoundingSphere(new Cartesian3(1.0, 2.0, 3.0), 4.0);
var result = sphere.clone();
expect(sphere).toNotBe(result);
expect(sphere).toEqual(result);
});
it('clone with a result parameter', function() {
var sphere = new BoundingSphere(new Cartesian3(1.0, 2.0, 3.0), 4.0);
var result = new BoundingSphere();
var returnedResult = sphere.clone(result);
expect(result).toNotBe(sphere);
expect(result).toBe(returnedResult);
expect(result).toEqual(sphere);
});
it('clone works with "this" result parameter', function() {
var expectedCenter = new Cartesian3(1.0, 2.0, 3.0);
var expectedRadius = 1.0;
var sphere = new BoundingSphere(expectedCenter, expectedRadius);
var returnedResult = sphere.clone(sphere);
expect(sphere).toBe(returnedResult);
expect(sphere.center).toEqual(expectedCenter);
expect(sphere.radius).toEqual(expectedRadius);
});
it('clone clones undefined', function() {
expect(BoundingSphere.clone(undefined)).toBe(undefined);
});
it('equals', function() {
var sphere = new BoundingSphere(new Cartesian3(1.0, 2.0, 3.0), 4.0);
expect(sphere.equals(new BoundingSphere(new Cartesian3(1.0, 2.0, 3.0), 4.0))).toEqual(true);
expect(sphere.equals(new BoundingSphere(new Cartesian3(5.0, 2.0, 3.0), 4.0))).toEqual(false);
expect(sphere.equals(new BoundingSphere(new Cartesian3(1.0, 6.0, 3.0), 4.0))).toEqual(false);
expect(sphere.equals(new BoundingSphere(new Cartesian3(1.0, 2.0, 7.0), 4.0))).toEqual(false);
expect(sphere.equals(new BoundingSphere(new Cartesian3(1.0, 2.0, 3.0), 8.0))).toEqual(false);
expect(sphere.equals(undefined)).toEqual(false);
});
it('fromPoints without positions returns an empty sphere', function() {
var sphere = BoundingSphere.fromPoints();
expect(sphere.center).toEqual(Cartesian3.ZERO);
expect(sphere.radius).toEqual(0.0);
});
it('fromPoints works with one point', function() {
var expectedCenter = new Cartesian3(1.0, 2.0, 3.0);
var sphere = BoundingSphere.fromPoints([expectedCenter]);
expect(sphere.center).toEqual(expectedCenter);
expect(sphere.radius).toEqual(0.0);
});
it('fromPoints computes a center from points', function() {
var sphere = BoundingSphere.fromPoints(getPositions());
expect(sphere.center).toEqual(positionsCenter);
expect(sphere.radius).toEqual(positionsRadius);
});
it('fromPoints contains all points (naive)', function() {
var sphere = BoundingSphere.fromPoints(getPositions());
var radius = sphere.radius;
var center = sphere.center;
var r = new Cartesian3(radius, radius, radius);
var max = Cartesian3.add(r, center, new Cartesian3());
var min = Cartesian3.subtract(center, r, new Cartesian3());
var positions = getPositions();
var numPositions = positions.length;
for ( var i = 0; i < numPositions; i++) {
var currentPos = positions[i];
expect(currentPos.x <= max.x && currentPos.x >= min.x).toEqual(true);
expect(currentPos.y <= max.y && currentPos.y >= min.y).toEqual(true);
expect(currentPos.z <= max.z && currentPos.z >= min.z).toEqual(true);
}
});
it('fromPoints contains all points (ritter)', function() {
var positions = getPositions();
positions.push(new Cartesian3(1, 1, 1), new Cartesian3(2, 2, 2), new Cartesian3(3, 3, 3));
var sphere = BoundingSphere.fromPoints(positions);
var radius = sphere.radius;
var center = sphere.center;
var r = new Cartesian3(radius, radius, radius);
var max = Cartesian3.add(r, center, new Cartesian3());
var min = Cartesian3.subtract(center, r, new Cartesian3());
var numPositions = positions.length;
for ( var i = 0; i < numPositions; i++) {
var currentPos = positions[i];
expect(currentPos.x <= max.x && currentPos.x >= min.x).toEqual(true);
expect(currentPos.y <= max.y && currentPos.y >= min.y).toEqual(true);
expect(currentPos.z <= max.z && currentPos.z >= min.z).toEqual(true);
}
});
it('fromVertices without positions returns an empty sphere', function() {
var sphere = BoundingSphere.fromVertices();
expect(sphere.center).toEqual(Cartesian3.ZERO);
expect(sphere.radius).toEqual(0.0);
});
it('fromVertices works with one point', function() {
var expectedCenter = new Cartesian3(1.0, 2.0, 3.0);
var sphere = BoundingSphere.fromVertices([expectedCenter.x, expectedCenter.y, expectedCenter.z]);
expect(sphere.center).toEqual(expectedCenter);
expect(sphere.radius).toEqual(0.0);
});
it('fromVertices computes a center from points', function() {
var sphere = BoundingSphere.fromVertices(getPositionsAsFlatArray());
expect(sphere.center).toEqual(positionsCenter);
expect(sphere.radius).toEqual(positionsRadius);
});
it('fromVertices contains all points (naive)', function() {
var sphere = BoundingSphere.fromVertices(getPositionsAsFlatArray());
var radius = sphere.radius;
var center = sphere.center;
var r = new Cartesian3(radius, radius, radius);
var max = Cartesian3.add(r, center, new Cartesian3());
var min = Cartesian3.subtract(center, r, new Cartesian3());
var positions = getPositions();
var numPositions = positions.length;
for ( var i = 0; i < numPositions; i++) {
var currentPos = positions[i];
expect(currentPos.x <= max.x && currentPos.x >= min.x).toEqual(true);
expect(currentPos.y <= max.y && currentPos.y >= min.y).toEqual(true);
expect(currentPos.z <= max.z && currentPos.z >= min.z).toEqual(true);
}
});
it('fromVertices contains all points (ritter)', function() {
var positions = getPositionsAsFlatArray();
positions.push(1, 1, 1, 2, 2, 2, 3, 3, 3);
var sphere = BoundingSphere.fromVertices(positions);
var radius = sphere.radius;
var center = sphere.center;
var r = new Cartesian3(radius, radius, radius);
var max = Cartesian3.add(r, center, new Cartesian3());
var min = Cartesian3.subtract(center, r, new Cartesian3());
var numElements = positions.length;
for (var i = 0; i < numElements; i += 3) {
expect(positions[i] <= max.x && positions[i] >= min.x).toEqual(true);
expect(positions[i + 1] <= max.y && positions[i + 1] >= min.y).toEqual(true);
expect(positions[i + 2] <= max.z && positions[i + 2] >= min.z).toEqual(true);
}
});
it('fromVertices works with a stride of 5', function() {
var sphere = BoundingSphere.fromVertices(getPositionsAsFlatArrayWithStride5(), undefined, 5);
expect(sphere.center).toEqual(positionsCenter);
expect(sphere.radius).toEqual(positionsRadius);
});
it('fromVertices works with defined center', function() {
var center = new Cartesian3(1.0, 2.0, 3.0);
var sphere = BoundingSphere.fromVertices(getPositionsAsFlatArrayWithStride5(), center, 5);
expect(sphere.center).toEqual(Cartesian3.add(positionsCenter, center, new Cartesian3()));
expect(sphere.radius).toEqual(positionsRadius);
});
it('fromVertices requires a stride of at least 3', function() {
function callWithStrideOf2() {
BoundingSphere.fromVertices(getPositionsAsFlatArray(), undefined, 2);
}
expect(callWithStrideOf2).toThrowDeveloperError();
});
it('fromVertices fills result parameter if specified', function() {
var center = new Cartesian3(1.0, 2.0, 3.0);
var result = new BoundingSphere();
var sphere = BoundingSphere.fromVertices(getPositionsAsFlatArrayWithStride5(), center, 5, result);
expect(sphere).toEqual(result);
expect(result.center).toEqual(Cartesian3.add(positionsCenter, center, new Cartesian3()));
expect(result.radius).toEqual(positionsRadius);
});
it('fromRectangle2D creates an empty sphere if no rectangle provided', function() {
var sphere = BoundingSphere.fromRectangle2D();
expect(sphere.center).toEqual(Cartesian3.ZERO);
expect(sphere.radius).toEqual(0.0);
});
it('fromRectangle2D', function() {
var rectangle = Rectangle.MAX_VALUE;
var projection = new GeographicProjection(Ellipsoid.UNIT_SPHERE);
var expected = new BoundingSphere(Cartesian3.ZERO, Math.sqrt(rectangle.east * rectangle.east + rectangle.north * rectangle.north));
expect(BoundingSphere.fromRectangle2D(rectangle, projection)).toEqual(expected);
});
it('fromRectangle3D creates an empty sphere if no rectangle provided', function() {
var sphere = BoundingSphere.fromRectangle3D();
expect(sphere.center).toEqual(Cartesian3.ZERO);
expect(sphere.radius).toEqual(0.0);
});
it('fromRectangle3D', function() {
var rectangle = Rectangle.MAX_VALUE;
var ellipsoid = Ellipsoid.WGS84;
var expected = new BoundingSphere(Cartesian3.ZERO, ellipsoid.maximumRadius);
expect(BoundingSphere.fromRectangle3D(rectangle, ellipsoid)).toEqual(expected);
});
it('fromRectangle3D with height', function() {
var rectangle = new Rectangle(0.1, -0.3, 0.2, -0.4);
var height = 100000.0;
var ellipsoid = Ellipsoid.WGS84;
var points = Rectangle.subsample(rectangle, ellipsoid, height);
var expected = BoundingSphere.fromPoints(points);
expect(BoundingSphere.fromRectangle3D(rectangle, ellipsoid, height)).toEqual(expected);
});
it('fromCornerPoints', function() {
var sphere = BoundingSphere.fromCornerPoints(new Cartesian3(-1.0, -0.0, 0.0), new Cartesian3(1.0, 0.0, 0.0));
expect(sphere).toEqual(new BoundingSphere(Cartesian3.ZERO, 1.0));
});
it('fromCornerPoints with a result parameter', function() {
var sphere = new BoundingSphere();
var result = BoundingSphere.fromCornerPoints(new Cartesian3(0.0, -1.0, 0.0), new Cartesian3(0.0, 1.0, 0.0), sphere);
expect(result).toBe(sphere);
expect(result).toEqual(new BoundingSphere(Cartesian3.ZERO, 1.0));
});
it('fromCornerPoints throws without corner', function() {
expect(function() {
BoundingSphere.fromCornerPoints();
}).toThrowDeveloperError();
});
it('fromCornerPoints throws without oppositeCorner', function() {
expect(function() {
BoundingSphere.fromCornerPoints(Cartesian3.UNIT_X);
}).toThrowDeveloperError();
});
it('fromEllipsoid', function() {
var ellipsoid = Ellipsoid.WGS84;
var sphere = BoundingSphere.fromEllipsoid(ellipsoid);
expect(sphere.center).toEqual(Cartesian3.ZERO);
expect(sphere.radius).toEqual(ellipsoid.maximumRadius);
});
it('fromEllipsoid with a result parameter', function() {
var ellipsoid = Ellipsoid.WGS84;
var sphere = new BoundingSphere(new Cartesian3(1.0, 2.0, 3.0), 4.0);
var result = BoundingSphere.fromEllipsoid(ellipsoid, sphere);
expect(result).toBe(sphere);
expect(result).toEqual(new BoundingSphere(Cartesian3.ZERO, ellipsoid.maximumRadius));
});
it('fromEllipsoid throws without ellipsoid', function() {
expect(function() {
BoundingSphere.fromEllipsoid();
}).toThrowDeveloperError();
});
it('sphere on the positive side of a plane', function() {
var sphere = new BoundingSphere(Cartesian3.ZERO, 0.5);
var normal = Cartesian3.negate(Cartesian3.UNIT_X, new Cartesian3());
var position = Cartesian3.UNIT_X;
var plane = new Cartesian4(normal.x, normal.y, normal.z, -Cartesian3.dot(normal, position));
expect(sphere.intersect(plane)).toEqual(Intersect.INSIDE);
});
it('sphere on the negative side of a plane', function() {
var sphere = new BoundingSphere(Cartesian3.ZERO, 0.5);
var normal = Cartesian3.UNIT_X;
var position = Cartesian3.UNIT_X;
var plane = new Cartesian4(normal.x, normal.y, normal.z, -Cartesian3.dot(normal, position));
expect(sphere.intersect(plane)).toEqual(Intersect.OUTSIDE);
});
it('sphere intersecting a plane', function() {
var sphere = new BoundingSphere(Cartesian3.UNIT_X, 0.5);
var normal = Cartesian3.UNIT_X;
var position = Cartesian3.UNIT_X;
var plane = new Cartesian4(normal.x, normal.y, normal.z, -Cartesian3.dot(normal, position));
expect(sphere.intersect(plane)).toEqual(Intersect.INTERSECTING);
});
it('expands to contain another sphere', function() {
var bs1 = new BoundingSphere(Cartesian3.negate(Cartesian3.UNIT_X, new Cartesian3()), 1.0);
var bs2 = new BoundingSphere(Cartesian3.UNIT_X, 1.0);
var expected = new BoundingSphere(Cartesian3.ZERO, 2.0);
expect(BoundingSphere.union(bs1, bs2)).toEqual(expected);
});
it('union result parameter is caller', function() {
var bs1 = new BoundingSphere(Cartesian3.multiplyBy(scalar: Cartesian3.negate(Cartesian3.UNIT_X, new Cartesian3()), 3.0, new Cartesian3()), 3.0);
var bs2 = new BoundingSphere(Cartesian3.UNIT_X, 1.0);
var expected = new BoundingSphere(Cartesian3.negate(Cartesian3.UNIT_X, new Cartesian3()), 5.0);
BoundingSphere.union(bs1, bs2, bs1);
expect(bs1).toEqual(expected);
});
it('expands to contain another point', function() {
var bs = new BoundingSphere(Cartesian3.negate(Cartesian3.UNIT_X, new Cartesian3()), 1.0);
var point = Cartesian3.UNIT_X;
var expected = new BoundingSphere(Cartesian3.negate(Cartesian3.UNIT_X, new Cartesian3()), 2.0);
expect(BoundingSphere.expand(bs, point)).toEqual(expected);
});
it('applies transform', function() {
var bs = new BoundingSphere(Cartesian3.ZERO, 1.0);
var transform = Matrix4.fromTranslation(new Cartesian3(1.0, 2.0, 3.0));
var expected = new BoundingSphere(new Cartesian3(1.0, 2.0, 3.0), 1.0);
expect(BoundingSphere.transform(bs, transform)).toEqual(expected);
});
it('applies scale transform', function() {
var bs = new BoundingSphere(Cartesian3.ZERO, 1.0);
var transform = Matrix4.fromScale(new Cartesian3(1.0, 2.0, 3.0));
var expected = new BoundingSphere(Cartesian3.ZERO, 3.0);
expect(BoundingSphere.transform(bs, transform)).toEqual(expected);
});
it('applies transform without scale', function() {
var bs = new BoundingSphere(Cartesian3.ZERO, 1.0);
var transform = Matrix4.fromTranslation(new Cartesian3(1.0, 2.0, 3.0));
var expected = new BoundingSphere(new Cartesian3(1.0, 2.0, 3.0), 1.0);
expect(BoundingSphere.transformWithoutScale(bs, transform)).toEqual(expected);
});
it('transformWithoutScale ignores scale', function() {
var bs = new BoundingSphere(Cartesian3.ZERO, 1.0);
var transform = Matrix4.fromScale(new Cartesian3(1.0, 2.0, 3.0));
var expected = new BoundingSphere(Cartesian3.ZERO, 1.0);
expect(BoundingSphere.transformWithoutScale(bs, transform)).toEqual(expected);
});
*/
func testFindsDistances () {
let bs = BoundingSphere(center: Cartesian3.zero(), radius: 1.0)
let position = Cartesian3(x: -2.0, y: 1.0, z: 0.0)
let direction = Cartesian3.unitX()
let expected = Interval(start: 1.0, stop: 3.0)
XCTAssertTrue(bs.computePlaneDistances(position, direction: direction) == expected, "finds distances")
}
/*
it('estimated distance squared to point', function() {
var bs = new BoundingSphere(Cartesian3.ZERO, 1.0);
var position = new Cartesian3(-2.0, 1.0, 0.0);
var expected = Cartesian3.magnitudeSquared(position) - 1.0;
expect(BoundingSphere.distanceSquaredTo(bs, position)).toEqual(expected);
});
it('projectTo2D', function() {
var positions = getPositions();
var projection = new GeographicProjection();
var positions2D = [];
for (var i = 0; i < positions.length; ++i) {
var position = positions[i];
var cartographic = projection.ellipsoid.cartesianToCartographic(position);
positions2D.push(projection.project(cartographic));
}
var boundingSphere3D = BoundingSphere.fromPoints(positions);
var boundingSphere2D = BoundingSphere.projectTo2D(boundingSphere3D, projection);
var actualSphere = BoundingSphere.fromPoints(positions2D);
actualSphere.center = new Cartesian3(actualSphere.center.z, actualSphere.center.x, actualSphere.center.y);
expect(boundingSphere2D.center).toEqualEpsilon(actualSphere.center, CesiumMath.EPSILON6);
expect(boundingSphere2D.radius).toBeGreaterThan(actualSphere.radius);
});
it('projectTo2D with result parameter', function() {
var positions = getPositions();
var projection = new GeographicProjection();
var sphere = new BoundingSphere();
var positions2D = [];
for (var i = 0; i < positions.length; ++i) {
var position = positions[i];
var cartographic = projection.ellipsoid.cartesianToCartographic(position);
positions2D.push(projection.project(cartographic));
}
var boundingSphere3D = BoundingSphere.fromPoints(positions);
var boundingSphere2D = BoundingSphere.projectTo2D(boundingSphere3D, projection, sphere);
var actualSphere = BoundingSphere.fromPoints(positions2D);
actualSphere.center = new Cartesian3(actualSphere.center.z, actualSphere.center.x, actualSphere.center.y);
expect(boundingSphere2D).toBe(sphere);
expect(boundingSphere2D.center).toEqualEpsilon(actualSphere.center, CesiumMath.EPSILON6);
expect(boundingSphere2D.radius).toBeGreaterThan(actualSphere.radius);
});
it('can pack and unpack', function() {
var array = [];
var boundingSphere = new BoundingSphere();
boundingSphere.center = new Cartesian3(1, 2, 3);
boundingSphere.radius = 4;
BoundingSphere.pack(boundingSphere, array);
expect(array.length).toEqual(BoundingSphere.packedLength);
expect(BoundingSphere.unpack(array)).toEqual(boundingSphere);
});
it('can pack and unpack with offset', function() {
var packed = new Array(3);
var offset = 3;
var boundingSphere = new BoundingSphere();
boundingSphere.center = new Cartesian3(1, 2, 3);
boundingSphere.radius = 4;
BoundingSphere.pack(boundingSphere, packed, offset);
expect(packed.length).toEqual(offset + BoundingSphere.packedLength);
var result = new BoundingSphere();
var returnedResult = BoundingSphere.unpack(packed, offset, result);
expect(returnedResult).toBe(result);
expect(result).toEqual(boundingSphere);
});
it('pack throws with undefined boundingSphere', function() {
var array = [];
expect(function() {
BoundingSphere.pack(undefined, array);
}).toThrowDeveloperError();
});
it('pack throws with undefined array', function() {
var boundingSphere = new BoundingSphere();
expect(function() {
BoundingSphere.pack(boundingSphere, undefined);
}).toThrowDeveloperError();
});
it('unpack throws with undefined array', function() {
expect(function() {
BoundingSphere.unpack(undefined);
}).toThrowDeveloperError();
});
it('static projectTo2D throws without sphere', function() {
expect(function() {
BoundingSphere.projectTo2D();
}).toThrowDeveloperError();
});
it('clone returns undefined with no parameter', function() {
expect(BoundingSphere.clone()).toBeUndefined();
});
it('union throws with no left parameter', function() {
var right = new BoundingSphere();
expect(function() {
BoundingSphere.union(undefined, right);
}).toThrowDeveloperError();
});
it('union throws with no right parameter', function() {
var left = new BoundingSphere();
expect(function() {
BoundingSphere.union(left, undefined);
}).toThrowDeveloperError();
});
it('expand throws without a sphere', function() {
var plane = new Cartesian3();
expect(function() {
BoundingSphere.expand(undefined, plane);
}).toThrowDeveloperError();
});
it('expand throws without a point', function() {
var sphere = new BoundingSphere();
expect(function() {
BoundingSphere.expand(sphere, undefined);
}).toThrowDeveloperError();
});
it('intersect throws without a sphere', function() {
var plane = new Cartesian4();
expect(function() {
BoundingSphere.intersect(undefined, plane);
}).toThrowDeveloperError();
});
it('intersect throws without a plane', function() {
var sphere = new BoundingSphere();
expect(function() {
BoundingSphere.intersect(sphere, undefined);
}).toThrowDeveloperError();
});
it('transform throws without a sphere', function() {
expect(function() {
BoundingSphere.transform();
}).toThrowDeveloperError();
});
it('transform throws without a transform', function() {
var sphere = new BoundingSphere();
expect(function() {
BoundingSphere.transform(sphere);
}).toThrowDeveloperError();
});
it('distanceSquaredTo throws without a sphere', function() {
expect(function() {
BoundingSphere.distanceSquaredTo();
}).toThrowDeveloperError();
});
it('distanceSquaredTo throws without a cartesian', function() {
expect(function() {
BoundingSphere.distanceSquaredTo(new BoundingSphere());
}).toThrowDeveloperError();
});
it('transformWithoutScale throws without a sphere', function() {
expect(function() {
BoundingSphere.transformWithoutScale();
}).toThrowDeveloperError();
});
it('transformWithoutScale throws without a transform', function() {
var sphere = new BoundingSphere();
expect(function() {
BoundingSphere.transformWithoutScale(sphere);
}).toThrowDeveloperError();
});
it('computePlaneDistances throws without a sphere', function() {
expect(function() {
BoundingSphere.computePlaneDistances();
}).toThrowDeveloperError();
});
it('computePlaneDistances throws without a position', function() {
expect(function() {
BoundingSphere.computePlaneDistances(new BoundingSphere());
}).toThrowDeveloperError();
});
it('computePlaneDistances throws without a direction', function() {
expect(function() {
BoundingSphere.computePlaneDistances(new BoundingSphere(), new Cartesian3());
}).toThrowDeveloperError();
});
function expectBoundingSphereToContainPoint(boundingSphere, point, projection) {
var pointInCartesian = projection.project(point);
var distanceFromCenter = Cartesian3.magnitude(Cartesian3.subtract(pointInCartesian, boundingSphere.center, new Cartesian3()));
// The distanceFromCenter for corner points at the height extreme should equal the
// bounding sphere's radius. But due to rounding errors it can end up being
// very slightly greater. Pull in the distanceFromCenter slightly to
// account for this possibility.
distanceFromCenter -= CesiumMath.EPSILON9;
expect(distanceFromCenter).toBeLessThanOrEqualTo(boundingSphere.radius);
}
it('fromRectangleWithHeights2D includes specified min and max heights', function() {
var rectangle = new Rectangle(0.1, 0.5, 0.2, 0.6);
var projection = new GeographicProjection();
var minHeight = -327.0;
var maxHeight = 2456.0;
var boundingSphere = BoundingSphere.fromRectangleWithHeights2D(rectangle, projection, minHeight, maxHeight);
// Test that the corners are inside the bounding sphere.
var point = Rectangle.southwest(rectangle).clone();
point.height = minHeight;
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
point = Rectangle.southwest(rectangle).clone();
point.height = maxHeight;
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
point = Rectangle.northeast(rectangle).clone();
point.height = minHeight;
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
point = Rectangle.northeast(rectangle).clone();
point.height = maxHeight;
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
point = Rectangle.southeast(rectangle).clone();
point.height = minHeight;
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
point = Rectangle.southeast(rectangle).clone();
point.height = maxHeight;
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
point = Rectangle.northwest(rectangle).clone();
point.height = minHeight;
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
point = Rectangle.northwest(rectangle).clone();
point.height = maxHeight;
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
// Test that the center is inside the bounding sphere
point = Rectangle.center(rectangle).clone();
point.height = minHeight;
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
point = Rectangle.center(rectangle).clone();
point.height = maxHeight;
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
// Test that the edge midpoints are inside the bounding sphere.
point = new Cartographic(Rectangle.center(rectangle).longitude, rectangle.south, minHeight);
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
point = new Cartographic(Rectangle.center(rectangle).longitude, rectangle.south, maxHeight);
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
point = new Cartographic(Rectangle.center(rectangle).longitude, rectangle.north, minHeight);
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
point = new Cartographic(Rectangle.center(rectangle).longitude, rectangle.north, maxHeight);
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
point = new Cartographic(rectangle.west, Rectangle.center(rectangle).latitude, minHeight);
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
point = new Cartographic(rectangle.west, Rectangle.center(rectangle).latitude, maxHeight);
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
point = new Cartographic(rectangle.east, Rectangle.center(rectangle).latitude, minHeight);
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
point = new Cartographic(rectangle.east, Rectangle.center(rectangle).latitude, maxHeight);
expectBoundingSphereToContainPoint(boundingSphere, point, projection);
});
});
*/
}
| apache-2.0 | b5335dd7b6e6b497d1a0844c49571be6 | 34.95935 | 144 | 0.7565 | 3.847202 | false | false | false | false |
naukri-engineering/Blooper | ios/Blooper/Blooper/Network/WebServiceManager.swift | 1 | 4226 | //
// WebServiceManager.swift
// Blooper
//
// Created by Ikjot Kaur on 09/04/16.
// Copyright © 2016 Naukri. All rights reserved.
//
import UIKit
class WebServiceManager: NSObject {
static var loggedInID:String?
static var appId:String!
static var versionNum:String!
static var apiURL:String!
static var debuggingEnabled:Bool!
static var crashUploadInProgress:Bool = false
class func uploadCrashToServer(debug:Bool)
{
if(crashUploadInProgress == true)
{
return
}
crashUploadInProgress = true
debuggingEnabled = debug
versionNum = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as! String
let serverDictonary = NSMutableDictionary()
serverDictonary.setObject(SOURCE_APP, forKey: SOURCE_KEY)
serverDictonary.setObject(appId, forKey: APP_ID_KEY)
if(loggedInID != nil)
{
serverDictonary.setObject(loggedInID!, forKey: USER_ID_KEY)
}
let enviromentDictonary = NSMutableDictionary()
enviromentDictonary.setObject(NSDictionary(objects: [OS_IOS,UIDevice.currentDevice().systemVersion], forKeys: [NAME_KEY,VERSION_KEY]), forKey: OS_KEY)
enviromentDictonary.setObject(NSDictionary(objects: [versionNum], forKeys: [VERSION_KEY]), forKey: APP_KEY)
enviromentDictonary.setObject(NSDictionary(objects: [UIDevice.currentDevice().model], forKeys: [NAME_KEY]), forKey: DEVICE_KEY)
serverDictonary.setObject(enviromentDictonary, forKey: ENVIRONMENT_KEY)
let crashArray = NSMutableArray()
let currentTimeStamp: Double! = NSDate().timeIntervalSince1970
let currentTime: NSString! = NSString(format:"%f", currentTimeStamp)
let fetchedObjects: [Crash]! = Crash.getCrash() as! [Crash]
if(fetchedObjects.count > 0)
{
for crashObj:Crash in fetchedObjects
{
let serverDict = NSMutableDictionary()
serverDict.setObject(EXCEPTION_NAME, forKey: TAG_KEY)
serverDict.setObject(currentTime, forKey: TIMESTAMP_KEY)
serverDict.setObject(EXCEPTION_TYPE, forKey: EXCEPTION_TYPE_KEY)
serverDict.setObject(EXCEPTION_MESSAGE, forKey: MESSAGE_KEY)
serverDict.setObject(crashObj.crashDescription!, forKey: STACK_TRACE_KEY)
crashArray.addObject(serverDict)
}
serverDictonary.setObject(crashArray, forKey: EXCETIONS_KEY)
let serverData:NSData!
do {
try serverData = NSJSONSerialization.dataWithJSONObject(serverDictonary, options: NSJSONWritingOptions.PrettyPrinted)
let mystring = NSString.init(data: serverData, encoding: NSUTF8StringEncoding)
WebServiceManager.sendSeverCrash(mystring!)
} catch let error{
if(debuggingEnabled == true)
{
print("Error ocurred -> \(error)")
}
}
}
else
{
if(debuggingEnabled == true)
{
print("No data in database")
}
}
}
class func sendSeverCrash(paramString:NSString!)
{
let request:NSMutableURLRequest! = NSMutableURLRequest(URL: NSURL(string: apiURL)!)
request.HTTPMethod = HTTP_METHOD_POST
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
if let errorInfo = error
{
if(debuggingEnabled == true)
{
print("Error occured in sending data to server -> \(errorInfo.description)")
}
}
else
{
if(debuggingEnabled == true)
{
print("Crash successfully uploaded")
}
Crash.deleteCrash()
crashUploadInProgress = false
}
}
}
}
| mit | 8941fa85b33c5238b6832e29799ac66a | 38.12037 | 162 | 0.60284 | 5.209618 | false | false | false | false |
kingcos/CS193P_2017 | FaceIt/FaceIt/FaceViewController.swift | 1 | 4034 | //
// FaceViewController.swift
// FaceIt
//
// Created by 买明 on 24/02/2017.
// Copyright © 2017 买明. All rights reserved.
//
import UIKit
class FaceViewController: VCLLoggingViewController {
@IBOutlet weak var faceView: FaceView! {
didSet {
let handler = #selector(FaceView.changeScale(byReactingTo:))
// 捏合手势(目标为 faceView)
let pinchRecognizer = UIPinchGestureRecognizer(target: faceView, action: handler)
faceView.addGestureRecognizer(pinchRecognizer)
// 点按手势
// let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(toggleEyes(byReactingTp:)))
// tapRecognizer.numberOfTapsRequired = 1
// faceView.addGestureRecognizer(tapRecognizer)
// 上下扫手势
let swipeUpRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(increaseHappiness))
swipeUpRecognizer.direction = .up
let swipeDownRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(decreaseHappiness))
swipeDownRecognizer.direction = .down
faceView.addGestureRecognizer(swipeUpRecognizer)
faceView.addGestureRecognizer(swipeDownRecognizer)
// 初始化时并不调用 didSet;一旦 Outlet 连接到,才调用 didSet
updateUI()
}
}
// 初始化表情
var expression = FacialExpression(eyes: .closed, mouth: .neutral) {
didSet {
updateUI()
}
}
private let mouthCurvatures = [FacialExpression.Mouth.grin: 0.5,
.frown: -1.0,
.smile: 1.0,
.neutral: 0.0,
.smirk: -0.5]
private struct HeadShake {
static let angle = CGFloat.pi / 6
static let segmentDuration: TimeInterval = 0.5
}
private func rotateFace(by angle: CGFloat) {
faceView.transform = faceView.transform.rotated(by: angle)
}
private func shakeHead() {
UIView.animate(withDuration: HeadShake.segmentDuration,
animations: { self.rotateFace(by: HeadShake.angle) },
completion: { finished in
if finished {
UIView.animate(withDuration: HeadShake.segmentDuration,
animations: { self.rotateFace(by: -HeadShake.angle * 2) },
completion: { finished in
UIView.animate(withDuration: HeadShake.segmentDuration,
animations: { self.rotateFace(by: HeadShake.angle) })
})
}
})
}
// 更新 UI
func updateUI() {
switch expression.eyes {
case .open:
// ?: 当 faceView 未初始化(为 nil),则后续代码不执行;若不加 ? 且为 nil 时,程序崩溃
faceView?.eyesOpen = true
case .closed:
faceView?.eyesOpen = false
case .squinting:
// Lecture 15
// faceView?.eyesOpen = false
break
}
faceView?.mouthCurvature = mouthCurvatures[expression.mouth] ?? 0.0
}
func toggleEyes(byReactingTp tapRecognizer: UITapGestureRecognizer) {
if tapRecognizer.state == .ended {
let eyes: FacialExpression.Eyes = (expression.eyes == .closed) ? .open : .closed
expression = FacialExpression(eyes: eyes, mouth: expression.mouth)
}
}
func increaseHappiness() {
expression = expression.happier
}
func decreaseHappiness() {
expression = expression.sadder
}
@IBAction func shakeHead(_ sender: UITapGestureRecognizer) {
shakeHead()
}
}
| mit | 83fec9a1426680ef53823ca6f9a26270 | 34.605505 | 116 | 0.54857 | 5.099869 | false | false | false | false |
csujedihy/Yilp | Yelp/BorderUIView.swift | 1 | 4145 | //
// BorderUIView.swift
// Yelp
//
// Created by YiHuang on 2/13/16.
// Copyright © 2016 TotemTraining. All rights reserved.
// Below are from https://github.com/TotemTraining/UIViewWithSelectableBorders
import UIKit
// MARK: - UIView
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor? {
get {
return UIColor(red: 238/255, green: 238/255, blue: 243/255, alpha: 1.0)
}
set {
layer.borderColor = newValue?.CGColor
}
}
@IBInspectable var leftBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: 0.0, width: newValue, height: bounds.height))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = borderColor
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[line(==lineWidth)]", options: [], metrics: metrics, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[line]|", options: [], metrics: nil, views: views))
}
}
@IBInspectable var topBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: 0.0, width: bounds.width, height: newValue))
line.translatesAutoresizingMaskIntoConstraints = false
print(borderColor)
line.backgroundColor = borderColor
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[line]|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[line(==lineWidth)]", options: [], metrics: metrics, views: views))
}
}
@IBInspectable var rightBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: bounds.width, y: 0.0, width: newValue, height: bounds.height))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = borderColor
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("[line(==lineWidth)]|", options: [], metrics: metrics, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[line]|", options: [], metrics: nil, views: views))
}
}
@IBInspectable var bottomBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: bounds.height, width: bounds.width, height: newValue))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = borderColor
print(borderColor)
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[line]|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[line(==lineWidth)]|", options: [], metrics: metrics, views: views))
}
}
} | gpl-3.0 | 536ef027a838cea2d2a5e4f1f68c2b38 | 36.342342 | 145 | 0.588562 | 5.212579 | false | false | false | false |
KlubJagiellonski/pola-ios | BuyPolish/Pola/UI/ProductSearch/About/AboutDoubleCell.swift | 1 | 2062 | import UIKit
final class AboutDoubleCell: AboutBaseCell {
enum Segment: Int {
case first
case second
case none
}
private let firstButton = UIButton(type: .custom)
private let secondButton = UIButton(type: .custom)
var selectedSegment = Segment.none
func configure(rowInfo: DoubleAboutRow) {
firstButton.setTitle(rowInfo.0.title, for: .normal)
secondButton.setTitle(rowInfo.1.title, for: .normal)
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
applyStyle(for: firstButton)
contentView.addSubview(firstButton)
applyStyle(for: secondButton)
contentView.addSubview(secondButton)
selectionStyle = .none
}
override func layoutSubviews() {
super.layoutSubviews()
var frame = CGRect(x: backgroundHorizontalMargin,
y: backgroundVerticalMargin,
width: (contentView.frame.width - (3 * backgroundHorizontalMargin)) / 2,
height: contentView.frame.height - (2 * backgroundVerticalMargin))
firstButton.frame = frame
frame.origin.x += frame.maxX
secondButton.frame = frame
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let hitted = super.hitTest(point, with: event)
if hitted == firstButton {
selectedSegment = .first
} else if hitted == secondButton {
selectedSegment = .second
} else {
selectedSegment = .none
}
return self
}
private func applyStyle(for button: UIButton) {
button.contentHorizontalAlignment = .left
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)
button.backgroundColor = Theme.lightBackgroundColor
button.setTitleColor(Theme.defaultTextColor, for: .normal)
button.titleLabel?.font = Theme.normalFont
}
}
| gpl-2.0 | 055a78ac62a6df3671d7e10831bffc5b | 33.366667 | 99 | 0.633851 | 4.992736 | false | false | false | false |
DataArt/SmartSlides | PresentatorS/Extensions/Extensions.swift | 1 | 3202 | //
// Extensions.swift
// PresentatorS
//
// Created by Roman Ivchenko on 12/14/15.
// Copyright © 2015 DataArt. All rights reserved.
//
import Foundation
extension UIAlertController {
class func showAlertWithTitle(title : String?, message : String?, completionBlock : ((UIAlertAction) -> Void)?) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .Cancel, handler: completionBlock))
let vc = UIApplication.sharedApplication().keyWindow!.rootViewController!.topMostViewController()
vc.presentViewController(alertController, animated: true, completion: nil)
}
class func showAlertWithMessage(message : String?, completionBlock : ((UIAlertAction) -> Void)?) {
let alertController = UIAlertController(title: "Alert", message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .Cancel, handler: completionBlock))
let vc = UIApplication.sharedApplication().keyWindow!.rootViewController!.topMostViewController()
vc.presentViewController(alertController, animated: true, completion: nil)
}
class func showAlertWithMessageAndMultipleAnswers(message : String?, affirmativeCompletionBlock : ((UIAlertAction) -> Void)?, negativeCompletionBlock : ((UIAlertAction) -> Void)?) {
let alertController = UIAlertController(title: "Alert", message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: negativeCompletionBlock))
alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: affirmativeCompletionBlock))
let vc = UIApplication.sharedApplication().keyWindow!.rootViewController!.topMostViewController()
vc.presentViewController(alertController, animated: true, completion: nil)
}
}
extension UIViewController {
func topMostViewController() -> UIViewController {
// Handling Modal views
if let presentedViewController = self.presentedViewController {
return presentedViewController.topMostViewController()
}
// Handling UIViewController's added as subviews to some other views.
else {
for view in self.view.subviews
{
// Key property which most of us are unaware of / rarely use.
if let subViewController = view.nextResponder() {
if subViewController is UIViewController {
let viewController = subViewController as! UIViewController
return viewController.topMostViewController()
}
}
}
return self
}
}
}
extension UITabBarController {
override func topMostViewController() -> UIViewController {
return self.selectedViewController!.topMostViewController()
}
}
extension UINavigationController {
override func topMostViewController() -> UIViewController {
return self.visibleViewController!.topMostViewController()
}
} | mit | 8e917aea4be18e69d47b95161f4c0409 | 44.098592 | 185 | 0.686973 | 5.927778 | false | false | false | false |
adrfer/swift | test/SILGen/lifetime_unions.swift | 10 | 3374 | // RUN: %target-swift-frontend -parse-as-library -emit-silgen %s | FileCheck %s
enum TrivialUnion {
case Foo
case Bar(Int)
case Bas(Int, Int)
}
class C {
init() {}
}
enum NonTrivialUnion1 {
case Foo
case Bar(Int)
case Bas(Int, C)
}
enum NonTrivialUnion2 {
case Foo
case Bar(C)
case Bas(Int, C)
}
enum NonTrivialUnion3 {
case Bar(C)
case Bas(Int, C)
}
/* TODO: Address-only unions
enum AddressOnlyUnion<T> {
case Foo
case Bar(T)
case Bas(Int, T)
}
*/
func getTrivialUnion() -> TrivialUnion { return .Foo }
func getNonTrivialUnion1() -> NonTrivialUnion1 { return .Foo }
func getNonTrivialUnion2() -> NonTrivialUnion2 { return .Foo }
func getNonTrivialUnion3() -> NonTrivialUnion3 { return .Bar(C()) }
/* TODO: Address-only unions
func getAddressOnlyUnion<T>(_: T.Type) -> AddressOnlyUnion<T> { return .Foo }
*/
// CHECK-LABEL: sil hidden @_TF15lifetime_unions19destroyUnionRValuesFT_T_ : $@convention(thin) () -> () {
func destroyUnionRValues() {
// CHECK: [[GET_TRIVIAL_UNION:%.*]] = function_ref @_TF15lifetime_unions15getTrivialUnionFT_OS_12TrivialUnion : $@convention(thin) () -> TrivialUnion
// CHECK: [[TRIVIAL_UNION:%.*]] = apply [[GET_TRIVIAL_UNION]]() : $@convention(thin) () -> TrivialUnion
// CHECK-NOT: [[TRIVIAL_UNION]]
getTrivialUnion()
// CHECK: [[GET_NON_TRIVIAL_UNION_1:%.*]] = function_ref @_TF15lifetime_unions19getNonTrivialUnion1FT_OS_16NonTrivialUnion1 : $@convention(thin) () -> @owned NonTrivialUnion1
// CHECK: [[NON_TRIVIAL_UNION_1:%.*]] = apply [[GET_NON_TRIVIAL_UNION_1]]() : $@convention(thin) () -> @owned NonTrivialUnion1
// CHECK: release_value [[NON_TRIVIAL_UNION_1]] : $NonTrivialUnion1
getNonTrivialUnion1()
// CHECK: [[GET_NON_TRIVIAL_UNION_2:%.*]] = function_ref @_TF15lifetime_unions19getNonTrivialUnion2FT_OS_16NonTrivialUnion2 : $@convention(thin) () -> @owned NonTrivialUnion2
// CHECK: [[NON_TRIVIAL_UNION_2:%.*]] = apply [[GET_NON_TRIVIAL_UNION_2]]() : $@convention(thin) () -> @owned NonTrivialUnion2
// CHECK: release_value [[NON_TRIVIAL_UNION_2]] : $NonTrivialUnion2
getNonTrivialUnion2()
// CHECK: [[GET_NON_TRIVIAL_UNION_3:%.*]] = function_ref @_TF15lifetime_unions19getNonTrivialUnion3FT_OS_16NonTrivialUnion3 : $@convention(thin) () -> @owned NonTrivialUnion3
// CHECK: [[NON_TRIVIAL_UNION_3:%.*]] = apply [[GET_NON_TRIVIAL_UNION_3]]() : $@convention(thin) () -> @owned NonTrivialUnion3
// CHECK: release_value [[NON_TRIVIAL_UNION_3]] : $NonTrivialUnion3
getNonTrivialUnion3()
/* TODO: Address-only unions
// C/HECK: [[GET_ADDRESS_ONLY_UNION:%.*]] = function_ref @_TF15lifetime_unions19getAddressOnlyUnionU__FMQ_GOS_16AddressOnlyUnionQ__ : $@convention(thin) <T> T.Type -> AddressOnlyUnion<T>
// C/HECK: [[GET_ADDRESS_ONLY_UNION_SPEC:%.*]] = specialize [[GET_ADDRESS_ONLY_UNION]] : $@convention(thin) <T> T.Type -> AddressOnlyUnion<T>, $@thin Int64.Type -> AddressOnlyUnion<Int64>, T = Int
// C/HECK: [[ADDRESS_ONLY_UNION_ADDR:%.*]] = alloc_stack $AddressOnlyUnion<Int64>
// C/HECK: apply [[GET_ADDRESS_ONLY_UNION_SPEC]]([[ADDRESS_ONLY_UNION_ADDR]], {{%.*}}) : $@thin Int64.Type -> AddressOnlyUnion<Int64>
// C/HECK: destroy_addr [[ADDRESS_ONLY_UNION_ADDR]] : $*AddressOnlyUnion<Int64>
// C/HECK: dealloc_stack [[ADDRESS_ONLY_UNION_ADDR]] : $*AddressOnlyUnion<Int64>
getAddressOnlyUnion(Int)
*/
}
| apache-2.0 | 224548865c824333c7e000d80a654882 | 42.818182 | 200 | 0.678127 | 3.442857 | false | false | false | false |
tuannme/Up | Up+/Up+/Controller/ChannelViewController.swift | 1 | 2996 | //
// ChannelViewController.swift
// Up+
//
// Created by Dreamup on 3/6/17.
// Copyright © 2017 Dreamup. All rights reserved.
//
import UIKit
import SendBirdSDK
import AFNetworking
class ChannelViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tbView: UITableView!
var arrChannel:[SBDOpenChannel]! = []
override func viewDidLoad() {
super.viewDidLoad()
let query = SBDOpenChannel.createOpenChannelListQuery()!
query.loadNextPage(completionHandler: { (channels, error) in
if error != nil {
NSLog("Error: %@", error!)
return
}
self.arrChannel = channels
DispatchQueue.main.async(execute: {
self.tbView.reloadData()
})
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backAction(_ sender: Any) {
self.navigationController!.popViewController(animated: true)
}
// tableView delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("numbercount %d",arrChannel.count)
return arrChannel.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tbView .dequeueReusableCell(withIdentifier: "cell")
let name = cell!.contentView.viewWithTag(111) as! UILabel
let channel = arrChannel[indexPath.row]
name.text = channel.name
let avatar = cell!.contentView.viewWithTag(222) as! UIImageView
ImageCache.shareInstance.getImageURL(url: channel.coverUrl!, completion: {
image -> Void in
DispatchQueue.main.async(execute: {
avatar.image = image
})
})
// let url = URL(string: channel.coverUrl!)
// avatar.setImageWith(url!, placeholderImage: nil)
avatar.layer.cornerRadius = avatar.frame.width/2
avatar.clipsToBounds = true
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tbView.deselectRow(at: indexPath, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let index = tbView.indexPathForSelectedRow
let channel = arrChannel[index!.row]
let destinationVC = segue.destination as! MessageBaseViewController
object_setClass(destinationVC, MessageGroupViewController.self)
//(destinationVC as! MessageGroupViewController).channelURL = channel.channelUrl
//destinationVC.channelURL = channel.channelUrl
}
}
| mit | d66baaa2bb30050e66cbb6cfb90a3c46 | 28.362745 | 100 | 0.607012 | 5.386691 | false | false | false | false |
DanielZakharin/Shelfie | Shelfie/Pods/PieCharts/PieCharts/Layer/Impl/LineText/Anim/AlphaPieLineTextLayerAnimator.swift | 3 | 708 | //
// AlphaPieLineTextLayerAnimator.swift
// PieCharts
//
// Created by Ivan Schuetz on 30/12/2016.
// Copyright © 2016 Ivan Schuetz. All rights reserved.
//
import UIKit
public struct AlphaPieLineTextLayerAnimator: PieLineTextLayerAnimator {
public var duration: TimeInterval = 0.3
public func animate(_ layer: CALayer) {
let anim = CABasicAnimation(keyPath: "opacity")
anim.fromValue = 0
anim.toValue = 1
anim.duration = duration
layer.add(anim, forKey: "alphaAnim")
}
public func animate(_ label: UILabel) {
label.alpha = 0
UIView.animate(withDuration: duration) {
label.alpha = 1
}
}
}
| gpl-3.0 | 9d7d788d8229c50610ae964c6675a98b | 23.37931 | 71 | 0.628006 | 4.183432 | false | false | false | false |
jeremyabannister/JABSwiftCore | JABSwiftCore/NSDateExtension.swift | 1 | 5722 | //
// NSDateExtension.swift
// JABSwiftCore
//
// Created by Jeremy Bannister on 7/7/15.
// Copyright (c) 2015 Jeremy Bannister. All rights reserved.
//
import Foundation
extension Date {
// MARK:
// MARK: Init
// MARK:
public init(dateString: String) {
self.init(dateString: dateString, beginning: true)
}
public init(dateString:String, beginning: Bool) {
let components = dateString.components(separatedBy: " ")
if components.count == 3 {
let dayAsString = String(components[1][..<components[1].index(components[1].endIndex, offsetBy: -3)])
// let dayAsString = components[1].substring(to: components[1].characters.index(components[1].endIndex, offsetBy: -3))
var monthIndex = -1
for i in 0..<Date.months.count {
let month = Date.months[i]
if month == components[0] {
monthIndex = i
}
}
if monthIndex == -1 { // If the month was not found then check against the abbreviated versions of the months
for i in 0..<Date.months.count {
let month = Date.monthsShort[i]
if month == components[0] {
monthIndex = i
}
}
}
let dateStringFormatter = DateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd"
dateStringFormatter.locale = Locale(identifier: "en_US_POSIX")
if let d = dateStringFormatter.date(from: String(format: "%@-%02d-%@", components[2], monthIndex + 1, dayAsString)) {
if beginning { self = Date.init(timeInterval:0, since: d) }
else { self = Date.init(timeInterval:86370, since: d) }
} else {
if beginning { self = Date.init(timeInterval:0, since: Date()) }
else { self = Date.init(timeInterval:86370, since: Date()) }
}
} else {
self = Date.init(timeInterval:0, since: Date())
}
}
// MARK:
// MARK: Components
// MARK:
// MARK: Class
public static var months: [String] { return ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] }
public static var monthsShort: [String] { return ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"] }
public static var daysOfWeek: [String] { return ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] }
public static var daysOfWeekShort: [String] { return ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] }
public static var daysOfWeekMedium: [String] { return ["Sun", "Mon", "Tues", "Weds", "Thurs", "Fri", "Sat"] }
// MARK: Instance
public var fullDateString: String { return String(format: "%@ %@, %@", monthString, dayStringOrdinal, yearString) }
public var fullDateStringShort: String { return String(format: "%@ %@, %@", monthStringShort, dayStringOrdinal, yearString) }
public var year: Int { return (Calendar.current as NSCalendar).components(.year, from: self).year! }
public var yearString: String { return String(format: "%d", year) }
public var month: Int { return (Calendar.current as NSCalendar).components(.month, from: self).month! }
public var monthString: String { return Date.months[month - 1] }
public var monthStringShort: String { return Date.monthsShort[month - 1] }
public var weekOfYear: Int { return (Calendar.current as NSCalendar).components(.weekOfYear, from: self).weekOfYear! }
public var weekOfYearString: String { return String(format: "%d", weekOfYear) }
public var day: Int { return (Calendar.current as NSCalendar).components(.day, from: self).day! }
public var dayString: String { return String(format: "%d", day) }
public var dayStringOrdinal: String { return dayString + ["st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"][day - 1] }
public var dayOfWeek: Int { return (Calendar.current as NSCalendar).components(.weekday, from: self).weekday! - 1 }
public var dayOfWeekString: String { return Date.daysOfWeek[dayOfWeek] }
public var dayOfWeekStringShort: String { return Date.daysOfWeekShort[dayOfWeek] }
public var dayOfWeekStringMedium: String { return Date.daysOfWeekMedium[dayOfWeek] }
public var hour: Int { return (Calendar.current as NSCalendar).components(.hour, from: self).hour! }
public var hourString: String { return String(format: "%d", hour) }
public var minute: Int { return (Calendar.current as NSCalendar).components(.minute, from: self).minute! }
public var minuteString: String { return String(format: "%d", minute) }
public var second: Int { return (Calendar.current as NSCalendar).components(.second, from: self).second! }
public var secondString: String { return String(format: "%d", second) }
public var millisecond: Int {
var integer = 0.0
let fraction = modf(self.timeIntervalSinceReferenceDate, &integer)
return Int(fraction * 1000)
}
// MARK:
// MARK: Methods
// MARK:
public func numberOfDaysUntil(_ futureDate: Date, inclusive: Bool) -> Int? {
if (futureDate > self) {
let unitFlags = NSCalendar.Unit.day
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let components = (calendar as NSCalendar).components(unitFlags, from: self, to: futureDate, options: [])
guard let comDay = components.day else { return nil }
if inclusive { return comDay + 1 }
else { return components.day }
}
return nil
}
public func tomorrow () -> Date { return self.addingTimeInterval(86400) }
public func yesterday () -> Date { return self.addingTimeInterval(-86400) }
}
| mit | 3232e58c06ffdd94d1f41970bd0a8d79 | 44.055118 | 256 | 0.646977 | 3.911141 | false | true | false | false |
strike65/SwiftyStats | SwiftyStats/CommonSource/Examine/SSExamine.swift | 1 | 39591 | //
// SSExamine.swift
// SwiftyStats
//
// Created by strike65 on 01.07.17.
//
/*
Copyright (2017-2019) strike65
GNU GPL 3+
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, version 3 of the License.
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
#if os(macOS) || os(iOS)
import os.log
#endif
/** SSExamine
This class contains all the data that you want to evaluate. SSExamine expects data that corresponds to the `Hashable`, `Comparable` and `Codable` protocols.
Which statistics are available depends on the type of data. For nominal data, for example, an average will not be meaningful and will therefore not be calculated.
If a certain statistical measure is not available, the result will be `nil`. It is therefore important that you check all results for this.
SSExamine was primarily developed with Objective-C and had in particular the requirement to create frequency tables for the entered data and to update these
tables whenever data was added or removed. Internally, the data is therefore stored in a kind of frequency table. If, for example, the element "A" occurs
a 100 times in the data set to be evaluated, the element is not stored 100 times, but only once. At the same time, a reference to the frequency of thi
element is saved.
If elements are added to an SSExamine instance, the order of "arrival" is also registered. This makes it possible to reconstruct the "original data" from
an SSExamine instance.
- Important:
- `SSElement` = The Type of data to be processed.
- `FPT` = The type of emitted statistics. Must conform to SSFloatingPoint
*/
public class SSExamine<SSElement, FPT>: NSObject, SSExamineContainer, NSCopying, Codable where SSElement: Hashable & Comparable & Codable, FPT: SSFloatingPoint, FPT: Codable {
// MARK: OPEN/PUBLIC VARS
/**
An object representing the content of the SSExamine instance (experimental).
A placeholder to specify the type of stored data.
*/
public var rootObject: Any?
/**
User defined tag
*/
public var tag: String?
/**
Human readable description
*/
public var descriptionString: String?
/**
Name of the table
*/
public var name: String?
/**
Significance level to use, default: 0.05
*/
private var _alpha: FPT = FPT.zero
public var alpha: FPT {
get {
return _alpha
}
set(newAlpha) {
_alpha = newAlpha
}
}
/** Indicates if there are changes
*/
public var hasChanges: Bool! = false
/** Defines the level of measurement
*/
public var levelOfMeasurement: SSLevelOfMeasurement! = .interval
/** If true, the instance contains numerical data
*/
public var isNumeric: Bool! = true
/** Returns the number of unique SSElements
*/
public var length: Int {
return items.count
}
/** Returns true, if count == 0, i.e. there are no data
*/
public var isEmpty: Bool {
return count == 0
}
/** The total number of observations (= sum of all absolute frequencies)
*/
public var sampleSize: Int {
return count
}
/** Returns a Dictionary<element<SSElement>,cumulative frequency<Double>>
*/
public var cumulativeRelativeFrequencies: Dictionary<SSElement, FPT> {
// updateCumulativeFrequencies()
return cumRelFrequencies
}
/**
Returns a the hash for the instance.
*/
public override var hash: Int {
if !isEmpty {
if let a = elementsAsArray(sortOrder: .raw) {
var hasher = Hasher()
hasher.combine(a)
return hasher.finalize()
}
else {
return 0
}
}
else {
return 0
}
}
/// Overridden
/// Two SSExamine objects are assumed to be equal, iff the arrays of all elements in unsorted order are equal.
/// - Parameter object: The object to compare to
/// - Important: Properties like "name" or "tag" are not included
public override func isEqual(_ object: Any?) -> Bool {
if let o: SSExamine<SSElement, FPT> = object as? SSExamine<SSElement, FPT> {
if !self.isEmpty && !o.isEmpty {
let a1 = self.elementsAsArray(sortOrder: .raw)!
let a2 = o.elementsAsArray(sortOrder: .raw)!
return a1 == a2
}
else {
return false
}
}
else {
return false
}
}
/// Returns all unique elements as a Dictionary \<element\<SSElement\>:frequency\<Int\>\>
public var elements: Dictionary<SSElement, Int> {
return items
}
/// Returns a dictionary containing one array for each element. This array contains the order in which the elements were appended.
public var sequences: Dictionary<SSElement, Array<Int>> {
return sequence
}
// MARK: PRIVATE VARS
private var sequence: Dictionary<SSElement, Array<Int>> = [:]
private var items: Dictionary<SSElement, Int> = [:]
private var relFrequencies: Dictionary<SSElement, FPT> = [:]
private var cumRelFrequencies: Dictionary<SSElement, FPT> = [:]
private var allItemsAscending: Array<SSElement> = []
internal var aMean: FPT? = nil
// sum over all absolute frequencies (= sampleSize)
private var count: Int = 0
// MARK: INITIALIZERS
//: General initializer.
public override init() {
super.init()
initializeSSExamine()
}
private func createName(name: String?) {
if let n = name {
self.name = n
}
else {
self.tag = UUID.init().uuidString
self.name = self.tag
}
}
/// Initializes a SSExamine instance using a string or an array<SSElement>
/// - Parameter object: The object used
/// - Parameter name: The name of the instance.
/// - Parameter characterSet: Set containing all characters to include by string analysis. If a type other than String is used, this parameter will be ignored. If a string is used to initialize the class and characterSet is nil, then all characters will be appended.
/// - Parameter lom: Level of Measurement
/// - Throws: SSSwiftyStatsError.missingData if object is not a string or an Array\<SSElement\>
public init(withObject object: Any, levelOfMeasurement lom: SSLevelOfMeasurement, name: String?, characterSet: CharacterSet?) throws {
// allow only arrays an strings as 'object'
guard ((object is String && object is SSElement) || (object is Array<SSElement>)) else {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Error creating SSExamine instance", log: .log_dev, type: .error)
}
#endif
throw SSSwiftyStatsError(type: .missingData, file: #file, line: #line, function: #function)
}
super.init()
createName(name: name)
self.levelOfMeasurement = lom
if object is String {
self.levelOfMeasurement = .nominal
self.initializeWithString(string: object as! String, characterSet: characterSet)
}
else if object is Array<SSElement> {
self.initializeWithArray((object as! Array<SSElement>))
}
}
/// Returns: New table by analyzing string. Taking characterSet into account, when set
/// - Parameter array: The array containing the elements
/// - Parameter characterSet: Set containing all characters to include by string analysis. If a type other than String is used, this parameter will be ignored. If a string is used to initialize the class and characterSet is nil, then all characters will be appended.
public init(withArray array: Array<SSElement>, name: String?, characterSet: CharacterSet?) {
super.init()
createName(name: name)
self.initializeWithArray(array)
}
/// Loads the content of a file interpreting the elements separated by `separator` as values using the specified encoding. Data are assumed to be numeric.
///
/// The property `name`will be set to filename.
/// - Parameter path: The path to the file (e.g. ~/data/data.dat)
/// - Parameter separator: The separator used in the file
/// - Parameter stringEncoding: The encoding to use. Default: .utf8
/// - Parameter elementsEnclosedBy: A string that encloses each element.
/// - Throws: SSSwiftyStatsError if the file doesn't exist or can't be accessed.
/// - Important: It is assumed that the elements are numeric.
public class func examine(fromFile path: String, separator: String, elementsEnclosedBy: String? = nil, stringEncoding: String.Encoding = String.Encoding.utf8, _ parser: (String?) -> SSElement?) throws -> SSExamine<SSElement, FPT>? {
let fileManager = FileManager.default
let fullFilename: String = NSString(string: path).expandingTildeInPath
if !fileManager.fileExists(atPath: fullFilename) || !fileManager.isReadableFile(atPath: fullFilename) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("File not found", log: .log_fs, type: .error)
}
#endif
throw SSSwiftyStatsError(type: .fileNotFound, file: #file, line: #line, function: #function)
}
let filename = NSURL(fileURLWithPath: fullFilename).lastPathComponent!
var numberArray: Array<SSElement> = Array<SSElement>()
var go: Bool = true
do {
let importedString = try String.init(contentsOfFile: fullFilename, encoding: stringEncoding)
if importedString.contains(separator) {
if importedString.count > 0 {
let temporaryStrings: Array<String> = importedString.components(separatedBy: separator)
let separatedStrings: Array<String>
if let e = elementsEnclosedBy {
separatedStrings = temporaryStrings.map( {
$0.replacingOccurrences(of: e, with: "")
} )
}
else {
separatedStrings = temporaryStrings
}
for string in separatedStrings {
if string.count > 0 {
if let value = parser(string) {
numberArray.append(value)
}
else {
go = false
break
}
}
}
}
}
else {
return nil
}
}
catch {
return nil
}
if go {
return SSExamine<SSElement, FPT>.init(withArray: numberArray, name: filename, characterSet: nil)
}
else {
return nil
}
}
/// Imitializes a new Instance from a json file created by `exportJSONString(fileName:, atomically:, overwrite:, stringEncoding:)`
/// - Parameter path: The path to the file (e.g. ~/data/data.dat)
/// - Parameter stringEncoding: The encoding to use.
/// - Throws: if the file doesn't exist or can't be accessed or a the json file is invalid
public class func examine(fromJSONFile path: String, stringEncoding: String.Encoding = String.Encoding.utf8) throws -> SSExamine<SSElement, FPT>? {
let fileManager = FileManager.default
let fullFilename: String = NSString(string: path).expandingTildeInPath
if !fileManager.fileExists(atPath: fullFilename) || !fileManager.isReadableFile(atPath: fullFilename) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("File not found", log: .log_fs, type: .error)
}
#endif
throw SSSwiftyStatsError(type: .fileNotFound, file: #file, line: #line, function: #function)
}
let url = URL.init(fileURLWithPath: fullFilename)
if let jsonString = try? String.init(contentsOf: url), let data = jsonString.data(using: stringEncoding) {
do {
let result = try JSONDecoder().decode(SSExamine<SSElement, FPT>.self, from: data)
return result as SSExamine<SSElement, FPT>
}
catch {
throw error
}
}
else {
return nil
}
}
/// Exports the object as JSON to the given path using the specified encoding.
/// - Parameter path: Path to the file
/// - Parameter atomically: If true, the object will be written to a temporary file first. This file will be renamed upon completion.
/// - Parameter overwrite: If true, an existing file will be overwritten.
/// - Parameter stringEncoding: String encoding
/// - Throws: SSSwiftyStatsError if the file could not be written
public func exportJSONString(fileName path: String, atomically: Bool = true, overwrite: Bool, stringEncoding: String.Encoding = String.Encoding.utf8) throws -> Bool {
let fileManager = FileManager.default
let fullName = NSString(string: path).expandingTildeInPath
if fileManager.fileExists(atPath: fullName) {
if !overwrite {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("File already exists", log: .log_fs, type: .error)
}
#endif
throw SSSwiftyStatsError(type: .fileExists, file: #file, line: #line, function: #function)
}
else {
do {
try fileManager.removeItem(atPath: fullName)
}
catch {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Can't remove file", log: .log_fs, type: .error)
}
#endif
throw SSSwiftyStatsError(type: .fileNotWriteable, file: #file, line: #line, function: #function)
}
}
}
let jsonEncode = JSONEncoder()
do {
let data = try jsonEncode.encode(self)
if let jsonString = String.init(data: data, encoding: stringEncoding) {
try jsonString.write(to: URL.init(fileURLWithPath: fullName), atomically: true, encoding: stringEncoding)
return true
}
else {
return false
}
}
catch {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Unable to write json", log: .log_fs, type: .error)
}
#endif
return false
}
}
/// TODO: enclose elements in ""
/// Saves the object to the given path using the specified encoding.
/// - Parameter path: Path to the file
/// - Parameter atomically: If true, the object will be written to a temporary file first. This file will be renamed upon completion.
/// - Parameter overwrite: If true, an existing file will be overwritten.
/// - Parameter separator: Separator to use.
/// - Parameter stringEncoding: String encoding
/// - Parameter encloseElementsBy: Defaulf = nil
/// - Throws: SSSwiftyStatsError if the file could not be written
public func saveTo(fileName path: String, atomically: Bool = true, overwrite: Bool, separator: String = ",", encloseElementsBy: String? = nil, asRow: Bool = true, stringEncoding: String.Encoding = String.Encoding.utf8) throws -> Bool {
var result = true
let fileManager = FileManager.default
let fullName = NSString(string: path).expandingTildeInPath
if fileManager.fileExists(atPath: fullName) {
if !overwrite {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("File already exists", log: .log_fs, type: .error)
}
#endif
throw SSSwiftyStatsError(type: .fileExists, file: #file, line: #line, function: #function)
}
else {
do {
try fileManager.removeItem(atPath: fullName)
}
catch {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Can't remove file", log: .log_fs, type: .error)
}
#endif
throw SSSwiftyStatsError(type: .fileNotWriteable, file: #file, line: #line, function: #function)
}
}
}
if let s = elementsAsString(withDelimiter: separator, asRow: asRow, encloseElementsBy: encloseElementsBy) {
do {
try s.write(toFile: fullName, atomically: atomically, encoding: stringEncoding)
}
catch {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("File could not be written", log: .log_fs, type: .error)
}
#endif
result = false
}
}
return result
}
/// Returns a SSExamine instance initialized using the string provided. Level of measurement will be set to .nominal.
/// - Parameter string: String
/// - Parameter characterSet: If characterSet is not nil, only characters contained in the set will be appended
public class func examineWithString(_ string: String, name: String?, characterSet: CharacterSet?) -> SSExamine<String, FPT>? {
do {
let result:SSExamine<String, FPT> = try SSExamine<String, FPT>(withObject: string, levelOfMeasurement: .nominal, name: name, characterSet: characterSet)
return result
}
catch {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Error creating SSExamine instance", log: .log_dev, type: .error)
}
#endif
return nil
}
}
/// Initialize the table using a string. Append only characters contained in characterSet
/// - Parameter string: String
/// - Parameter characterSet: If characterSet is not nil, only characters contained in the set will be appended
private func initializeWithString(string: String, characterSet: CharacterSet?) {
initializeSSExamine()
isNumeric = false
var index: String.Index = string.startIndex
var offset: Int = 0
if index < string.endIndex {
if let cs: CharacterSet = characterSet {
for scalar in string.unicodeScalars {
if cs.contains(scalar) {
append(String(string[index]) as! SSElement)
}
offset = offset.advanced(by: 1)
index = string.index(string.startIndex, offsetBy: offset)
}
}
else {
for c: Character in string {
append(String(c) as! SSElement)
}
}
}
}
/// Initializes a new instance using an array
/// - Parameter array: The array containing the elements
private func initializeWithArray(_ array: Array<SSElement>) {
initializeSSExamine()
if array.count > 0 {
if Helpers.isNumber(array.first) {
isNumeric = true
}
else {
isNumeric = false
}
for item in array {
append(item)
}
}
}
/// # Danger!!
/// Sets default values, removes all items, reset all statistics.
fileprivate func initializeSSExamine() {
sequence.removeAll()
items.removeAll()
relFrequencies.removeAll()
cumRelFrequencies.removeAll()
count = 0
descriptionString = "SSExamine Instance - standard"
alpha = Helpers.makeFP(0.05)
hasChanges = false
isNumeric = true
aMean = nil
}
// MARK: Codable protocol
/// All the coding keys to encode
private enum CodingKeys: String, CodingKey {
case tag = "TAG"
case name
case descriptionString
case alpha
case levelOfMeasurement
case isNumeric
case data
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(self.name, forKey: CodingKeys.name)
try container.encodeIfPresent(self.tag, forKey: CodingKeys.tag)
try container.encodeIfPresent(self.descriptionString, forKey: CodingKeys.descriptionString)
try container.encodeIfPresent(self._alpha, forKey: CodingKeys.alpha)
try container.encodeIfPresent(self.levelOfMeasurement.rawValue, forKey: CodingKeys.levelOfMeasurement)
try container.encodeIfPresent(self.isNumeric, forKey: CodingKeys.isNumeric)
try container.encodeIfPresent(self.elementsAsArray(sortOrder: .raw), forKey: CodingKeys.data)
}
required public init(from decoder: Decoder) throws {
super.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.tag = try container.decodeIfPresent(String.self, forKey: CodingKeys.tag)
self.name = try container.decodeIfPresent(String.self, forKey: CodingKeys.name)
self.descriptionString = try container.decodeIfPresent(String.self, forKey: CodingKeys.descriptionString)
self._alpha = try container.decodeIfPresent(FPT.self, forKey: CodingKeys.alpha) ?? FPT.zero
if let lm = try container.decodeIfPresent(String.self, forKey: CodingKeys.levelOfMeasurement) {
self.levelOfMeasurement = SSLevelOfMeasurement(rawValue:lm)
}
self.isNumeric = try container.decodeIfPresent(Bool.self, forKey: .isNumeric)
if let data: Array<SSElement> = try container.decodeIfPresent(Array<SSElement>.self, forKey: CodingKeys.data) {
self.initializeWithArray(data)
}
}
// MARK: NSCopying
public func copy(with zone: NSZone? = nil) -> Any {
let res: SSExamine = SSExamine()
if !isEmpty {
res.tag = self.tag
res.descriptionString = self.descriptionString
res.name = self.name
res.alpha = self.alpha
res.levelOfMeasurement = self.levelOfMeasurement
res.hasChanges = self.hasChanges
let a: Array<SSElement> = elementsAsArray(sortOrder: .raw)!
for item in a {
res.append(item)
}
}
return res
}
/// Updates cumulative frequencies
private func updateCumulativeFrequencies() {
// 1. Alle Werte nach Größe sortieren
// 2. crf(n) = crf(n-1) + rf(n)
if !isEmpty {
let temp = self.uniqueElements(sortOrder: .ascending)!
var i: Int = 0
cumRelFrequencies.removeAll()
for key in temp {
if i == 0 {
cumRelFrequencies[key] = rFrequency(key)
}
else {
cumRelFrequencies[key] = cumRelFrequencies[temp[i - 1]]! + rFrequency(key)
}
i = i + 1
}
allItemsAscending = self.uniqueElements(sortOrder: .ascending)!
}
}
// MARK: SSExamineContainer Protocol
/// Returns true, if the table contains the item
/// - Parameter item: Item to search
public func contains(_ element: SSElement) -> Bool {
if !isEmpty {
let test = items.contains(where: { (key: SSElement, value: Int) -> Bool in
if key == element {
return true
}
else {
return false
}
})
return test
}
else {
return false
}
}
/// Returns the relative Frequency of item
/// - Parameter element: Item
public func rFrequency(_ element: SSElement) -> FPT {
//
if let rf = self.elements[element] {
return Helpers.makeFP(rf) / Helpers.makeFP(self.sampleSize)
}
else {
return 0
}
}
/// Returns the absolute frequency of item
/// - Parameter element: Item
public func frequency(_ element: SSElement) -> Int {
if contains(element) {
return items[element]!
}
else {
return 0
}
}
/// Appends <item> and updates frequencies
/// - Parameter element: Item
public func append(_ element: SSElement) {
var tempPos: Array<Int>
let test = items.contains(where: { (key: SSElement, value: Int) in
if key == element {
return true
}
else {
return false
}
})
var currentFrequency: Int
if test {
currentFrequency = items[element]! + 1
items[element] = currentFrequency
count = count + 1
sequence[element]!.append(count)
}
else {
items[element] = 1
count = count + 1
tempPos = Array()
tempPos.append(count)
sequence[element] = tempPos
}
updateCumulativeFrequencies()
}
/// Appends n elements
/// - Parameter n: Count of elements to append
/// - Parameter elements: Item to append
public func append(repeating n: Int, element: SSElement) {
for _ in 1...n {
append(element)
}
updateCumulativeFrequencies()
}
/// Appends elements from an array
/// - Parameter array: Array containing elements to add
public func append(contentOf array: Array<SSElement>) {
if array.count > 0 {
if isEmpty {
if Helpers.isNumber(array.first) {
isNumeric = true
}
else {
isNumeric = false
}
}
for item in array {
append(item)
}
}
}
/// Appends the characters of the given string. Only characters contained in the character set are appended.
/// - Parameter text: The text
/// - Parameter characterSet: A CharacterSet containing the characters to include. If nil, all characters of text will be appended.
/// - Throws: SSSwiftyStatsError if <SSElement> of the receiver is not of type String
public func append(text: String, characterSet: CharacterSet?) throws {
if !(SSElement.self is String.Type) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Can only append strings", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError(type: .invalidArgument, file: #file, line: #line, function: #function)
}
else {
var index: String.Index = text.startIndex
var offset: Int = 0
if index < text.endIndex {
if let cs: CharacterSet = characterSet {
for scalar in text.unicodeScalars {
if cs.contains(scalar) {
append(String(text[index]) as! SSElement)
}
offset = offset.advanced(by: 1)
index = text.index(text.startIndex, offsetBy: offset)
}
}
else {
for c: Character in text {
append(String(c) as! SSElement)
}
}
}
}
}
/// Removes item from the table.
/// - Parameter item: Item
/// - Parameter allOccurences: If false, only the first item found will be removed. Default: false
public func remove(_ element: SSElement, allOccurences all: Bool = false) {
if !isEmpty {
if contains(element) {
var temp: Array<SSElement> = elementsAsArray(sortOrder: .raw)!
// remove all elements
if all {
temp = temp.filter({ $0 != element})
}
else {
// remove only the first occurence
let s: Array<Int> = sequence[element]!
temp.remove(at:s.first! - 1)
}
items.removeAll()
relFrequencies.removeAll()
cumRelFrequencies.removeAll()
sequence.removeAll()
count = 0
for i in temp {
append(i)
}
}
}
}
/// Removes all elements leaving an empty object
public func removeAll() {
count = 0
items.removeAll()
sequence.removeAll()
relFrequencies.removeAll()
cumRelFrequencies.removeAll()
isNumeric = true
hasChanges = true
}
}
extension SSExamine {
// MARK: Elements
/// Returns all elements as one string. Elements are delimited by del.
/// - Parameter del: The delimiter. Can be nil or empty.
/// - Parameter asRow: If true, the parameter `del` will be omitted. The Name of the instance will ve used as header for the row
/// - Parameter encloseElementsBy: Default: nil.
public func elementsAsString(withDelimiter del: String?, asRow: Bool = true, encloseElementsBy: String? = nil) -> String? {
let a: Array<SSElement> = elementsAsArray(sortOrder: .raw)!
var res: String = String()
if !asRow {
if let n = self.name {
res = res + n + "\n"
}
}
for item in a {
if let e = encloseElementsBy {
res = res + e + "\(item)" + e
}
else {
res = res + "\(item)"
}
if asRow {
if let d = del {
res = res + d
}
}
else {
res = res + "\n"
}
}
if let d = del {
if d.count > 0 {
for _ in 1...d.count {
res = String(res.dropLast())
}
}
}
if res.count > 0 {
return res
}
else {
return nil
}
}
/// Returns true, if index is valid
private func isValidIndex(index: Int) -> Bool {
return index >= 0 && index < self.sampleSize
}
/// Returns the indexed element
subscript(_ index: Int) -> SSElement? {
if isValidIndex(index: index) {
if !self.isEmpty {
let a = self.elementsAsArray(sortOrder: .raw)!
return a[index]
}
else {
return nil
}
}
else {
fatalError("Index out of range")
}
}
/// Returns an array containing all elements.
/// - Parameter sortOrder: The sort sortOrder.
/// - Returns: An array containing all elements sortOrdered as specified.
public func elementsAsArray(sortOrder: SSDataArraySortOrder) -> Array<SSElement>? {
if !isEmpty {
var temp: Array<SSElement> = Array<SSElement>()
var result: Array<SSElement>
for (item, freq) in self.elements {
for _ in 1...freq {
temp.append(item)
}
}
switch sortOrder {
case .ascending:
result = temp.sorted(by: {$0 < $1})
case .descending:
result = temp.sorted(by: {$0 > $1})
case .none:
result = temp
case .raw:
temp.removeAll(keepingCapacity: true)
for _ in 1...self.sampleSize {
temp.append(self.elements.keys[self.elements.keys.startIndex])
}
for (item, seq) in self.sequences {
for i in seq {
temp[i - 1] = item
}
}
result = temp
}
return result
}
else {
return nil
}
}
/// Returns an array containing all unique elements.
/// - Parameter sortOrder: Sorting order
public func uniqueElements(sortOrder: SSSortUniqeItems) -> Array<SSElement>? {
var result: Array<SSElement>? = nil
if !isEmpty {
var temp: Array<SSElement> = Array<SSElement>()
switch sortOrder {
case .ascending:
for (item, _) in self.elements {
temp.append(item)
}
result = temp.sorted(by: {$0 < $1})
case .descending:
for (item, _) in self.elements {
temp.append(item)
}
result = temp.sorted(by: {$0 > $1})
case .none:
for (item, _) in self.elements {
temp.append(item)
}
result = temp
}
}
return result
}
// MARK: Frequencies
/// Returns the frequency table as an array, ordered as speciefied.
/// - Parameter sortOrder: SSFrequencyTableSortsortOrder
public func frequencyTable(sortOrder: SSFrequencyTableSortOrder) -> Array<SSFrequencyTableItem<SSElement, FPT>> {
var result = Array<SSFrequencyTableItem<SSElement,FPT>>()
var tableItem: SSFrequencyTableItem<SSElement,FPT>
if self.sampleSize > 0 {
let n = Double(self.sampleSize)
for (item, freq) in self.elements {
let f: Double = Double(freq)
tableItem = SSFrequencyTableItem<SSElement,FPT>(withItem: item, relativeFrequency: Helpers.makeFP(f) / Helpers.makeFP(n), frequency: freq)
result.append(tableItem)
}
switch sortOrder {
case .none:
return result
case .valueAscending:
return result.sorted(by: { $0.item < $1.item})
case .valueDescending:
return result.sorted(by: { $0.item > $1.item})
case .frequencyAscending:
return result.sorted(by: { $0.frequency < $1.frequency})
case .frequencyDescending:
return result.sorted(by: { $0.frequency > $1.frequency})
}
}
else {
return result
}
}
/// Returns the cumulative frequency table
/// - Parameter format: SSCumulativeFrequencyTableFormat
public func cumulativeFrequencyTable(format: SSCumulativeFrequencyTableFormat) -> Array<SSCumulativeFrequencyTableItem<SSElement, FPT>> {
var tableItem: SSCumulativeFrequencyTableItem<SSElement,FPT>
var cumRelFreq: FPT = 0
var cumAbsFreq: FPT = 0
var result = Array<SSCumulativeFrequencyTableItem<SSElement,FPT>>()
let frequencyTable = self.frequencyTable(sortOrder: .valueAscending)
switch format {
case .eachUniqueItem:
for fItem:SSFrequencyTableItem<SSElement,FPT> in frequencyTable {
cumAbsFreq = cumAbsFreq + Helpers.makeFP(fItem.frequency)
cumRelFreq = cumRelFreq + fItem.relativeFrequency
for _ in (Helpers.integerValue(cumAbsFreq) - fItem.frequency)...(Helpers.integerValue(cumAbsFreq) - 1) {
tableItem = SSCumulativeFrequencyTableItem<SSElement,FPT>(withItem: fItem.item, cumulativeRelativeFrequency: cumRelFreq, cumulativefrequency: Helpers.integerValue(cumAbsFreq))
result.append(tableItem)
}
}
case .eachItem:
for fItem:SSFrequencyTableItem<SSElement, FPT> in frequencyTable {
cumAbsFreq = cumAbsFreq + Helpers.makeFP(fItem.frequency)
cumRelFreq = cumRelFreq + fItem.relativeFrequency
tableItem = SSCumulativeFrequencyTableItem<SSElement, FPT>(withItem: fItem.item, cumulativeRelativeFrequency: cumRelFreq, cumulativefrequency: Helpers.integerValue(cumAbsFreq))
result.append(tableItem)
}
}
return result
}
/// Empirical CDF of item
/// - Parameter item: The item for which the cdf will be returned.
public func eCDF(_ item: SSElement) -> FPT {
var result: FPT = FPT.nan
if let min = self.minimum, let max = self.maximum {
if item < min {
return 0
}
else if item > max {
return 1
}
if self.contains(item) {
result = self.cumulativeRelativeFrequencies[item]!
}
else {
for itm in self.uniqueElements(sortOrder: .ascending)! {
if itm < item {
result = self.cumulativeRelativeFrequencies[itm]!
}
}
}
}
return result
}
/// The smallest frequency. Can be nil for empty tables.
public var smallestFrequency: Int? {
if !isEmpty {
return (self.frequencyTable(sortOrder: .frequencyAscending).first?.frequency)!
}
else {
return nil
}
}
/// The largest frequency Can be nil for empty tables.
public var largestFrequency: Int? {
if !isEmpty {
return (self.frequencyTable(sortOrder: .frequencyAscending).last?.frequency)!
}
else {
return nil
}
}
}
| gpl-3.0 | 4481e7409628e53b60b39d9527260fce | 36.103093 | 270 | 0.551744 | 5.060591 | false | false | false | false |
xoyip/AzureStorageApiClient | Pod/Classes/AzureStorage/Request.swift | 1 | 1006 | //
// Request.swift
// AzureStorageApiClient
//
// Created by Hiromasa Ohno on 2015/08/10.
// Copyright (c) 2015 Hiromasa Ohno. All rights reserved.
//
import Foundation
public protocol Request {
var method: String { get }
typealias Response: Any
func path() -> String
func additionalHeaders() -> [String:String]
func body() -> NSData?
func convertResponseObject(object: AnyObject?) -> Response?
func responseTypes() -> Set<String>?
}
public class RequestUtility {
class func headerForXmlBody(xml: NSData?) -> [String : String] {
var headers = ["Content-Type": "application/atom+xml; charset=utf-8", "Content-Encoding": "UTF-8"]
if let data = xml {
headers["Content-Length"] = "\(data.length)"
var md5data = data.md5()
if let md5 = md5data?.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) {
headers["Content-Md5"] = md5
}
}
return headers
}
} | mit | 3c8d50478d37be35abf7dfca3384806f | 27.771429 | 106 | 0.619284 | 4.106122 | false | false | false | false |
C4Framework/C4iOS | C4/UI/View+Animation.swift | 2 | 4048 | // Copyright © 2014 C4
//
// 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 QuartzCore
import UIKit
/// Extension to View that handles animating of basic properties.
public extension View {
/// Internal function for creating a basic animation and applying that to the receiver.
/// - parameter keyPath: The identifier to animate
/// - parameter toValue: The value to which the identifier will be animated
internal func animateKeyPath(_ keyPath: String, toValue: AnyObject) {
let anim = CABasicAnimation()
anim.duration = 0.25
anim.beginTime = CACurrentMediaTime()
anim.keyPath = keyPath
anim.fromValue = view.layer.presentation()?.value(forKeyPath: keyPath)
anim.toValue = toValue
view.layer.add(anim, forKey: "C4AnimateKeyPath: \(keyPath)")
view.layer.setValue(toValue, forKeyPath: keyPath)
}
/// A class-level function that executes an animation using a specified block of code.
///
/// - parameter duration: The length of time in seconds for the animation to execute.
/// - parameter animations: A block of code with specified animations to execute.
public class func animate(duration: Double, animations: @escaping () -> Void) {
UIView.animate(withDuration: duration, animations: animations)
}
/// A class-level function that executes an animation using a specified block of code, with parameters for delaying and completion.
///
/// - parameter duration: The length of time in seconds for the animation to execute.
/// - parameter delay: The length of time in seconds to wait before executing the specified block of code.
/// - parameter completion: A block of code to execute when the animation completes.
/// - parameter animations: A block of code with specified animations to execute.
public class func animate(duration: Double, delay: Double, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) {
UIView.animate(withDuration: duration, animations: animations, completion: completion)
}
/// A class-level function that executes an animation using a specified block of code, with parameters for delaying, completion and animation options.
///
/// - parameter duration: The length of time in seconds for the animation to execute.
/// - parameter delay: The length of time in seconds to wait before executing the specified block of code.
/// - parameter options: Options for animating views using block objects, see: UIViewAnimationOptions.
/// - parameter animations: A block of code with specified animations to execute.
/// - parameter completion: A block of code to execute when the animation completes.
public class func animate(duration: Double, delay: Double, options: UIViewAnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) {
UIView.animate(withDuration: duration, delay: delay, options: options, animations: animations, completion: completion)
}
}
| mit | 68da5401a7ca84ed0def6344042702b1 | 59.402985 | 162 | 0.728194 | 4.905455 | false | false | false | false |
sschiau/swift-package-manager | Sources/PackageModel/Product.swift | 1 | 3271 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
/// The type of product.
public enum ProductType: CustomStringConvertible, Equatable {
/// The type of library.
public enum LibraryType: String, Codable {
/// Static library.
case `static`
/// Dynamic library.
case `dynamic`
/// The type of library is unspecified and should be decided by package manager.
case automatic
}
/// A library product.
case library(LibraryType)
/// An executable product.
case executable
/// A test product.
case test
public var description: String {
switch self {
case .executable:
return "executable"
case .test:
return "test"
case .library(let type):
switch type {
case .automatic:
return "automatic"
case .dynamic:
return "dynamic"
case .static:
return "static"
}
}
}
}
public class Product {
/// The name of the product.
public let name: String
/// The type of product to create.
public let type: ProductType
/// The list of targets to combine to form the product.
///
/// This is never empty, and is only the targets which are required to be in
/// the product, but not necessarily their transitive dependencies.
public let targets: [Target]
/// The path to linux main file.
public let linuxMain: AbsolutePath?
/// The suffix for REPL product name.
public static let replProductSuffix: String = "__REPL"
/// Returns true if this product supports the given platform.
public func supportsPlatform(_ platform: Platform) -> Bool {
// A product supports a platform if all of its targets support that platform.
//
// We might need something different once we have support for
// target-level platform specification. Maybe the product's
// platform should be the intersection of the platforms
// specified by its targets.
for target in self.targets {
if !target.supportsPlatform(platform) {
return false
}
}
return true
}
public init(name: String, type: ProductType, targets: [Target], linuxMain: AbsolutePath? = nil) {
precondition(!targets.isEmpty)
if type == .executable {
assert(targets.filter({ $0.type == .executable }).count == 1,
"Executable products should have exactly one executable target.")
}
if linuxMain != nil {
assert(type == .test, "Linux main should only be set on test products")
}
self.name = name
self.type = type
self.targets = targets
self.linuxMain = linuxMain
}
}
extension Product: CustomStringConvertible {
public var description: String {
return "<Product: \(name)>"
}
}
| apache-2.0 | ee78cb9fd97239d386e647e15203a0d4 | 27.946903 | 101 | 0.610517 | 4.918797 | false | true | false | false |
taku0/swift3-mode | test/swift-files/statements.swift | 1 | 9074 | // swift3-mode:test:eval (setq-local swift3-mode:basic-offset 4)
// swift3-mode:test:eval (setq-local swift3-mode:parenthesized-expression-offset 2)
// swift3-mode:test:eval (setq-local swift3-mode:multiline-statement-offset 2)
// swift3-mode:test:eval (setq-local swift3-mode:switch-case-offset 0)
// For-in statements
for x in xs {
foo()
foo()
}
for x
in xs {
foo()
foo()
}
for x in
xs {
foo()
foo()
}
for x
in
xs {
foo()
foo()
}
for
x
in
xs {
foo()
foo()
}
for
x
in xs
.foo() { // swift3-mode:test:known-bug
foo()
foo()
}
for
(
x,
y
)
in
xs
.foo() +++ { z in // swift3-mode:test:known-bug
bar()
} {
foo()
foo()
}
for
case
( // swift3-mode:test:known-bug
x,
y
)
in
xs
.foo() +++ { z in // swift3-mode:test:known-bug
bar()
bar()
} {
foo()
foo()
}
for case
( // swift3-mode:test:known-bug
x,
y
)
in
xs
.foo() +++ { z in // swift3-mode:test:known-bug
bar()
bar()
} {
foo()
foo()
}
for Foo
.Bar(x) // swift3-mode:test:known-bug
in
xs {
foo()
foo()
}
for
Foo
.Bar(x) // swift3-mode:test:known-bug
in
xs {
foo()
foo()
}
for x as
Foo // swift3-mode:test:known-bug
in
xs {
foo()
foo()
}
for x
in
xs
.foo // swift3-mode:test:known-bug
where // swift3-mode:test:known-bug
aaa
.bbb(x) {
foo()
foo()
}
for x
in
xs where
aaa
.bbb(x) {
foo()
foo()
}
for x
in
xs
where aaa
.bbb(x) { // swift3-mode:test:known-bug
foo()
foo()
}
for x
in
xs where aaa
.bbb(x) { // swift3-mode:test:known-bug
foo()
foo()
}
for
x in xs
where
aaa.bbb(x) {
foo()
foo()
}
// While statements
while foo
.bar() +++ { x in
foo()
foo()
} {
foo()
foo()
}
while
foo
.bar() +++ { x in
foo()
foo()
} {
foo()
foo()
}
while
let
x
=
xx,
var
y
=
yy,
x
==
y,
case
(
a,
b
)
=
ab {
foo()
foo()
}
while let
x
=
xx,
var
y
=
yy,
x
==
y,
case
(
a,
b
)
=
ab {
foo()
foo()
}
while let
x
=
xx
, var
y
=
yy
, x
==
y
, case
(
a,
b
)
=
ab
{
foo()
foo()
}
// Repeat-while statements
repeat {
foo()
foo()
} while foo
.bar() // swift3-mode:test:known-bug
.baz()
repeat {
foo()
foo()
} while
foo
.bar() // swift3-mode:test:known-bug
.baz()
repeat {
foo()
foo()
}
while
foo
.bar() // swift3-mode:test:known-bug
.baz()
repeat {
foo()
foo()
}
while foo
.bar() // swift3-mode:test:known-bug
.baz()
// If statement
if x
.foo()
.bar() {
foo()
foo()
}
if
x
.foo()
.bar() {
foo()
foo()
}
if
let
x
=
xx,
var
y
=
yy,
x
==
y,
case
(
a,
b
)
=
ab {
foo()
foo()
}
if foo() {
foo()
foo()
foo()
} else if foo() {
foo()
foo()
foo()
} else if foo
.bar()
.baz() +++ { x in
return x
},
foo
.bar()
.baz() +++ { x in
return x
} {
foo()
foo()
foo()
} else if
foo
.bar()
.baz() +++ { x in
return x
},
foo
.bar()
.baz() +++ { x in
return x
} {
foo()
foo()
foo()
}
// Guard statement
guard
foo
.foo() else {
bar()
bar()
}
guard
foo
.foo()
else {
bar()
bar()
}
guard foo
.foo()
.foo() +++ { x in
foo()
} else {
bar()
bar()
}
guard
foo
.foo()
.foo() +++ { x in
foo()
} else {
bar()
bar()
}
guard
let
x
=
xx,
var
y
=
yy,
x
==
y,
case
(
a,
b
)
=
ab
else {
foo()
foo()
}
guard
let
x
=
xx,
var
y
=
yy,
x
==
y,
case
(
a,
b
)
=
ab else {
foo() // swift3-mode:test:known-bug
foo()
} // swift3-mode:test:known-bug
// Switch statement
switch foo
.bar {
case foo:
foo()
foo()
default:
foo()
foo()
} // swift3-mode:test:known-bug
switch
foo
.bar {
case foo:
foo()
foo()
default:
foo()
foo()
} // swift3-mode:test:known-bug
switch foo {
case foo:
foo()
.bar()
foo()
default:
foo()
foo()
}
switch foo {
case .P(let x)
where
foo
.bar(),
.Q(let x)
where
foo
.bar(),
.R(let x)
where
foo
.bar():
foo()
foo()
default:
foo()
foo()
}
switch foo {
case let .P(x)
where
foo
.bar(),
let .Q(x)
where
foo
.bar(),
let .R(x)
where
foo
.bar():
foo()
foo()
default:
foo()
foo()
}
switch foo {
case
let .P(x)
where
foo
.bar(),
let .Q(x)
where
foo
.bar(),
let .R(x)
where
foo
.bar():
foo()
foo()
default:
foo()
foo()
}
switch foo {
case
let .P(x)
where
foo
.bar(),
let .Q(x)
where
foo
.bar(),
let .R(x)
where
foo
.bar():
foo()
foo()
default:
foo()
foo()
}
switch foo {
case let
.P(x) // swift3-mode:test:known-bug
where // swift3-mode:test:known-bug
foo
.bar(),
let
.Q(x)
where // swift3-mode:test:known-bug
foo
.bar(),
let
.R(x)
where // swift3-mode:test:known-bug
foo
.bar():
foo()
foo()
default:
foo()
foo()
}
switch foo {
case
let
.P(x) // swift3-mode:test:known-bug
where // swift3-mode:test:known-bug
foo
.bar(),
let
.Q(x)
where // swift3-mode:test:known-bug
foo
.bar(),
let
.R(x)
where // swift3-mode:test:known-bug
foo
.bar():
foo()
foo()
default:
foo()
foo()
}
switch foo {
case
let Foo
.P(x) // swift3-mode:test:known-bug
where // swift3-mode:test:known-bug
foo
.bar(),
let Foo
.Q(x)
where // swift3-mode:test:known-bug
foo
.bar(),
let Foo
.R(x)
where // swift3-mode:test:known-bug
foo
.bar():
foo()
foo()
case
Foo
.P, // swift3-mode:test:known-bug
Foo
.Q,
Foo
.R:
default:
foo()
foo()
}
switch foo {
case
let
Foo // swift3-mode:test:known-bug
.P(x)
where // swift3-mode:test:known-bug
foo
.bar(),
let
Foo
.Q(x)
where // swift3-mode:test:known-bug
foo
.bar(),
let
Foo
.R(x)
where // swift3-mode:test:known-bug
foo
.bar():
foo()
foo()
default:
foo()
foo()
}
switch foo {
case
is
Foo // swift3-mode:test:known-bug
where // swift3-mode:test:known-bug
foo
.bar(),
is
Foo
where // swift3-mode:test:known-bug
foo
.bar(),
let Foo
.Bar
.Baz
where // swift3-mode:test:known-bug
foo
.bar():
foo()
foo()
default:
foo()
foo()
}
// swift3-mode:test:eval (setq-local swift3-mode:switch-case-offset 2)
switch foo {
case foo:
foo() // swift3-mode:test:known-bug
foo()
default:
foo() // swift3-mode:test:known-bug
foo()
}
// swift3-mode:test:eval (setq-local swift3-mode:switch-case-offset 0)
// Labeled statements
foo:
if foo
.bar == baz {
}
foo:
if
foo
.bar == baz {
}
foo:
for
x
in
xs {
foo()
foo()
}
// Control transfer statements
while foo() {
break
continue
return
foo()
throw
foo()
switch foo() {
case A:
foo()
fallthrough
case B:
foo()
fallthrough
default:
foo()
}
}
// Defer statements
defer {
foo()
bar()
baz()
}
// Do statements
do {
} catch Foo
.Bar(x)
where // swift3-mode:test:known-bug
foo()
.bar() {
foo()
foo()
} catch
Foo // swift3-mode:test:known-bug
.Bar(x)
where
foo()
.bar() {
foo()
foo()
} catch
where // swift3-mode:test:known-bug
foo()
.bar() {
foo()
foo()
}
// Conditional control statements
func foo() {
#if foo
foo()
foo()
#elsif foo
foo()
foo()
#else
foo()
foo()
#end
}
| gpl-3.0 | 9f9c24fa88e244eb6f0a2ae1f9e9f7c0 | 10.27205 | 83 | 0.412938 | 3.113933 | false | true | false | false |
victor/SwiftCLI | SwiftCLI/Commands/LightweightCommand.swift | 1 | 3814 | //
// LightweightCommand.swift
// SwiftCLI
//
// Created by Jake Heiser on 7/25/14.
// Copyright (c) 2014 jakeheis. All rights reserved.
//
import Foundation
typealias CommandExecutionBlock = ((arguments: NSDictionary, options: Options) -> CommandResult)
class LightweightCommand: Command {
var lightweightCommandName: String = ""
var lightweightCommandSignature: String = ""
var lightweightCommandShortDescription: String = ""
var lightweightCommandShortcut: String? = nil
var lightweightExecutionBlock: CommandExecutionBlock? = nil
var shouldFailOnUnrecognizedOptions = true
var shouldShowHelpOnHFlag = true
var printingBehaviorOnUnrecognizedOptions: UnrecognizedOptionsPrintingBehavior = .PrintAll
private var flagHandlingBlocks: [LightweightCommandFlagOptionHandler] = []
private var keyHandlingBlocks: [LightweightCommandKeyOptionHandler] = []
init(commandName: String) {
super.init()
lightweightCommandName = commandName
}
override func commandName() -> String {
return lightweightCommandName
}
override func commandSignature() -> String {
return lightweightCommandSignature
}
override func commandShortDescription() -> String {
return lightweightCommandShortDescription
}
override func commandShortcut() -> String? {
return lightweightCommandShortcut
}
// MARK: - Options
func handleFlags(flags: [String], block: OptionsFlagBlock?, usage: String = "") {
let handler = LightweightCommandFlagOptionHandler(flags: flags, flagBlock: block, usage: usage)
flagHandlingBlocks.append(handler)
}
func handleKeys(keys: [String], block: OptionsKeyBlock?, usage: String = "", valueSignature: String = "value") {
let handler = LightweightCommandKeyOptionHandler(keys: keys, keyBlock: block, usage: usage, valueSignature: valueSignature)
keyHandlingBlocks.append(handler)
}
override func handleOptions() {
for handlingBlock in flagHandlingBlocks {
onFlags(handlingBlock.flags, block: handlingBlock.flagBlock, usage: handlingBlock.usage)
}
for handlingBlock in keyHandlingBlocks {
onKeys(handlingBlock.keys, block: handlingBlock.keyBlock, usage: handlingBlock.usage, valueSignature: handlingBlock.valueSignature)
}
}
override func showHelpOnHFlag() -> Bool {
return shouldShowHelpOnHFlag
}
override func unrecognizedOptionsPrintingBehavior() -> UnrecognizedOptionsPrintingBehavior {
return printingBehaviorOnUnrecognizedOptions
}
override func failOnUnrecognizedOptions() -> Bool {
return shouldFailOnUnrecognizedOptions
}
// MARK: - Execution
override func execute() -> CommandResult {
return lightweightExecutionBlock!(arguments: arguments, options: options)
}
// MARK: - Option block wrappers
class LightweightCommandFlagOptionHandler {
let flags: [String]
let flagBlock: OptionsFlagBlock?
let usage: String
init(flags: [String], flagBlock: OptionsFlagBlock?, usage: String) {
self.flags = flags
self.flagBlock = flagBlock
self.usage = usage
}
}
class LightweightCommandKeyOptionHandler {
let keys: [String]
let keyBlock: OptionsKeyBlock?
let usage: String
let valueSignature: String
init(keys: [String], keyBlock: OptionsKeyBlock?, usage: String, valueSignature: String) {
self.keys = keys
self.keyBlock = keyBlock
self.usage = usage
self.valueSignature = valueSignature
}
}
}
| mit | e8ec45afaa083b77f31f29328795b0d1 | 31.598291 | 143 | 0.669114 | 5.282548 | false | false | false | false |
glorybird/KeepReading2 | kr/kr/ui/ReadListViewController.swift | 1 | 2829 | //
// ReadListViewController.swift
// kr
//
// Created by FanFamily on 16/1/20.
// Copyright © 2016年 glorybird. All rights reserved.
//
import UIKit
class ReadListViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, KrCollectionViewCellDelegate, UIScrollViewDelegate, SpringLayoutDelegate {
@IBOutlet weak var collectionView: UICollectionView!
var count:Int = 5
var downProgressCell:KrCollectionViewCell?
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
(collectionView as UIScrollView).delegate = self
collectionView.alwaysBounceVertical = true
collectionView.collectionViewLayout = SpringLayout()
(collectionView.collectionViewLayout as! SpringLayout).delegate = self
collectionView.registerNib(UINib(nibName: "KrCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "identifier")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cellIdentifier = "identifier"
let cell:KrCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath:indexPath) as! KrCollectionViewCell
cell.resetToNornalStatus()
cell.delegate = self
cell.layer.borderColor = UIColor.whiteColor().CGColor
cell.layer.borderWidth = 2
cell.layer.cornerRadius = 10
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return count
}
func didDownProgressView(cell: KrCollectionViewCell) {
if downProgressCell != nil {
downProgressCell!.resetToNornalStatus()
}
let index = collectionView.indexPathForCell(cell)
if index != nil {
let springLayout = (collectionView.collectionViewLayout as! SpringLayout)
springLayout.removeAllBehavior()
springLayout.installBehaviorsDropDown(CGFloat(index!.row), offset:cell.progressView!.frame.size.height + 10)
}
downProgressCell = cell
}
func didUpProgressView(cell: KrCollectionViewCell) {
let springLayout = (collectionView.collectionViewLayout as! SpringLayout)
springLayout.removeAllBehavior()
springLayout.installBehaviors(0.0)
downProgressCell = nil
}
func changeToNewBounds(newBounds: CGRect) {
if downProgressCell != nil {
downProgressCell!.resetToNornalStatus()
}
}
}
| apache-2.0 | a912613540f84d7924f99f3c6c598feb | 36.184211 | 176 | 0.701345 | 5.743902 | false | false | false | false |
Urinx/SublimeCode | Sublime/Sublime/Utils/Extension/Operation.swift | 1 | 784 | //
// Operation.swift
// Sublime
//
// Created by Eular on 4/20/16.
// Copyright © 2016 Eular. All rights reserved.
//
import Foundation
// MARK: - Operation
func + (left: Int, right: String) -> String {
return "\(left)"+right
}
func + (left: String, right: Int) -> String {
return left+"\(right)"
}
func * (left: String, right: Int) -> String {
var s = ""
for _ in 0..<right { s += left }
return s
}
func % (left: Int, right: Int) -> Int {
var tmp = left
tmp %= right
return tmp >= 0 ? tmp : tmp + right
}
func / (left: CGFloat, right: Int) -> CGFloat {
return left / CGFloat(right)
}
func * (left: CGFloat, right: Int) -> CGFloat {
return left * CGFloat(right)
}
func <<<T> (inout left: [T], right: T) {
left.append(right)
}
| gpl-3.0 | 78344504a2cf3cade76ad42b8ed1578b | 17.642857 | 48 | 0.572158 | 3.058594 | false | false | false | false |
bmbrina/BMCustomTableView | Pod/Classes/BMCustomTableView.swift | 1 | 1098 | //
// BMCustomTableView.swift
// Pods
//
// Created by Barbara Brina on 10/22/15.
//
//
import QuartzCore
public class BMCustomTableView : UITableView {
public func customizeCell(cell: UITableViewCell) {
var rotate: CATransform3D
let value = CGFloat((90.0 * M_PI) / 180.0)
rotate = CATransform3DMakeRotation(value, 0.0, 0.7, 0.4)
rotate.m34 = 1.0 / -600
cell.layer.shadowColor = UIColor.blackColor().CGColor
cell.layer.shadowOffset = CGSizeMake(10, 10)
cell.alpha = 0
cell.layer.transform = rotate
cell.layer.anchorPoint = CGPointMake(0, 0.5)
if(cell.layer.position.x != 0){
cell.layer.position = CGPointMake(0, cell.layer.position.y);
}
UIView.beginAnimations("rotate", context: nil)
UIView.setAnimationDuration(0.8)
cell.layer.transform = CATransform3DIdentity
cell.alpha = 1
cell.layer.shadowOffset = CGSizeMake(0, 0)
UIView.commitAnimations()
}
}
| mit | 468182dd6c18ad13245a9d9ae5f1126c | 25.142857 | 72 | 0.581967 | 4.174905 | false | false | false | false |
noxytrux/RescueKopter | RescueKopter/KPTModelManager.swift | 1 | 933 | //
// KPTModelManager.swift
// RescueKopter
//
// Created by Marcin Pędzimąż on 15.11.2014.
// Copyright (c) 2014 Marcin Pedzimaz. All rights reserved.
//
import UIKit
import Metal
class KPTModelManager {
static let sharedInstance = KPTModelManager()
private var modelsCache = [String: KPTModel]()
required init() {
}
func loadModel(name: String!, device: MTLDevice!) -> KPTModel? {
let model = modelsCache[name]
if let model = model {
return model
}
let loadedModel = KPTModel()
let info = loadedModel.load(name, device: device)
if info.loaded == false {
print("Error while loadin model: \(info.error!)");
return nil
}
modelsCache[name] = loadedModel
return loadedModel
}
}
| mit | 904680104088ac57c6d79b88678a3550 | 19.666667 | 68 | 0.533333 | 4.65 | false | false | false | false |
RylynnLai/V2EX--practise | V2EX/Nodes/RLNodesVC.swift | 1 | 2026 | //
// RLNodesVC.swift
// V2EX
//
// Created by LLZ on 16/3/24.
// Copyright © 2016年 ucs. All rights reserved.
//
import UIKit
class RLNodesVC: UIViewController {
private lazy var bubblesView:RLBubblesView = {
var bView = RLBubblesView.init(frame: UIScreen.mainScreen().bounds)
bView.nodeBtnAction = {[weak self] (nodeModel)->Void in
if let strongSelf = self {
let nodeTopicsTVC = RLNodeTopicsTVC.init(style: .Grouped)
nodeTopicsTVC.nodeModel = nodeModel
strongSelf.hidesBottomBarWhenPushed = true
strongSelf.navigationController?.pushViewController(nodeTopicsTVC, animated:true)
strongSelf.hidesBottomBarWhenPushed = false
}
}
return bView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.bubblesView)
loadData()
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.hidden = true
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.navigationBar.hidden = false
}
private func loadData() {
RLNetWorkManager.defaultNetWorkManager.requestWithPath("/api/nodes/all.json", success: {[weak self] (response) in
let allNodes = RLNode.mj_objectArrayWithKeyValuesArray(response)
let nodeModels:NSMutableSet = NSMutableSet.init(array: allNodes as [AnyObject])
for node in nodeModels{
if Int((node as! RLNode).topics!)! < 100 {//话题数目少于100条的不显示
nodeModels.removeObject(node)
}
}
if let strongSelf = self {
strongSelf.bubblesView.nodeModels = nodeModels
}
}, failure:{})
}
}
| mit | d817e9fdf18b9ff24dfef1ecff6d2534 | 32.35 | 121 | 0.618191 | 4.798561 | false | false | false | false |
Kushki/kushki-ios | Example/kushki-ios/QuestionsSecureValidationViewController.swift | 1 | 2062 | //
// QuestionsSecureValidationViewController.swift
// kushki-ios_Example
//
// Created by Bryan Lema on 9/11/19.
// Copyright © 2019 Kushki. All rights reserved.
//
import UIKit
import Kushki
class QuestionsSecureValidationViewController: UIViewController {
@IBOutlet weak var secureServiceIdField: UITextField!
@IBOutlet weak var secureServiceField: UITextField!
@IBOutlet weak var cityCodeField: UITextField!
@IBOutlet weak var stateCodeField: UITextField!
@IBOutlet weak var phoneField: UITextField!
@IBOutlet weak var expeditionDateField: UITextField!
@IBOutlet weak var ResponseView: UITextView!
var kushkiTransfer : Kushki?
let publicTransferMerchantId: String? = "a499dddde82b433f832f26f685cbe468"
override func viewDidLoad() {
super.viewDidLoad()
kushkiTransfer = Kushki(publicMerchantId: self.publicTransferMerchantId!,
currency: "COP",
environment: KushkiEnvironment.testing)
}
@IBAction func handleTouchUpInside(_ sender: Any) {
kushkiTransfer!.requestSecureValidation(cityCode: cityCodeField.text!, expeditionDate: expeditionDateField.text!, phone: phoneField.text!, secureService: secureServiceField.text!, secureServiceId: secureServiceIdField.text!, stateCode: stateCodeField.text!){questionnarie in
let message = questionnarie.isSuccessful() ?
questionnarie.questionnarieCode : questionnarie.code + ": " + questionnarie.message
DispatchQueue.main.async(execute: {
let alert = UIAlertController(title: "Kushki Token",
message: message,
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
self.present(alert, animated: true)
self.ResponseView.text = "Response questions subscription transfer token: \n\n" + message
})
}
}
}
| mit | 1a485e253803d3d8135cb7cb4618d236 | 46.930233 | 282 | 0.666667 | 4.954327 | false | false | false | false |
akosma/Swift-Presentation | PresentationKit/Demos/NinetyNineBeersDemo.swift | 1 | 1566 | final public class NinetyNineBeersDemo: BaseDemo {
override public var description : String {
return "This demo is a very personal take on the \"99 bottles of beer\" song and puzzle."
}
override public var URL : NSURL {
return NSURL(string: "http://rosettacode.org/wiki/99_Bottles_of_Beer")
}
override public func show() {
var beers = "🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺🍺"
var count = countElements(beers)
func sayGlasses(count: Int) -> String {
return count > 1 ? "\(count) glasses" : (count == 1 ? "1 glass" : "No more glasses")
}
while count >= 0 {
var glasses = sayGlasses(count)
println("\(glasses) of beer on the wall,")
println("\(glasses) of beer.")
if count > 0 {
beers = dropLast(beers)
count = countElements(beers)
var glasses = sayGlasses(count)
println("Take one down and pass it around,")
println("\(glasses) of beer on the wall.")
println(beers)
}
else {
break
}
}
}
}
| bsd-2-clause | 1f4693007ee0b9ed5ce769d84f128e69 | 34.25 | 121 | 0.470449 | 4.937743 | false | false | false | false |
natestedman/Endpoint | Endpoint/BaseURLEndpoint+Providers.swift | 1 | 1361 | // Endpoint
// Written in 2016 by Nate Stedman <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all copyright and
// related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with
// this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
import Foundation
extension BaseURLEndpoint where Self: HTTPMethodProvider
{
/**
A default implementation of `BaseURLEndpoint`'s requirement.
- parameter baseURL: The base URL.
*/
public func request(baseURL: URL) -> URLRequest?
{
var URL: Foundation.URL? = baseURL
if let provider = self as? RelativeURLStringProvider
{
URL = Foundation.URL(string: provider.relativeURLString, relativeTo: baseURL)
}
if let provider = self as? QueryItemsProvider
{
URL = URL?.transformWithComponents({ components in
components.queryItems = provider.queryItems
})
}
return URL?.buildRequest(
httpMethod: httpMethod,
headerFields: (self as? HeaderFieldsProvider)?.headerFields,
body: (self as? BodyProvider)?.body
)
}
}
| cc0-1.0 | c317bccaad14fabefaee37d91fffcda2 | 31.404762 | 89 | 0.661278 | 4.826241 | false | false | false | false |
eggswift/pull-to-refresh | Sources/Animator/ESRefreshHeaderAnimator.swift | 1 | 6539 | //
// ESRefreshHeaderView.swift
//
// Created by egg swift on 16/4/7.
// Copyright (c) 2013-2016 ESPullToRefresh (https://github.com/eggswift/pull-to-refresh)
// Icon from http://www.iconfont.cn
//
// 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 QuartzCore
import UIKit
open class ESRefreshHeaderAnimator: UIView, ESRefreshProtocol, ESRefreshAnimatorProtocol, ESRefreshImpactProtocol {
open var pullToRefreshDescription = NSLocalizedString("Pull to refresh", comment: "") {
didSet {
if pullToRefreshDescription != oldValue {
titleLabel.text = pullToRefreshDescription;
}
}
}
open var releaseToRefreshDescription = NSLocalizedString("Release to refresh", comment: "")
open var loadingDescription = NSLocalizedString("Loading...", comment: "")
open var view: UIView { return self }
open var insets: UIEdgeInsets = UIEdgeInsets.zero
open var trigger: CGFloat = 60.0
open var executeIncremental: CGFloat = 60.0
open var state: ESRefreshViewState = .pullToRefresh
fileprivate let imageView: UIImageView = {
let imageView = UIImageView.init()
let frameworkBundle = Bundle(for: ESRefreshAnimator.self)
if /* CocoaPods static */ let path = frameworkBundle.path(forResource: "ESPullToRefresh", ofType: "bundle"),let bundle = Bundle(path: path) {
imageView.image = UIImage(named: "icon_pull_to_refresh_arrow", in: bundle, compatibleWith: nil)
}else if /* Carthage */ let bundle = Bundle.init(identifier: "com.eggswift.ESPullToRefresh") {
imageView.image = UIImage(named: "icon_pull_to_refresh_arrow", in: bundle, compatibleWith: nil)
} else if /* CocoaPods */ let bundle = Bundle.init(identifier: "org.cocoapods.ESPullToRefresh") {
imageView.image = UIImage(named: "ESPullToRefresh.bundle/icon_pull_to_refresh_arrow", in: bundle, compatibleWith: nil)
} else /* Manual */ {
imageView.image = UIImage(named: "icon_pull_to_refresh_arrow")
}
return imageView
}()
fileprivate let titleLabel: UILabel = {
let label = UILabel.init(frame: CGRect.zero)
label.font = UIFont.systemFont(ofSize: 14.0)
label.textColor = UIColor.init(white: 0.625, alpha: 1.0)
label.textAlignment = .left
return label
}()
fileprivate let indicatorView: UIActivityIndicatorView = {
let indicatorView = UIActivityIndicatorView.init(style: .gray)
indicatorView.isHidden = true
return indicatorView
}()
public override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.text = pullToRefreshDescription
self.addSubview(imageView)
self.addSubview(titleLabel)
self.addSubview(indicatorView)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open func refreshAnimationBegin(view: ESRefreshComponent) {
indicatorView.startAnimating()
indicatorView.isHidden = false
imageView.isHidden = true
titleLabel.text = loadingDescription
imageView.transform = CGAffineTransform(rotationAngle: 0.000001 - CGFloat.pi)
}
open func refreshAnimationEnd(view: ESRefreshComponent) {
indicatorView.stopAnimating()
indicatorView.isHidden = true
imageView.isHidden = false
titleLabel.text = pullToRefreshDescription
imageView.transform = CGAffineTransform.identity
}
open func refresh(view: ESRefreshComponent, progressDidChange progress: CGFloat) {
// Do nothing
}
open func refresh(view: ESRefreshComponent, stateDidChange state: ESRefreshViewState) {
guard self.state != state else {
return
}
self.state = state
switch state {
case .refreshing, .autoRefreshing:
titleLabel.text = loadingDescription
self.setNeedsLayout()
break
case .releaseToRefresh:
titleLabel.text = releaseToRefreshDescription
self.setNeedsLayout()
self.impact()
UIView.animate(withDuration: 0.2, delay: 0.0, options: UIView.AnimationOptions(), animations: {
[weak self] in
self?.imageView.transform = CGAffineTransform(rotationAngle: 0.000001 - CGFloat.pi)
}) { (animated) in }
break
case .pullToRefresh:
titleLabel.text = pullToRefreshDescription
self.setNeedsLayout()
UIView.animate(withDuration: 0.2, delay: 0.0, options: UIView.AnimationOptions(), animations: {
[weak self] in
self?.imageView.transform = CGAffineTransform.identity
}) { (animated) in }
break
default:
break
}
}
open override func layoutSubviews() {
super.layoutSubviews()
let s = self.bounds.size
let w = s.width
let h = s.height
UIView.performWithoutAnimation {
titleLabel.sizeToFit()
titleLabel.center = CGPoint.init(x: w / 2.0, y: h / 2.0)
indicatorView.center = CGPoint.init(x: titleLabel.frame.origin.x - 16.0, y: h / 2.0)
imageView.frame = CGRect.init(x: titleLabel.frame.origin.x - 28.0, y: (h - 18.0) / 2.0, width: 18.0, height: 18.0)
}
}
}
| mit | 84cb6b565334790c50832976ae795b97 | 40.649682 | 149 | 0.655146 | 4.759098 | false | false | false | false |
YuantongL/Cross-Train | ICrossCommander/gallary.swift | 1 | 8607 | //
// gallary.swift
// ICrossCommander
//
// Created by Lyt on 12/22/14.
// Copyright (c) 2014 Lyt. All rights reserved.
//
//This class is the view of gallary
import Foundation
import SpriteKit
var grav:CGFloat = 0 //scrolling gravity count
var dograv = false
class gallary: SKScene {
var did = false; //Record if the first time enter the view
var back:SKSpriteNode! //Back button
var background:SKSpriteNode! //Background
var gallary_content:[SKSpriteNode] = []
override func didMoveToView(view: SKView) {
if(did == false){
did = true
self.scaleMode = SKSceneScaleMode.AspectFill
//Background
background = SKSpriteNode(texture:SKTexture(imageNamed:"background_gallary"))
background.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
background.setScale(0.91)
background.zPosition = 1
self.addChild(background)
//Back button
back = SKSpriteNode(texture: SKTexture(imageNamed: "back_icon"))
back.position = CGPoint(x:CGRectGetMidX(self.frame) - 460, y:CGRectGetMidY(self.frame) + 235)
back.zPosition = 6
back.setScale(2.6)
self.addChild(back)
var transit_fan:SKSpriteNode = SKSpriteNode(texture: SKTexture(imageNamed: "transit_zheng"))
transit_fan.position = CGPoint(x:CGRectGetMidX(self.frame) + 130, y:CGRectGetMidY(self.frame))
transit_fan.zPosition = 100
transit_fan.setScale(1.0)
self.addChild(transit_fan)
//Add 10 elements into the array
for i in 0...9{
var content:SKSpriteNode = SKSpriteNode(texture: SKTexture(imageNamed: "gallary_content"))
content.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGFloat(550 - i*130))
content.zPosition = 2
self.addChild(content)
var t:SKLabelNode = SKLabelNode(text: String(i))
content.addChild(t)
gallary_content.append(content)
}
transit_fan.runAction(SKAction.moveTo(CGPoint(x:CGRectGetMidX(self.frame) - 1200, y:CGRectGetMidY(self.frame)), duration: 0.5), completion: {()
transit_fan.removeFromParent()
})
}else{
var transit_fan:SKSpriteNode = SKSpriteNode(texture: SKTexture(imageNamed: "transit_zheng"))
transit_fan.position = CGPoint(x:CGRectGetMidX(self.frame) + 130, y:CGRectGetMidY(self.frame))
transit_fan.zPosition = 100
transit_fan.setScale(1.0)
self.addChild(transit_fan)
transit_fan.runAction(SKAction.moveTo(CGPoint(x:CGRectGetMidX(self.frame) - 1200, y:CGRectGetMidY(self.frame)), duration: 0.5), completion: {()
transit_fan.removeFromParent()
})
}
}
//----------------------Functions for touches----------------------
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
var touch:UITouch = touches.first as! UITouch
let pnow:CGPoint = touch.locationInNode(self)
let pold:CGPoint = touch.previousLocationInNode(self)
let tran:CGFloat = pnow.y - pold.y //If < zero, move upwards
if(tran < 0 && gallary_content[0].position.y > 550){
//Going upwards
if(gallary_content[0].position.y + tran < 550){
for k in 0...gallary_content.count - 1{
gallary_content[k].position = CGPoint(x: CGRectGetMidX(self.frame), y: CGFloat(550 - k*130))
}
}else{
grav = tran
for i in 0...gallary_content.count - 1{
gallary_content[i].position.y += tran
}
}
}else if(tran > 0 && gallary_content[gallary_content.count - 1].position.y < 200){
//Going downwards
if(gallary_content[gallary_content.count - 1].position.y + tran > 200){
for k in 0...gallary_content.count - 1{
gallary_content[k].position = CGPoint(x: CGRectGetMidX(self.frame), y: CGFloat(200 + (gallary_content.count - 1 - k)*130))
}
}else{
grav = tran
for i in 0...gallary_content.count - 1{
gallary_content[i].position.y += tran
}
}
}
if(grav < -50){
grav = -50
}else if(grav > 50){
grav = 50
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
dograv = true
back.texture = SKTexture(imageNamed: "back_icon")
var tnode:SKSpriteNode = self.nodeAtPoint((touches.first as! UITouch).locationInNode(self)) as! SKSpriteNode
if(tnode.isEqual(back)){
//back to main
var transit_zheng:SKSpriteNode = SKSpriteNode(texture: SKTexture(imageNamed: "transit_zheng"))
transit_zheng.position = CGPoint(x:CGRectGetMidX(self.frame) - 1200, y:CGRectGetMidY(self.frame))
transit_zheng.zPosition = 100
transit_zheng.setScale(1.0)
self.addChild(transit_zheng)
transit_zheng.runAction(SKAction.moveTo(CGPoint(x:CGRectGetMidX(self.frame) + 160, y:CGRectGetMidY(self.frame)), duration: 0.5), completion: {()
//Set back the content places
grav = 0
for k in 0...self.gallary_content.count - 1{
self.gallary_content[k].position = CGPoint(x: CGRectGetMidX(self.frame), y: CGFloat(550 - k*130))
}
Bank.storeScene(self, x: 3)
self.view?.presentScene(Bank.getScene(1))
transit_zheng.removeFromParent()
})
}
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
dograv = false
var tnode:SKSpriteNode = self.nodeAtPoint((touches.first as! UITouch).locationInNode(self)) as! SKSpriteNode
if(tnode.isEqual(back)){
back.texture = SKTexture(imageNamed: "back_icon_t")
}
}
//----------------------End of touch functions----------------------
//This function was called each frame
override func update(currentTime: CFTimeInterval) {
//This function is used to implement scrolling gravity
if(dograv == true){
if(grav > 0){
//Go upwards
if(gallary_content[gallary_content.count - 1].position.y < 200){
if(gallary_content[gallary_content.count - 1].position.y + grav > 200){
for k in 0...gallary_content.count - 1{
gallary_content[k].position = CGPoint(x: CGRectGetMidX(self.frame), y: CGFloat(200 + (gallary_content.count - 1 - k)*130))
}
grav = 0
}else{
for k in 0...gallary_content.count - 1{
gallary_content[k].position = CGPoint(x: CGRectGetMidX(self.frame), y: gallary_content[k].position.y + grav)
}
grav -= 2.0
if(grav < 0){
grav = 0
}
}
}else{
grav = 0
}
}else if(grav < 0){
//Go down
if(gallary_content[0].position.y > 550){
if(gallary_content[0].position.y + grav < 550){
for k in 0...gallary_content.count - 1{
gallary_content[k].position = CGPoint(x: CGRectGetMidX(self.frame), y: CGFloat(550 - k*130))
}
grav = 0
}else{
for k in 0...gallary_content.count - 1{
gallary_content[k].position = CGPoint(x: CGRectGetMidX(self.frame), y: gallary_content[k].position.y + grav)
}
grav += 2.0
if(grav > 0){
grav = 0
}
}
}else{
grav = 0
}
}
}
}
}
| mit | b018eb43e492afce535b42e16b1b33fc | 39.219626 | 156 | 0.518183 | 4.657468 | false | false | false | false |
Div99/2048-Swift3 | 2048/ViewController.swift | 1 | 10903 | //
// ViewController.swift
// 2048
//
// Created by Divyansh Garg on 11/23/16.
// Copyright © 2016 Divyansh. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate {
var collectionview: UICollectionView!
var headerview: HeaderView!
var GameModel: Model!
let auto = AutoMove()
var tiles : [[TileView]] = []
let radius: CGFloat = 3
let slideTime: CGFloat = 0.2
let flashTime: CGFloat = 0.1
let tilePopMaxScale: CGFloat = 1.1
let tileMergeExpandTime: TimeInterval = 0.08
let tileMergeContractTime: TimeInterval = 0.08
override func viewDidLoad() {
super.viewDidLoad()
GameModel = Model()
GameModel.addNewTile()
tiles = Array(repeating: Array(repeating: TileView(), count: Model.size), count: Model.size)
let layout = UICollectionViewFlowLayout()
layout.headerReferenceSize = CGSize(width: view.frame.width, height: 100)
collectionview = UICollectionView(frame: view.frame, collectionViewLayout: layout)
// Register cell classes
collectionview.register(TileView.self, forCellWithReuseIdentifier: reuseIdentifier)
collectionview.register(HeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerView")
collectionview.backgroundColor = .gray
collectionview.dataSource = self
collectionview.delegate = self
view.addSubview(collectionview)
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeRight.direction = UISwipeGestureRecognizerDirection.right
self.view.addGestureRecognizer(swipeRight)
let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeDown.direction = UISwipeGestureRecognizerDirection.down
self.view.addGestureRecognizer(swipeDown)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeLeft.direction = UISwipeGestureRecognizerDirection.left
self.view.addGestureRecognizer(swipeLeft)
let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeUp.direction = UISwipeGestureRecognizerDirection.up
self.view.addGestureRecognizer(swipeUp)
}
override func viewDidAppear(_ animated: Bool) {
showTile(tile: GameModel.initialTilePos)
fillBackground()
}
func fillBackground() {
for r in 0 ..< Model.size {
for c in 0 ..< Model.size {
let cell = tiles[r][c]
let x = cell.frame.minX
let y = cell.frame.minY
let size = cell.frame.width
let background = UIView(frame: CGRect(x: x, y: y, width: size, height: size))
background.layer.cornerRadius = radius
background.backgroundColor = .lightGray
collectionview.addSubview(background)
collectionview.sendSubview(toBack: background)
}
}
}
func showTile(tile: (Model.Location, Int)) {
let cell = tiles[tile.0.row][tile.0.col]
cell.setValue(v: tile.1)
}
func doMove(dx: Int, dy: Int) {
let moves: [Model.Move] = GameModel.doMove(dx: dx, dy: dy)
for m in moves {
let origFrame = tiles[m.from.row][m.from.col].frame
let finalFrame = tiles[m.to.row][m.to.col].frame
UIView.animate(withDuration: TimeInterval(slideTime),
delay: 0.0,
animations: {
// Slide tile
self.tiles[m.from.row][m.from.col].frame = finalFrame
},
completion: { (finished: Bool) -> Void in
self.displayTiles(m: m, f: origFrame)
self.showNewTile()
if(m.merge) {
if(self.GameModel.tiles[m.to.row][m.to.col] == 2048) {
self.userWon()
}
self.mergeAnimation(m: m)
}
})
}
}
func displayTiles(m: Model.Move, f: CGRect) {
let tile0 = tiles[m.from.row][m.from.col]
let tile1 = tiles[m.to.row][m.to.col]
tile0.setValue(v: self.GameModel.tile(r: m.from.row, c: m.from.col))
tile1.setValue(v: self.GameModel.tile(r: m.to.row, c: m.to.col))
tile0.frame = f
}
func showNewTile() {
let r = GameModel.initialTilePos.0.row
let c = GameModel.initialTilePos.0.col
let tile = tiles[r][c]
tile.setValue(v: GameModel.initialTilePos.1)
}
func mergeAnimation(m: Model.Move) {
let tile = tiles[m.to.row][m.to.col]
// Pop tile
UIView.animate(withDuration: self.tileMergeExpandTime,
animations: {
tile.layer.setAffineTransform(CGAffineTransform(scaleX: self.tilePopMaxScale, y: self.tilePopMaxScale))
self.headerview.setScore(score: self.GameModel.score)
},
completion: { finished in
// Contract tile to original size
UIView.animate(withDuration: self.tileMergeContractTime) {
tile.layer.setAffineTransform(CGAffineTransform.identity)
}
})
}
func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if(GameModel.gameOver) {
gameOver()
}
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
//print("Swiped right")
doMove(dx: 1, dy: 0)
break
case UISwipeGestureRecognizerDirection.down:
//print("Swiped down")
doMove(dx: 0, dy: 1)
break
case UISwipeGestureRecognizerDirection.left:
//print("Swiped left")
doMove(dx: -1, dy: 0)
break
case UISwipeGestureRecognizerDirection.up:
// print("Swiped up")
doMove(dx: 0, dy: -1)
break
default:
break
}
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 16
}
func userWon() {
let alert = UIAlertController(title: "You are the king of the World", message: "", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Worthy", style: UIAlertActionStyle.default, handler: {(action:UIAlertAction) in
self.reset() }));
alert.addAction(UIAlertAction(title: "Not worthy", style: UIAlertActionStyle.default, handler: {(action:UIAlertAction) in exit(0) }));
self.present(alert, animated: true, completion: nil)
}
func gameOver() {
let alert = UIAlertController(title: "YOU LOST !!!", message: "Would you like to try again ?", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Retry", style: UIAlertActionStyle.default, handler: {(action:UIAlertAction) in
self.reset() }));
alert.addAction(UIAlertAction(title: "Defeated", style: UIAlertActionStyle.default, handler: {(action:UIAlertAction) in exit(0) }));
self.present(alert, animated: true, completion: nil)
}
func reset() {
GameModel = Model()
GameModel.addNewTile()
headerview.setScore(score: 0)
for r in 0 ..< Model.size {
for c in 0 ..< Model.size {
tiles[r][c].setValue(v: GameModel.tile(r: r, c: c))
}
}
}
func tapped() {
let d = auto.bestMove(g: GameModel, depth: 2)
if let a = d {
doMove(dx: a.dx, dy: a.dy)
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! TileView
cell.layer.masksToBounds = true
cell.layer.cornerRadius = radius
let col = indexPath.item % 4
let row = (indexPath.item - col) / 4
tiles[row][col] = cell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 70, left: 10, bottom: 0, right: 10)
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerView", for: indexPath) as! HeaderView
headerView.frame.size.height = 100
headerview = headerView
let tap = UITapGestureRecognizer(target: self, action: #selector(tapped))
//tap.numberOfTapsRequired = 3
headerView.scoreLabel.addGestureRecognizer(tap)
return headerView
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let separator: CGFloat = 6.0 * 3.0
let size = (view.frame.width - separator - 20) / 4.0
return CGSize(width: size, height: size)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 6
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 6
}
}
| mit | 22ec371c0d70cf871ad9589c84e3e798 | 39.080882 | 184 | 0.5898 | 5.191429 | false | false | false | false |
YoungGary/Sina | Sina/Sina/Classes/Message消息/MessageViewController.swift | 1 | 3053 | //
// MessageViewController.swift
// Sina
//
// Created by YOUNG on 16/9/4.
// Copyright © 2016年 Young. All rights reserved.
//
import UIKit
class MessageViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
visitorView.setupVisitorViewInfo("visitordiscover_image_message", text: "登录后,别人评论你的微薄,给你发消息,都会在这里收到通知")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 3e8bec53ece12840503cc917e184323a | 31.967033 | 157 | 0.683333 | 5.424955 | false | false | false | false |
xedin/swift | stdlib/public/core/UTF32.swift | 1 | 2454 | //===--- UTF32.swift ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension Unicode {
@frozen
public enum UTF32 {
case _swift3Codec
}
}
extension Unicode.UTF32 : Unicode.Encoding {
public typealias CodeUnit = UInt32
public typealias EncodedScalar = CollectionOfOne<UInt32>
@inlinable
internal static var _replacementCodeUnit: CodeUnit {
@inline(__always) get { return 0xFFFD }
}
@inlinable
public static var encodedReplacementCharacter : EncodedScalar {
return EncodedScalar(_replacementCodeUnit)
}
@inlinable
@inline(__always)
public static func _isScalar(_ x: CodeUnit) -> Bool {
return true
}
/// Returns whether the given code unit represents an ASCII scalar
@_alwaysEmitIntoClient
public static func isASCII(_ x: CodeUnit) -> Bool {
return x <= 0x7F
}
@inlinable
@inline(__always)
public static func decode(_ source: EncodedScalar) -> Unicode.Scalar {
return Unicode.Scalar(_unchecked: source.first!)
}
@inlinable
@inline(__always)
public static func encode(
_ source: Unicode.Scalar
) -> EncodedScalar? {
return EncodedScalar(source.value)
}
@frozen
public struct Parser {
@inlinable
public init() { }
}
public typealias ForwardParser = Parser
public typealias ReverseParser = Parser
}
extension UTF32.Parser : Unicode.Parser {
public typealias Encoding = Unicode.UTF32
/// Parses a single Unicode scalar value from `input`.
@inlinable
public mutating func parseScalar<I : IteratorProtocol>(
from input: inout I
) -> Unicode.ParseResult<Encoding.EncodedScalar>
where I.Element == Encoding.CodeUnit {
let n = input.next()
if _fastPath(n != nil), let x = n {
// Check code unit is valid: not surrogate-reserved and within range.
guard _fastPath((x &>> 11) != 0b1101_1 && x <= 0x10ffff)
else { return .error(length: 1) }
// x is a valid scalar.
return .valid(UTF32.EncodedScalar(x))
}
return .emptyInput
}
}
| apache-2.0 | bfd97043029cde4ead8e883c3921e19d | 26.573034 | 80 | 0.647514 | 4.461818 | false | false | false | false |
Za1006/TIY-Assignments | OutaTime/TimeCircuitsViewController.swift | 1 | 2695 | //
// ViewController.swift
// Gigawatts
//
// Created by Elizabeth Yeh on 10/8/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
@objc protocol DatePickerDelegate
{
func destinationDateWasChosen(destinationCount: NSDate)
}
class TimeCircutsViewController: UIViewController, DatePickerDelegate
{
@IBOutlet var destinationTimeLabel: UILabel!
let dateFormat: String!
// NSDateFormatter?
// let dateFormatter = NSDateFormatter()
// dateFormatter.dateFormat = "mm-dd-yyyy"
// return date!
@IBOutlet var setAndStopDestinationButton: UIButton!
@IBOutlet var lastTimeDepartureLabel: UILabel!
@IBOutlet var speedLabel: UILabel!
@IBOutlet var presentTimeLabel: UILabel!
var originalCount = 88
var currentSpeed = 0
// unable to set @IBOutlet from storyboard
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func destinationDateWasChosen(destinationDateWasChosen: NSDate)
{
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "ShowDatePickerSegue"
{
let datePickerVC = segue.destinationViewController as DatePickerViewController
datePickerVC.delegate = self
}
}
}
// MARK: - DatePicker Delegate
func destinationDateWasChosen(destinationCount: NSDate)
// func destinationDateWasChosen(destinationCount: NSDate)
{
// destinationTimeLabel.text = dateFormatter.stringFromDate
// (dateFormat into a string: dateFormatter.stringFromDate. see Quiz)
}
// MARK: - Action Handlers
@IBAction func setDesticationTapped(sender: UIButton)
{
}
@IBAction func travelBackTapped(sender: UIButton)
{
startTimer()
}
// MARK: - Private
private func startTimer()
{
if timer == nil
{
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updatespeedLabel", userInfo: nil, repeats: true)
// setAndStopDestinationButton.setTitle("Pause", forState: UIControlState.Normal)
}
func updateSpeedLabel()
{
if currentSpeed != 88
{
currentSpeed += 1
speedLabel.text = String(currentspeed)
}
else
{
stopTimer()
lastTimeDepartureLabel.text = presentTimeLabel.text
presentTimeLabel.text = destinationTimeLabel.text
}
}
} | cc0-1.0 | e0a8bbd2149f0b9bf4c5ab27e264f762 | 22.434783 | 133 | 0.66778 | 4.810714 | false | false | false | false |
SmallwolfiOS/ChangingToSwift | ChangingToSwift01/ChangingToSwift01/ViewController.swift | 1 | 2741 | //
// ViewController.swift
// ChangingToSwift01
//
// Created by 马海平 on 16/5/25.
// Copyright © 2016年 MHP. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var dataArray = ["打电话","发短信","发邮件","用Safari打开网址","拓展"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
changeBackgroundColor()
self.tableView.tableFooterView = UIView.init()//影藏多余的cell
}
func changeBackgroundColor() {
self.view.backgroundColor = UIColor.whiteColor()
}
//MARK:函数标签
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
//TODO:要做的函数标签
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
//FIXME:修复bug
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
cell.textLabel?.text = String.init(format: "%@", dataArray[indexPath.row])
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("点击了第\(indexPath.section)组第\(indexPath.row)行")
ActionForCellWithIndexPath(indexPath)
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 60
}
func ActionForCellWithIndexPath(indexPath:NSIndexPath) {
switch indexPath.row {
case 0:
print("点击了打电话")
HP_Util.callNumberEndBackUpSuggest("18810901468", view: self.view)
case 1:
HP_Util.messageTo("18810901468")
case 2:
HP_Util.emailTo("[email protected]")
case 3:
HP_Util.openInSafariUrl("http://www.baidu.com")
case 4:
performSegueWithIdentifier("PushToDetail", sender: self.dataArray[indexPath.row])
default:
break
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let strValue = sender as! String
if segue.identifier == "PushToDetail" {
let pushVC = segue.destinationViewController
pushVC.title = strValue
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 21af3090cd5cc6103e8922cf59c3e222 | 30.404762 | 109 | 0.644428 | 4.831502 | false | false | false | false |
TrustWallet/trust-wallet-ios | Trust/Wallet/ViewControllers/ImportWalletViewController.swift | 1 | 11063 | // Copyright DApps Platform Inc. All rights reserved.
import UIKit
import Eureka
import TrustCore
import QRCodeReaderViewController
protocol ImportWalletViewControllerDelegate: class {
func didImportAccount(account: WalletInfo, fields: [WalletInfoField], in viewController: ImportWalletViewController)
}
final class ImportWalletViewController: FormViewController {
let keystore: Keystore
let coin: Coin
private lazy var viewModel: ImportWalletViewModel = {
return ImportWalletViewModel(coin: coin)
}()
struct Values {
static let segment = "segment"
static let keystore = "keystore"
static let privateKey = "privateKey"
static let password = "password"
static let name = "name"
static let watch = "watch"
static let phrase = "phrase"
}
var segmentRow: SegmentedRow<String>? {
return form.rowBy(tag: Values.segment)
}
var keystoreRow: TextAreaRow? {
return form.rowBy(tag: Values.keystore)
}
var phraseRow: TextAreaRow? {
return form.rowBy(tag: Values.phrase)
}
var privateKeyRow: TextAreaRow? {
return form.rowBy(tag: Values.privateKey)
}
var passwordRow: TextFloatLabelRow? {
return form.rowBy(tag: Values.password)
}
var addressRow: TextFloatLabelRow? {
return form.rowBy(tag: Values.watch)
}
var nameRow: TextFloatLabelRow? {
return form.rowBy(tag: Values.name)
}
weak var delegate: ImportWalletViewControllerDelegate?
init(
keystore: Keystore,
for coin: Coin
) {
self.keystore = keystore
self.coin = coin
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
title = viewModel.title
navigationItem.rightBarButtonItems = [
UIBarButtonItem(image: R.image.qr_code_icon(), style: .done, target: self, action: #selector(openReader)),
]
if UserDefaults.standard.bool(forKey: "FASTLANE_SNAPSHOT") {
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.demo()
}
}
let recipientRightView = AddressFieldView()
recipientRightView.translatesAutoresizingMaskIntoConstraints = false
recipientRightView.pasteButton.addTarget(self, action: #selector(pasteAddressAction), for: .touchUpInside)
recipientRightView.qrButton.addTarget(self, action: #selector(openReader), for: .touchUpInside)
let initialName = WalletInfo.initialName(index: keystore.wallets.count)
form
+++ Section()
<<< SegmentedRow<String>(Values.segment) {
$0.options = [
ImportSelectionType.mnemonic.title,
ImportSelectionType.keystore.title,
ImportSelectionType.privateKey.title,
ImportSelectionType.address.title,
]
$0.value = ImportSelectionType.mnemonic.title
}
// Keystore JSON
+++ Section(footer: ImportSelectionType.keystore.footerTitle) {
$0.hidden = Eureka.Condition.function([Values.segment], { [weak self] _ in
return self?.segmentRow?.value != ImportSelectionType.keystore.title
})
}
<<< AppFormAppearance.textArea(tag: Values.keystore) { [weak self] in
$0.placeholder = self?.viewModel.keystorePlaceholder
$0.textAreaHeight = .fixed(cellHeight: 140)
$0.add(rule: RuleRequired())
}
<<< AppFormAppearance.textFieldFloat(tag: Values.password) {
$0.validationOptions = .validatesOnDemand
}.cellUpdate { cell, _ in
cell.textField.isSecureTextEntry = true
cell.textField.textAlignment = .left
cell.textField.placeholder = R.string.localizable.password()
}
// Private Key
+++ Section(footer: ImportSelectionType.privateKey.footerTitle) {
$0.hidden = Eureka.Condition.function([Values.segment], { [weak self] _ in
return self?.segmentRow?.value != ImportSelectionType.privateKey.title
})
}
<<< AppFormAppearance.textArea(tag: Values.privateKey) { [weak self] in
$0.placeholder = self?.viewModel.privateKeyPlaceholder
$0.textAreaHeight = .fixed(cellHeight: 140)
$0.add(rule: RuleRequired())
$0.add(rule: PrivateKeyRule())
}
// Mnemonic
+++ Section(footer: ImportSelectionType.mnemonic.footerTitle) {
$0.hidden = Eureka.Condition.function([Values.segment], { [weak self] _ in
return self?.segmentRow?.value != ImportSelectionType.mnemonic.title
})
}
<<< AppFormAppearance.textArea(tag: Values.phrase) { [weak self] in
$0.placeholder = self?.viewModel.mnemonicPlaceholder
$0.textAreaHeight = .fixed(cellHeight: 140)
$0.add(rule: RuleRequired())
$0.cell.textView?.autocapitalizationType = .none
}
// Watch
+++ Section(footer: ImportSelectionType.address.footerTitle) {
$0.hidden = Eureka.Condition.function([Values.segment], { [weak self] _ in
return self?.segmentRow?.value != ImportSelectionType.address.title
})
}
<<< AppFormAppearance.textFieldFloat(tag: Values.watch) {
$0.add(rule: RuleRequired())
$0.add(rule: EthereumAddressRule())
}.cellUpdate { [weak self] cell, _ in
cell.textField.placeholder = self?.viewModel.watchAddressPlaceholder
cell.textField.rightView = recipientRightView
cell.textField.rightViewMode = .always
}
// Name
+++ Section()
<<< AppFormAppearance.textFieldFloat(tag: Values.name) {
$0.value = initialName
}.cellUpdate { cell, _ in
cell.textField.textAlignment = .left
cell.textField.placeholder = R.string.localizable.name()
}
+++ Section()
<<< ButtonRow(NSLocalizedString("importWallet.import.button.title", value: "Import", comment: "")) {
$0.title = $0.tag
}.onCellSelection { [weak self] _, _ in
self?.importWallet()
}
}
func didImport(account: WalletInfo, name: String) {
delegate?.didImportAccount(account: account, fields: [
.name(name),
.backup(true),
], in: self)
}
func importWallet() {
let validatedError = keystoreRow?.section?.form?.validate()
guard let errors = validatedError, errors.isEmpty else { return }
let validatedAdressError = addressRow?.section?.form?.validate()
guard let addressErrors = validatedAdressError, addressErrors.isEmpty else { return }
let keystoreInput = keystoreRow?.value?.trimmed ?? ""
let privateKeyInput = privateKeyRow?.value?.trimmed ?? ""
let password = passwordRow?.value ?? ""
let addressInput = addressRow?.value?.trimmed ?? ""
let phraseInput = phraseRow?.value?.trimmed ?? ""
let name = nameRow?.value?.trimmed ?? ""
let words = phraseInput.components(separatedBy: " ").map { $0.trimmed.lowercased() }
displayLoading(text: NSLocalizedString("importWallet.importingIndicator.label.title", value: "Importing wallet...", comment: ""), animated: false)
let type = ImportSelectionType(title: segmentRow?.value)
let importType: ImportType = {
switch type {
case .keystore:
return .keystore(string: keystoreInput, password: password)
case .privateKey:
return .privateKey(privateKey: privateKeyInput)
case .mnemonic:
return .mnemonic(words: words, password: password, derivationPath: coin.derivationPath(at: 0))
case .address:
let address = EthereumAddress(string: addressInput)! // EthereumAddress validated by form view.
return .address(address: address)
}
}()
keystore.importWallet(type: importType, coin: coin) { result in
self.hideLoading(animated: false)
switch result {
case .success(let account):
self.didImport(account: account, name: name)
case .failure(let error):
self.displayError(error: error)
}
}
}
@objc func demo() {
//Used for taking screenshots to the App Store by snapshot
let demoWallet = WalletType.address(Coin.ethereum, EthereumAddress(string: "0xD663bE6b87A992C5245F054D32C7f5e99f5aCc47")!)
let walletInfo = WalletInfo(type: demoWallet, info: WalletObject.from(demoWallet))
delegate?.didImportAccount(account: walletInfo, fields: [], in: self)
}
@objc func openReader() {
let controller = QRCodeReaderViewController()
controller.delegate = self
present(controller, animated: true, completion: nil)
}
func setValueForCurrentField(string: String) {
let type = ImportSelectionType(title: segmentRow?.value)
switch type {
case .keystore:
keystoreRow?.value = string
case .privateKey:
privateKeyRow?.value = string
case .address:
guard let result = QRURLParser.from(string: string) else { return }
addressRow?.value = result.address
case .mnemonic:
phraseRow?.value = string
}
tableView.reloadData()
}
@objc func pasteAddressAction() {
let value = UIPasteboard.general.string?.trimmed
addressRow?.value = value
tableView.reloadData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension ImportWalletViewController: QRCodeReaderDelegate {
func readerDidCancel(_ reader: QRCodeReaderViewController!) {
reader.stopScanning()
reader.dismiss(animated: true, completion: nil)
}
func reader(_ reader: QRCodeReaderViewController!, didScanResult result: String!) {
reader.stopScanning()
setValueForCurrentField(string: result)
reader.dismiss(animated: true)
}
}
extension WalletInfo {
static var emptyName: String {
return "Unnamed " + R.string.localizable.wallet()
}
static func initialName(index numberOfWallets: Int) -> String {
if numberOfWallets == 0 {
return R.string.localizable.mainWallet()
}
return String(format: "%@ %@", R.string.localizable.wallet(), "\(numberOfWallets + 1)"
)
}
}
| gpl-3.0 | b9628ac047340aa1b08afc82e54ba3fd | 37.681818 | 154 | 0.601555 | 4.98109 | false | false | false | false |
Weebly/Cereal | Example/EditTrainViewController.swift | 2 | 1579 | //
// EditTrainViewController.swift
// Cereal
//
// Created by James Richard on 9/30/15.
// Copyright © 2015 Weebly. All rights reserved.
//
import UIKit
protocol EditTrainViewControllerDelegate: class {
func editTrainViewController(_ editTrainViewController: EditTrainViewController, didSaveTrain train: Train)
}
class EditTrainViewController: UIViewController {
var train: Train!
weak var delegate: EditTrainViewControllerDelegate?
@IBOutlet var makeTextField: UITextField!
@IBOutlet var modelTextField: UITextField!
@IBOutlet var carsLabel: UILabel!
@IBOutlet var stepperView: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
makeTextField.text = train.make
modelTextField.text = train.model
carsLabel.text = String(train.cars)
stepperView.value = Double(train.cars)
}
@IBAction func savePressed() {
delegate?.editTrainViewController(self, didSaveTrain: train)
performSegue(withIdentifier: "UnwindToVehicleList", sender: self)
}
@IBAction func textValueChanged(_ textField: UITextField) {
switch textField {
case makeTextField: train = Train(make: textField.text ?? "", model: train.model, cars: train.cars)
case modelTextField: train = Train(make: train.make, model: textField.text ?? "", cars: train.cars)
default: break
}
}
@IBAction func cylindersStepperChanged(_ stepper: UIStepper) {
let cars = Int(stepper.value)
train.cars = cars
carsLabel.text = String(cars)
}
}
| bsd-3-clause | 215a4e9c1e002e091b1a9cd7e0fe59d7 | 31.204082 | 111 | 0.690748 | 4.534483 | false | false | false | false |
nathawes/swift | test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-stdlib_equatable-1distinct_use.swift | 19 | 1449 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %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-NOT: @"$s4main5ValueOyAA7IntegerVGMf"
enum Value<First : Equatable> {
case first(First)
}
struct Integer : Equatable {
let value: Int
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
func doit() {
consume( Value.first(Integer(value: 13)) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, %swift.type* %1, i8** %2) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_CONFORMANCE:%[0-9]+]] = bitcast i8** %2 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_TYPE]],
// CHECK-SAME: i8* [[ERASED_CONFORMANCE]],
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | 1853774f9b473c31433b1f13ea59c8a8 | 32.697674 | 157 | 0.628019 | 3.006224 | false | false | false | false |
nathawes/swift | test/Incremental/PrivateDependencies/reference-dependencies-dynamic-lookup-fine.swift | 15 | 2813 | // REQUIRES: shell
// Also uses awk:
// XFAIL OS=windows
// RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -primary-file %t/main.swift -emit-reference-dependencies-path - > %t.swiftdeps
// Check that the output is deterministic.
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -primary-file %t/main.swift -emit-reference-dependencies-path - > %t-2.swiftdeps
// RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t.swiftdeps %t-processed.swiftdeps
// RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t-2.swiftdeps %t-2-processed.swiftdeps
// RUN: diff %t-processed.swiftdeps %t-2-processed.swiftdeps
// RUN: %FileCheck %s < %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=NEGATIVE %s < %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=DUPLICATE %s < %t-processed.swiftdeps
// REQUIRES: objc_interop
import Foundation
@objc @objcMembers class Base : NSObject {
// CHECK-DAG: dynamicLookup implementation '' foo true
// CHECK-DAG: dynamicLookup interface '' foo true
func foo() {}
// CHECK-DAG: dynamicLookup implementation '' bar true
// CHECK-DAG: dynamicLookup interface '' bar true
// DUPLICATE-NOT: dynamicLookup implementation '' bar true
// DUPLICATE: dynamicLookup implementation '' bar true
// DUPLICATE-NOT: dynamicLookup implementation '' bar true
// DUPLICATE-NOT: dynamicLookup interface '' bar true
// DUPLICATE: dynamicLookup interface '' bar true
// DUPLICATE-NOT: dynamicLookup interface '' bar true
func bar(_ x: Int, y: Int) {}
func bar(_ str: String) {}
// CHECK-DAG: dynamicLookup implementation '' prop true
// CHECK-DAG: dynamicLookup interface '' prop true
var prop: String?
// CHECK-DAG: dynamicLookup implementation '' unusedProp true
// CHECK-DAG: dynamicLookup interface '' unusedProp true
var unusedProp: Int = 0
// CHECK-DAG: dynamicLookup implementation '' classFunc true
// CHECK-DAG: dynamicLookup interface '' classFunc true
class func classFunc() {}
}
func getAnyObject() -> AnyObject? { return nil }
func testDynamicLookup(_ obj: AnyObject) {
// CHECK-DAG: dynamicLookup interface '' description false
_ = obj.description
// CHECK-DAG: dynamicLookup interface '' method false
_ = obj.method(5, with: 5.0 as Double)
// TODO: unable to resolve ambiguity
// C/HECK-DAG: dynamicLookup interface '' subscript false
// _ = obj[2] as Any
// _ = obj[2] as Any!
}
// CHECK-DAG: dynamicLookup interface '' counter false
let globalUse = getAnyObject()?.counter
// NEGATIVE-NOT: dynamicLookup interface '' cat1Method false
// NEGATIVE-NOT: dynamicLookup interface '' unusedProp false
| apache-2.0 | 035a1a5cf08025c6b405b38d5e137cc9 | 37.534247 | 153 | 0.701386 | 3.760695 | false | false | false | false |
gowansg/firefox-ios | Client/Frontend/Browser/SearchLoader.swift | 1 | 3765 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
private let URLBeforePathRegex = NSRegularExpression(pattern: "^https?://([^/]+/)", options: nil, error: nil)!
// TODO: Swift currently requires that classes extending generic classes must also be generic.
// This is a workaround until that requirement is fixed.
typealias SearchLoader = _SearchLoader<AnyObject, AnyObject>
/**
* Shared data source for the SearchViewController and the URLBar domain completion.
* Since both of these use the same SQL query, we can perform the query once and dispatch the results.
*/
class _SearchLoader<UnusedA, UnusedB>: Loader<Cursor, SearchViewController> {
private let history: BrowserHistory
private let urlBar: URLBarView
init(history: BrowserHistory, urlBar: URLBarView) {
self.history = history
self.urlBar = urlBar
super.init()
}
var query: String = "" {
didSet {
if query.isEmpty {
self.load(Cursor(status: .Success, msg: "Empty query"))
return
}
let options = QueryOptions(filter: query, filterType: FilterType.Url, sort: QuerySort.Frecency)
self.history.get(options, complete: { (cursor: Cursor) in
if cursor.status != .Success {
println("Err: \(cursor.statusMessage)")
} else {
self.load(cursor)
self.urlBar.setAutocompleteSuggestion(self.getAutocompleteSuggestion(cursor))
}
})
}
}
private func getAutocompleteSuggestion(cursor: Cursor) -> String? {
for result in cursor {
let url = (result as! Site).url
// Extract the pre-path substring from the URL. This should be more efficient than parsing via
// NSURL since we need to only look at the beginning of the string.
// Note that we won't match non-HTTP(S) URLs.
if let match = URLBeforePathRegex.firstMatchInString(url, options: nil, range: NSRange(location: 0, length: count(url))) {
// If the pre-path component starts with the filter, just use it as is.
let prePathURL = (url as NSString).substringWithRange(match.rangeAtIndex(0))
if prePathURL.startsWith(query) {
return prePathURL
}
// Otherwise, find and use any matching domain.
// To simplify the search, prepend a ".", and search the string for ".query".
// For example, for http://en.m.wikipedia.org, domainWithDotPrefix will be ".en.m.wikipedia.org".
// This allows us to use the "." as a separator, so we can match "en", "m", "wikipedia", and "org",
let domain = (url as NSString).substringWithRange(match.rangeAtIndex(1))
let domainWithDotPrefix: String = ".\(domain)"
if let range = domainWithDotPrefix.rangeOfString(".\(query)", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) {
// We don't actually want to match the top-level domain ("com", "org", etc.) by itself, so
// so make sure the result includes at least one ".".
let matchedDomain: String = domainWithDotPrefix.substringFromIndex(advance(range.startIndex, 1))
if matchedDomain.contains(".") {
return matchedDomain
}
}
}
}
return nil
}
}
| mpl-2.0 | 943e25b037c7826231304b0a2dfde32d | 45.481481 | 159 | 0.607437 | 4.839332 | false | false | false | false |
huonw/swift | stdlib/public/SDK/Foundation/URL.swift | 1 | 66803 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
/**
URLs to file system resources support the properties defined below. Note that not all property values will exist for all file system URLs. For example, if a file is located on a volume that does not support creation dates, it is valid to request the creation date property, but the returned value will be nil, and no error will be generated.
Only the fields requested by the keys you pass into the `URL` function to receive this value will be populated. The others will return `nil` regardless of the underlying property on the file system.
As a convenience, volume resource values can be requested from any file system URL. The value returned will reflect the property value for the volume on which the resource is located.
*/
public struct URLResourceValues {
fileprivate var _values: [URLResourceKey: Any]
fileprivate var _keys: Set<URLResourceKey>
public init() {
_values = [:]
_keys = []
}
fileprivate init(keys: Set<URLResourceKey>, values: [URLResourceKey: Any]) {
_values = values
_keys = keys
}
private func contains(_ key: URLResourceKey) -> Bool {
return _keys.contains(key)
}
private func _get<T>(_ key : URLResourceKey) -> T? {
return _values[key] as? T
}
private func _get(_ key : URLResourceKey) -> Bool? {
return (_values[key] as? NSNumber)?.boolValue
}
private func _get(_ key: URLResourceKey) -> Int? {
return (_values[key] as? NSNumber)?.intValue
}
private mutating func _set(_ key : URLResourceKey, newValue : Any?) {
_keys.insert(key)
_values[key] = newValue
}
private mutating func _set(_ key : URLResourceKey, newValue : String?) {
_keys.insert(key)
_values[key] = newValue as NSString?
}
private mutating func _set(_ key : URLResourceKey, newValue : [String]?) {
_keys.insert(key)
_values[key] = newValue as NSObject?
}
private mutating func _set(_ key : URLResourceKey, newValue : Date?) {
_keys.insert(key)
_values[key] = newValue as NSDate?
}
private mutating func _set(_ key : URLResourceKey, newValue : URL?) {
_keys.insert(key)
_values[key] = newValue as NSURL?
}
private mutating func _set(_ key : URLResourceKey, newValue : Bool?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
private mutating func _set(_ key : URLResourceKey, newValue : Int?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
/// A loosely-typed dictionary containing all keys and values.
///
/// If you have set temporary keys or non-standard keys, you can find them in here.
public var allValues : [URLResourceKey : Any] {
return _values
}
/// The resource name provided by the file system.
public var name: String? {
get { return _get(.nameKey) }
set { _set(.nameKey, newValue: newValue) }
}
/// Localized or extension-hidden name as displayed to users.
public var localizedName: String? { return _get(.localizedNameKey) }
/// True for regular files.
public var isRegularFile: Bool? { return _get(.isRegularFileKey) }
/// True for directories.
public var isDirectory: Bool? { return _get(.isDirectoryKey) }
/// True for symlinks.
public var isSymbolicLink: Bool? { return _get(.isSymbolicLinkKey) }
/// True for the root directory of a volume.
public var isVolume: Bool? { return _get(.isVolumeKey) }
/// True for packaged directories.
///
/// - note: You can only set or clear this property on directories; if you try to set this property on non-directory objects, the property is ignored. If the directory is a package for some other reason (extension type, etc), setting this property to false will have no effect.
public var isPackage: Bool? {
get { return _get(.isPackageKey) }
set { _set(.isPackageKey, newValue: newValue) }
}
/// True if resource is an application.
@available(macOS 10.11, iOS 9.0, *)
public var isApplication: Bool? { return _get(.isApplicationKey) }
#if os(macOS)
/// True if the resource is scriptable. Only applies to applications.
@available(macOS 10.11, *)
public var applicationIsScriptable: Bool? { return _get(.applicationIsScriptableKey) }
#endif
/// True for system-immutable resources.
public var isSystemImmutable: Bool? { return _get(.isSystemImmutableKey) }
/// True for user-immutable resources
public var isUserImmutable: Bool? {
get { return _get(.isUserImmutableKey) }
set { _set(.isUserImmutableKey, newValue: newValue) }
}
/// True for resources normally not displayed to users.
///
/// - note: If the resource is a hidden because its name starts with a period, setting this property to false will not change the property.
public var isHidden: Bool? {
get { return _get(.isHiddenKey) }
set { _set(.isHiddenKey, newValue: newValue) }
}
/// True for resources whose filename extension is removed from the localized name property.
public var hasHiddenExtension: Bool? {
get { return _get(.hasHiddenExtensionKey) }
set { _set(.hasHiddenExtensionKey, newValue: newValue) }
}
/// The date the resource was created.
public var creationDate: Date? {
get { return _get(.creationDateKey) }
set { _set(.creationDateKey, newValue: newValue) }
}
/// The date the resource was last accessed.
public var contentAccessDate: Date? {
get { return _get(.contentAccessDateKey) }
set { _set(.contentAccessDateKey, newValue: newValue) }
}
/// The time the resource content was last modified.
public var contentModificationDate: Date? {
get { return _get(.contentModificationDateKey) }
set { _set(.contentModificationDateKey, newValue: newValue) }
}
/// The time the resource's attributes were last modified.
public var attributeModificationDate: Date? { return _get(.attributeModificationDateKey) }
/// Number of hard links to the resource.
public var linkCount: Int? { return _get(.linkCountKey) }
/// The resource's parent directory, if any.
public var parentDirectory: URL? { return _get(.parentDirectoryURLKey) }
/// URL of the volume on which the resource is stored.
public var volume: URL? { return _get(.volumeURLKey) }
/// Uniform type identifier (UTI) for the resource.
public var typeIdentifier: String? { return _get(.typeIdentifierKey) }
/// User-visible type or "kind" description.
public var localizedTypeDescription: String? { return _get(.localizedTypeDescriptionKey) }
/// The label number assigned to the resource.
public var labelNumber: Int? {
get { return _get(.labelNumberKey) }
set { _set(.labelNumberKey, newValue: newValue) }
}
/// The user-visible label text.
public var localizedLabel: String? {
get { return _get(.localizedLabelKey) }
}
/// An identifier which can be used to compare two file system objects for equality using `isEqual`.
///
/// Two object identifiers are equal if they have the same file system path or if the paths are linked to same inode on the same file system. This identifier is not persistent across system restarts.
public var fileResourceIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.fileResourceIdentifierKey) }
/// An identifier that can be used to identify the volume the file system object is on.
///
/// Other objects on the same volume will have the same volume identifier and can be compared using for equality using `isEqual`. This identifier is not persistent across system restarts.
public var volumeIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.volumeIdentifierKey) }
/// The optimal block size when reading or writing this file's data, or nil if not available.
public var preferredIOBlockSize: Int? { return _get(.preferredIOBlockSizeKey) }
/// True if this process (as determined by EUID) can read the resource.
public var isReadable: Bool? { return _get(.isReadableKey) }
/// True if this process (as determined by EUID) can write to the resource.
public var isWritable: Bool? { return _get(.isWritableKey) }
/// True if this process (as determined by EUID) can execute a file resource or search a directory resource.
public var isExecutable: Bool? { return _get(.isExecutableKey) }
/// The file system object's security information encapsulated in a FileSecurity object.
public var fileSecurity: NSFileSecurity? {
get { return _get(.fileSecurityKey) }
set { _set(.fileSecurityKey, newValue: newValue) }
}
/// True if resource should be excluded from backups, false otherwise.
///
/// This property is only useful for excluding cache and other application support files which are not needed in a backup. Some operations commonly made to user documents will cause this property to be reset to false and so this property should not be used on user documents.
public var isExcludedFromBackup: Bool? {
get { return _get(.isExcludedFromBackupKey) }
set { _set(.isExcludedFromBackupKey, newValue: newValue) }
}
#if os(macOS)
/// The array of Tag names.
public var tagNames: [String]? { return _get(.tagNamesKey) }
#endif
/// The URL's path as a file system path.
public var path: String? { return _get(.pathKey) }
/// The URL's path as a canonical absolute file system path.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var canonicalPath: String? { return _get(.canonicalPathKey) }
/// True if this URL is a file system trigger directory. Traversing or opening a file system trigger will cause an attempt to mount a file system on the trigger directory.
public var isMountTrigger: Bool? { return _get(.isMountTriggerKey) }
/// An opaque generation identifier which can be compared using `==` to determine if the data in a document has been modified.
///
/// For URLs which refer to the same file inode, the generation identifier will change when the data in the file's data fork is changed (changes to extended attributes or other file system metadata do not change the generation identifier). For URLs which refer to the same directory inode, the generation identifier will change when direct children of that directory are added, removed or renamed (changes to the data of the direct children of that directory will not change the generation identifier). The generation identifier is persistent across system restarts. The generation identifier is tied to a specific document on a specific volume and is not transferred when the document is copied to another volume. This property is not supported by all volumes.
@available(macOS 10.10, iOS 8.0, *)
public var generationIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.generationIdentifierKey) }
/// The document identifier -- a value assigned by the kernel to a document (which can be either a file or directory) and is used to identify the document regardless of where it gets moved on a volume.
///
/// The document identifier survives "safe save" operations; i.e it is sticky to the path it was assigned to (`replaceItem(at:,withItemAt:,backupItemName:,options:,resultingItem:) throws` is the preferred safe-save API). The document identifier is persistent across system restarts. The document identifier is not transferred when the file is copied. Document identifiers are only unique within a single volume. This property is not supported by all volumes.
@available(macOS 10.10, iOS 8.0, *)
public var documentIdentifier: Int? { return _get(.documentIdentifierKey) }
/// The date the resource was created, or renamed into or within its parent directory. Note that inconsistent behavior may be observed when this attribute is requested on hard-linked items. This property is not supported by all volumes.
@available(macOS 10.10, iOS 8.0, *)
public var addedToDirectoryDate: Date? { return _get(.addedToDirectoryDateKey) }
#if os(macOS)
/// The quarantine properties as defined in LSQuarantine.h. To remove quarantine information from a file, pass `nil` as the value when setting this property.
@available(macOS 10.10, *)
public var quarantineProperties: [String : Any]? {
get {
let value = _values[.quarantinePropertiesKey]
// If a caller has caused us to stash NSNull in the dictionary (via set), make sure to return nil instead of NSNull
if value is NSNull {
return nil
} else {
return value as? [String : Any]
}
}
set {
// Use NSNull for nil, a special case for deleting quarantine
// properties
_set(.quarantinePropertiesKey, newValue: newValue ?? NSNull())
}
}
#endif
/// Returns the file system object type.
public var fileResourceType: URLFileResourceType? { return _get(.fileResourceTypeKey) }
/// The user-visible volume format.
public var volumeLocalizedFormatDescription : String? { return _get(.volumeLocalizedFormatDescriptionKey) }
/// Total volume capacity in bytes.
public var volumeTotalCapacity : Int? { return _get(.volumeTotalCapacityKey) }
/// Total free space in bytes.
public var volumeAvailableCapacity : Int? { return _get(.volumeAvailableCapacityKey) }
#if os(macOS) || os(iOS)
/// Total available capacity in bytes for "Important" resources, including space expected to be cleared by purging non-essential and cached resources. "Important" means something that the user or application clearly expects to be present on the local system, but is ultimately replaceable. This would include items that the user has explicitly requested via the UI, and resources that an application requires in order to provide functionality.
/// Examples: A video that the user has explicitly requested to watch but has not yet finished watching or an audio file that the user has requested to download.
/// This value should not be used in determining if there is room for an irreplaceable resource. In the case of irreplaceable resources, always attempt to save the resource regardless of available capacity and handle failure as gracefully as possible.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var volumeAvailableCapacityForImportantUsage: Int64? { return _get(.volumeAvailableCapacityForImportantUsageKey) }
/// Total available capacity in bytes for "Opportunistic" resources, including space expected to be cleared by purging non-essential and cached resources. "Opportunistic" means something that the user is likely to want but does not expect to be present on the local system, but is ultimately non-essential and replaceable. This would include items that will be created or downloaded without an explicit request from the user on the current device.
/// Examples: A background download of a newly available episode of a TV series that a user has been recently watching, a piece of content explicitly requested on another device, and a new document saved to a network server by the current user from another device.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var volumeAvailableCapacityForOpportunisticUsage: Int64? { return _get(.volumeAvailableCapacityForOpportunisticUsageKey) }
#endif
/// Total number of resources on the volume.
public var volumeResourceCount : Int? { return _get(.volumeResourceCountKey) }
/// true if the volume format supports persistent object identifiers and can look up file system objects by their IDs.
public var volumeSupportsPersistentIDs : Bool? { return _get(.volumeSupportsPersistentIDsKey) }
/// true if the volume format supports symbolic links.
public var volumeSupportsSymbolicLinks : Bool? { return _get(.volumeSupportsSymbolicLinksKey) }
/// true if the volume format supports hard links.
public var volumeSupportsHardLinks : Bool? { return _get(.volumeSupportsHardLinksKey) }
/// true if the volume format supports a journal used to speed recovery in case of unplanned restart (such as a power outage or crash). This does not necessarily mean the volume is actively using a journal.
public var volumeSupportsJournaling : Bool? { return _get(.volumeSupportsJournalingKey) }
/// true if the volume is currently using a journal for speedy recovery after an unplanned restart.
public var volumeIsJournaling : Bool? { return _get(.volumeIsJournalingKey) }
/// true if the volume format supports sparse files, that is, files which can have 'holes' that have never been written to, and thus do not consume space on disk. A sparse file may have an allocated size on disk that is less than its logical length.
public var volumeSupportsSparseFiles : Bool? { return _get(.volumeSupportsSparseFilesKey) }
/// For security reasons, parts of a file (runs) that have never been written to must appear to contain zeroes. true if the volume keeps track of allocated but unwritten runs of a file so that it can substitute zeroes without actually writing zeroes to the media.
public var volumeSupportsZeroRuns : Bool? { return _get(.volumeSupportsZeroRunsKey) }
/// true if the volume format treats upper and lower case characters in file and directory names as different. Otherwise an upper case character is equivalent to a lower case character, and you can't have two names that differ solely in the case of the characters.
public var volumeSupportsCaseSensitiveNames : Bool? { return _get(.volumeSupportsCaseSensitiveNamesKey) }
/// true if the volume format preserves the case of file and directory names. Otherwise the volume may change the case of some characters (typically making them all upper or all lower case).
public var volumeSupportsCasePreservedNames : Bool? { return _get(.volumeSupportsCasePreservedNamesKey) }
/// true if the volume supports reliable storage of times for the root directory.
public var volumeSupportsRootDirectoryDates : Bool? { return _get(.volumeSupportsRootDirectoryDatesKey) }
/// true if the volume supports returning volume size values (`volumeTotalCapacity` and `volumeAvailableCapacity`).
public var volumeSupportsVolumeSizes : Bool? { return _get(.volumeSupportsVolumeSizesKey) }
/// true if the volume can be renamed.
public var volumeSupportsRenaming : Bool? { return _get(.volumeSupportsRenamingKey) }
/// true if the volume implements whole-file flock(2) style advisory locks, and the O_EXLOCK and O_SHLOCK flags of the open(2) call.
public var volumeSupportsAdvisoryFileLocking : Bool? { return _get(.volumeSupportsAdvisoryFileLockingKey) }
/// true if the volume implements extended security (ACLs).
public var volumeSupportsExtendedSecurity : Bool? { return _get(.volumeSupportsExtendedSecurityKey) }
/// true if the volume should be visible via the GUI (i.e., appear on the Desktop as a separate volume).
public var volumeIsBrowsable : Bool? { return _get(.volumeIsBrowsableKey) }
/// The largest file size (in bytes) supported by this file system, or nil if this cannot be determined.
public var volumeMaximumFileSize : Int? { return _get(.volumeMaximumFileSizeKey) }
/// true if the volume's media is ejectable from the drive mechanism under software control.
public var volumeIsEjectable : Bool? { return _get(.volumeIsEjectableKey) }
/// true if the volume's media is removable from the drive mechanism.
public var volumeIsRemovable : Bool? { return _get(.volumeIsRemovableKey) }
/// true if the volume's device is connected to an internal bus, false if connected to an external bus, or nil if not available.
public var volumeIsInternal : Bool? { return _get(.volumeIsInternalKey) }
/// true if the volume is automounted. Note: do not mistake this with the functionality provided by kCFURLVolumeSupportsBrowsingKey.
public var volumeIsAutomounted : Bool? { return _get(.volumeIsAutomountedKey) }
/// true if the volume is stored on a local device.
public var volumeIsLocal : Bool? { return _get(.volumeIsLocalKey) }
/// true if the volume is read-only.
public var volumeIsReadOnly : Bool? { return _get(.volumeIsReadOnlyKey) }
/// The volume's creation date, or nil if this cannot be determined.
public var volumeCreationDate : Date? { return _get(.volumeCreationDateKey) }
/// The `URL` needed to remount a network volume, or nil if not available.
public var volumeURLForRemounting : URL? { return _get(.volumeURLForRemountingKey) }
/// The volume's persistent `UUID` as a string, or nil if a persistent `UUID` is not available for the volume.
public var volumeUUIDString : String? { return _get(.volumeUUIDStringKey) }
/// The name of the volume
public var volumeName : String? {
get { return _get(.volumeNameKey) }
set { _set(.volumeNameKey, newValue: newValue) }
}
/// The user-presentable name of the volume
public var volumeLocalizedName : String? { return _get(.volumeLocalizedNameKey) }
/// true if the volume is encrypted.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsEncrypted : Bool? { return _get(.volumeIsEncryptedKey) }
/// true if the volume is the root filesystem.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsRootFileSystem : Bool? { return _get(.volumeIsRootFileSystemKey) }
/// true if the volume supports transparent decompression of compressed files using decmpfs.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsCompression : Bool? { return _get(.volumeSupportsCompressionKey) }
/// true if this item is synced to the cloud, false if it is only a local file.
public var isUbiquitousItem : Bool? { return _get(.isUbiquitousItemKey) }
/// true if this item has conflicts outstanding.
public var ubiquitousItemHasUnresolvedConflicts : Bool? { return _get(.ubiquitousItemHasUnresolvedConflictsKey) }
/// true if data is being downloaded for this item.
public var ubiquitousItemIsDownloading : Bool? { return _get(.ubiquitousItemIsDownloadingKey) }
/// true if there is data present in the cloud for this item.
public var ubiquitousItemIsUploaded : Bool? { return _get(.ubiquitousItemIsUploadedKey) }
/// true if data is being uploaded for this item.
public var ubiquitousItemIsUploading : Bool? { return _get(.ubiquitousItemIsUploadingKey) }
/// returns the download status of this item.
public var ubiquitousItemDownloadingStatus : URLUbiquitousItemDownloadingStatus? { return _get(.ubiquitousItemDownloadingStatusKey) }
/// returns the error when downloading the item from iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemDownloadingError : NSError? { return _get(.ubiquitousItemDownloadingErrorKey) }
/// returns the error when uploading the item to iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemUploadingError : NSError? { return _get(.ubiquitousItemUploadingErrorKey) }
/// returns whether a download of this item has already been requested with an API like `startDownloadingUbiquitousItem(at:) throws`.
@available(macOS 10.10, iOS 8.0, *)
public var ubiquitousItemDownloadRequested : Bool? { return _get(.ubiquitousItemDownloadRequestedKey) }
/// returns the name of this item's container as displayed to users.
@available(macOS 10.10, iOS 8.0, *)
public var ubiquitousItemContainerDisplayName : String? { return _get(.ubiquitousItemContainerDisplayNameKey) }
#if os(macOS) || os(iOS)
// true if ubiquitous item is shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousItemIsShared: Bool? { return _get(.ubiquitousItemIsSharedKey) }
// The current user's role for this shared item, or nil if not shared
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemCurrentUserRole: URLUbiquitousSharedItemRole? { return _get(.ubiquitousSharedItemCurrentUserRoleKey) }
// The permissions for the current user, or nil if not shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemCurrentUserPermissions: URLUbiquitousSharedItemPermissions? { return _get(.ubiquitousSharedItemCurrentUserPermissionsKey) }
// The name components for the owner, or nil if not shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemOwnerNameComponents: PersonNameComponents? { return _get(.ubiquitousSharedItemOwnerNameComponentsKey) }
// The name components for the most recent editor, or nil if not shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemMostRecentEditorNameComponents: PersonNameComponents? { return _get(.ubiquitousSharedItemMostRecentEditorNameComponentsKey) }
#endif
#if !os(macOS)
/// The protection level for this file
@available(iOS 9.0, *)
public var fileProtection : URLFileProtection? { return _get(.fileProtectionKey) }
#endif
/// Total file size in bytes
///
/// - note: Only applicable to regular files.
public var fileSize : Int? { return _get(.fileSizeKey) }
/// Total size allocated on disk for the file in bytes (number of blocks times block size)
///
/// - note: Only applicable to regular files.
public var fileAllocatedSize : Int? { return _get(.fileAllocatedSizeKey) }
/// Total displayable size of the file in bytes (this may include space used by metadata), or nil if not available.
///
/// - note: Only applicable to regular files.
public var totalFileSize : Int? { return _get(.totalFileSizeKey) }
/// Total allocated size of the file in bytes (this may include space used by metadata), or nil if not available. This can be less than the value returned by `totalFileSize` if the resource is compressed.
///
/// - note: Only applicable to regular files.
public var totalFileAllocatedSize : Int? { return _get(.totalFileAllocatedSizeKey) }
/// true if the resource is a Finder alias file or a symlink, false otherwise
///
/// - note: Only applicable to regular files.
public var isAliasFile : Bool? { return _get(.isAliasFileKey) }
}
/**
A URL is a type that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data.
You can construct URLs and access their parts. For URLs that represent local files, you can also manipulate properties of those files directly, such as changing the file's last modification date. Finally, you can pass URLs to other APIs to retrieve the contents of those URLs. For example, you can use the URLSession classes to access the contents of remote resources, as described in URL Session Programming Guide.
URLs are the preferred way to refer to local files. Most objects that read data from or write data to a file have methods that accept a URL instead of a pathname as the file reference. For example, you can get the contents of a local file URL as `String` by calling `func init(contentsOf:encoding) throws`, or as a `Data` by calling `func init(contentsOf:options) throws`.
*/
public struct URL : ReferenceConvertible, Equatable {
public typealias ReferenceType = NSURL
fileprivate var _url : NSURL
public typealias BookmarkResolutionOptions = NSURL.BookmarkResolutionOptions
public typealias BookmarkCreationOptions = NSURL.BookmarkCreationOptions
/// Initialize with string.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: String) {
guard !string.isEmpty else { return nil }
if let inner = NSURL(string: string) {
_url = URL._converted(from: inner)
} else {
return nil
}
}
/// Initialize with string, relative to another URL.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: String, relativeTo url: URL?) {
guard !string.isEmpty else { return nil }
if let inner = NSURL(string: string, relativeTo: url) {
_url = URL._converted(from: inner)
} else {
return nil
}
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
@available(macOS 10.11, iOS 9.0, *)
public init(fileURLWithPath path: String, isDirectory: Bool, relativeTo base: URL?) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory, relativeTo: base))
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
@available(macOS 10.11, iOS 9.0, *)
public init(fileURLWithPath path: String, relativeTo base: URL?) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, relativeTo: base))
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
public init(fileURLWithPath path: String, isDirectory: Bool) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory))
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
public init(fileURLWithPath path: String) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path))
}
/// Initializes a newly created URL using the contents of the given data, relative to a base URL.
///
/// If the data representation is not a legal URL string as ASCII bytes, the URL object may not behave as expected. If the URL cannot be formed then this will return nil.
@available(macOS 10.11, iOS 9.0, *)
public init?(dataRepresentation: Data, relativeTo url: URL?, isAbsolute: Bool = false) {
guard dataRepresentation.count > 0 else { return nil }
if isAbsolute {
_url = URL._converted(from: NSURL(absoluteURLWithDataRepresentation: dataRepresentation, relativeTo: url))
} else {
_url = URL._converted(from: NSURL(dataRepresentation: dataRepresentation, relativeTo: url))
}
}
/// Initializes a URL that refers to a location specified by resolving bookmark data.
@available(swift, obsoleted: 4.2)
public init?(resolvingBookmarkData data: Data, options: BookmarkResolutionOptions = [], relativeTo url: URL? = nil, bookmarkDataIsStale: inout Bool) throws {
var stale : ObjCBool = false
_url = URL._converted(from: try NSURL(resolvingBookmarkData: data, options: options, relativeTo: url, bookmarkDataIsStale: &stale))
bookmarkDataIsStale = stale.boolValue
}
/// Initializes a URL that refers to a location specified by resolving bookmark data.
@available(swift, introduced: 4.2)
public init(resolvingBookmarkData data: Data, options: BookmarkResolutionOptions = [], relativeTo url: URL? = nil, bookmarkDataIsStale: inout Bool) throws {
var stale : ObjCBool = false
_url = URL._converted(from: try NSURL(resolvingBookmarkData: data, options: options, relativeTo: url, bookmarkDataIsStale: &stale))
bookmarkDataIsStale = stale.boolValue
}
/// Creates and initializes an NSURL that refers to the location specified by resolving the alias file at url. If the url argument does not refer to an alias file as defined by the NSURLIsAliasFileKey property, the NSURL returned is the same as url argument. This method fails and returns nil if the url argument is unreachable, or if the original file or directory could not be located or is not reachable, or if the original file or directory is on a volume that could not be located or mounted. The URLBookmarkResolutionWithSecurityScope option is not supported by this method.
@available(macOS 10.10, iOS 8.0, *)
public init(resolvingAliasFileAt url: URL, options: BookmarkResolutionOptions = []) throws {
self.init(reference: try NSURL(resolvingAliasFileAt: url, options: options))
}
/// Initializes a newly created URL referencing the local file or directory at the file system representation of the path. File system representation is a null-terminated C string with canonical UTF-8 encoding.
public init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory: Bool, relativeTo baseURL: URL?) {
_url = URL._converted(from: NSURL(fileURLWithFileSystemRepresentation: path, isDirectory: isDirectory, relativeTo: baseURL))
}
public var hashValue: Int {
return _url.hash
}
// MARK: -
/// Returns the data representation of the URL's relativeString.
///
/// If the URL was initialized with `init?(dataRepresentation:relativeTo:isAbsolute:)`, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the `relativeString` encoded with UTF8 string encoding.
@available(macOS 10.11, iOS 9.0, *)
public var dataRepresentation: Data {
return _url.dataRepresentation
}
// MARK: -
// Future implementation note:
// NSURL (really CFURL, which provides its implementation) has quite a few quirks in its processing of some more esoteric (and some not so esoteric) strings. We would like to move much of this over to the more modern NSURLComponents, but binary compat concerns have made this difficult.
// Hopefully soon, we can replace some of the below delegation to NSURL with delegation to NSURLComponents instead. It cannot be done piecemeal, because otherwise we will get inconsistent results from the API.
/// Returns the absolute string for the URL.
public var absoluteString: String {
if let string = _url.absoluteString {
return string
} else {
// This should never fail for non-file reference URLs
return ""
}
}
/// The relative portion of a URL.
///
/// If `baseURL` is nil, or if the receiver is itself absolute, this is the same as `absoluteString`.
public var relativeString: String {
return _url.relativeString
}
/// Returns the base URL.
///
/// If the URL is itself absolute, then this value is nil.
public var baseURL: URL? {
return _url.baseURL
}
/// Returns the absolute URL.
///
/// If the URL is itself absolute, this will return self.
public var absoluteURL: URL {
if let url = _url.absoluteURL {
return url
} else {
// This should never fail for non-file reference URLs
return self
}
}
// MARK: -
/// Returns the scheme of the URL.
public var scheme: String? {
return _url.scheme
}
/// Returns true if the scheme is `file:`.
public var isFileURL: Bool {
return _url.isFileURL
}
// This thing was never really part of the URL specs
@available(*, unavailable, message: "Use `path`, `query`, and `fragment` instead")
public var resourceSpecifier: String {
fatalError()
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the host component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var host: String? {
return _url.host
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the port component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var port: Int? {
return _url.port?.intValue
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the user component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var user: String? {
return _url.user
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the password component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var password: String? {
return _url.password
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the path component of the URL; otherwise it returns an empty string.
///
/// If the URL contains a parameter string, it is appended to the path with a `;`.
/// - note: This function will resolve against the base `URL`.
/// - returns: The path, or an empty string if the URL has an empty path.
public var path: String {
if let parameterString = _url.parameterString {
if let path = _url.path {
return path + ";" + parameterString
} else {
return ";" + parameterString
}
} else if let path = _url.path {
return path
} else {
return ""
}
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the relative path of the URL; otherwise it returns nil.
///
/// This is the same as path if baseURL is nil.
/// If the URL contains a parameter string, it is appended to the path with a `;`.
///
/// - note: This function will resolve against the base `URL`.
/// - returns: The relative path, or an empty string if the URL has an empty path.
public var relativePath: String {
if let parameterString = _url.parameterString {
if let path = _url.relativePath {
return path + ";" + parameterString
} else {
return ";" + parameterString
}
} else if let path = _url.relativePath {
return path
} else {
return ""
}
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the fragment component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var fragment: String? {
return _url.fragment
}
@available(*, unavailable, message: "use the 'path' property")
public var parameterString: String? {
fatalError()
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the query of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var query: String? {
return _url.query
}
/// Returns true if the URL path represents a directory.
@available(macOS 10.11, iOS 9.0, *)
public var hasDirectoryPath: Bool {
return _url.hasDirectoryPath
}
/// Passes the URL's path in file system representation to `block`.
///
/// File system representation is a null-terminated C string with canonical UTF-8 encoding.
/// - note: The pointer is not valid outside the context of the block.
@available(macOS 10.9, iOS 7.0, *)
public func withUnsafeFileSystemRepresentation<ResultType>(_ block: (UnsafePointer<Int8>?) throws -> ResultType) rethrows -> ResultType {
return try block(_url.fileSystemRepresentation)
}
// MARK: -
// MARK: Path manipulation
/// Returns the path components of the URL, or an empty array if the path is an empty string.
public var pathComponents: [String] {
// In accordance with our above change to never return a nil path, here we return an empty array.
return _url.pathComponents ?? []
}
/// Returns the last path component of the URL, or an empty string if the path is an empty string.
public var lastPathComponent: String {
return _url.lastPathComponent ?? ""
}
/// Returns the path extension of the URL, or an empty string if the path is an empty string.
public var pathExtension: String {
return _url.pathExtension ?? ""
}
/// Returns a URL constructed by appending the given path component to self.
///
/// - parameter pathComponent: The path component to add.
/// - parameter isDirectory: If `true`, then a trailing `/` is added to the resulting path.
public func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) -> URL {
if let result = _url.appendingPathComponent(pathComponent, isDirectory: isDirectory) {
return result
} else {
// Now we need to do something more expensive
if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) {
c.path = (c.path as NSString).appendingPathComponent(pathComponent)
if let result = c.url {
return result
} else {
// Couldn't get url from components
// Ultimate fallback:
return self
}
} else {
return self
}
}
}
/// Returns a URL constructed by appending the given path component to self.
///
/// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`.
/// - parameter pathComponent: The path component to add.
public func appendingPathComponent(_ pathComponent: String) -> URL {
if let result = _url.appendingPathComponent(pathComponent) {
return result
} else {
// Now we need to do something more expensive
if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) {
c.path = (c.path as NSString).appendingPathComponent(pathComponent)
if let result = c.url {
return result
} else {
// Couldn't get url from components
// Ultimate fallback:
return self
}
} else {
// Ultimate fallback:
return self
}
}
}
/// Returns a URL constructed by removing the last path component of self.
///
/// This function may either remove a path component or append `/..`.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
public func deletingLastPathComponent() -> URL {
// This is a slight behavior change from NSURL, but better than returning "http://www.example.com../".
if path.isEmpty {
return self
}
if let result = _url.deletingLastPathComponent.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Returns a URL constructed by appending the given path extension to self.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
///
/// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged.
/// - parameter pathExtension: The extension to append.
public func appendingPathExtension(_ pathExtension: String) -> URL {
if path.isEmpty {
return self
}
if let result = _url.appendingPathExtension(pathExtension) {
return result
} else {
return self
}
}
/// Returns a URL constructed by removing any path extension.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
public func deletingPathExtension() -> URL {
if path.isEmpty {
return self
}
if let result = _url.deletingPathExtension.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Appends a path component to the URL.
///
/// - parameter pathComponent: The path component to add.
/// - parameter isDirectory: Use `true` if the resulting path is a directory.
public mutating func appendPathComponent(_ pathComponent: String, isDirectory: Bool) {
self = appendingPathComponent(pathComponent, isDirectory: isDirectory)
}
/// Appends a path component to the URL.
///
/// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`.
/// - parameter pathComponent: The path component to add.
public mutating func appendPathComponent(_ pathComponent: String) {
self = appendingPathComponent(pathComponent)
}
/// Appends the given path extension to self.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
/// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged.
/// - parameter pathExtension: The extension to append.
public mutating func appendPathExtension(_ pathExtension: String) {
self = appendingPathExtension(pathExtension)
}
/// Returns a URL constructed by removing the last path component of self.
///
/// This function may either remove a path component or append `/..`.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
public mutating func deleteLastPathComponent() {
self = deletingLastPathComponent()
}
/// Returns a URL constructed by removing any path extension.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
public mutating func deletePathExtension() {
self = deletingPathExtension()
}
/// Returns a `URL` with any instances of ".." or "." removed from its path.
public var standardized : URL {
// The NSURL API can only return nil in case of file reference URL, which we should not be
if let result = _url.standardized.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Standardizes the path of a file URL.
///
/// If the `isFileURL` is false, this method does nothing.
public mutating func standardize() {
self = self.standardized
}
/// Standardizes the path of a file URL.
///
/// If the `isFileURL` is false, this method returns `self`.
public var standardizedFileURL : URL {
// NSURL should not return nil here unless this is a file reference URL, which should be impossible
if let result = _url.standardizingPath.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Resolves any symlinks in the path of a file URL.
///
/// If the `isFileURL` is false, this method returns `self`.
public func resolvingSymlinksInPath() -> URL {
// NSURL should not return nil here unless this is a file reference URL, which should be impossible
if let result = _url.resolvingSymlinksInPath.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Resolves any symlinks in the path of a file URL.
///
/// If the `isFileURL` is false, this method does nothing.
public mutating func resolveSymlinksInPath() {
self = self.resolvingSymlinksInPath()
}
// MARK: - Reachability
/// Returns whether the URL's resource exists and is reachable.
///
/// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.
public func checkResourceIsReachable() throws -> Bool {
var error : NSError?
let result = _url.checkResourceIsReachableAndReturnError(&error)
if let e = error {
throw e
} else {
return result
}
}
/// Returns whether the promised item URL's resource exists and is reachable.
///
/// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.
@available(macOS 10.10, iOS 8.0, *)
public func checkPromisedItemIsReachable() throws -> Bool {
var error : NSError?
let result = _url.checkPromisedItemIsReachableAndReturnError(&error)
if let e = error {
throw e
} else {
return result
}
}
// MARK: - Resource Values
/// Sets the resource value identified by a given resource key.
///
/// This method writes the new resource values out to the backing store. Attempts to set a read-only resource property or to set a resource property not supported by the resource are ignored and are not considered errors. This method is currently applicable only to URLs for file system resources.
///
/// `URLResourceValues` keeps track of which of its properties have been set. Those values are the ones used by this function to determine which properties to write.
public mutating func setResourceValues(_ values: URLResourceValues) throws {
try _url.setResourceValues(values._values)
}
/// Return a collection of resource values identified by the given resource keys.
///
/// This method first checks if the URL object already caches the resource value. If so, it returns the cached resource value to the caller. If not, then this method synchronously obtains the resource value from the backing store, adds the resource value to the URL object's cache, and returns the resource value to the caller. The type of the resource value varies by resource property (see resource key definitions). If this method does not throw and the resulting value in the `URLResourceValues` is populated with nil, it means the resource property is not available for the specified resource and no errors occurred when determining the resource property was not available. This method is currently applicable only to URLs for file system resources.
///
/// When this function is used from the main thread, resource values cached by the URL (except those added as temporary properties) are removed the next time the main thread's run loop runs. `func removeCachedResourceValue(forKey:)` and `func removeAllCachedResourceValues()` also may be used to remove cached resource values.
///
/// Only the values for the keys specified in `keys` will be populated.
public func resourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues {
return URLResourceValues(keys: keys, values: try _url.resourceValues(forKeys: Array(keys)))
}
/// Sets a temporary resource value on the URL object.
///
/// Temporary resource values are for client use. Temporary resource values exist only in memory and are never written to the resource's backing store. Once set, a temporary resource value can be copied from the URL object with `func resourceValues(forKeys:)`. The values are stored in the loosely-typed `allValues` dictionary property.
///
/// To remove a temporary resource value from the URL object, use `func removeCachedResourceValue(forKey:)`. Care should be taken to ensure the key that identifies a temporary resource value is unique and does not conflict with system defined keys (using reverse domain name notation in your temporary resource value keys is recommended). This method is currently applicable only to URLs for file system resources.
public mutating func setTemporaryResourceValue(_ value : Any, forKey key: URLResourceKey) {
_url.setTemporaryResourceValue(value, forKey: key)
}
/// Removes all cached resource values and all temporary resource values from the URL object.
///
/// This method is currently applicable only to URLs for file system resources.
public mutating func removeAllCachedResourceValues() {
_url.removeAllCachedResourceValues()
}
/// Removes the cached resource value identified by a given resource value key from the URL object.
///
/// Removing a cached resource value may remove other cached resource values because some resource values are cached as a set of values, and because some resource values depend on other resource values (temporary resource values have no dependencies). This method is currently applicable only to URLs for file system resources.
public mutating func removeCachedResourceValue(forKey key: URLResourceKey) {
_url.removeCachedResourceValue(forKey: key)
}
/// Get resource values from URLs of 'promised' items.
///
/// A promised item is not guaranteed to have its contents in the file system until you use `FileCoordinator` to perform a coordinated read on its URL, which causes the contents to be downloaded or otherwise generated. Promised item URLs are returned by various APIs, including currently:
/// NSMetadataQueryUbiquitousDataScope
/// NSMetadataQueryUbiquitousDocumentsScope
/// A `FilePresenter` presenting the contents of the directory located by -URLForUbiquitousContainerIdentifier: or a subdirectory thereof
///
/// The following methods behave identically to their similarly named methods above (`func resourceValues(forKeys:)`, etc.), except that they allow you to get resource values and check for presence regardless of whether the promised item's contents currently exist at the URL. You must use these APIs instead of the normal URL resource value APIs if and only if any of the following are true:
/// You are using a URL that you know came directly from one of the above APIs
/// You are inside the accessor block of a coordinated read or write that used NSFileCoordinatorReadingImmediatelyAvailableMetadataOnly, NSFileCoordinatorWritingForDeleting, NSFileCoordinatorWritingForMoving, or NSFileCoordinatorWritingContentIndependentMetadataOnly
///
/// Most of the URL resource value keys will work with these APIs. However, there are some that are tied to the item's contents that will not work, such as `contentAccessDateKey` or `generationIdentifierKey`. If one of these keys is used, the method will return a `URLResourceValues` value, but the value for that property will be nil.
@available(macOS 10.10, iOS 8.0, *)
public func promisedItemResourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues {
return URLResourceValues(keys: keys, values: try _url.promisedItemResourceValues(forKeys: Array(keys)))
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func setResourceValue(_ value: AnyObject?, forKey key: URLResourceKey) throws {
fatalError()
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func setResourceValues(_ keyedValues: [URLResourceKey : AnyObject]) throws {
fatalError()
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func getResourceValue(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>, forKey key: URLResourceKey) throws {
fatalError()
}
// MARK: - Bookmarks and Alias Files
/// Returns bookmark data for the URL, created with specified options and resource values.
public func bookmarkData(options: BookmarkCreationOptions = [], includingResourceValuesForKeys keys: Set<URLResourceKey>? = nil, relativeTo url: URL? = nil) throws -> Data {
let result = try _url.bookmarkData(options: options, includingResourceValuesForKeys: keys.flatMap { Array($0) }, relativeTo: url)
return result as Data
}
/// Returns the resource values for properties identified by a specified array of keys contained in specified bookmark data. If the result dictionary does not contain a resource value for one or more of the requested resource keys, it means those resource properties are not available in the bookmark data.
public static func resourceValues(forKeys keys: Set<URLResourceKey>, fromBookmarkData data: Data) -> URLResourceValues? {
return NSURL.resourceValues(forKeys: Array(keys), fromBookmarkData: data).map { URLResourceValues(keys: keys, values: $0) }
}
/// Creates an alias file on disk at a specified location with specified bookmark data. bookmarkData must have been created with the URLBookmarkCreationSuitableForBookmarkFile option. bookmarkFileURL must either refer to an existing file (which will be overwritten), or to location in an existing directory.
public static func writeBookmarkData(_ data : Data, to url: URL) throws {
// Options are unused
try NSURL.writeBookmarkData(data, to: url, options: 0)
}
/// Initializes and returns bookmark data derived from an alias file pointed to by a specified URL. If bookmarkFileURL refers to an alias file created prior to OS X v10.6 that contains Alias Manager information but no bookmark data, this method synthesizes bookmark data for the file.
public static func bookmarkData(withContentsOf url: URL) throws -> Data {
let result = try NSURL.bookmarkData(withContentsOf: url)
return result as Data
}
/// Given an NSURL created by resolving a bookmark data created with security scope, make the resource referenced by the url accessible to the process. When access to this resource is no longer needed the client must call stopAccessingSecurityScopedResource. Each call to startAccessingSecurityScopedResource must be balanced with a call to stopAccessingSecurityScopedResource (Note: this is not reference counted).
@available(macOS 10.7, iOS 8.0, *)
public func startAccessingSecurityScopedResource() -> Bool {
return _url.startAccessingSecurityScopedResource()
}
/// Revokes the access granted to the url by a prior successful call to startAccessingSecurityScopedResource.
@available(macOS 10.7, iOS 8.0, *)
public func stopAccessingSecurityScopedResource() {
_url.stopAccessingSecurityScopedResource()
}
// MARK: - Bridging Support
/// We must not store an NSURL without running it through this function. This makes sure that we do not hold a file reference URL, which changes the nullability of many NSURL functions.
private static func _converted(from url: NSURL) -> NSURL {
// Future readers: file reference URL here is not the same as playgrounds "file reference"
if url.isFileReferenceURL() {
// Convert to a file path URL, or use an invalid scheme
return (url.filePathURL ?? URL(string: "com-apple-unresolvable-file-reference-url:")!) as NSURL
} else {
return url
}
}
fileprivate init(reference: NSURL) {
_url = URL._converted(from: reference).copy() as! NSURL
}
private var reference : NSURL {
return _url
}
public static func ==(lhs: URL, rhs: URL) -> Bool {
return lhs.reference.isEqual(rhs.reference)
}
}
extension URL : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURL {
return _url
}
public static func _forceBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) {
if !_conditionallyBridgeFromObjectiveC(source, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) -> Bool {
result = URL(reference: source)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURL?) -> URL {
var result: URL?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension URL : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return _url.description
}
public var debugDescription: String {
return _url.debugDescription
}
}
extension NSURL : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as URL)
}
}
extension URL : CustomPlaygroundQuickLookable {
@available(*, deprecated, message: "URL.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .url(absoluteString)
}
}
extension URL : Codable {
private enum CodingKeys : Int, CodingKey {
case base
case relative
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let relative = try container.decode(String.self, forKey: .relative)
let base = try container.decodeIfPresent(URL.self, forKey: .base)
guard let url = URL(string: relative, relativeTo: base) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "Invalid URL string."))
}
self = url
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.relativeString, forKey: .relative)
if let base = self.baseURL {
try container.encode(base, forKey: .base)
}
}
}
//===----------------------------------------------------------------------===//
// File references, for playgrounds.
//===----------------------------------------------------------------------===//
extension URL : _ExpressibleByFileReferenceLiteral {
public init(fileReferenceLiteralResourceName name: String) {
self = Bundle.main.url(forResource: name, withExtension: nil)!
}
}
public typealias _FileReferenceLiteralType = URL
| apache-2.0 | 9563d20ed7a8577dccc4182399bee2f1 | 52.102544 | 765 | 0.686242 | 4.992004 | false | false | false | false |
Staance/DKChainableAnimationKit | DKChainableAnimationKit/Classes/DKKeyFrameAnimation.swift | 1 | 10631 | //
// DKKeyFrameAnimation.swift
// DKChainableAnimationKit
//
// Created by Draveness on 15/5/13.
// Copyright (c) 2015年 Draveness. All rights reserved.
//
import UIKit
public class DKKeyFrameAnimation: CAKeyframeAnimation {
internal let kFPS = 60
internal typealias DKKeyframeAnimationFunction = (Double, Double, Double, Double) -> Double;
internal var fromValue: AnyObject!
internal var toValue: AnyObject!
internal var functionBlock: DKKeyframeAnimationFunction!
convenience init(keyPath path: String!) {
self.init()
self.keyPath = path
self.functionBlock = DKKeyframeAnimationFunctionLinear
}
internal func calculte() {
self.createValueArray()
}
internal func createValueArray() {
if let fromValue: AnyObject = self.fromValue, let toValue: AnyObject = self.toValue {
if valueIsKindOf(NSNumber) {
self.values = self.valueArrayFor(startValue: CGFloat(fromValue.floatValue), endValue: CGFloat(toValue.floatValue)) as [AnyObject]
} else if valueIsKindOf(UIColor) {
let fromColor = self.fromValue.CGColor
let toColor = self.toValue.CGColor
let fromComponents = CGColorGetComponents(fromColor)
let toComponents = CGColorGetComponents(toColor)
let redValues = self.valueArrayFor(startValue: fromComponents[0], endValue: toComponents[0]) as! [CGFloat]
let greenValues = self.valueArrayFor(startValue: fromComponents[1], endValue: toComponents[1]) as! [CGFloat]
let blueValues = self.valueArrayFor(startValue: fromComponents[2], endValue: toComponents[2]) as! [CGFloat]
let alphaValues = self.valueArrayFor(startValue: fromComponents[3], endValue: toComponents[3]) as! [CGFloat]
self.values = self.colorArrayFrom(redValues: redValues, greenValues: greenValues, blueValues: blueValues, alphaValues: alphaValues) as [AnyObject]
} else if valueIsKindOf(NSValue) {
self.fromValue.objCType
let valueType: NSString! = NSString(CString: self.fromValue.objCType, encoding: 1)
if valueType.containsString("CGRect") {
let fromRect = self.fromValue.CGRectValue
let toRect = self.toValue.CGRectValue
let xValues = self.valueArrayFor(startValue: fromRect.origin.x, endValue: toRect.origin.x) as! [CGFloat]
let yValues = self.valueArrayFor(startValue: fromRect.origin.y, endValue: toRect.origin.x) as! [CGFloat]
let widthValues = self.valueArrayFor(startValue: fromRect.size.width, endValue: toRect.size.width) as! [CGFloat]
let heightValues = self.valueArrayFor(startValue: fromRect.size.height, endValue: toRect.size.height) as! [CGFloat]
self.values = self.rectArrayFrom(xValues: xValues, yValues: yValues, widthValues: widthValues, heightValues: heightValues) as [AnyObject]
} else if valueType.containsString("CGPoint") {
let fromPoint = self.fromValue.CGPointValue
let toPoint = self.toValue.CGPointValue
let path = self.createPathFromXYValues(self.valueArrayFor(startValue: fromPoint.x, endValue: toPoint.x), yValues: self.valueArrayFor(startValue: fromPoint.y, endValue: toPoint.y))
self.path = path
} else if valueType.containsString("CGSize") {
let fromSize = self.fromValue.CGSizeValue()
let toSize = self.toValue.CGSizeValue()
let path = self.createPathFromXYValues(self.valueArrayFor(startValue: fromSize.width, endValue: toSize.width), yValues: self.valueArrayFor(startValue: fromSize.height, endValue: toSize.height))
self.path = path
} else if valueType.containsString("CATransform3D") {
let fromTransform = self.fromValue.CATransform3DValue
let toTransform = self.toValue.CATransform3DValue
let m11 = self.valueArrayFor(startValue: fromTransform.m11, endValue: toTransform.m11)
let m12 = self.valueArrayFor(startValue: fromTransform.m12, endValue: toTransform.m12)
let m13 = self.valueArrayFor(startValue: fromTransform.m13, endValue: toTransform.m13)
let m14 = self.valueArrayFor(startValue: fromTransform.m14, endValue: toTransform.m14)
let m21 = self.valueArrayFor(startValue: fromTransform.m21, endValue: toTransform.m21)
let m22 = self.valueArrayFor(startValue: fromTransform.m22, endValue: toTransform.m22)
let m23 = self.valueArrayFor(startValue: fromTransform.m23, endValue: toTransform.m23)
let m24 = self.valueArrayFor(startValue: fromTransform.m24, endValue: toTransform.m24)
let m31 = self.valueArrayFor(startValue: fromTransform.m31, endValue: toTransform.m31)
let m32 = self.valueArrayFor(startValue: fromTransform.m32, endValue: toTransform.m32)
let m33 = self.valueArrayFor(startValue: fromTransform.m33, endValue: toTransform.m33)
let m34 = self.valueArrayFor(startValue: fromTransform.m34, endValue: toTransform.m34)
let m41 = self.valueArrayFor(startValue: fromTransform.m41, endValue: toTransform.m41)
let m42 = self.valueArrayFor(startValue: fromTransform.m42, endValue: toTransform.m42)
let m43 = self.valueArrayFor(startValue: fromTransform.m43, endValue: toTransform.m43)
let m44 = self.valueArrayFor(startValue: fromTransform.m44, endValue: toTransform.m44)
self.values = self.createTransformArrayFrom(
m11: m11, m12: m12, m13: m13, m14: m14,
m21: m21, m22: m22, m23: m23, m24: m24,
m31: m31, m32: m32, m33: m33, m34: m34,
m41: m41, m42: m42, m43: m43, m44: m44) as [AnyObject]
}
}
self.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
}
}
private func createTransformArrayFrom(
m11 m11: NSArray, m12: NSArray, m13: NSArray, m14: NSArray,
m21: NSArray, m22: NSArray, m23: NSArray, m24: NSArray,
m31: NSArray, m32: NSArray, m33: NSArray, m34: NSArray,
m41: NSArray, m42: NSArray, m43: NSArray, m44: NSArray) -> NSArray {
let numberOfTransforms = m11.count;
let values = NSMutableArray(capacity: numberOfTransforms)
var value: CATransform3D!
for (var i = 1; i < numberOfTransforms; i++) {
value = CATransform3DIdentity;
value.m11 = CGFloat(m11.objectAtIndex(i).floatValue)
value.m12 = CGFloat(m12.objectAtIndex(i).floatValue)
value.m13 = CGFloat(m13.objectAtIndex(i).floatValue)
value.m14 = CGFloat(m14.objectAtIndex(i).floatValue)
value.m21 = CGFloat(m21.objectAtIndex(i).floatValue)
value.m22 = CGFloat(m22.objectAtIndex(i).floatValue)
value.m23 = CGFloat(m23.objectAtIndex(i).floatValue)
value.m24 = CGFloat(m24.objectAtIndex(i).floatValue)
value.m31 = CGFloat(m31.objectAtIndex(i).floatValue)
value.m32 = CGFloat(m32.objectAtIndex(i).floatValue)
value.m33 = CGFloat(m33.objectAtIndex(i).floatValue)
value.m44 = CGFloat(m34.objectAtIndex(i).floatValue)
value.m41 = CGFloat(m41.objectAtIndex(i).floatValue)
value.m42 = CGFloat(m42.objectAtIndex(i).floatValue)
value.m43 = CGFloat(m43.objectAtIndex(i).floatValue)
value.m44 = CGFloat(m44.objectAtIndex(i).floatValue)
values.addObject(NSValue(CATransform3D: value))
}
return values
}
private func createPathFromXYValues(xValues: NSArray, yValues: NSArray) -> CGPathRef {
let numberOfPoints = xValues.count
let path = CGPathCreateMutable()
var value = CGPoint(
x: CGFloat(xValues.objectAtIndex(0).floatValue),
y: CGFloat(yValues.objectAtIndex(0).floatValue))
CGPathMoveToPoint(path, nil, value.x, value.y)
for i in 1..<numberOfPoints {
value = CGPoint(
x: CGFloat(xValues.objectAtIndex(i).floatValue),
y: CGFloat(yValues.objectAtIndex(i).floatValue))
CGPathAddLineToPoint(path, nil, value.x, value.y)
}
return path
}
private func valueIsKindOf(klass: AnyClass) -> Bool {
return self.fromValue.isKindOfClass(klass) && self.toValue.isKindOfClass(klass)
}
private func rectArrayFrom(xValues xValues: [CGFloat], yValues: [CGFloat], widthValues: [CGFloat], heightValues: [CGFloat]) -> NSArray {
let numberOfRects = xValues.count
let values: NSMutableArray = []
var value: NSValue
for i in 1..<numberOfRects {
value = NSValue(CGRect: CGRect(x: xValues[i], y: yValues[i], width: widthValues[i], height: heightValues[i]))
values.addObject(value)
}
return values
}
private func colorArrayFrom(redValues redValues: [CGFloat], greenValues: [CGFloat], blueValues: [CGFloat], alphaValues: [CGFloat]) -> [CGColor] {
let numberOfColors = redValues.count
var values: [CGColor] = []
var value: CGColor!
for i in 1..<numberOfColors {
value = UIColor(red: redValues[i], green: greenValues[i], blue: blueValues[i], alpha: alphaValues[i]).CGColor
values.append(value)
}
return values
}
private func valueArrayFor(startValue startValue: CGFloat, endValue: CGFloat) -> NSArray {
let startValue = Double(startValue)
let endValue = Double(endValue)
let steps: Int = Int(ceil(Double(kFPS) * self.duration)) + 2
let increment = 1.0 / (Double)(steps - 1)
var progress = 0.0
var v = 0.0
var value = 0.0
var valueArray: [Double] = []
for i in 0..<steps {
v = self.functionBlock(self.duration * progress * 1000, 0, 1, self.duration * 1000);
value = startValue + v * (endValue - startValue);
valueArray.append(value)
progress += increment
}
return valueArray
}
}
| mit | 4753795681b5ae9355cc96fd50ea4460 | 50.597087 | 213 | 0.627623 | 4.647573 | false | false | false | false |
lorentey/BigInt | Sources/Codable.swift | 2 | 5309 | //
// Codable.swift
// BigInt
//
// Created by Károly Lőrentey on 2017-8-11.
// Copyright © 2016-2017 Károly Lőrentey.
//
// Little-endian to big-endian
struct Units<Unit: FixedWidthInteger, Words: RandomAccessCollection>: RandomAccessCollection
where Words.Element: FixedWidthInteger, Words.Index == Int {
typealias Word = Words.Element
let words: Words
init(of type: Unit.Type, _ words: Words) {
precondition(Word.bitWidth % Unit.bitWidth == 0 || Unit.bitWidth % Word.bitWidth == 0)
self.words = words
}
var count: Int { return (words.count * Word.bitWidth + Unit.bitWidth - 1) / Unit.bitWidth }
var startIndex: Int { return 0 }
var endIndex: Int { return count }
subscript(_ index: Int) -> Unit {
let index = count - 1 - index
if Unit.bitWidth == Word.bitWidth {
return Unit(words[index])
}
else if Unit.bitWidth > Word.bitWidth {
let c = Unit.bitWidth / Word.bitWidth
var unit: Unit = 0
var j = 0
for i in (c * index) ..< Swift.min(c * (index + 1), words.endIndex) {
unit |= Unit(words[i]) << j
j += Word.bitWidth
}
return unit
}
// Unit.bitWidth < Word.bitWidth
let c = Word.bitWidth / Unit.bitWidth
let i = index / c
let j = index % c
return Unit(truncatingIfNeeded: words[i] >> (j * Unit.bitWidth))
}
}
extension Array where Element: FixedWidthInteger {
// Big-endian to little-endian
init<Unit: FixedWidthInteger>(count: Int?, generator: () throws -> Unit?) rethrows {
typealias Word = Element
precondition(Word.bitWidth % Unit.bitWidth == 0 || Unit.bitWidth % Word.bitWidth == 0)
self = []
if Unit.bitWidth == Word.bitWidth {
if let count = count {
self.reserveCapacity(count)
}
while let unit = try generator() {
self.append(Word(unit))
}
}
else if Unit.bitWidth > Word.bitWidth {
let wordsPerUnit = Unit.bitWidth / Word.bitWidth
if let count = count {
self.reserveCapacity(count * wordsPerUnit)
}
while let unit = try generator() {
var shift = Unit.bitWidth - Word.bitWidth
while shift >= 0 {
self.append(Word(truncatingIfNeeded: unit >> shift))
shift -= Word.bitWidth
}
}
}
else {
let unitsPerWord = Word.bitWidth / Unit.bitWidth
if let count = count {
self.reserveCapacity((count + unitsPerWord - 1) / unitsPerWord)
}
var word: Word = 0
var c = 0
while let unit = try generator() {
word <<= Unit.bitWidth
word |= Word(unit)
c += Unit.bitWidth
if c == Word.bitWidth {
self.append(word)
word = 0
c = 0
}
}
if c > 0 {
self.append(word << c)
var shifted: Word = 0
for i in self.indices {
let word = self[i]
self[i] = shifted | (word >> c)
shifted = word << (Word.bitWidth - c)
}
}
}
self.reverse()
}
}
extension BigInt: Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
// Decode sign
let sign: BigInt.Sign
switch try container.decode(String.self) {
case "+":
sign = .plus
case "-":
sign = .minus
default:
throw DecodingError.dataCorrupted(.init(codingPath: container.codingPath,
debugDescription: "Invalid big integer sign"))
}
// Decode magnitude
let words = try [UInt](count: container.count?.advanced(by: -1)) { () -> UInt64? in
guard !container.isAtEnd else { return nil }
return try container.decode(UInt64.self)
}
let magnitude = BigUInt(words: words)
self.init(sign: sign, magnitude: magnitude)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(sign == .plus ? "+" : "-")
let units = Units(of: UInt64.self, self.magnitude.words)
if units.isEmpty {
try container.encode(0 as UInt64)
}
else {
try container.encode(contentsOf: units)
}
}
}
extension BigUInt: Codable {
public init(from decoder: Decoder) throws {
let value = try BigInt(from: decoder)
guard value.sign == .plus else {
throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath,
debugDescription: "BigUInt cannot hold a negative value"))
}
self = value.magnitude
}
public func encode(to encoder: Encoder) throws {
try BigInt(sign: .plus, magnitude: self).encode(to: encoder)
}
}
| mit | 3ceeb9be23ddbca0d45af9f590d8d508 | 33.219355 | 110 | 0.522624 | 4.669014 | false | false | false | false |
Tj3n/TVNExtensions | Helper/LineView.swift | 1 | 1630 | //
// LineView.swift
// TVNExtensions
//
// Created by Tien Nhat Vu on 6/26/18.
//
import UIKit
@IBDesignable
public class LineView: UIView {
@IBInspectable public var lineColor: UIColor = .black {
didSet {
setNeedsDisplay()
}
}
@IBInspectable public var dashPhase: CGFloat = 0 {
didSet {
setNeedsDisplay()
}
}
@IBInspectable public var dashLength: CGFloat = 0 {
didSet {
setNeedsDisplay()
}
}
public var dashLengthPatterns: [CGFloat]?
public var lineJoin: CGLineJoin = .round
public var lineCap: CGLineCap = .butt
@IBInspectable public var masksToBounds: Bool {
get {
return self.layer.masksToBounds
}
set {
self.layer.masksToBounds = newValue
}
}
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override public func draw(_ rect: CGRect) {
// Drawing code
guard let context = UIGraphicsGetCurrentContext() else {
fatalError("No context")
}
context.setLineWidth(rect.size.height)
context.setLineDash(phase: dashPhase, lengths: dashLengthPatterns ?? [dashLength])
context.setLineJoin(lineJoin)
context.setLineCap(lineCap)
context.setStrokeColor(lineColor.cgColor)
context.move(to: .zero)
context.addLine(to: CGPoint(x: rect.maxX, y: 0))
context.strokePath()
context.saveGState()
setNeedsDisplay()
}
}
| mit | be06a68ff478d59a53fe5a552a1e601a | 24.873016 | 90 | 0.602454 | 4.909639 | false | false | false | false |
ypopovych/ExpressCommandLine | Sources/swift-express/Core/FileManager+Exists.swift | 1 | 3295 | //===--- FileManager+Exists.swift -------------------------------------------===//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express Command Line
//
//Swift Express Command Line 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.
//
//Swift Express Command Line 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 Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>.
//
//===------------------------------------------------------------------------===//
import Foundation
extension FileManager {
func directoryExists(at URL: URL) -> Bool {
do {
let attrs = try attributesOfItem(atPath: URL.path)
return attrs[FileAttributeKey.type] as? FileAttributeType == FileAttributeType.typeDirectory
} catch {
return false;
}
}
func fileExists(at URL: URL) -> Bool {
do {
let attrs = try attributesOfItem(atPath: URL.path)
return attrs[FileAttributeKey.type] as? FileAttributeType == FileAttributeType.typeRegular
} catch {
return false;
}
}
var tempDirectory: URL {
return URL(fileURLWithPath: NSTemporaryDirectory())
}
#if os(Linux)
func _copyItem(at srcURL: URL, to dstURL: URL) throws {
if fileExists(at: srcURL) {
try copyFile(at: srcURL, to: dstURL)
} else {
try copyDirectory(at: srcURL, to: dstURL)
}
}
private func copyFile(at srcURL: URL, to dstURL: URL) throws {
let inFile = try FileHandle(forReadingFrom: srcURL)
defer {
inFile.closeFile()
}
if !fileExists(at: dstURL) {
try Data().write(to: dstURL)
}
let outFile = try FileHandle(forWritingTo: dstURL)
defer {
outFile.synchronizeFile()
outFile.closeFile()
}
var bytes = inFile.readData(ofLength: 1024*1024)
while bytes.count > 0 {
outFile.write(bytes)
bytes = inFile.readData(ofLength: 1024*1024)
}
}
private func copyDirectory(at srcURL: URL, to dstURL: URL) throws {
if !directoryExists(at: dstURL) {
try createDirectory(at: dstURL, withIntermediateDirectories: true, attributes: nil)
}
for item in try contentsOfDirectory(at: srcURL, includingPropertiesForKeys: nil) {
if fileExists(at: item) {
try copyFile(at: item, to: dstURL.appendingPathComponent(item.lastPathComponent))
} else {
try copyDirectory(at: item, to: dstURL.appendingPathComponent(item.lastPathComponent))
}
}
}
#else
func _copyItem(at srcURL: URL, to dstURL: URL) throws {
try copyItem(at: srcURL, to: dstURL)
}
#endif
}
| gpl-3.0 | 340b3e4a1b79c35bd9f4720b24177ce7 | 34.815217 | 104 | 0.599697 | 4.789244 | false | false | false | false |
quire-io/SwiftyChrono | Sources/Parsers/FR/FRTimeAgoFormatParser.swift | 1 | 3657 | //
// FRTimeAgoFormatParser.swift
// SwiftyChrono
//
// Created by Jerry Chen on 2/6/17.
// Copyright © 2017 Potix. All rights reserved.
//
import Foundation
private let PATTERN = "(\\W|^)il y a\\s*([0-9]+|une?)\\s*(minutes?|heures?|semaines?|jours?|mois|années?|ans?)(?=(?:\\W|$))"
public class FRTimeAgoFormatParser: Parser {
override var pattern: String { return PATTERN }
override var language: Language { return .french }
override public func extract(text: String, ref: Date, match: NSTextCheckingResult, opt: [OptionType: Int]) -> ParsedResult? {
let idx = match.range(at: 0).location
if idx > 0 && NSRegularExpression.isMatch(forPattern: "\\w", in: text.substring(from: idx - 1, to: idx)) {
return nil
}
let (matchText, index) = matchTextAndIndex(from: text, andMatchResult: match)
var result = ParsedResult(ref: ref, index: index, text: matchText)
let number: Int
let numberText = match.string(from: text, atRangeIndex: 2).lowercased()
let parsedNumber = Int(numberText)
if parsedNumber == nil {
if NSRegularExpression.isMatch(forPattern: "demi", in: numberText) {
number = HALF
} else {
number = 1
}
} else {
number = parsedNumber!
}
var date = ref
let matchText3 = match.string(from: text, atRangeIndex: 3)
func ymdResult() -> ParsedResult {
result.start.imply(.day, to: date.day)
result.start.imply(.month, to: date.month)
result.start.imply(.year, to: date.year)
result.start.assign(.hour, value: date.hour)
result.start.assign(.minute, value: date.minute)
result.tags[.frTimeAgoFormatParser] = true
return result
}
if NSRegularExpression.isMatch(forPattern: "heure", in: matchText3) {
date = number != HALF ? date.added(-number, .hour) : date.added(-30, .minute)
return ymdResult()
} else if NSRegularExpression.isMatch(forPattern: "minute", in: matchText3) {
date = number != HALF ? date.added(-number, .minute) : date.added(-30, .second)
return ymdResult()
}
if NSRegularExpression.isMatch(forPattern: "semaine", in: matchText3) {
date = number != HALF ? date.added(-number * 7, .day) : date.added(-3, .day).added(-12, .hour)
result.start.imply(.day, to: date.day)
result.start.imply(.month, to: date.month)
result.start.imply(.year, to: date.year)
result.start.imply(.weekday, to: date.weekday)
result.tags[.frTimeAgoFormatParser] = true
return result
} else if NSRegularExpression.isMatch(forPattern: "jour", in: matchText3) {
date = number != HALF ? date.added(-number, .day) : date.added(-12, .hour)
} else if NSRegularExpression.isMatch(forPattern: "mois", in: matchText3) {
date = number != HALF ? date.added(-number, .month) : date.added(-(date.numberOf(.day, inA: .month) ?? 30)/2, .day)
} else if NSRegularExpression.isMatch(forPattern: "années?|ans?", in: matchText3) {
date = number != HALF ? date.added(-number, .year) : date.added(-6, .month)
}
result.start.assign(.day, value: date.day)
result.start.assign(.month, value: date.month)
result.start.assign(.year, value: date.year)
result.tags[.frTimeAgoFormatParser] = true
return result
}
}
| mit | 8e0160fef08a24e2fa8b7f43bf3b2d7c | 40.522727 | 129 | 0.584565 | 4.06 | false | false | false | false |
gaowanli/PinGo | PinGo/PinGo/Discover/TopicDetail/TopicDetailCell.swift | 1 | 1516 | //
// TopicDetailCell.swift
// PinGo
//
// Created by GaoWanli on 16/2/4.
// Copyright © 2016年 GWL. All rights reserved.
//
import UIKit
class TopicDetailCell: UICollectionViewCell {
@IBOutlet fileprivate weak var userIconbutton: UIButton!
@IBOutlet fileprivate weak var userNameLabel: UILabel!
@IBOutlet fileprivate weak var startNumButton: UIButton!
@IBOutlet fileprivate weak var bgImageView: UIImageView!
@IBOutlet fileprivate weak var descLabel: UILabel!
@IBOutlet fileprivate weak var startButton: UIButton!
var topicInfo: TopicInfo? {
didSet {
if let user = topicInfo?.userInfo {
if let headUrlStr = user.headUrl {
if let headUrl = URL(string: headUrlStr) {
userIconbutton.kf.setBackgroundImage(with: headUrl, for: .normal)
}
}
userNameLabel.text = user.nickname
}
startButton.setTitle(topicInfo?.commentCnt, for: UIControlState())
if let resUrlStr = topicInfo?.resUrl {
if let resUrl = URL(string: resUrlStr) {
bgImageView.kf.setImage(with: resUrl)
}
}
descLabel.text = topicInfo?.content
}
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = 5
layer.masksToBounds = true
}
}
| mit | d6e2f3930dbb1d6d252c7ac032e84753 | 29.26 | 89 | 0.569068 | 5.094276 | false | false | false | false |
silence0201/Swift-Study | SimpleProject/ImageCircle/ImageCircle/ViewController.swift | 1 | 1642 | //
// ViewController.swift
// ImageCircle
//
// Created by 杨晴贺 on 2017/3/14.
// Copyright © 2017年 Silence. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let iv = UIImageView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
iv.center = view.center
view.addSubview(iv)
iv.image = image(image: UIImage(named:"立华奏5.jpg")!, size: CGSize(width: 300, height: 300))
}
// 将给定的图片进行拉伸,并且返回新的图像
func image(image: UIImage,size: CGSize,backColor: UIColor = UIColor.white) -> UIImage {
let rect = CGRect(origin: CGPoint(), size: size)
// 上下文,在内存中开辟一个地址,和屏幕无关
// size: 绘图的尺寸
// opaque: 是否包含透明 false为透明
// scale: 屏幕分辨率,默认生成1的分辨率,图片质量不好,可以指定为0,会使用当前设备的屏幕分辨率
UIGraphicsBeginImageContextWithOptions(size, true, 0)
// 设置填充
backColor.setFill()
UIRectFill(rect)
// 实例一个原型的路径
let path = UIBezierPath(ovalIn: rect)
// 进行路径裁剪
path.addClip()
image.draw(in: rect)
// 绘制内切的圆形
UIColor.darkGray.setStroke()
path.lineWidth = 2
path.stroke()
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result ?? UIImage()
}
}
| mit | e0dee58f8117fe0bf45667fd5be1bf38 | 24.472727 | 98 | 0.591006 | 3.870166 | false | false | false | false |
matoushybl/iKGK-ios | iKGK/ChoosingController.swift | 1 | 2695 | //
// ChoosingController.swift
// iKGK
//
// Created by Matouš Hýbl on 19/04/15.
// Copyright (c) 2015 KGK. All rights reserved.
//
import UIKit
import Realm
import SwiftKit
class ChoosingController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
private let realm = RLMRealm.defaultRealm()
private let segmentedControl = UISegmentedControl(items: ["Classes", "Teachers"])
private let cellIdentifier = "Cell"
var classes: [ClassModel] = []
var teachers: [TeacherModel] = []
let onClassSelected = Event<ChoosingController, ClassModel>()
let onTeacherSelected = Event<ChoosingController, TeacherModel>()
override func loadView() {
super.loadView()
loadData()
tableView = UITableView()
tableView.dataSource = self
tableView.delegate = self
tableView.registerClass(ChooserTableCell.self, forCellReuseIdentifier: cellIdentifier)
segmentedControl.tintColor = UIColor.whiteColor()
segmentedControl.selectedSegmentIndex = 0
segmentedControl.valueChanged += { [unowned self] data in
self.tableView.reloadData()
}
navigationItem.titleView = segmentedControl
navigationItem.hidesBackButton = true
}
private func loadData() {
for aClass in ClassModel.allObjects() {
classes.append(aClass as! ClassModel)
}
for teacher in TeacherModel.allObjects() {
teachers.append(teacher as! TeacherModel)
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! ChooserTableCell
if(segmentedControl.selectedSegmentIndex == 0) {
cell.title = classes[indexPath.row].name
} else {
cell.title = teachers[indexPath.row].name
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if(segmentedControl.selectedSegmentIndex == 0) {
onClassSelected.fire(self, input: classes[indexPath.row])
} else {
onTeacherSelected.fire(self, input: teachers[indexPath.row])
}
navigationController?.popViewControllerAnimated(true)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(segmentedControl.selectedSegmentIndex == 0) {
return Int(classes.count)
} else {
return Int(teachers.count)
}
}
}
| mit | ea860d0bdc1109054257588b118741bd | 32.6625 | 118 | 0.655774 | 5.353877 | false | false | false | false |
SpectacularFigo/SwiftWB | SwiftWB/SwiftWB/Home/Compose/Controller/FHComposeViewController.swift | 1 | 5191 | //
// FHComposeViewController.swift
// SwiftWB
//
// Created by Figo Han on 2017-03-23.
// Copyright © 2017 Figo Han. All rights reserved.
//
import UIKit
import SnapKit
class FHComposeViewController: UIViewController {
// MARK:- properties
@IBOutlet weak var composeTextView: UITextView!
var placeholderLabel : UILabel?
@IBOutlet weak var toolBar: UIToolbar!
@IBOutlet weak var toolBarBotttomConstraint: NSLayoutConstraint!
@IBOutlet weak var getPicButton: UIButton!
// MARK:- system call backs
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewWillAppear(_ animated: Bool) {
self.composeTextView.becomeFirstResponder()
// self.composeTextView.contentInset = UIEdgeInsets(top: 66, left:15, bottom: 0, right: 15) // textView 继承自UIScrollView 等, contentInset 是UIScrollView 的属性。
// self.composeTextView.alwaysBounceHorizontal = false
// composeTextView.showsVerticalScrollIndicator = true
}
override func viewDidLoad() {
// Do any additional setup after loading the view.
super.viewDidLoad()
settingupNavigationITems()
settingupPlaceHolderLabel()
toolBarButtonSetup()
// 设置监听
// add observer to UITextView
NotificationCenter.default.addObserver(self, selector: #selector(composedContentChanged(note:)), name: NSNotification.Name.UITextViewTextDidChange, object: composeTextView)
// add observer to UIKeyborad
NotificationCenter.default.addObserver(self, selector: #selector(toolBarChangesFrame(notification:)), name: NSNotification.Name.UIKeyboardDidChangeFrame, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
// After deinitializing observer must be removed from default notification center
NotificationCenter.default.removeObserver(self)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
// MARK:- UISetup
extension FHComposeViewController
{
func settingupNavigationITems() -> Void {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(dismissComposeController))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Post", style: .plain, target: self, action: #selector(postTweet))
navigationItem.leftBarButtonItem?.isEnabled = false
}
func settingupPlaceHolderLabel() -> Void {
let placeHolderLabel = UILabel()
composeTextView.addSubview(placeHolderLabel)
placeHolderLabel.snp.makeConstraints { (make) in
make.top.equalTo(composeTextView)
make.leading.equalToSuperview()
}
placeHolderLabel.text = "What is Happening"
placeHolderLabel.textColor = UIColor.orange
placeHolderLabel.font = UIFont.systemFont(ofSize: 18.0)
self.placeholderLabel = placeHolderLabel
}
func toolBarButtonSetup() {
getPicButton.addTarget(self, action: #selector(getPicButtonClick), for: UIControlEvents.touchUpInside)
}
}
// MARK:- Events
extension FHComposeViewController{
@objc fileprivate func dismissComposeController() {
self.dismiss(animated: true, completion: nil)
}
@objc fileprivate func postTweet(){
print("postTweet")
}
@objc fileprivate func toolBarChangesFrame(notification: Notification){
print(notification)
let keyboardFrame = notification.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! CGRect
let keyboardHeight = keyboardFrame.height
let animationDuration = notification.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! Double
toolBarBotttomConstraint.constant = keyboardHeight
UIView.animate(withDuration: animationDuration) {
self.view.layoutIfNeeded()
}
}
@objc fileprivate func composedContentChanged(note : NSNotification){
if composeTextView.hasText {
navigationItem.leftBarButtonItem?.isEnabled = true
placeholderLabel?.isHidden = true
}
else{
navigationItem.leftBarButtonItem?.isEnabled = false
placeholderLabel?.isHidden = false
}
}
@objc fileprivate func getPicButtonClick(){
print("getPicButtonClick")
}
}
| apache-2.0 | ad2a67ab113cec40a74954f216cb88c4 | 27.20765 | 180 | 0.641224 | 5.780515 | false | false | false | false |
OatmealCode/Oatmeal | Pod/Classes/Extensions/Swift/Int.swift | 1 | 4480 | //
// Int.swift
// Cent
//
// Created by Ankur Patel on 6/30/14.
// Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved.
//
import Foundation
import SwiftyJSON
public struct CalendarMath {
private let unit: NSCalendarUnit
private let value: Int
private var calendar: NSCalendar {
return NSCalendar.autoupdatingCurrentCalendar()
}
public init(unit: NSCalendarUnit, value: Int) {
self.unit = unit
self.value = value
}
private func generateComponents(modifer: (Int) -> (Int) = (+)) -> NSDateComponents {
let components = NSDateComponents()
components.setValue(modifer(value), forComponent: unit)
return components
}
internal func from(date: NSDate) -> NSDate? {
return calendar.dateByAddingComponents(generateComponents(), toDate: date, options: [])
}
internal var fromNow: NSDate? {
return from(NSDate())
}
internal func before(date: NSDate) -> NSDate? {
return calendar.dateByAddingComponents(generateComponents(-), toDate: date, options: [])
}
internal var ago: NSDate? {
return before(NSDate())
}
}
public extension Int {
/// Check if it is even
///
/// :return Bool whether int is even
public var isEven: Bool {
get {
return self % 2 == 0
}
}
/// Check if it is odd
///
/// :return Bool whether int is odd
public var isOdd: Bool {
get {
return self % 2 == 1
}
}
/// Get ASCII character from integer
///
/// :return Character represented for the given integer
public var char: Character {
get {
return Character(UnicodeScalar(self))
}
}
/// Get the next int
///
/// :return next int
public func next() -> Int {
return self + 1
}
/// Get the previous int
///
/// :return previous int
public func prev() -> Int {
return self - 1
}
/// Invoke the callback from int down to and including limit
///
/// :params limit the min value to iterate upto
/// :params callback to invoke
public func downTo(limit: Int, callback: () -> ()) {
var selfCopy = self
while selfCopy-- >= limit {
callback()
}
}
/// Invoke the callback from int down to and including limit passing the index
///
/// :params limit the min value to iterate upto
/// :params callback to invoke
public func downTo(limit: Int, callback: (Int) -> ()) {
var selfCopy = self
while selfCopy >= limit {
callback(selfCopy--)
}
}
/// GCD metod return greatest common denominator with number passed
///
/// :param number
/// :return Greatest common denominator
public func gcd(n: Int) -> Int {
return $.gcd(self, n)
}
/// LCM method return least common multiple with number passed
///
/// :param number
/// :return Least common multiple
public func lcm(n: Int) -> Int {
return $.lcm(self, n)
}
/// Returns random number from 0 upto but not including value of integer
///
/// :return Random number
public func random() -> Int {
return $.random(self)
}
/// Returns Factorial of integer
///
/// :return factorial
public func factorial() -> Int {
return $.factorial(self)
}
/// Returns true if i is in closed interval
///
/// :param i to check if it is in interval
/// :param interval to check in
/// :return true if it is in interval otherwise false
public func isIn(interval: ClosedInterval<Int>) -> Bool {
return $.it(self, isIn: interval)
}
/// Returns true if i is in half open interval
///
/// :param i to check if it is in interval
/// :param interval to check in
/// :return true if it is in interval otherwise false
public func isIn(interval: HalfOpenInterval<Int>) -> Bool {
return $.it(self, isIn: interval)
}
/// Returns true if i is in range
///
/// :param i to check if it is in range
/// :param interval to check in
/// :return true if it is in interval otherwise false
public func isIn(interval: Range<Int>) -> Bool {
return $.it(self, isIn: interval)
}
}
extension Int : Resolveable
{
public static var entityName : String? = "Int"
} | mit | 1e163a5573cdc32bdf69dc8b797afa5c | 24.03352 | 96 | 0.579688 | 4.516129 | false | false | false | false |
shuuchen/SwiftTips | function.swift | 1 | 3947 | // an empty tuple of type Void is returned if return value is not specified
func greeting(name: String) {
println("hello \(name)")
}
let retVal = greeting("Jimmy") // (0 elements)
// return a tuple
func minMax(arr: [Int]) -> (min: Int, max: Int) {
var min = arr[0]
var max = arr[0]
for i in arr {
if i < min {
min = i
}
if i > max {
max = i
}
}
return (min, max)
}
let bounds = minMax([4, 6, 2, 6, 3, 45])
bounds.min
bounds.max
// return an optional tuple
// usually with safety check
// the entire tuple can be nil
func _minMax(arr: [Int]) -> (min: Int, max: Int)? {
// safety check
if arr.isEmpty {
return nil
}
var min = arr[0]
var max = arr[0]
for i in arr {
if i < min {
min = i
}
if i > max {
max = i
}
}
return (min, max)
}
// use optional binding to accesss the return value
if let bounds = _minMax([4, 6, 2, 6, 3, 45]) {
bounds.max
bounds.min
}
// external parameter name
// used to invoke the function
// must be always labeled
func hello(from me: String, to you: String) -> String {
return "say hello from \(me) to \(you)"
}
hello(from: "Jimmy", to: "Maggie")
// external parameter name can be omitted
// by using _
// may not work before v2.1
func something(str: String, knows: Bool) -> String {
if knows {
return "I know \(str)"
} else {
return "I dont know \(str)"
}
}
something("drink house", true)
// variadic parameters
// 0 or more value of a specific type
// used as a constant array within function
// a function may have at most 1 variadic parameter
func average(numbers: Double...) -> Double {
var total = 0.0
for n in numbers {
total += n
}
return total / Double(numbers.count)
}
average(4.5, 5, 90, 2.8)
// variable parameters
// parameters are constant by default
// using var to specify variable parameter, can be used as a local variable
// use return value to get the varied parameter (not like pointer in C)
func fillRight(var str: String, numOfBit: Int, c: Character) -> String {
for _ in 0..<numOfBit {
str.append(c)
}
return str
}
fillRight("Rox", 5, "-")
// inout parameters
// like pointer parameter in C, also use & to invoke
// cannot be a constant or a literal value
func swap(inout a: Int, inout b: Int) {
var tmp = a
a = b
b = tmp
}
var a = 5
var b = 9
swap(&a, &b)
a
b
// function type
// like function pointer in C
// can be used for function assignment
// determined by the types of both parameters and return values
let ava: (Double...) -> Double = average
let _ava = average // auto type inference by Swift
ava(23.5, 76.8, 9, 0.8, 1, 5)
// can be used as parameters to other functions
// the function implementation depends on the parameter
func add(a: Int, b: Int) -> Int {
return a + b
}
func sub(a: Int, b: Int) -> Int {
return a - b
}
func printMathResult(mathFunc: (Int, Int) -> Int, a: Int, b: Int) {
println("math result of a and b is \(mathFunc(a, b))")
}
printMathResult(add, 5, 7)
// can be used as return values
func chooseMathFunc(isAdd: Bool) -> (Int, Int) -> Int {
return isAdd ? add : sub
}
var mathFunc = chooseMathFunc(true)
mathFunc(5, 6)
// nested function
// function defined in the scope of another function
// are hidden outside of the scope but can be returned to use in another scope
func chooseMathFunc2(isMul: Bool) -> (Int, Int) -> Int {
func mul(a: Int, b: Int) -> Int {
return a * b
}
func div(a: Int, b: Int) -> Int {
return a / b
}
return isMul ? mul : div
}
mathFunc = chooseMathFunc2(false)
mathFunc(9, 3)
| mit | 97f82af34d6b5ab68fb736fb735bdb87 | 18.348039 | 78 | 0.575627 | 3.508444 | false | false | false | false |
cao903775389/MRCBaseLibrary | Example/MRCBaseLibrary/LoginViewController.swift | 1 | 2005 | //
// LoginViewController.swift
// MRCBaseLibrary
//
// Created by 逢阳曹 on 2017/6/13.
// Copyright © 2017年 CocoaPods. All rights reserved.
//
import UIKit
//对外部以Target-Action的形式提供入口
class Target_Login: NSObject {
func Action_fetchLoginViewController(_ params: [String: Any]?) -> LoginViewController {
let vc = LoginViewController()
vc.complete = params?["complete"] as? ActionComplete
vc.target = params?["target"] as? String
vc.action = params?["action"] as? String
return vc
}
}
class LoginViewController: MRCBaseViewController {
//登录成功回调
fileprivate var complete: ActionComplete?
//登录成功后需要执行的Target
fileprivate var target: String?
//登录成功后需要执行的Action
fileprivate var action: String?
//登录成功后需要执行的Action传递参数
fileprivate var params: [String: Any]?
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func loginSuccess(_ sender: UIButton) {
guard target != nil && action != nil else {
complete?(nil)
return
}
self.dismiss(animated: true) {[unowned self] in
UserDefaults.LoginStatus.set(value: "登录了", forKey: .lastLoginTime)
MRCMediator.sharedMRCMediator().performTarget(self.target!, actionName: self.action!, params: self.params) { result in
//继续需要执行Target-Action
self.complete?(result)
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 76622d5a3fe5bb50747cf832fd0be7aa | 25.8 | 130 | 0.621002 | 4.598039 | false | false | false | false |
Pretz/SwiftGraphics | SwiftGraphics_UnitTests/ConvexHullTests.swift | 3 | 2040 | //
// ConvexHullTests.swift
// SwiftGraphics
//
// Created by Jonathan Wight on 9/17/14.
// Copyright (c) 2014 schwa.io. All rights reserved.
//
import XCTest
import SwiftGraphics
//extension CGPoint : Comparable {
//}
//
//public func < (lhs: CGPoint, rhs: CGPoint) -> Bool {
// return lhs.y < rhs.y ? true : (lhs.y == rhs.y ? (lhs.x < rhs.x ? true : false) : false)
//}
//
//class ConvexHullTests: XCTestCase {
// func testMonotoneChain1() {
// let p = [
// CGPoint(x: 0, y: 0),
// CGPoint(x: 10, y: 0),
// CGPoint(x: 10, y: 10),
// CGPoint(x: 0, y: 10),
// CGPoint(x: 5, y: 5), // Not in hull
// ]
// let hull = monotoneChain(p).sorted(<)
// let expected = Array <CGPoint> (p[0...3]).sorted(<)
// XCTAssertEqual(hull, expected)
// }
//
// func testMonotoneChain2() {
// let p = [
// CGPoint(x: 0, y: 0),
// CGPoint(x: 10, y: 0),
// CGPoint(x: 10, y: 10),
// CGPoint(x: 0, y: 10),
// ]
// let hull = monotoneChain(p).sorted(<)
// let expected = Array <CGPoint> (p[0...3]).sorted(<)
// XCTAssertEqual(hull, expected)
// }
//
// func testMonotoneChain3() {
// let p = [
// CGPoint(x: 0, y: 0),
// CGPoint(x: 10, y: 0),
// CGPoint(x: 10, y: 10),
// ]
// let hull = monotoneChain(p).sorted(<)
// let expected = p.sorted(<)
// XCTAssertEqual(hull, expected)
// }
//
// func testMonotoneChain4() {
// let p = [
// CGPoint(x: 0, y: 0),
// CGPoint(x: 10, y: 0),
// ]
// let hull = monotoneChain(p).sorted(<)
// let expected = p.sorted(<)
// XCTAssertEqual(hull, expected)
// }
//
// func testMonotoneChain5() {
// let p = [
// CGPoint(x: 0, y: 0),
// ]
// let hull = monotoneChain(p).sorted(<)
// let expected = p.sorted(<)
// XCTAssertEqual(hull, expected)
// }
//}
| bsd-2-clause | a4e4690e8a9304d971804e5c9813e8e6 | 26.567568 | 93 | 0.47451 | 3.1875 | false | true | false | false |
Mazy-ma/DemoBySwift | EmotionKeyboard/EmotionKeyboard/EmotionKeyboardView/TopTitlesView.swift | 1 | 7546 | //
// TopTitlesView.swift
// NewsFrameworkDemo
//
// Created by Mazy on 2017/7/25.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
protocol TopTitlesViewDelegate {
func didClickTopTitleView(_ titlesView: TopTitlesView, selectedIndex index : Int)
}
class TopTitlesView: UIView {
// MARK: 对外属性
var delegate: TopTitlesViewDelegate?
fileprivate lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.frame = self.bounds
scrollView.showsHorizontalScrollIndicator = false
return scrollView
}()
fileprivate lazy var indicatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.red
return view
}()
fileprivate var titles: [String]
fileprivate var titleLabels: [UILabel] = [UILabel]()
fileprivate var currentIndex : Int = 0
fileprivate var titleProperty: TitleViewProperty
init(frame: CGRect, titles: [String], titleProperty: TitleViewProperty) {
self.titles = titles
self.titleProperty = titleProperty
super.init(frame: frame)
layoutIfNeeded()
setNeedsLayout()
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TopTitlesView {
func setupUI() {
backgroundColor = UIColor.white
addSubview(scrollView)
setupTitleLabels()
setupTitleLabelsPosition()
setupIndicatorView()
setShadow()
}
fileprivate func setShadow(){
if !titleProperty.isNeedShadowInBottom { return }
self.layer.shadowColor = UIColor.lightGray.cgColor
self.layer.shadowOpacity = 0.3
self.layer.shadowOffset = CGSize(width: 0, height: 2)
self.layer.shadowRadius = 2
self.layer.masksToBounds = false
self.layer.magnificationFilter = kCAFilterLinear
}
fileprivate func setupTitleLabels() {
for (index, title) in titles.enumerated() {
let label = UILabel()
label.text = title
label.textAlignment = .center
label.font = titleProperty.font
label.textColor = titleProperty.normalColor
label.tag = 1024 + index
label.isUserInteractionEnabled = true
if index == 0 {
label.textColor = titleProperty.selectedColor
}
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick))
label.addGestureRecognizer(tapGesture)
scrollView.addSubview(label)
titleLabels.append(label)
}
}
fileprivate func setupTitleLabelsPosition() {
for (index, label) in titleLabels.enumerated() {
var titleX: CGFloat = 0
var titleW: CGFloat = 0
let titleY: CGFloat = 0
let titleH: CGFloat = bounds.height
if titleProperty.isScrollEnable { // 可以滚动
titleW = label.intrinsicContentSize.width
if index == 0 {
titleX = titleProperty.titleMargin * 0.5
} else {
let preLabel = titleLabels[index - 1]
titleX = preLabel.frame.maxX + titleProperty.titleMargin
}
} else { // 不可滚动
titleW = bounds.width/CGFloat(titles.count)
titleX = titleW * CGFloat(index)
}
label.frame = CGRect(x: titleX, y: titleY, width: titleW, height: titleH)
if titleProperty.isScrollEnable {
scrollView.contentSize = CGSize(width: titleLabels.last!.frame.maxX + titleProperty.titleMargin*0.5, height: 0)
}
}
}
fileprivate func setupIndicatorView() {
indicatorView.isHidden = titleProperty.isHiddenBottomLine
indicatorView.backgroundColor = UIColor.red
if !titleProperty.isScrollEnable {
indicatorView.frame = titleLabels.first!.frame
} else {
let titleW: CGFloat = titleLabels.first!.intrinsicContentSize.width
indicatorView.frame.origin.x = (titleLabels.first!.bounds.width-titleW) * 0.5
indicatorView.frame.size.width = titleW
}
indicatorView.frame.size.height = 2
indicatorView.frame.origin.y = bounds.height - 2
scrollView.addSubview(indicatorView)
}
}
extension TopTitlesView {
func titleLabelClick(tapGesture: UITapGestureRecognizer) {
// 获取当前Label
guard let currentLabel = tapGesture.view as? UILabel else { return }
// 如果是重复点击同一个Title,那么直接返回
if (currentLabel.tag-1024 == currentIndex) { return }
// 获取之前的Label
let oldLabel = titleLabels[currentIndex]
// 切换文字的颜色
currentLabel.textColor = UIColor.red
oldLabel.textColor = UIColor.darkGray
currentIndex = currentLabel.tag-1024
delegate?.didClickTopTitleView(self, selectedIndex: currentIndex)
// 7.调整bottomLine
if !titleProperty.isHiddenBottomLine {
UIView.animate(withDuration: 0.25, animations: {
self.indicatorView.frame.origin.x = currentLabel.frame.origin.x
self.indicatorView.frame.size.width = currentLabel.frame.size.width
})
}
contentViewDidEndScrollAndAdjustLabelPosition()
}
func contentViewDidEndScrollAndAdjustLabelPosition() {
// 0.如果是不需要滚动,则不需要调整中间位置
guard titleProperty.isScrollEnable else { return }
// 1.获取获取目标的Label
let targetLabel = titleLabels[currentIndex]
// 2.计算和中间位置的偏移量
var offSetX = targetLabel.center.x - bounds.width * 0.5
if offSetX < 0 {
offSetX = 0
}
let maxOffset = scrollView.contentSize.width - bounds.width
if offSetX > maxOffset {
offSetX = maxOffset
}
// 3.滚动UIScrollView
UIView.animate(withDuration: 0.25) {
self.scrollView.setContentOffset(CGPoint(x: offSetX, y: 0), animated: false)
}
}
}
// MARK:- 对外暴露的方法
extension TopTitlesView {
func setTitleWithContentOffset(_ contentOffsetX: CGFloat) {
let index: Int = Int(contentOffsetX/bounds.width + 0.5)
currentIndex = index
_ = titleLabels.map({ $0.textColor = titleProperty.normalColor })
let currentLabel = titleLabels[index]
let firstLabel = titleLabels[0]
currentLabel.textColor = titleProperty.selectedColor
var offset: CGFloat = 0
if titleProperty.isScrollEnable {
offset = currentLabel.frame.origin.x + currentLabel.intrinsicContentSize.width/2
} else {
offset = contentOffsetX/CGFloat(self.titles.count) + firstLabel.center.x
}
UIView.animate(withDuration: 0.25) {
self.indicatorView.center.x = offset
if self.titleProperty.isScrollEnable {
self.indicatorView.frame.size.width = currentLabel.intrinsicContentSize.width
}
}
}
}
| apache-2.0 | db178e7f22d3343a14bc91c245e59e10 | 31.427313 | 127 | 0.600734 | 5.284279 | false | false | false | false |
mozilla/focus | OpenInFocus/ActionViewController.swift | 4 | 5136 | /* 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 Social
import MobileCoreServices
extension NSObject {
func callSelector(selector: Selector, object: AnyObject?, delay: TimeInterval) {
let delay = delay * Double(NSEC_PER_SEC)
let time = DispatchTime(uptimeNanoseconds: UInt64(delay))
DispatchQueue.main.asyncAfter(deadline: time) {
Thread.detachNewThreadSelector(selector, toTarget: self, with: object)
}
}
}
extension NSURL {
var encodedUrl: String? { return absoluteString?.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.alphanumerics) }
}
extension NSItemProvider {
var isText: Bool { return hasItemConformingToTypeIdentifier(String(kUTTypeText)) }
var isUrl: Bool { return hasItemConformingToTypeIdentifier(String(kUTTypeURL)) }
func processText(completion: CompletionHandler?) {
loadItem(forTypeIdentifier: String(kUTTypeText), options: nil, completionHandler: completion)
}
func processUrl(completion: CompletionHandler?) {
loadItem(forTypeIdentifier: String(kUTTypeURL), options: nil, completionHandler: completion)
}
}
class ActionViewController: SLComposeServiceViewController {
private var isKlar: Bool { return (Bundle.main.infoDictionary!["CFBundleIdentifier"] as! String).contains("Klar") }
private var urlScheme: String { return isKlar ? "firefox-klar" : "firefox-focus" }
override func isContentValid() -> Bool { return true }
override func didSelectPost() { return }
func focusUrl(url: String) -> NSURL? {
return NSURL(string: "\(self.urlScheme)://open-url?url=\(url)")
}
func textUrl(text: String) -> NSURL? {
guard let query = text.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return nil }
return NSURL(string: "\(self.urlScheme)://open-text?text=\(query)")
}
override func configurationItems() -> [Any]! {
let inputItems: [NSExtensionItem] = (extensionContext?.inputItems as? [NSExtensionItem]) ?? []
var urlProvider: NSItemProvider?
var textProvider: NSItemProvider?
// Look for the first URL the host application is sharing.
// If there isn't a URL grab the first text item
for item: NSExtensionItem in inputItems {
let attachments: [NSItemProvider] = (item.attachments as? [NSItemProvider]) ?? []
for attachment in attachments {
if urlProvider == nil && attachment.isUrl {
urlProvider = attachment
} else if textProvider == nil && attachment.isText {
textProvider = attachment
}
}
}
// If a URL is found, process it. Otherwise we will try to convert
// the text item to a URL falling back to sending just the text.
if let urlProvider = urlProvider {
urlProvider.processUrl { (urlItem, error) in
guard let focusUrl = (urlItem as? NSURL)?.encodedUrl.flatMap(self.focusUrl) else { self.cancel(); return }
self.handleUrl(focusUrl)
}
} else if let textProvider = textProvider {
textProvider.processText { (textItem, error) in
guard let text = textItem as? String else { self.cancel(); return }
if let url = NSURL(string: text) {
guard let focusUrl = url.encodedUrl.flatMap(self.focusUrl) else { self.cancel(); return }
self.handleUrl(focusUrl)
} else {
guard let focusUrl = self.textUrl(text: text) else { self.cancel(); return }
self.handleUrl(focusUrl)
}
}
} else {
// If no item was processed. Cancel the share action to prevent the
// extension from locking the host application due to the hidden
// ViewController
self.cancel()
}
return []
}
private func handleUrl(_ url: NSURL) {
// From http://stackoverflow.com/questions/24297273/openurl-not-work-in-action-extension
var responder = self as UIResponder?
let selectorOpenURL = sel_registerName("openURL:")
while responder != nil {
if responder!.responds(to: selectorOpenURL) {
responder!.callSelector(selector: selectorOpenURL, object: url, delay: 0)
}
responder = responder!.next
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: UInt64(0.1 * Double(NSEC_PER_SEC)))) {
self.cancel()
}
}
override func viewDidAppear(_ animated: Bool) {
// Stop keyboard from showing
textView.resignFirstResponder()
textView.isEditable = false
super.viewDidAppear(animated)
}
override func willMove(toParentViewController parent: UIViewController?) {
view.alpha = 0
}
}
| mpl-2.0 | ed5fd7e261eeb2b2deef1ec81a0ae014 | 39.440945 | 129 | 0.635125 | 4.91954 | false | false | false | false |
glimpseio/ChannelZ | Playgrounds/Introduction.playground/section-18-original.swift | 1 | 568 | struct ViewModel {
let amount = ∞(Double(0))∞
let amountMax = Double(100.0)
}
let vm = ViewModel()
let stepper = UIStepper()
stepper.maximumValue = vm.amountMax
stepper∞stepper.value <=∞=> vm.amount
let slider = UISlider()
slider.maximumValue = Float(vm.amountMax)
slider∞slider.value <~∞~> vm.amount
stepper.value += 25.0
assert(slider.value == 25.0)
assert(vm.amount.source.value == 25.0)
slider.value += 30.0
assert(stepper.value == 55.0)
assert(vm.amount.source.value == 55.0)
println("slider: \(slider.value) stepper: \(stepper.value)")
| mit | 6335bbf4f003c3018bf7c14bb8bd139c | 22.166667 | 60 | 0.697842 | 3.021739 | false | false | false | false |
shaymanjohn/speccyMac | speccyMac/z80/Z80+ddcb.swift | 1 | 1612 | //
// Z80+ddcb.swift
// speccyMac
//
// Created by John Ward on 21/07/2017.
// Copyright © 2017 John Ward. All rights reserved.
//
import Foundation
extension ZilogZ80 {
final func ddcbprefix(opcode: UInt8, first: UInt8) throws {
let instruction = instructionSet.cbprefix[opcode]
let offsetAddress = first > 127 ? ixy.value &- (UInt16(256) - UInt16(first)) : ixy.value &+ UInt16(first)
// log(instruction)
switch opcode {
case 0x06:
memory.rlc(offsetAddress)
case 0x0e:
memory.rrc(offsetAddress)
case 0x2e:
memory.sra(offsetAddress)
case 0x46, 0x4e, 0x56, 0x5e, 0x66, 0x6e, 0x76, 0x7e:
let bitValue = (opcode - 0x46) >> 3
memory.indexBit(bitValue, address: offsetAddress)
case 0x86, 0x8e, 0x96, 0x9e, 0xa6, 0xae, 0xb6, 0xbe:
let bitValue = (opcode - 0x86) >> 3
memory.indexRes(bitValue, address: offsetAddress)
case 0xc6, 0xce, 0xd6, 0xde, 0xe6, 0xee, 0xf6, 0xfe:
let bitValue = (opcode - 0xc6) >> 3
memory.indexSet(bitValue, address: offsetAddress)
default:
throw NSError(domain: "z80+ddcb", code: 1, userInfo: ["opcode" : String(opcode, radix: 16, uppercase: true), "instruction" : instruction.opcode, "pc" : pc])
}
pc = pc &+ instruction.length + 2
incCounters(instruction.tstates + 8)
r.inc()
r.inc()
}
}
| gpl-3.0 | 63daa154408b344071dce913f1c78c90 | 29.396226 | 168 | 0.539417 | 3.502174 | false | false | false | false |
amleszk/RxPasscode | RxPasscode/PasscodePresenter+Scenarios.swift | 1 | 4050 |
extension PasscodePresenter {
func presentWithBlurBackground() {
screenshotAndPresentPasscodeObstructionIfNeeded()
}
func presentWithValidatePasscode(allowCancel: Bool = false, completion: PresentationCompletion? = nil) {
screenshotAndPresentPasscodeObstructionIfNeeded()
guard let passcodeDatasource = passcodeDatasource else {
return
}
var numberOfTries = 0
let existingPasscode: [Int] = passcodeDatasource.passcode()
passcodeLockViewController = PasscodeLockViewController(validateCode: { passcode in
return self.passcodeValidateHandler(existingPasscode, nextPasscode: passcode, numberOfTries: &numberOfTries)
}, dismiss: passcodeDismiss(completion))
passcodeLockViewController.cancelButtonEnabled = allowCancel
passcodeView.pinView(passcodeLockViewController.view)
}
func presentWithNewPasscode(completion: PresentationCompletion? = nil) {
screenshotAndPresentPasscodeObstructionIfNeeded()
var newPasscode: [Int] = []
passcodeLockViewController = PasscodeLockViewController(validateCode: { passcode in
return self.passcodeSetNewHandler(passcode, capturedPasscode: &newPasscode)
}, dismiss: passcodeDismiss(completion))
passcodeLockViewController.cancelButtonEnabled = true
passcodeView.pinView(passcodeLockViewController.view)
}
func presentWithChangePasscode(completion: PresentationCompletion? = nil) {
screenshotAndPresentPasscodeObstructionIfNeeded()
guard let passcodeDatasource = passcodeDatasource else {
return
}
let existingPasscode: [Int] = passcodeDatasource.passcode()
var validated = false
var newPasscode: [Int] = []
var numberOfTries = 0
passcodeLockViewController = PasscodeLockViewController(validateCode: { passcode in
if !validated {
return self.passcodeEnterNewHandler(existingPasscode, nextPasscode: passcode, numberOfTries: &numberOfTries, validated: &validated)
} else {
return self.passcodeSetNewHandler(passcode, capturedPasscode: &newPasscode)
}
}, dismiss: passcodeDismiss(completion))
passcodeLockViewController.cancelButtonEnabled = true
passcodeView.pinView(passcodeLockViewController.view)
}
//MARK: Callbacks
func passcodeDismiss(completion: PresentationCompletion? = nil) -> PresentationCompletion {
return { didCancel in
self.dismissAnimated(true) {
completion?(didCancel)
}
}
}
func passcodeSetNewHandler(nextPasscode: [Int], inout capturedPasscode: [Int]) -> PasscodeLockViewController.PasscodeResponse {
if capturedPasscode.count == 0 {
capturedPasscode = nextPasscode
return .ReEnter
} else if capturedPasscode == nextPasscode {
passcodeDatasource?.didSetNewPasscode(capturedPasscode)
return .Accepted
} else {
return .Invalid
}
}
func passcodeValidateHandler(existingPasscode: [Int], nextPasscode: [Int], inout numberOfTries: Int) -> PasscodeLockViewController.PasscodeResponse {
if nextPasscode == existingPasscode {
return .Accepted
} else {
numberOfTries += 1
if numberOfTries >= passcodeMaxNumberTries {
passcodeDatasource?.didFailAllPasscodeAttempts()
}
return .Invalid
}
}
func passcodeEnterNewHandler(existingPasscode: [Int], nextPasscode: [Int], inout numberOfTries: Int, inout validated: Bool) -> PasscodeLockViewController.PasscodeResponse {
var value = self.passcodeValidateHandler(existingPasscode, nextPasscode: nextPasscode, numberOfTries: &numberOfTries)
if(value == .Accepted) {
validated = true
value = .EnterNew
}
return value
}
}
| mit | d3aca59d701b5ce7135ce0bc0ee90bd3 | 42.085106 | 176 | 0.673333 | 6.035768 | false | false | false | false |
thierrybucco/Eureka | Source/Rows/Common/SelectorRow.swift | 7 | 3564 | // SelectorRow.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
open class PushSelectorCell<T: Equatable> : Cell<T>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func update() {
super.update()
accessoryType = .disclosureIndicator
editingAccessoryType = accessoryType
selectionStyle = row.isDisabled ? .none : .default
}
}
/// Generic row type where a user must select a value among several options.
open class SelectorRow<Cell: CellType, VCType: TypedRowControllerType>: OptionsRow<Cell>, PresenterRowType where Cell: BaseCell, VCType: UIViewController, VCType.RowValue == Cell.Value {
/// Defines how the view controller will be presented, pushed, etc.
open var presentationMode: PresentationMode<VCType>?
/// Will be called before the presentation occurs.
open var onPresentCallback: ((FormViewController, VCType) -> Void)?
required public init(tag: String?) {
super.init(tag: tag)
}
/**
Extends `didSelect` method
*/
open override func customDidSelect() {
super.customDidSelect()
guard let presentationMode = presentationMode, !isDisabled else { return }
if let controller = presentationMode.makeController() {
controller.row = self
controller.title = selectorTitle ?? controller.title
onPresentCallback?(cell.formViewController()!, controller)
presentationMode.present(controller, row: self, presentingController: self.cell.formViewController()!)
} else {
presentationMode.present(nil, row: self, presentingController: self.cell.formViewController()!)
}
}
/**
Prepares the pushed row setting its title and completion callback.
*/
open override func prepare(for segue: UIStoryboardSegue) {
super.prepare(for: segue)
guard let rowVC = segue.destination as? VCType else { return }
rowVC.title = selectorTitle ?? rowVC.title
rowVC.onDismissCallback = presentationMode?.onDismissCallback ?? rowVC.onDismissCallback
onPresentCallback?(cell.formViewController()!, rowVC)
rowVC.row = self
}
}
| mit | baca3e0063bf40f319ae2498e8480151 | 40.929412 | 186 | 0.708474 | 5.019718 | false | false | false | false |
gdamron/PaulaSynth | PaulaSynth/TileView.swift | 1 | 1804 | //
// TileView.swift
// PaulaSynth
//
// Created by Grant Damron on 10/21/16.
// Copyright © 2016 Grant Damron. All rights reserved.
//
import UIKit
@IBDesignable
class TileView: UIView {
@IBInspectable
var color: UIColor = UIColor.clear {
didSet {
tile?.backgroundColor = color
}
}
@IBInspectable
var trailing: CGFloat = 0.0 {
didSet {
trailingMargin?.constant = trailing
}
}
@IBInspectable
var top: CGFloat = 0.0 {
didSet {
topMargin?.constant = top
}
}
@IBInspectable
var bottom: CGFloat = 0.0 {
didSet {
bottomMargin?.constant = bottom
}
}
@IBInspectable
var leading: CGFloat = 0.0 {
didSet {
leadingMargin?.constant = leading
}
}
@IBOutlet var view: UIView!
@IBOutlet weak var tile: UIView?
@IBOutlet weak var trailingMargin: NSLayoutConstraint?
@IBOutlet weak var topMargin: NSLayoutConstraint?
@IBOutlet weak var bottomMargin: NSLayoutConstraint?
@IBOutlet weak var leadingMargin: NSLayoutConstraint?
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "TileView", bundle: bundle)
view = (nib.instantiate(withOwner: self, options: nil)[0] as! UIView)
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
updateConstraintsIfNeeded()
}
override func prepareForInterfaceBuilder() {
setup()
}
}
| apache-2.0 | 39e68e128e7ac23f264aaa45808cccc5 | 23.364865 | 77 | 0.586245 | 4.646907 | false | false | false | false |
jphacks/KB_01 | jphacks/ViewController/SearchViewController/SearchViewController.swift | 1 | 8729 | //
// SearchViewController.swift
// jphacks
//
// Created by 内村祐之 on 2015/11/28.
// Copyright © 2015年 at. All rights reserved.
//
import Foundation
import UIKit
import CoreLocation
class SearchViewController: BaseViewController {
@IBOutlet weak var startLocationButton: UIButton!
@IBOutlet weak var targetLocationButton: UIButton!
@IBOutlet weak var searchButton: UIButton!
@IBOutlet weak var sightSeeingsToggle: SpotOptionButton!
@IBOutlet weak var toiletToggle: SpotOptionButton!
@IBOutlet weak var nightSpotsToggle: SpotOptionButton!
@IBOutlet weak var monumentsToggle: SpotOptionButton!
@IBOutlet weak var convinienceToggle: SpotOptionButton!
@IBOutlet weak var theatersToggle: SpotOptionButton!
var splashImageView: UIImageView!
var walkAnimationImageView: UIImageView!
let locationManager = CLLocationManager()
@IBAction func GoToMapView(sender: AnyObject) {
var spots: [Spot] = []
if sightSeeingsToggle.hilightened {
spots += SpotManager.sharedController.sightseeingSpotRepository.spots as [Spot]
}
if toiletToggle.hilightened {
spots += SpotManager.sharedController.toiletSpotRepository.spots as [Spot]
}
if nightSpotsToggle.hilightened {
spots += SpotManager.sharedController.nightViewSpotRepository.spots as [Spot]
}
if monumentsToggle.hilightened {
spots += SpotManager.sharedController.sculptureSpotRepository.spots as [Spot]
}
if theatersToggle.hilightened {
spots += SpotManager.sharedController.filmingLocationSpotRepository.spots as [Spot]
}
var viaLocations: [CLLocationCoordinate2D] = []
if let spot = SpotManager.startSpot {
viaLocations.append(CLLocationCoordinate2D(latitude: spot.latitude, longitude: spot.longitude))
} else {
if let coordinate = locationManager.location?.coordinate {
viaLocations.append(coordinate)
} else {
let alertViewController = UIAlertController(title: "現在地", message: "位置情報を取得できません", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alertViewController, animated: true, completion: { dispatch_after(2, dispatch_get_main_queue(), {self.dismissViewControllerAnimated(true, completion: nil)}) })
return
}
}
if let spot = SpotManager.targetSpot {
viaLocations.append(CLLocationCoordinate2D(latitude: spot.latitude, longitude: spot.longitude))
} else {
let alertViewController = UIAlertController(title: "未入力", message: "目的地を設定", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alertViewController, animated: true, completion: { dispatch_after(2, dispatch_get_main_queue(), {self.dismissViewControllerAnimated(true, completion: nil)}) })
return
}
let storyboard = UIStoryboard(name: "MapView", bundle: nil)
let controller = storyboard.instantiateInitialViewController() as! MapViewController
controller.spots = spots
controller.viaLocations = viaLocations
self.presentViewController(controller, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// 位置情報に関して権限をもらう
locationManager.delegate = self
let status = CLLocationManager.authorizationStatus()
if(status == CLAuthorizationStatus.NotDetermined) {
locationManager.requestAlwaysAuthorization()
}
let header = SearchHeaderView()
header.setup(CGRectMake(0, UIApplication.sharedApplication().statusBarFrame.height, self.view.bounds.width, 50))
self.view.addSubview(header)
searchButton.layer.cornerRadius = 60
let frame = CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y, width: self.view.frame.size.width + 100, height: self.view.frame.size.height + 100)
self.splashImageView = UIImageView(frame: frame)
self.splashImageView.center = self.view.center
self.splashImageView.image = UIImage(named: "splash")
self.view.addSubview(self.splashImageView)
let frame2 = CGRect(x: self.view.center.x, y: self.view.center.y, width: 50, height: 50)
self.walkAnimationImageView = UIImageView(frame: frame2)
self.walkAnimationImageView.center = self.view.center
self.walkAnimationImageView.center.y += 70
self.walkAnimationImageView.animationImages = [UIImage]()
self.walkAnimationImageView.image = UIImage(named: "walk_00000")
for i in 0..<30 {
let frameName = String(format: "walk_%05d", i)
self.walkAnimationImageView.animationImages?.append(UIImage(named: frameName)!)
}
self.view.addSubview(self.walkAnimationImageView)
}
override func viewWillAppear(animated: Bool) {
startLocationButton.setTitle(SpotManager.startSpot?.name ?? "(現在地)", forState: .Normal)
targetLocationButton.setTitle(SpotManager.targetSpot?.name ?? "(タップして設定)", forState: .Normal)
}
override func viewDidAppear(animated: Bool) {
self.walkAnimationImageView.animationDuration = 1
self.walkAnimationImageView.startAnimating()
UIView.animateWithDuration(0.6, // 0.3
delay: 1.0, // 1.0,
options: UIViewAnimationOptions.CurveEaseOut,
animations: { () in
self.splashImageView.transform = CGAffineTransformMakeScale(0.9, 0.9)
self.walkAnimationImageView.transform = CGAffineTransformMakeScale(0.9, 0.9)
}, completion: nil
)
UIView.animateWithDuration(0.5, // 0.2,
delay: 1.6, // 1.3,
options: UIViewAnimationOptions.CurveEaseOut,
animations: { () in
self.splashImageView.transform = CGAffineTransformMakeScale(1.2, 1.2)
self.splashImageView.alpha = 0
self.walkAnimationImageView.transform = CGAffineTransformMakeScale(1.2, 1.2)
self.walkAnimationImageView.alpha = 0
}, completion: { (Bool) in
self.splashImageView.removeFromSuperview()
self.walkAnimationImageView.removeFromSuperview()
})
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func SetStartLocation(sender: AnyObject) {
let storyboard = UIStoryboard(name: "SpotSetView", bundle: nil)
let controller = storyboard.instantiateInitialViewController() as! SpotSetViewController
controller.completion = {(spot:Spot?) -> Void in
SpotManager.startSpot = spot
}
self.presentViewController(controller, animated: true, completion: nil)
}
@IBAction func SetTargetLocation(sender: AnyObject) {
let storyboard = UIStoryboard(name: "SpotSetView", bundle: nil)
let controller = storyboard.instantiateInitialViewController() as! SpotSetViewController
controller.completion = {(spot:Spot?) -> Void in
SpotManager.targetSpot = spot
}
self.presentViewController(controller, animated: true, completion: nil)
}
}
extension SearchViewController: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch (status) {
case .NotDetermined:
print("NotDetermined")
case .Restricted:
print("Restricted")
case .Denied:
print("Denied")
case .AuthorizedAlways:
print("AuthorizedAlways")
locationManager.desiredAccuracy = kCLLocationAccuracyBest// 取得精度の設定.
locationManager.distanceFilter = 1// 取得頻度の設定.
locationManager.startUpdatingLocation()
case .AuthorizedWhenInUse:
print("AuthorizedWhenInUse")
}
}
// 位置情報がupdateされた時
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("\(manager.location?.coordinate.latitude),\(manager.location?.coordinate.longitude)")
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print(error)
}
}
| mit | 7fa2fdcb1cf556a02f23d5abbbfc2237 | 42.313131 | 202 | 0.668027 | 5.175619 | false | false | false | false |
KimBin/DTCollectionViewManager | Example/Example/SectionsViewController.swift | 1 | 2375 | //
// SectionsViewController.swift
// DTCollectionViewManagerExample
//
// Created by Denys Telezhkin on 24.08.15.
// Copyright © 2015 Denys Telezhkin. All rights reserved.
//
import UIKit
import DTCollectionViewManager
func randomColor() -> UIColor {
let randomRed:CGFloat = CGFloat(drand48())
let randomGreen:CGFloat = CGFloat(drand48())
let randomBlue:CGFloat = CGFloat(drand48())
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
class SectionsViewController: UIViewController, DTCollectionViewManageable, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var collectionView: UICollectionView?
var sectionNumber = 0
override func viewDidLoad() {
super.viewDidLoad()
self.manager.startManagingWithDelegate(self)
self.manager.registerCellClass(SolidColorCollectionCell)
self.manager.registerHeaderClass(SimpleTextCollectionReusableView)
self.manager.registerFooterClass(SimpleTextCollectionReusableView)
(self.collectionView?.collectionViewLayout as? UICollectionViewFlowLayout)?.headerReferenceSize = CGSize(width: 320, height: 50)
(self.collectionView?.collectionViewLayout as? UICollectionViewFlowLayout)?.footerReferenceSize = CGSize(width: 320, height: 50)
self.addSection()
self.addSection()
}
@IBAction func addSection()
{
sectionNumber++
let section = self.manager.memoryStorage.sectionAtIndex(manager.memoryStorage.sections.count)
section.collectionHeaderModel = "Section \(sectionNumber) header"
section.collectionFooterModel = "Section \(sectionNumber) footer"
self.manager.memoryStorage.addItems([randomColor(), randomColor(), randomColor()], toSection: manager.memoryStorage.sections.count - 1)
}
@IBAction func removeSection(sender: AnyObject) {
if self.manager.memoryStorage.sections.count > 0 {
self.manager.memoryStorage.deleteSections(NSIndexSet(index: manager.memoryStorage.sections.count - 1))
}
}
@IBAction func moveSection(sender: AnyObject) {
if self.manager.memoryStorage.sections.count > 0 {
self.manager.memoryStorage.moveCollectionViewSection(self.manager.memoryStorage.sections.count - 1, toSection: 0)
}
}
}
| mit | 21948be567beee193f49040ba993b51a | 38.566667 | 143 | 0.713564 | 5.138528 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/CallAudioPlayer.swift | 1 | 982 | //
// CallAudioPlayer.swift
// Telegram
//
// Created by keepcoder on 04/05/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import AVFoundation
class CallAudioPlayer : NSObject, AVAudioPlayerDelegate {
private var player: AVAudioPlayer?;
public var completion:(()->Void)?
let tone: URL
init(_ url:URL, loops:Int, completion:(()->Void)? = nil) {
self.tone = url
self.player = try? AVAudioPlayer(contentsOf: url)
self.completion = completion
super.init()
player?.numberOfLoops = loops
player?.delegate = self
}
func play() {
player?.play()
}
func stop() {
player?.stop()
player?.delegate = nil
player = nil
}
deinit {
stop()
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
self.completion?()
player.delegate = nil
}
}
| gpl-2.0 | df0e996925754c5ce0ceadcd9a863be9 | 20.326087 | 88 | 0.577982 | 4.605634 | false | false | false | false |
wibosco/WhiteBoardCodingChallenges | WhiteBoardCodingChallenges/Challenges/HackerRank/Percentages/Percentages.swift | 1 | 1178 | //
// PlusMinus.swift
// WhiteBoardCodingChallenges
//
// Created by Boles on 07/05/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
//https://www.hackerrank.com/challenges/plus-minus
class Percentages: NSObject {
class func percentageOfUnqiueSets(array: [Int]) -> (positivePercentage: Double, negativePercentage: Double, zeroPercentage: Double) {
var postivesCount = 0
var negativesCount = 0
var zerosCount = 0
for value in array {
if value < 0 {
negativesCount = negativesCount + 1
}
else if value > 0 {
postivesCount = postivesCount + 1
}
else {
zerosCount = zerosCount + 1
}
}
let postivesPercentage = Double(postivesCount)/Double(array.count)
let negativesPercentage = Double(negativesCount)/Double(array.count)
let zerosPercentage = Double(zerosCount)/Double(array.count)
return (postivesPercentage, negativesPercentage, zerosPercentage)
}
}
| mit | a3056314fb10e284c19fd86b64d7b263 | 27.02381 | 137 | 0.567545 | 4.804082 | false | false | false | false |
SirapatBoonyasiwapong/grader | Sources/App/Controllers/ClassesController.swift | 1 | 7961 | import Foundation
import Vapor
import AuthProvider
public final class ClassesController {
let view: ViewRenderer
init(_ view: ViewRenderer) {
self.view = view
}
//Show class
func showClasses(request: Request) throws -> ResponseRepresentable {
if request.user != nil {
let myClasses: [Group]
let otherClasses: [Group]
if request.user!.role == .student {
myClasses = try Group.makeQuery().join(GroupUser.self, baseKey: "id", joinedKey: "group_id").filter(GroupUser.self, "user_id", request.user!.id!).all()
if myClasses.count == 0 {
otherClasses = try Group.all()
}
else {
let myClassIDs = myClasses.map { $0.id! }
otherClasses = try Group.makeQuery().filter("id", notIn: myClassIDs).all()
}
}
else {
myClasses = try Group.makeQuery().filter("ownerID", request.user!.id!).all()
otherClasses = try Group.makeQuery().filter("ownerID", .notEquals, request.user!.id!).all()
}
return try render("Classes/classes", ["myClasses": myClasses, "classes": otherClasses], for: request, with: view)
}
else {
let classes = try Group.all()
return try render("Classes/classes", ["classes": classes], for: request, with: view)
}
}
//GET Create class
func createClassForm(request: Request) throws -> ResponseRepresentable {
return try render("Classes/class-new", [:], for: request, with: view)
}
//POST Create class
func classForm(request: Request) throws -> ResponseRepresentable {
guard let name = request.data["name"]?.string,
let imageClass = request.formData?["image"] else{
throw Abort.badRequest
}
let classes = Group(name: name, ownerID: request.user!.id!)
try classes.save()
let path = "\(uploadPath)\(classes.id!.string!).jpg"
_ = save(bytes: imageClass.bytes!, path: path)
return Response(redirect: "/")
}
//GET Show all the events for a class
func showClassEvents(request: Request) throws -> ResponseRepresentable {
let classObj = try request.parameters.next(Group.self)
let classUser = try GroupUser.makeQuery().filter("user_id", request.user!.id!)
.filter("group_id", classObj.id!).first()
if request.user!.role == .student && (classUser == nil || classUser?.status == "Waiting") {
return Response(redirect: "/classes/\(classObj.id!.string!)/join")
}
let events = try Event.makeQuery().join(GroupEvent.self, baseKey: "id", joinedKey: "event_id").filter(GroupEvent.self, "group_id", classObj.id!).all()
return try render("Classes/events", ["class": classObj, "events": events], for: request, with: view)
}
//GET Show all the students in the class
func showClassUsers(request: Request) throws -> ResponseRepresentable {
let classObj = try request.parameters.next(Group.self)
let classUser = try GroupUser.makeQuery().filter("user_id", request.user!.id!)
.filter("group_id", classObj.id!).first()
return try render("Classes/join-class", ["class": classObj, "classUser": classUser], for: request, with: view)
}
//GET OtherClass
func joinClassForm(request: Request) throws -> ResponseRepresentable {
let classObj = try request.parameters.next(Group.self)
let classUserObj = try GroupUser.makeQuery().filter("group_id", classObj.id!).filter("user_id", request.user!.id!).first()
return try render("Classes/join-class", ["class": classObj, "classUser": classUserObj], for: request, with: view)
}
//POST Join class when student don't join class (OtherClasses)
func joinClass(request: Request) throws -> ResponseRepresentable {
let classObj = try request.parameters.next(Group.self)
let classUserObj = GroupUser(groupID: classObj.id!, userID: request.user!.id!, status: "Waiting")
try classUserObj.save()
return Response(redirect: "/classes/\(classObj.id!.string!)/join")
}
//GET Show all the events for a class
func showClassRanking(request: Request) throws -> ResponseRepresentable {
let classObj = try request.parameters.next(Group.self)
guard let user = request.user, classObj.isVisible(to: user) else {
throw Abort.unauthorized
}
let scores = try User.database!.raw("SELECT x.user_id, u.name, SUM(x.score) score, SUM(x.attempts) attempts, COUNT(1) problems FROM users u JOIN (SELECT s.user_id, s.event_problem_id, MAX(s.score) score, COUNT(1) attempts FROM submissions s JOIN event_problems ep ON s.event_problem_id = ep.id JOIN events e ON ep.event_id = e.id JOIN group_events ge ON e.id = ge.event_id WHERE ge.group_id = ? AND (s.created_at > e.starts_at OR e.starts_at IS NULL) AND (s.created_at < e.ends_at OR e.ends_at IS NULL) AND (s.language = e.language_restriction OR e.language_restriction IS NULL) GROUP BY s.user_id, event_problem_id) x ON u.id = x.user_id WHERE u.role = 1 GROUP BY x.user_id, u.name ORDER BY score DESC, attempts ASC, problems DESC", [classObj.id!])
return try render("Classes/class-ranking", ["class": classObj, "scores": scores], for: request, with: view)
}
//GET Delete a class
func deleteClass(request: Request) throws -> ResponseRepresentable {
let group = try request.parameters.next(Group.self)
try GroupUser.makeQuery().filter("group_id", group.id!).delete()
try GroupEvent.makeQuery().filter("group_id", group.id!).delete()
try Group.makeQuery().filter("id", group.id!).delete()
return Response(redirect: "/classes")
}
//GET Create new event in class
func createEvent(request: Request) throws -> ResponseRepresentable {
let classObj = try request.parameters.next(Group.self)
return try render("Classes/event-new", ["class": classObj], for: request, with: view)
}
//POST Submit event in class
func submitEvent(request: Request) throws -> ResponseRepresentable {
let group = try request.parameters.next(Group.self)
guard
let userId = request.user?.id,
let name = request.data["name"]?.string,
let imageEvent = request.formData?["image"]
else {
throw Abort.badRequest
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm"
let startsAt = request.data["starts_at_date"]?.string
.flatMap { rawDate in rawDate + " " + (request.data["starts_at_time"]?.string ?? "0:00") }
.flatMap { rawDateTime in formatter.date(from: rawDateTime) }
let endsAt = request.data["ends_at_date"]?.string
.flatMap { rawDate in rawDate + " " + (request.data["ends_at_time"]?.string ?? "0:00") }
.flatMap { rawDateTime in formatter.date(from: rawDateTime) }
let languageRestriction = request.data["language_restriction"]?.string.flatMap { raw in Language(rawValue: raw) }
let event = Event(
name: name,
userID: userId,
startsAt: startsAt,
endsAt: endsAt,
languageRestriction: languageRestriction
)
try event.save()
let groupEvent = GroupEvent(groupID: group.id!, eventID: event.id!)
try groupEvent.save()
let path = "\(uploadPath)\(event.id!.string!).jpg"
_ = save(bytes: imageEvent.bytes!, path: path)
return Response(redirect: "/classes/\(group.id!.string!)/events")
}
}
| mit | 5e6bf305f89796412ca436322cf2dda0 | 43.724719 | 757 | 0.608215 | 4.312568 | false | false | false | false |
Zhang-C-C/SWeibo | SWeibo/SWeibo/Classes/Others/UserAccount.swift | 1 | 3813 | //
// UserAccount.swift
// SWeibo
//
// Created by 诺达科技 on 16/10/27.
// Copyright © 2016年 诺达科技. All rights reserved.
//
import UIKit
//Swift要想打印对象,需要重写 CustomStringConvertible协议中的方法
class UserAccount: NSObject ,NSCoding{
//用户授权的唯一票据,用于调用微博的开放接口,同时也是第三方应用验证微博用户登录的唯一票据,第三方应用应该用该票据和自己应用内的用户建立唯一影射关系,来识别登录状态,不能使用本返回值里的UID字段来做登录识别。
var access_token: String?
//access_token的生命周期,单位是秒数。
var expires_in: String?
{
didSet{
expires_Date = NSDate(timeIntervalSinceNow: NSTimeInterval.init(expires_in!)!)
print("真正过期时间: \(expires_Date)")
}
}
var expires_Date: NSDate?
//授权用户的UID,本字段只是为了方便开发者,减少一次user/show接口调用而返回的,第三方应用不能用此字段作为用户登录状态的识别,只有access_token才是用户授权的唯一票据。
var uid: String?
/// 沙河路径
static let accountPath = "account.plist".cacheDir()
/**
将当前对象归档保存至沙盒
*/
func saveAccount()
{
NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
}
//用户是否登录标记
class func userLogin() -> Bool {
return loadAccount() != nil
}
/// 静态的用户账户属性
static var account: UserAccount?
/**
加载授权信息
- returns: 授权对象,可能为空
*/
class func loadAccount() -> UserAccount?
{
// 1.判断是否过期
if let date = account?.expires_Date where (date.compare(NSDate()) == NSComparisonResult.OrderedAscending)
{
// 如果已经过期,需要清空账号记录
account = nil
}
if account != nil {
return account
}
account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.accountPath) as? UserAccount
return account
}
// MARK: - NSCoding 归档接档使用的 key 保持一致即可
// 归档,aCoder 编码器,将对象转换成二进制数据保存到磁盘,和序列化很像
func encodeWithCoder(aCoder: NSCoder)
{
aCoder.encodeObject(access_token, forKey: "access_token")
aCoder.encodeObject(expires_in, forKey: "expires_in")
aCoder.encodeObject(uid, forKey: "uid")
}
// 解档方法,aDecoder 解码器,将保存在磁盘的二进制文件转换成 对象,和反序列化很像
required init?(coder aDecoder: NSCoder)
{
access_token = aDecoder.decodeObjectForKey("access_token") as? String
expires_in = aDecoder.decodeObjectForKey("expires_in") as? String
uid = aDecoder.decodeObjectForKey("uid") as? String
}
/**
赋值
- parameter dict: 字典
- returns: self
*/
init(dict: [String: AnyObject]) {
/*
access_token = dict["access_token"] as? String
expires_in = dict["expires_in"] as? String
uid = dict["uid"] as? String
*/
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
override var description: String {
//1.定义属性数组
let properties = ["access_token","expires_in","uid"]
//2.根据属性数组,将属性转为字符
let dict = self.dictionaryWithValuesForKeys(properties)
return "\(dict)"
}
}
| mit | 5430286aff4649066fb0b77025472fec | 25.293103 | 113 | 0.605246 | 3.860759 | false | false | false | false |
terflogag/BadgeSegmentControl | Example/Exemple/SegmentControlBarAppearence.swift | 1 | 1451 | //
// SegmentControlBarAppearence.swift
// BadgeSegmentControl
//
// Created by Florian Gabach on 28/04/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
class SegmentControlBarAppearence: NSObject {
class func appearance() -> BadgeSegmentControlAppearance {
let appearance = BadgeSegmentControlAppearance()
// Segment color
appearance.segmentOnSelectionColour = .clear
appearance.segmentOffSelectionColour = .clear
// Title font
appearance.titleOnSelectionFont = UIFont.systemFont(ofSize: 14)
appearance.titleOffSelectionFont = UIFont.systemFont(ofSize: 14)
// Title color
appearance.titleOnSelectionColour = UIColor(red:1.00, green:0.62, blue:0.22, alpha:1.00)
appearance.titleOffSelectionColour = UIColor.white
// Vertical margin
appearance.contentVerticalMargin = 10.0
// Border style
appearance.borderColor = .clear
appearance.cornerRadius = 0.0
appearance.borderWidth = 0.0
// Divider style
appearance.dividerWidth = 1.0
appearance.dividerColour = .clear
// Selection bar
appearance.showSelectionBar = true
appearance.selectionBarHeight = 5
appearance.selectionBarColor = UIColor.white.withAlphaComponent(0.5)
return appearance
}
}
| mit | 3da4eff82d5818fecb24b4389b41a56a | 29.851064 | 96 | 0.646207 | 5.272727 | false | false | false | false |
FutureKit/Swift-CocoaPod-iOS7-Example | CoolSampleAppThatRunsOniOS7/DummyProjectForSwiftPods/Pods/FutureKit/FutureKit/FutureBatch.swift | 1 | 9867 | //
// Future-Sequences.swift
// FutureKit
//
// Created by Michael Gray on 4/13/15.
// 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
// ---------------------------------------------------------------------------------------------------
//
// CONVERT an Array of Futures into a single Future
//
// ---------------------------------------------------------------------------------------------------
public typealias FutureBatch = FutureBatchOf<Any>
public class FutureBatchOf<T> {
public var subFutures = [Future<T>]()
// this future always succeeds. Returns an array of the individual Future.Completion values
// for each subFuture. use future to access
public var completionsFuture : Future<[Completion<T>]>
// this future succeeds iff all subFutues succeed.
public lazy var future : Future<[T]> = FutureBatchOf.checkAllCompletionsSucceeded(self.completionsFuture)
// internal final let synchObject : SynchronizationProtocol = GLOBAL_PARMS.LOCKING_STRATEGY.lockObject()
public init(f : [Future<T>]) {
self.subFutures = f
self.completionsFuture = FutureBatchOf.futureWithSubFutures(f)
}
public convenience init(futures : [AnyObject]) {
let f : [Future<T>] = FutureBatch.convertArray(futures)
self.init(f:f)
}
public convenience init(array : NSArray) {
let f : [Future<T>] = FutureBatch.convertArray(array as [AnyObject])
self.init(f:f)
}
func cancel() {
for f in self.subFutures {
f.cancel()
}
}
func append(f : Future<T>) -> Future<[T]> {
self.subFutures.append(f)
self.completionsFuture = self.completionsFuture.onSuccess { (var completions) -> Future<[Completion<T>]> in
return f.onComplete { (c) -> [Completion<T>] in
completions.append(c)
return completions
}
}
self.future = self.future.onSuccess({ (var results) -> Future<[T]> in
return f.onSuccess { (result) -> [T] in
results.append(result)
return results
}
})
return self.future
}
func append(f : AnyObject) -> Future<[T]> {
let future : Future<[T]> = (f as! FutureProtocol).convert()
return self.append(future)
}
public class func convertArray<S>(array:[Future<T>]) -> [Future<S>] {
var futures = [Future<S>]()
for a in array {
futures.append(a.convert())
}
return futures
}
public class func convertArray<S>(array:[AnyObject]) -> [Future<S>] {
var futures = [Future<S>]()
for a in array {
let f = a as! FutureProtocol
futures.append(f.convert())
}
return futures
}
// this always 'succeeds' once all Futures have finished
// each individual future in the array may succeed or fail
// you have to check the result of the array individually if you care
// Types are perserved, but all elements must be of the same type
public class func sequenceCompletionsWithSyncObject<T>(array : [Future<T>]) -> Future<[Completion<T>]> {
if (array.count < 2) {
return sequenceCompletionsByChaining(array)
}
else {
let promise = Promise<[Completion<T>]>()
var total = array.count
var result = [Completion<T>](count:array.count,repeatedValue:.Cancelled)
for (index, future) in enumerate(array) {
future.onComplete(.Immediate) { (completion: Completion<T>) -> Void in
promise.synchObject.modifyAsync({ () -> Int in
result[index] = completion
total--
return total
}, done: { (t) -> Void in
if (t == 0) {
promise.completeWithSuccess(result)
}
})
}
}
return promise.future
}
}
public class func sequenceCompletionsByChaining<T>(array : [Future<T>]) -> Future<[Completion<T>]> {
if (array.count == 0) {
let result = [Completion<T>]()
return Future<[Completion<T>]>(success: result)
}
else if (array.count == 1) {
let f = array.first!
return f.onComplete({ (c: Completion<T>) -> [Completion<T>] in
return [c]
})
}
else {
var lastFuture = array.last!
var firstFutures = array
firstFutures.removeLast()
return sequenceCompletionsByChaining(firstFutures).onSuccess({ (resultsFromFirstFutures : [Completion<T>]) -> Future<[Completion<T>]> in
return lastFuture.onComplete { (lastCompletionValue : Completion<T>) -> [Completion<T>] in
var allTheResults = resultsFromFirstFutures
allTheResults.append(lastCompletionValue)
return allTheResults
}
})
}
}
public class func futureWithSubFuturesAndSuccessChecks<T>(array : [Future<T>]) -> Future<[T]> {
return checkAllCompletionsSucceeded(futureWithSubFutures(array))
}
// should we use locks or recursion?
// After a lot of thinking, I think it's probably identical performance
public class func futureWithSubFutures<T>(array : [Future<T>]) -> Future<[Completion<T>]> {
if (GLOBAL_PARMS.BATCH_FUTURES_WITH_CHAINING) {
return sequenceCompletionsByChaining(array)
}
else {
return sequenceCompletionsWithSyncObject(array)
}
}
// will fail if any Future in the array fails.
// .Success means they all succeeded.
// the result is an array of each Future's result
/* public class func checkRollup<T>(f:Future<([T],[NSError],[Any?])>) -> Future<[T]> {
let ret = f.onSuccess { (rollup) -> Completion<[T]> in
let (results,errors,cancellations) = rollup
if (errors.count > 0) {
if (errors.count == 1) {
return .Fail(errors.first!)
}
else {
return .Fail(FutureNSError(error: .ErrorForMultipleErrors, userInfo:["errors" : errors]))
}
}
if (cancellations.count > 0) {
return .Cancelled(cancellations)
}
return .Success(results)
}
}
public class func rollupCompletions<T>(f : Future<[Completion<T>]>) -> Future<([T],[NSError],[Any?])> {
return f.map { (completions:[Completion<T>]) -> ([T],[NSError],[Any?]) in
var results = [T]()
var errors = [NSError]()
var cancellations = [Any?]()
for completion in completions {
switch completion.state {
case let .Success:
results.append(completion.result)
case let .Fail:
errors.append(completion.error)
case let .Cancelled(token):
cancellations.append(token)
}
}
return (results,errors,cancellations)
}
} */
public class func checkAllCompletionsSucceeded<T>(f : Future<[Completion<T>]>) -> Future<[T]> {
return f.onSuccess { (completions:[Completion<T>]) -> Completion<[T]> in
var results = [T]()
var errors = [NSError]()
var cancellations = 0
for completion in completions {
switch completion.state {
case let .Success:
let r = completion.result
results.append(r)
case let .Fail:
errors.append(completion.error)
case let .Cancelled:
cancellations++
}
}
if (errors.count > 0) {
if (errors.count == 1) {
return FAIL(errors.first!)
}
else {
return FAIL(FutureNSError(error: .ErrorForMultipleErrors, userInfo:["errors" : errors]))
}
}
if (cancellations > 0) {
return CANCELLED()
}
return SUCCESS(results)
}
}
/* class func toTask<T : AnyObject>(future : Future<T>) -> Task {
return future.onSuccess({ (success) -> AnyObject? in
return success
})
} */
}
| mit | d2b5af6bfbd96af9fc078fd48bb61a02 | 34.239286 | 148 | 0.541097 | 4.839137 | false | false | false | false |
jjatie/Charts | Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift | 1 | 10046 | //
// XAxisRendererHorizontalBarChart.swift
// Charts
//
// 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 CoreGraphics
import Foundation
open class XAxisRendererHorizontalBarChart: XAxisRenderer {
internal weak var chart: BarChartView?
public init(viewPortHandler: ViewPortHandler, axis: XAxis, transformer: Transformer?, chart: BarChartView)
{
super.init(viewPortHandler: viewPortHandler, axis: axis, transformer: transformer)
self.chart = chart
}
override open func computeAxis(min: Double, max: Double, inverted: Bool) {
var min = min, max = max
if let transformer = self.transformer,
viewPortHandler.contentWidth > 10,
!viewPortHandler.isFullyZoomedOutY
{
// calculate the starting and entry point of the y-labels (depending on
// zoom / contentrect bounds)
let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
min = inverted ? Double(p2.y) : Double(p1.y)
max = inverted ? Double(p1.y) : Double(p2.y)
}
computeAxisValues(min: min, max: max)
}
override open func computeSize() {
let longest = axis.getLongestLabel() as NSString
let labelSize = longest.size(withAttributes: [.font: axis.labelFont])
let labelWidth = floor(labelSize.width + axis.xOffset * 3.5)
let labelHeight = labelSize.height
let labelRotatedSize = CGSize(width: labelSize.width, height: labelHeight).rotatedBy(degrees: axis.labelRotationAngle)
axis.labelWidth = labelWidth
axis.labelHeight = labelHeight
axis.labelRotatedWidth = round(labelRotatedSize.width + axis.xOffset * 3.5)
axis.labelRotatedHeight = round(labelRotatedSize.height)
}
override open func renderAxisLabels(context: CGContext) {
guard
axis.isEnabled,
axis.isDrawLabelsEnabled,
chart?.data != nil
else { return }
let xoffset = axis.xOffset
switch axis.labelPosition {
case .top:
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
case .topInside:
drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
case .bottom:
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
case .bottomInside:
drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
case .bothSided:
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
}
}
/// draws the x-labels on the specified y-position
override open func drawLabels(context: CGContext, pos: CGFloat, anchor: CGPoint) {
guard let transformer = self.transformer else { return }
let labelFont = axis.labelFont
let labelTextColor = axis.labelTextColor
let labelRotationAngleRadians = axis.labelRotationAngle.DEG2RAD
let centeringEnabled = axis.isCenterAxisLabelsEnabled
// pre allocate to save performance (dont allocate in loop)
var position = CGPoint.zero
for i in 0 ..< axis.entryCount {
// only fill x values
position.x = 0.0
position.y = centeringEnabled ? CGFloat(axis.centeredEntries[i]) : CGFloat(axis.entries[i])
transformer.pointValueToPixel(&position)
if viewPortHandler.isInBoundsY(position.y),
let label = axis.valueFormatter?.stringForValue(axis.entries[i], axis: axis)
{
drawLabel(context: context,
formattedLabel: label,
x: pos,
y: position.y,
attributes: [.font: labelFont, .foregroundColor: labelTextColor],
anchor: anchor,
angleRadians: labelRotationAngleRadians)
}
}
}
open func drawLabel(
context: CGContext,
formattedLabel: String,
x: CGFloat,
y: CGFloat,
attributes: [NSAttributedString.Key: Any],
anchor: CGPoint,
angleRadians: CGFloat
) {
context.drawText(formattedLabel,
at: CGPoint(x: x, y: y),
anchor: anchor,
angleRadians: angleRadians,
attributes: attributes)
}
override open var gridClippingRect: CGRect {
var contentRect = viewPortHandler.contentRect
let dy = self.axis.gridLineWidth
contentRect.origin.y -= dy / 2.0
contentRect.size.height += dy
return contentRect
}
override open func drawGridLine(context: CGContext, x _: CGFloat, y: CGFloat) {
guard viewPortHandler.isInBoundsY(y) else { return }
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: y))
context.strokePath()
}
override open func renderAxisLine(context: CGContext) {
guard
axis.isEnabled,
axis.isDrawAxisLineEnabled
else { return }
context.saveGState()
defer { context.restoreGState() }
context.setStrokeColor(axis.axisLineColor.cgColor)
context.setLineWidth(axis.axisLineWidth)
if axis.axisLineDashLengths != nil {
context.setLineDash(phase: axis.axisLineDashPhase, lengths: axis.axisLineDashLengths)
} else {
context.setLineDash(phase: 0.0, lengths: [])
}
if axis.labelPosition == .top ||
axis.labelPosition == .topInside ||
axis.labelPosition == .bothSided
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom))
context.strokePath()
}
if axis.labelPosition == .bottom ||
axis.labelPosition == .bottomInside ||
axis.labelPosition == .bothSided
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
context.strokePath()
}
}
override open func renderLimitLines(context: CGContext) {
guard let transformer = self.transformer else { return }
let limitLines = axis.limitLines
guard !limitLines.isEmpty else { return }
let trans = transformer.valueToPixelMatrix
var position = CGPoint.zero
for l in limitLines where l.isEnabled {
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.y -= l.lineWidth / 2.0
clippingRect.size.height += l.lineWidth
context.clip(to: clippingRect)
position.x = 0.0
position.y = CGFloat(l.limit)
position = position.applying(trans)
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y))
context.setStrokeColor(l.lineColor.cgColor)
context.setLineWidth(l.lineWidth)
if l.lineDashLengths != nil {
context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!)
} else {
context.setLineDash(phase: 0.0, lengths: [])
}
context.strokePath()
let label = l.label
// if drawing the limit-value label is enabled
if l.drawLabelEnabled, !label.isEmpty {
let labelLineHeight = l.valueFont.lineHeight
let xOffset = 4.0 + l.xOffset
let yOffset = l.lineWidth + labelLineHeight + l.yOffset
let align: TextAlignment
let point: CGPoint
switch l.labelPosition {
case .topRight:
align = .right
point = CGPoint(x: viewPortHandler.contentRight - xOffset,
y: position.y - yOffset)
case .bottomRight:
align = .right
point = CGPoint(x: viewPortHandler.contentRight - xOffset,
y: position.y + yOffset - labelLineHeight)
case .topLeft:
align = .left
point = CGPoint(x: viewPortHandler.contentLeft + xOffset,
y: position.y - yOffset)
case .bottomLeft:
align = .left
point = CGPoint(x: viewPortHandler.contentLeft + xOffset,
y: position.y + yOffset - labelLineHeight)
}
context.drawText(label,
at: point,
align: align,
attributes: [.font: l.valueFont, .foregroundColor: l.valueTextColor])
}
}
}
}
| apache-2.0 | 3caf6bc4595f58dbebddd5f6ce60cbcf | 36.070111 | 126 | 0.591579 | 5.199793 | false | false | false | false |
pdcgomes/RendezVous | Vendor/docopt/Option.swift | 1 | 2738 | //
// Option.swift
// docopt
//
// Created by Pavel S. Mazurin on 2/28/15.
// Copyright (c) 2015 kovpas. All rights reserved.
//
import Foundation
internal class Option: LeafPattern {
internal var short: String?
internal var long: String?
internal var argCount: UInt
override internal var name: String? {
get {
return self.long ?? self.short
}
set {
}
}
override var description: String {
get {
return "Option(\(short), \(long), \(argCount), \(value))"
}
}
convenience init(_ option: Option) {
self.init(option.short, long: option.long, argCount: option.argCount, value: option.value)
}
init(_ short: String? = nil, long: String? = nil, argCount: UInt = 0, value: AnyObject? = false) {
assert(argCount <= 1)
self.short = short
self.long = long
self.argCount = argCount
super.init("", value: value)
if argCount > 0 && value as? Bool == false {
self.value = nil
} else {
self.value = value
}
}
static func parse(optionDescription: String) -> Option {
var short: String? = nil
var long: String? = nil
var argCount: UInt = 0
var value: AnyObject? = false
var (options, _, description) = optionDescription.strip().partition(" ")
options = options.stringByReplacingOccurrencesOfString(",", withString: " ", options: [], range: nil)
options = options.stringByReplacingOccurrencesOfString("=", withString: " ", options: [], range: nil)
for s in options.componentsSeparatedByString(" ").filter({!$0.isEmpty}) {
if s.hasPrefix("--") {
long = s
} else if s.hasPrefix("-") {
short = s
} else {
argCount = 1
}
}
if argCount == 1 {
let matched = description.findAll("\\[default: (.*)\\]", flags: .CaseInsensitive)
value = matched.count > 0 ? matched[0] : nil
}
return Option(short, long: long, argCount: argCount, value: value)
}
override func singleMatch<T: LeafPattern>(left: [T]) -> SingleMatchResult {
for var i = 0; i < left.count; i++ {
let pattern = left[i]
if pattern.name == name {
return (i, pattern)
}
}
return (0, nil)
}
}
func ==(lhs: Option, rhs: Option) -> Bool {
let valEqual = lhs as LeafPattern == rhs as LeafPattern
return lhs.short == rhs.short
&& lhs.long == lhs.long
&& lhs.argCount == rhs.argCount
&& valEqual
}
| mit | 606b892d516d3beae2c6676bb22fd0ff | 29.087912 | 109 | 0.530314 | 4.444805 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ChatListTouchBar.swift | 1 | 17880 | //
// ChatListTouchBar.swift
// Telegram
//
// Created by Mikhail Filimonov on 12/09/2018.
// Copyright © 2018 Telegram. All rights reserved.
//
import TGUIKit
import TelegramCore
import HackUtils
import SwiftSignalKit
import Postbox
@available(OSX 10.12.2, *)
private extension NSTouchBarItem.Identifier {
static let chatListSearch = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).touchBar.chatListSearch")
static let chatListNewChat = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).touchBar.chatListNewChat")
static let chatListRecent = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).touchBar.chatListRecent")
static let composeNewGroup = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).touchBar.composeNewGroup")
static let composeNewChannel = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).touchBar.composeNewChannel")
static let composeNewSecretChat = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).touchBar.composeNewSecretChat")
}
@available(OSX 10.12.2, *)
private class TouchBarRecentPeerItemView: NSScrubberItemView {
private let selectView = View()
private var imageView: AvatarControl = AvatarControl.init(font: .avatar(12))
private let fetchDisposable = MetaDisposable()
private var badgeNode: BadgeNode?
private var badgeView:View?
required override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(selectView)
addSubview(imageView)
imageView.setFrameSize(NSMakeSize(30, 30))
selectView.setFrameSize(NSMakeSize(30, 30))
selectView.layer?.cornerRadius = 15
selectView.layer?.borderColor = theme.colors.accent.cgColor
selectView.layer?.borderWidth = 1.5
selectView.layer?.opacity = 0
selectView.isEventLess = true
}
private(set) var peerId: PeerId?
func update(context: AccountContext, peer: TouchBarPeerItem, selected: Bool) {
self.peerId = peer.peer.id
if peer.unreadCount > 0 {
if badgeView == nil {
badgeView = View()
self.addSubview(badgeView!)
}
guard let badgeView = self.badgeView else {
return
}
badgeView.removeAllSubviews()
if peer.muted {
self.badgeNode = BadgeNode(.initialize(string: "\(peer.unreadCount)", color: theme.chatList.badgeTextColor, font: .medium(8)), theme.colors.grayText)
} else {
self.badgeNode = BadgeNode(.initialize(string: "\(peer.unreadCount)", color: theme.chatList.badgeTextColor, font: .medium(8)), theme.colors.accent)
}
guard let badgeNode = self.badgeNode else {
return
}
badgeNode.additionSize = NSMakeSize(0, 0)
badgeView.setFrameSize(badgeNode.size)
badgeNode.view = badgeView
badgeNode.setNeedDisplay()
needsLayout = true
} else {
self.badgeView?.removeFromSuperview()
self.badgeView = nil
}
imageView.setPeer(account: context.account, peer: peer.peer)
}
private var _selected: Bool = false
func updateSelected(_ selected: Bool) {
if self._selected != selected {
self._selected = selected
selectView.change(opacity: selected ? 1 : 0, animated: true, duration: 0.1, timingFunction: .spring)
if selected {
selectView.layer?.animateScaleSpring(from: 0.2, to: 1.0, duration: 0.2, removeOnCompletion: true)
imageView.layer?.animateScaleSpring(from: 1, to: 0.75, duration: 0.2, removeOnCompletion: false)
badgeView?.layer?.animateScaleSpring(from: 1, to: 0.75, duration: 0.2, removeOnCompletion: false)
} else {
selectView.layer?.animateScaleSpring(from: 1.0, to: 0.2, duration: 0.2, removeOnCompletion: false)
imageView.layer?.animateScaleSpring(from: 0.75, to: 1.0, duration: 0.2, removeOnCompletion: true)
badgeView?.layer?.animateScaleSpring(from: 0.75, to: 1.0, duration: 0.2, removeOnCompletion: true)
}
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateLayer() {
}
deinit {
fetchDisposable.dispose()
}
override func layout() {
super.layout()
selectView.center()
imageView.center()
guard let badgeView = self.badgeView else {
return
}
badgeView.setFrameOrigin(NSMakePoint(frame.width - badgeView.frame.width, badgeView.frame.height - 11))
}
}
@available(OSX 10.12.2, *)
private class RecentPeersScrubberBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrubberDataSource, NSScrubberFlowLayoutDelegate {
private static let peerIdentifier = "peerIdentifier"
var entries: [TouchBarPeerItem]
private let context: AccountContext
private let selected: ChatLocation?
init(identifier: NSTouchBarItem.Identifier, context: AccountContext, entries: [TouchBarPeerItem], selected: ChatLocation?) {
self.entries = entries
self.context = context
self.selected = selected
super.init(identifier: identifier)
let scrubber = NSScrubber()
scrubber.register(TouchBarRecentPeerItemView.self, forItemIdentifier: NSUserInterfaceItemIdentifier(rawValue: RecentPeersScrubberBarItem.peerIdentifier))
scrubber.mode = .free
scrubber.selectionBackgroundStyle = .none
scrubber.floatsSelectionViews = true
scrubber.delegate = self
scrubber.dataSource = self
let gesture = NSPressGestureRecognizer(target: self, action: #selector(self.pressGesture(_:)))
gesture.allowedTouchTypes = NSTouch.TouchTypeMask.direct
gesture.allowableMovement = 0
gesture.minimumPressDuration = 0
scrubber.addGestureRecognizer(gesture)
self.view = scrubber
}
@objc private func pressGesture(_ gesture: NSPressGestureRecognizer) {
let context = self.context
let runSelector:(Bool, Bool)->Void = { [weak self] cancelled, navigate in
guard let `self` = self else {
return
}
let scrollView = HackUtils.findElements(byClass: "NSScrollView", in: self.view)?.first as? NSScrollView
guard let container = scrollView?.documentView?.subviews.first else {
return
}
var point = gesture.location(in: container)
point.y = 0
for itemView in container.subviews {
if let itemView = itemView as? TouchBarRecentPeerItemView {
if NSPointInRect(point, itemView.frame) {
itemView.updateSelected(!cancelled)
if navigate, let peerId = itemView.peerId {
context.bindings.rootNavigation().push(ChatController(context: context, chatLocation: .peer(peerId)))
}
} else {
itemView.updateSelected(false)
}
}
}
}
switch gesture.state {
case .began:
runSelector(false, false)
case .failed, .cancelled:
runSelector(true, false)
case .ended:
runSelector(true, true)
case .changed:
runSelector(false, false)
case .possible:
break
@unknown default:
runSelector(false, false)
}
}
fileprivate var modalPreview: PreviewModalController?
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func numberOfItems(for scrubber: NSScrubber) -> Int {
return entries.count
}
func scrubber(_ scrubber: NSScrubber, didHighlightItemAt highlightedIndex: Int) {
scrubber.selectionBackgroundStyle = .none
}
func scrubber(_ scrubber: NSScrubber, viewForItemAt index: Int) -> NSScrubberItemView {
let itemView: NSScrubberItemView
let peer = self.entries[index]
let view = scrubber.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: RecentPeersScrubberBarItem.peerIdentifier), owner: nil) as! TouchBarRecentPeerItemView
view.update(context: context, peer: peer, selected: self.selected?.peerId == peer.peer.id)
itemView = view
return itemView
}
func scrubber(_ scrubber: NSScrubber, layout: NSScrubberFlowLayout, sizeForItemAt itemIndex: Int) -> NSSize {
return NSSize(width: 40, height: 40)
}
func scrubber(_ scrubber: NSScrubber, didSelectItemAt index: Int) {
}
}
@available(OSX 10.12.2, *)
final class ComposePopoverTouchBar : NSTouchBar, NSTouchBarDelegate {
private let newGroup:()->Void
private let newSecretChat:()->Void
private let newChannel:()->Void
init(newGroup:@escaping()->Void, newSecretChat:@escaping()->Void, newChannel:@escaping()->Void) {
self.newGroup = newGroup
self.newSecretChat = newSecretChat
self.newChannel = newChannel
super.init()
delegate = self
defaultItemIdentifiers = [.flexibleSpace, .composeNewGroup, .composeNewSecretChat, .composeNewChannel, .flexibleSpace]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func newGroupAction() {
newGroup()
}
@objc private func newSecretChatAction() {
newSecretChat()
}
@objc private func newChannelAction() {
newChannel()
}
func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
switch identifier {
case .composeNewGroup:
let item: NSCustomTouchBarItem = NSCustomTouchBarItem(identifier: identifier)
let image = NSImage(named: NSImage.Name("Icon_TouchBar_ComposeGroup"))!
let button = NSButton(title: strings().composePopoverNewGroup, image: image, target: self, action: #selector(newGroupAction))
item.view = button
item.customizationLabel = strings().composePopoverNewGroup
return item
case .composeNewChannel:
let item: NSCustomTouchBarItem = NSCustomTouchBarItem(identifier: identifier)
let image = NSImage(named: NSImage.Name("Icon_TouchBar_ComposeChannel"))!
let button = NSButton(title: strings().composePopoverNewChannel, image: image, target: self, action: #selector(newChannelAction))
item.view = button
item.customizationLabel = strings().composePopoverNewChannel
return item
case .composeNewSecretChat:
let item: NSCustomTouchBarItem = NSCustomTouchBarItem(identifier: identifier)
let image = NSImage(named: NSImage.Name("Icon_TouchBar_ComposeSecretChat"))!
let button = NSButton(title: strings().composePopoverNewSecretChat, image: image, target: self, action: #selector(newSecretChatAction))
item.view = button
item.customizationLabel = strings().composePopoverNewSecretChat
return item
default:
break
}
return nil
}
}
private struct TouchBarPeerItem : Equatable {
let peer: Peer
let unreadCount: Int32
let muted: Bool
static func ==(lhs: TouchBarPeerItem, rhs: TouchBarPeerItem) -> Bool {
return lhs.peer.id == rhs.peer.id
}
}
@available(OSX 10.12.2, *)
class ChatListTouchBar: NSTouchBar, NSTouchBarDelegate {
private let search:()->Void
private let newGroup:()->Void
private let newSecretChat:()->Void
private let newChannel:()->Void
private let context: AccountContext
private var peers:[TouchBarPeerItem] = []
private var selected: ChatLocation?
private let disposable = MetaDisposable()
init(context: AccountContext, search:@escaping()->Void, newGroup:@escaping()->Void, newSecretChat:@escaping()->Void, newChannel:@escaping()->Void) {
self.search = search
self.newGroup = newGroup
self.newSecretChat = newSecretChat
self.newChannel = newChannel
self.context = context
super.init()
delegate = self
customizationIdentifier = .windowBar
defaultItemIdentifiers = [.chatListNewChat, .flexibleSpace, .chatListSearch, .flexibleSpace]
customizationAllowedItemIdentifiers = defaultItemIdentifiers
// let recent:Signal<[TouchBarPeerItem], NoError> = recentlySearchedPeers(postbox: context.account.postbox) |> map { recent in
// return recent.prefix(10).compactMap { $0.peer.peer != nil ? TouchBarPeerItem(peer: $0.peer.peer!, unreadCount: $0.unreadCount, muted: $0.notificationSettings?.isMuted ?? false) : nil }
// }
// let top:Signal<[TouchBarPeerItem], NoError> = recentPeers(account: context.account) |> mapToSignal { top in
// switch top {
// case .disabled:
// return .single([])
// case let .peers(peers):
// let peers = Array(peers.prefix(7))
// return combineLatest(peers.map {context.account.viewTracker.peerView($0.id)}) |> mapToSignal { peerViews -> Signal<[TouchBarPeerItem], NoError> in
// return context.account.postbox.unreadMessageCountsView(items: peerViews.map {.peer($0.peerId)}) |> map { values in
// var peers:[TouchBarPeerItem] = []
// for peerView in peerViews {
// if let peer = peerViewMainPeer(peerView) {
// let isMuted = peerView.isMuted
// let unreadCount = values.count(for: .peer(peerView.peerId))
// peers.append(TouchBarPeerItem(peer: peer, unreadCount: unreadCount ?? 0, muted: isMuted))
// }
// }
// return peers
// }
// }
// }
// }
//
// let signal = combineLatest(queue: .mainQueue(), recent, top)
// disposable.set(signal.start(next: { [weak self] recent, top in
// self?.peers = (top + recent).prefix(14).uniqueElements
// self?.updateInterface()
// }))
}
private func identifiers() -> [NSTouchBarItem.Identifier] {
var items:[NSTouchBarItem.Identifier] = []
items.append(.chatListNewChat)
if peers.isEmpty {
items.append(.flexibleSpace)
items.append(.chatListSearch)
items.append(.flexibleSpace)
} else {
items.append(.fixedSpaceSmall)
items.append(.chatListRecent)
items.append(.fixedSpaceSmall)
}
return items
}
private func updateInterface() {
defaultItemIdentifiers = identifiers()
customizationAllowedItemIdentifiers = defaultItemIdentifiers
for identifier in itemIdentifiers {
switch identifier {
case .chatListRecent:
let view = (item(forIdentifier: identifier) as? RecentPeersScrubberBarItem)
view?.entries = self.peers
(view?.view as? NSScrubber)?.reloadData()
default:
break
}
}
}
deinit {
disposable.dispose()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
switch identifier {
case .chatListNewChat:
let item = NSPopoverTouchBarItem(identifier: identifier)
let button = NSButton(image: NSImage(named: NSImage.Name("Icon_TouchBar_Compose"))!, target: item, action: #selector(NSPopoverTouchBarItem.showPopover(_:)))
item.popoverTouchBar = ComposePopoverTouchBar(newGroup: self.newGroup, newSecretChat: self.newSecretChat, newChannel: self.newChannel)
item.collapsedRepresentation = button
item.customizationLabel = strings().touchBarLabelNewChat
return item
case .chatListSearch:
let item = NSCustomTouchBarItem(identifier: identifier)
let image = NSImage(named: NSImage.Name("Icon_TouchBar_Search"))!
let button = NSButton(title: strings().touchBarSearchUsersOrMessages, image: image, target: self, action: #selector(searchAction))
button.imagePosition = .imageLeft
button.imageHugsTitle = true
button.addWidthConstraint(relation: .equal, size: 350)
item.view = button
item.customizationLabel = button.title
return item
case .chatListRecent:
let scrubberItem: NSCustomTouchBarItem = RecentPeersScrubberBarItem(identifier: identifier, context: context, entries: self.peers, selected: self.selected)
return scrubberItem
default:
break
}
return nil
}
@objc private func composeAction() {
}
@objc private func searchAction() {
self.search()
}
}
| gpl-2.0 | ba27e8184d9b3ea49dce9ae229b767e5 | 38.122538 | 198 | 0.619498 | 5.203434 | false | false | false | false |
yarshure/Surf | Surf/SFWebViewController.swift | 1 | 3184 | //
// SFWebViewController.swift
// Surf
//
// Created by yarshure on 16/1/18.
// Copyright © 2016年 yarshure. All rights reserved.
//
import UIKit
import WebKit
class SFWebViewController: UIViewController{
var url:URL?
var headerInfo:String!
@IBOutlet var webView: WKWebView!
@IBOutlet weak var textView:UITextView!
override func viewDidLoad() {
super.viewDidLoad()
if (self.webView == nil) {
self.webView = WKWebView.init(frame: self.view.frame)
self.view.insertSubview(webView, at: 0)
}
self.title = headerInfo
textView.text = "loading"
edgesForExtendedLayout = .all
guard let url = url else {return}
guard let scheme = url.scheme else {return}
if scheme.hasPrefix("file") {
let content = try! String.init(contentsOf: url)
textView.text = content
webView.removeFromSuperview()
}else {
webView.frame = self.view.frame
webView.isOpaque = false;
webView.backgroundColor = UIColor.clear
textView.removeFromSuperview()
// let v = UIWebView.init(frame: self.view.frame)
// self.view.addSubview(v)
}
}
func loadContent() {
guard let url = url else {return}
guard let scheme = url.scheme else {return}
if scheme.hasPrefix("file") {
let content = try! String.init(contentsOf: url)
textView.text = content
}else {
let req = NSURLRequest.init(url: url)
// let v = UIWebView.init(frame: self.view.frame)
// self.view.addSubview(v)
webView.load(req as URLRequest)
webView.navigationDelegate = self
// webView.delegate = self
//textView.isHidden = true
}
//let data = try! NSData.init(contentsOfURL: url!)
//
//webView.loadHTMLString(content, baseURL: url)
//webView.loadData(data!, MIMEType: "application/txt", textEncodingName: "UTF-8", baseURL: NSURL.init(string: "http://abigt.net")!)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
loadContent()
}
#if !targetEnvironment(UIKitForMac)
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool{
return true
}
func webViewDidStartLoad(_ webView: UIWebView){
}
func webViewDidFinishLoad(_ webView: UIWebView){
let string = "addCSSRule('body', '-webkit-text-size-adjust: 10;')"
webView.stringByEvaluatingJavaScript(from: string)
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error){
print(error)
}
#endif
}
extension SFWebViewController:WKNavigationDelegate{
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error)
{
}
}
| bsd-3-clause | da854a9e486175054385ba2e01be62ed | 29.009434 | 139 | 0.576863 | 4.776276 | false | false | false | false |
xuzhenguo/LayoutComposer | Example/LayoutComposer/NestExampleViewController.swift | 1 | 6877 | //
// VBoxExampleViewController.swift
// LayoutComposer
//
// Created by Yusuke Kawakami on 2015/08/22.
// Copyright (c) 2015年 CocoaPods. All rights reserved.
//
import UIKit
import LayoutComposer
enum NestExampleType: Int {
case Example1
}
class NestExampleViewController: ExampleViewController {
let exampleType: NestExampleType
init(exampleType: NestExampleType, headerTitle: String) {
self.exampleType = exampleType
super.init(headerTitle: headerTitle)
}
required init(coder aDecoder: NSCoder) {
fatalError("not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func loadView() {
super.loadView()
switch exampleType {
case .Example1:
layoutExample1()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func layoutExample1() {
let profileContainer = UIView()
profileContainer.backgroundColor = UIColor.whiteColor()
profileContainer.layer.cornerRadius = 5
let icon = UIImageView(image: UIImage(named: "avatar.jpeg"))
icon.layer.cornerRadius = 2
let changeProfileBtn = UIButton.buttonWithType(.System) as! UIButton
changeProfileBtn.setTitle("Update Profile", forState: .Normal)
changeProfileBtn.layer.borderWidth = 1
changeProfileBtn.layer.borderColor = UIColor.lightGrayColor().CGColor
changeProfileBtn.titleLabel?.font = UIFont.systemFontOfSize(12)
changeProfileBtn.setTitleColor(UIColor.lightGrayColor(), forState: .Normal)
changeProfileBtn.layer.cornerRadius = 2
let nameLabel = UILabel()
nameLabel.textColor = UIColor.blackColor()
nameLabel.font = UIFont.systemFontOfSize(16)
nameLabel.text = "YKPaco"
let userIDLabel = UILabel()
userIDLabel.textColor = UIColor.grayColor()
userIDLabel.font = UIFont.systemFontOfSize(10)
userIDLabel.text = "@ykpaco"
let messageLabel = UILabel()
messageLabel.numberOfLines = 0
messageLabel.textColor = UIColor.blackColor()
messageLabel.font = UIFont.systemFontOfSize(12)
messageLabel.text = "Each layout pattern is able to contain other layout patterns as children and you can form camplicated layouts.\n" +
"Auto Layout code written by LayoutComposer expresses the view hierarchy." +
"It makes Auto Layout code very simple and intuitive"
let followLabel = UILabel()
followLabel.font = UIFont.systemFontOfSize(12)
followLabel.text = "150 follows"
followLabel.textColor = UIColor.darkGrayColor()
let followerLabel = UILabel()
followerLabel.font = UIFont.systemFontOfSize(12)
followerLabel.text = "130 followers"
followerLabel.textColor = UIColor.darkGrayColor()
contentView.applyLayout(VBox(), items: [
$(profileContainer, margins: (10, 10, 10, 10), layout: VBox(pack: .Fit, defaultMargins: (0, 10, 0, 10)), items: [
$(nil, height: 50, marginTop: 10, layout: Relative(), items: [
$(icon, width: 50, height: 50, halign: .Left),
$(changeProfileBtn, width: 100, height: 20, halign: .Right, valign: .Top)
]),
$(nameLabel, marginTop: 5),
$(userIDLabel, marginTop: 5),
$(messageLabel, marginTop: 5),
$(nil, height: 30, layout: HBox(), items: [
$(followLabel),
$(followerLabel, marginLeft: 10)
])
])
])
}
/*
private func layoutExample1() {
let messageContainer = UIView()
messageContainer.backgroundColor = UIColor.whiteColor()
let icon = UIImageView(image: UIImage(named: "avatar.jpeg"))
icon.layer.cornerRadius = 2
let changeProfileBtn = UIButton.buttonWithType(.Custom) as! UIButton
changeProfileBtn.layer.borderColor = UIColor.grayColor().CGColor
changeProfileBtn.setTitle("Update Profile", forState: .Normal)
let messageHeader = UIView()
let nameLabel = UILabel()
nameLabel.textColor = UIColor.blackColor()
nameLabel.font = UIFont.systemFontOfSize(16)
nameLabel.text = "YKPaco"
let userIDLabel = UILabel()
userIDLabel.textColor = UIColor.grayColor()
userIDLabel.font = UIFont.systemFontOfSize(10)
userIDLabel.text = "@ykpaco"
let dateLabel = UILabel()
dateLabel.textColor = UIColor.grayColor()
dateLabel.font = UIFont.systemFontOfSize(10)
dateLabel.text = "2015/07/20"
let messageLabel = UILabel()
messageLabel.numberOfLines = 0
messageLabel.textColor = UIColor.blackColor()
messageLabel.font = UIFont.systemFontOfSize(12)
messageLabel.text = "Each layout pattern is able to contain other layout patterns as children and you can form camplicated layouts.\n" +
"Auto Layout code written by LayoutComposer expresses the view hierarchy." +
"It makes Auto Layout code very simple and intuitive"
contentView.applyLayout(Fit(), items: [
$(messageContainer, margins: (10, 10, 10, 10), layout: VBox(align: .Start), items: [
$(icon, width: 50, height: 50, marginLeft: 10, marginTop: 10),
$(nil, flex: 1, margins: (10, 10, 0, 10), layout: VBox(pack: .Fit), items: [
$(messageHeader, height: 16, layout: HBox(), items: [
$(nameLabel),
$(userIDLabel, marginLeft: 10)
]),
$(messageLabel, marginTop: 10)
])
])
])
/*
contentView.applyLayout(Fit(), items: [
$(messageContainer, margins: (10, 10, 10, 10), layout: HBox(align: .Start), items: [
$(icon, width: 50, height: 50, marginLeft: 10, marginTop: 10),
$(nil, flex: 1, margins: (10, 10, 0, 10), layout: VBox(pack: .Fit), items: [
$(messageHeader, height: 16, layout: HBox(), items: [
$(nameLabel),
$(userIDLabel, marginLeft: 10)
]),
$(messageLabel, marginTop: 10)
])
])
])
*/
// add date label to right bottom of message header.
messageHeader.applyLayout(Relative(), item: $(dateLabel, halign: .Right, valign: .Center))
}
*/
}
| mit | 259539f0d289c9ed57d224f64831faae | 37.841808 | 144 | 0.594182 | 4.963899 | false | false | false | false |
austinzheng/swift | test/stdlib/subString.swift | 5 | 7725 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
var SubstringTests = TestSuite("SubstringTests")
func checkMatch<S: Collection, T: Collection>(_ x: S, _ y: T, _ i: S.Index)
where S.Index == T.Index, S.Iterator.Element == T.Iterator.Element,
S.Iterator.Element: Equatable
{
expectEqual(x[i], y[i])
}
SubstringTests.test("Equality") {
let s = "abcdefg"
let s1 = s[s.index(s.startIndex, offsetBy: 2) ..<
s.index(s.startIndex, offsetBy: 4)]
let s2 = s1[s1.startIndex..<s1.endIndex]
let s3 = s2[s1.startIndex..<s1.endIndex]
expectEqual(s1, "cd")
expectEqual(s2, "cd")
expectEqual(s3, "cd")
expectTrue("" == s.dropFirst(s.count))
expectTrue(s.dropFirst().dropFirst(s.count) == s.dropFirst(s.count))
expectEqual("ab" as String, s.prefix(2))
expectEqual("fg" as String, s.suffix(2))
#if _runtime(_ObjC)
expectTrue(s == s[...])
expectTrue(s[...] == s)
expectTrue(s.dropFirst(2) != s)
expectTrue(s == s.dropFirst(0))
expectTrue(s != s.dropFirst(1))
expectTrue(s != s.dropLast(1))
expectEqual(s[...], s[...])
expectEqual(s.dropFirst(0), s.dropFirst(0))
expectTrue(s == s.dropFirst(0))
expectTrue(s.dropFirst(2) != s.dropFirst(1))
expectNotEqual(s.dropLast(2), s.dropLast(1))
expectEqual(s.dropFirst(1), s.dropFirst(1))
expectTrue(s != s[...].dropFirst(1))
#endif
// equatable conformance
expectTrue("one,two,three".split(separator: ",").contains("two"))
expectTrue("one,two,three".split(separator: ",") == ["one","two","three"])
}
#if _runtime(_ObjC)
SubstringTests.test("Equality/Emoji")
.xfail(.osxMinor(10, 9, reason: "Mac OS X 10.9 has an old ICU"))
.xfail(.iOSMajor(7, reason: "iOS 7 has an old ICU"))
.code {
let s = "abcdefg"
let emoji: String = s + "😄👍🏽🇫🇷👩👩👧👦🙈" + "😡🇧🇪🇨🇦🇮🇳"
let i = emoji.firstIndex(of: "😄")!
expectEqual("😄👍🏽" as String, emoji[i...].prefix(2))
expectTrue("😄👍🏽🇫🇷👩👩👧👦🙈😡🇧🇪" as String == emoji[i...].dropLast(2))
expectTrue("🇫🇷👩👩👧👦🙈😡🇧🇪" as String == emoji[i...].dropLast(2).dropFirst(2))
expectTrue(s as String != emoji[i...].dropLast(2).dropFirst(2))
expectEqualSequence("😄👍🏽🇫🇷👩👩👧👦🙈😡🇧🇪" as String, emoji[i...].dropLast(2))
expectEqualSequence("🇫🇷👩👩👧👦🙈😡🇧🇪" as String, emoji[i...].dropLast(2).dropFirst(2))
}
#endif
SubstringTests.test("Comparison") {
var s = "abc"
s += "defg"
expectFalse(s < s[...])
expectTrue(s <= s[...])
expectTrue(s >= s[...])
expectFalse(s > s[...])
expectFalse(s[...] < s)
expectTrue(s[...] <= s)
expectTrue(s[...] >= s)
expectFalse(s[...] > s)
expectFalse(s[...] < s[...])
expectTrue(s[...] <= s[...])
expectTrue(s[...] >= s[...])
expectFalse(s[...] > s[...])
expectTrue(s < s.dropFirst())
expectFalse(s > s.dropFirst())
expectFalse(s < s.dropLast())
expectTrue(s > s.dropLast())
expectTrue(s.dropFirst() < s.dropFirst(2))
expectFalse(s.dropFirst() > s.dropFirst(2))
expectFalse(s.dropLast() < s.dropLast(2))
expectTrue(s.dropLast() > s.dropLast(2))
expectFalse(s.dropFirst() < s.dropFirst().dropLast())
expectTrue(s.dropFirst() > s.dropFirst().dropLast())
expectTrue(s.dropFirst() > s)
expectTrue(s.dropFirst() > s[...])
expectTrue(s >= s[...])
expectTrue(s.dropFirst() >= s.dropFirst())
// comparable conformance
expectEqualSequence("pen,pineapple,apple,pen".split(separator: ",").sorted(),
["apple", "pen", "pen", "pineapple"])
}
SubstringTests.test("Filter") {
var name = "😂Edward Woodward".dropFirst()
var filtered = name.filter { $0 != "d" }
expectType(Substring.self, &name)
expectType(String.self, &filtered)
expectEqual("Ewar Woowar", filtered)
}
SubstringTests.test("CharacterView") {
let s = "abcdefg"
var t = s.dropFirst(2)
var u = t.dropFirst(2)
checkMatch(s, t, t.startIndex)
checkMatch(s, t, t.index(after: t.startIndex))
checkMatch(s, t, t.index(before: t.endIndex))
checkMatch(s, t, u.startIndex)
checkMatch(t, u, u.startIndex)
checkMatch(t, u, u.index(after: u.startIndex))
checkMatch(t, u, u.index(before: u.endIndex))
expectEqual("", String(t.dropFirst(10)))
expectEqual("", String(t.dropLast(10)))
expectEqual("", String(u.dropFirst(10)))
expectEqual("", String(u.dropLast(10)))
t.replaceSubrange(t.startIndex...t.startIndex, with: ["C"])
u.replaceSubrange(u.startIndex...u.startIndex, with: ["E"])
expectEqual(String(u), "Efg")
expectEqual(String(t), "Cdefg")
expectEqual(s, "abcdefg")
}
SubstringTests.test("UnicodeScalars") {
let s = "abcdefg"
var t = s.unicodeScalars.dropFirst(2)
var u = t.dropFirst(2)
checkMatch(s.unicodeScalars, t, t.startIndex)
checkMatch(s.unicodeScalars, t, t.index(after: t.startIndex))
checkMatch(s.unicodeScalars, t, t.index(before: t.endIndex))
checkMatch(s.unicodeScalars, t, u.startIndex)
checkMatch(t, u, u.startIndex)
checkMatch(t, u, u.index(after: u.startIndex))
checkMatch(t, u, u.index(before: u.endIndex))
expectEqual("", String(t.dropFirst(10)))
expectEqual("", String(t.dropLast(10)))
expectEqual("", String(u.dropFirst(10)))
expectEqual("", String(u.dropLast(10)))
t.replaceSubrange(t.startIndex...t.startIndex, with: ["C"])
u.replaceSubrange(u.startIndex...u.startIndex, with: ["E"])
expectEqual(String(u), "Efg")
expectEqual(String(t), "Cdefg")
expectEqual(s, "abcdefg")
}
SubstringTests.test("UTF16View") {
let s = "abcdefg"
let t = s.utf16.dropFirst(2)
let u = t.dropFirst(2)
checkMatch(s.utf16, t, t.startIndex)
checkMatch(s.utf16, t, t.index(after: t.startIndex))
checkMatch(s.utf16, t, t.index(before: t.endIndex))
checkMatch(s.utf16, t, u.startIndex)
checkMatch(t, u, u.startIndex)
checkMatch(t, u, u.index(after: u.startIndex))
checkMatch(t, u, u.index(before: u.endIndex))
expectEqual("", String(t.dropFirst(10))!)
expectEqual("", String(t.dropLast(10))!)
expectEqual("", String(u.dropFirst(10))!)
expectEqual("", String(u.dropLast(10))!)
}
SubstringTests.test("Mutate Substring through utf16 view") {
let s = "abcdefg"
var ss = s[...]
expectEqual(s.startIndex, ss.startIndex)
expectEqual(s.count, ss.count)
let first = ss.utf16.removeFirst()
expectEqual(s.index(after: s.startIndex), ss.startIndex)
expectEqual(s.count - 1, ss.count)
}
SubstringTests.test("Mutate Substring through unicodeScalars view") {
let s = "abcdefg"
var ss = s[...]
expectEqual(s.startIndex, ss.startIndex)
expectEqual(s.count, ss.count)
ss.unicodeScalars.append("h")
expectEqual(s.startIndex, ss.startIndex)
expectEqual(s.count + 1, ss.count)
expectEqual(ss.last, "h")
expectEqual(s.last, "g")
}
SubstringTests.test("UTF8View") {
let strs = [
"abcdefg", // Small ASCII
"abéÏ", // Small Unicode
"012345678901234567890", // Large ASCII
"abéÏ012345678901234567890", // Large Unicode
]
for s in strs {
let count = s.count
let t = s.utf8.dropFirst(2)
let u = t.dropFirst(2)
checkMatch(s.utf8, t, t.startIndex)
checkMatch(s.utf8, t, t.index(after: t.startIndex))
checkMatch(s.utf8, t, u.startIndex)
checkMatch(t, u, u.startIndex)
checkMatch(t, u, u.index(after: u.startIndex))
expectEqual("", String(t.dropFirst(100))!)
expectEqual("", String(t.dropLast(100))!)
expectEqual("", String(u.dropFirst(100))!)
expectEqual("", String(u.dropLast(100))!)
}
}
SubstringTests.test("Persistent Content") {
var str = "abc"
str += "def"
expectEqual("bcdefg", str.dropFirst(1) + "g")
expectEqual("bcdefg", (str.dropFirst(1) + "g") as String)
}
runAllTests()
| apache-2.0 | 3ab592096f3630e953605f652f126ef4 | 30.06639 | 86 | 0.649392 | 3.200941 | false | true | false | false |
petester42/Moya | Demo/Tests/RACSignal+MoyaSpec.swift | 5 | 10230 | import Quick
import Moya
import ReactiveCocoa
import Nimble
#if os(iOS) || os(watchOS) || os(tvOS)
private func ImageJPEGRepresentation(image: Image, _ compression: CGFloat) -> NSData? {
return UIImageJPEGRepresentation(image, compression)
}
#elseif os(OSX)
private func ImageJPEGRepresentation(image: Image, _ compression: CGFloat) -> NSData? {
var imageRect: CGRect = CGRectMake(0, 0, image.size.width, image.size.height)
let imageRep = NSBitmapImageRep(CGImage: image.CGImageForProposedRect(&imageRect, context: nil, hints: nil)!)
return imageRep.representationUsingType(.NSJPEGFileType, properties:[:])
}
#endif
// Necessary since Image(named:) doesn't work correctly in the test bundle
private extension ImageType {
class func testPNGImage(named name: String) -> ImageType {
class TestClass { }
let bundle = NSBundle(forClass: TestClass().dynamicType)
let path = bundle.pathForResource(name, ofType: "png")
return Image(contentsOfFile: path!)!
}
}
private func signalSendingData(data: NSData, statusCode: Int = 200) -> RACSignal {
return RACSignal.createSignal { (subscriber) -> RACDisposable! in
subscriber.sendNext(Response(statusCode: statusCode, data: data, response: nil))
subscriber.sendCompleted()
return nil
}
}
class RACSignalMoyaSpec: QuickSpec {
override func spec() {
describe("status codes filtering") {
it("filters out unrequested status codes") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 10)
var errored = false
signal.filterStatusCodes(0...9).subscribeNext({ (object) -> Void in
fail("called on non-correct status code: \(object)")
}, error: { (error) -> Void in
errored = true
})
expect(errored).to(beTruthy())
}
it("filters out non-successful status codes") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 404)
var errored = false
signal.filterSuccessfulStatusCodes().subscribeNext({ (object) -> Void in
fail("called on non-success status code: \(object)")
}, error: { (error) -> Void in
errored = true
})
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = NSData()
let signal = signalSendingData(data)
var called = false
signal.filterSuccessfulStatusCodes().subscribeNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("filters out non-successful status and redirect codes") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 404)
var errored = false
signal.filterSuccessfulStatusAndRedirectCodes().subscribeNext({ (object) -> Void in
fail("called on non-success status code: \(object)")
}, error: { (error) -> Void in
errored = true
})
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = NSData()
let signal = signalSendingData(data)
var called = false
signal.filterSuccessfulStatusAndRedirectCodes().subscribeNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("passes through correct redirect codes") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 304)
var called = false
signal.filterSuccessfulStatusAndRedirectCodes().subscribeNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("passes through correct redirect codes") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 304)
var called = false
signal.filterSuccessfulStatusAndRedirectCodes().subscribeNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("knows how to filter individual status codes") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 42)
var called = false
signal.filterStatusCode(42).subscribeNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("filters out different individual status code") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 43)
var errored = false
signal.filterStatusCode(42).subscribeNext({ (object) -> Void in
fail("called on non-success status code: \(object)")
}, error: { (error) -> Void in
errored = true
})
expect(errored).to(beTruthy())
}
}
describe("image maping") {
it("maps data representing an image to an image") {
let image = Image.testPNGImage(named: "testImage")
let data = ImageJPEGRepresentation(image, 0.75)
let signal = signalSendingData(data!)
var size: CGSize?
signal.mapImage().subscribeNext { (image) -> Void in
size = image.size
}
expect(size).to(equal(image.size))
}
it("ignores invalid data") {
let data = NSData()
let signal = signalSendingData(data)
var receivedError: NSError?
signal.mapImage().subscribeNext({ (object) -> Void in
fail("next called for invalid data")
}, error: { (error) -> Void in
receivedError = error
})
expect(receivedError).toNot(beNil())
expect(receivedError?.domain) == MoyaErrorDomain
expect(receivedError?.code).to(equal(MoyaErrorCode.ImageMapping.rawValue))
}
}
describe("JSON mapping") {
it("maps data representing some JSON to that JSON") {
let json = ["name": "John Crighton", "occupation": "Astronaut"]
let data = try! NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
let signal = signalSendingData(data)
var receivedJSON: [String: String]?
signal.mapJSON().subscribeNext { (json) -> Void in
if let json = json as? [String: String] {
receivedJSON = json
}
}
expect(receivedJSON?["name"]).to(equal(json["name"]))
expect(receivedJSON?["occupation"]).to(equal(json["occupation"]))
}
it("returns a Cocoa error domain for invalid JSON") {
let json = "{ \"name\": \"john }"
let data = json.dataUsingEncoding(NSUTF8StringEncoding)
let signal = signalSendingData(data!)
var receivedError: NSError?
signal.mapJSON().subscribeNext({ (object) -> Void in
fail("next called for invalid data")
}, error: { (error) -> Void in
receivedError = error
})
expect(receivedError).toNot(beNil())
expect(receivedError?.domain).to(equal("\(NSCocoaErrorDomain)"))
}
}
describe("string mapping") {
it("maps data representing a string to a string") {
let string = "You have the rights to the remains of a silent attorney."
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
let signal = signalSendingData(data!)
var receivedString: String?
signal.mapString().subscribeNext { (string) -> Void in
receivedString = string as? String
return
}
expect(receivedString).to(equal(string))
}
it("ignores invalid data") {
let data = NSData(bytes: [0x11FFFF] as [UInt32], length: 1) //Byte exceeding UTF8
let signal = signalSendingData(data)
var receivedError: NSError?
signal.mapString().subscribeNext({ (object) -> Void in
fail("next called for invalid data")
}, error: { (error) -> Void in
receivedError = error
})
expect(receivedError).toNot(beNil())
expect(receivedError?.domain) == MoyaErrorDomain
expect(receivedError?.code).to(equal(MoyaErrorCode.StringMapping.rawValue))
}
}
}
}
| mit | f1fe984ca42c8baea3e2c3ba807b0b7b | 39.275591 | 117 | 0.489345 | 6.071217 | false | false | false | false |
Tchoupinax/filldatabase | Sources/request.swift | 1 | 1507 | //
// request.swift
// filldatabase
//
// Created by Corentin Filoche on 02/08/2017.
//
//
import Foundation
class Request
{
//
//
// Attributes
private var quantity : Any
private var type : String
private var table : String
private var order : [String]
private var data : [String:String]
//
//
// Constructor
init()
{
self.quantity = 0
self.type = ""
self.table = ""
self.order = [String]()
self.data = [String:String]()
}
//
//
// Getters and setters
public func setQuantity(quantity: Any) { self.quantity = quantity }
public func setType(type: String) { self.type = type }
public func setTable(table: String) { self.table = table }
public func getQuantity() -> Any { return self.quantity }
public func getType() -> String { return self.type }
public func getTable() -> String { return self.table }
public func getKey(at: Int) -> String { return self.order[at] }
public func getData(at: Int) -> String { return getData(withKey: self.order[at]) }
public func getDataCount() -> Int { return self.order.count }
//
//
// Private helpers
private func getData(withKey: String) -> String { return self.data[withKey]! }
//
//
// Adding a data in this request
public func addingData(key: String, value: String)
{
// Saving order
self.order.append(key)
// Store data
self.data[key] = value
}
}
| mit | 06eefd0a2e06092763c29c0c65106514 | 24.982759 | 86 | 0.591904 | 3.914286 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/CodeStarNotifications/CodeStarNotifications_Shapes.swift | 1 | 34546 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import Foundation
import SotoCore
extension CodeStarNotifications {
// MARK: Enums
public enum DetailType: String, CustomStringConvertible, Codable {
case basic = "BASIC"
case full = "FULL"
public var description: String { return self.rawValue }
}
public enum ListEventTypesFilterName: String, CustomStringConvertible, Codable {
case resourceType = "RESOURCE_TYPE"
case serviceName = "SERVICE_NAME"
public var description: String { return self.rawValue }
}
public enum ListNotificationRulesFilterName: String, CustomStringConvertible, Codable {
case createdBy = "CREATED_BY"
case eventTypeId = "EVENT_TYPE_ID"
case resource = "RESOURCE"
case targetAddress = "TARGET_ADDRESS"
public var description: String { return self.rawValue }
}
public enum ListTargetsFilterName: String, CustomStringConvertible, Codable {
case targetAddress = "TARGET_ADDRESS"
case targetStatus = "TARGET_STATUS"
case targetType = "TARGET_TYPE"
public var description: String { return self.rawValue }
}
public enum NotificationRuleStatus: String, CustomStringConvertible, Codable {
case disabled = "DISABLED"
case enabled = "ENABLED"
public var description: String { return self.rawValue }
}
public enum TargetStatus: String, CustomStringConvertible, Codable {
case active = "ACTIVE"
case deactivated = "DEACTIVATED"
case inactive = "INACTIVE"
case pending = "PENDING"
case unreachable = "UNREACHABLE"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct CreateNotificationRuleRequest: AWSEncodableShape {
/// A unique, client-generated idempotency token that, when provided in a request, ensures the request cannot be repeated with a changed parameter. If a request with the same parameters is received and a token is included, the request returns information about the initial request that used that token. The AWS SDKs prepopulate client request tokens. If you are using an AWS SDK, an idempotency token is created for you.
public let clientRequestToken: String?
/// The level of detail to include in the notifications for this resource. BASIC will include only the contents of the event as it would appear in AWS CloudWatch. FULL will include any supplemental information provided by AWS CodeStar Notifications and/or the service for the resource for which the notification is created.
public let detailType: DetailType
/// A list of event types associated with this notification rule. For a list of allowed events, see EventTypeSummary.
public let eventTypeIds: [String]
/// The name for the notification rule. Notifictaion rule names must be unique in your AWS account.
public let name: String
/// The Amazon Resource Name (ARN) of the resource to associate with the notification rule. Supported resources include pipelines in AWS CodePipeline, repositories in AWS CodeCommit, and build projects in AWS CodeBuild.
public let resource: String
/// The status of the notification rule. The default value is ENABLED. If the status is set to DISABLED, notifications aren't sent for the notification rule.
public let status: NotificationRuleStatus?
/// A list of tags to apply to this notification rule. Key names cannot start with "aws".
public let tags: [String: String]?
/// A list of Amazon Resource Names (ARNs) of SNS topics to associate with the notification rule.
public let targets: [Target]
public init(clientRequestToken: String? = CreateNotificationRuleRequest.idempotencyToken(), detailType: DetailType, eventTypeIds: [String], name: String, resource: String, status: NotificationRuleStatus? = nil, tags: [String: String]? = nil, targets: [Target]) {
self.clientRequestToken = clientRequestToken
self.detailType = detailType
self.eventTypeIds = eventTypeIds
self.name = name
self.resource = resource
self.status = status
self.tags = tags
self.targets = targets
}
public func validate(name: String) throws {
try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, max: 256)
try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, min: 1)
try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, pattern: "^[\\w:/-]+$")
try self.eventTypeIds.forEach {
try validate($0, name: "eventTypeIds[]", parent: name, max: 200)
try validate($0, name: "eventTypeIds[]", parent: name, min: 1)
}
try self.validate(self.name, name: "name", parent: name, max: 64)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9\\-_ ]+$")
try self.validate(self.resource, name: "resource", parent: name, pattern: "^arn:aws[^:\\s]*:[^:\\s]*:[^:\\s]*:[0-9]{12}:[^\\s]+$")
try self.tags?.forEach {
try validate($0.key, name: "tags.key", parent: name, max: 128)
try validate($0.key, name: "tags.key", parent: name, min: 1)
try validate($0.key, name: "tags.key", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$")
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256)
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$")
}
try self.targets.forEach {
try $0.validate(name: "\(name).targets[]")
}
try self.validate(self.targets, name: "targets", parent: name, max: 10)
}
private enum CodingKeys: String, CodingKey {
case clientRequestToken = "ClientRequestToken"
case detailType = "DetailType"
case eventTypeIds = "EventTypeIds"
case name = "Name"
case resource = "Resource"
case status = "Status"
case tags = "Tags"
case targets = "Targets"
}
}
public struct CreateNotificationRuleResult: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the notification rule.
public let arn: String?
public init(arn: String? = nil) {
self.arn = arn
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
}
}
public struct DeleteNotificationRuleRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the notification rule you want to delete.
public let arn: String
public init(arn: String) {
self.arn = arn
}
public func validate(name: String) throws {
try self.validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
}
}
public struct DeleteNotificationRuleResult: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the deleted notification rule.
public let arn: String?
public init(arn: String? = nil) {
self.arn = arn
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
}
}
public struct DeleteTargetRequest: AWSEncodableShape {
/// A Boolean value that can be used to delete all associations with this SNS topic. The default value is FALSE. If set to TRUE, all associations between that target and every notification rule in your AWS account are deleted.
public let forceUnsubscribeAll: Bool?
/// The Amazon Resource Name (ARN) of the SNS topic to delete.
public let targetAddress: String
public init(forceUnsubscribeAll: Bool? = nil, targetAddress: String) {
self.forceUnsubscribeAll = forceUnsubscribeAll
self.targetAddress = targetAddress
}
public func validate(name: String) throws {
try self.validate(self.targetAddress, name: "targetAddress", parent: name, max: 320)
try self.validate(self.targetAddress, name: "targetAddress", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case forceUnsubscribeAll = "ForceUnsubscribeAll"
case targetAddress = "TargetAddress"
}
}
public struct DeleteTargetResult: AWSDecodableShape {
public init() {}
}
public struct DescribeNotificationRuleRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the notification rule.
public let arn: String
public init(arn: String) {
self.arn = arn
}
public func validate(name: String) throws {
try self.validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
}
}
public struct DescribeNotificationRuleResult: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the notification rule.
public let arn: String
/// The name or email alias of the person who created the notification rule.
public let createdBy: String?
/// The date and time the notification rule was created, in timestamp format.
public let createdTimestamp: Date?
/// The level of detail included in the notifications for this resource. BASIC will include only the contents of the event as it would appear in AWS CloudWatch. FULL will include any supplemental information provided by AWS CodeStar Notifications and/or the service for the resource for which the notification is created.
public let detailType: DetailType?
/// A list of the event types associated with the notification rule.
public let eventTypes: [EventTypeSummary]?
/// The date and time the notification rule was most recently updated, in timestamp format.
public let lastModifiedTimestamp: Date?
/// The name of the notification rule.
public let name: String?
/// The Amazon Resource Name (ARN) of the resource associated with the notification rule.
public let resource: String?
/// The status of the notification rule. Valid statuses are on (sending notifications) or off (not sending notifications).
public let status: NotificationRuleStatus?
/// The tags associated with the notification rule.
public let tags: [String: String]?
/// A list of the SNS topics associated with the notification rule.
public let targets: [TargetSummary]?
public init(arn: String, createdBy: String? = nil, createdTimestamp: Date? = nil, detailType: DetailType? = nil, eventTypes: [EventTypeSummary]? = nil, lastModifiedTimestamp: Date? = nil, name: String? = nil, resource: String? = nil, status: NotificationRuleStatus? = nil, tags: [String: String]? = nil, targets: [TargetSummary]? = nil) {
self.arn = arn
self.createdBy = createdBy
self.createdTimestamp = createdTimestamp
self.detailType = detailType
self.eventTypes = eventTypes
self.lastModifiedTimestamp = lastModifiedTimestamp
self.name = name
self.resource = resource
self.status = status
self.tags = tags
self.targets = targets
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case createdBy = "CreatedBy"
case createdTimestamp = "CreatedTimestamp"
case detailType = "DetailType"
case eventTypes = "EventTypes"
case lastModifiedTimestamp = "LastModifiedTimestamp"
case name = "Name"
case resource = "Resource"
case status = "Status"
case tags = "Tags"
case targets = "Targets"
}
}
public struct EventTypeSummary: AWSDecodableShape {
/// The system-generated ID of the event.
public let eventTypeId: String?
/// The name of the event.
public let eventTypeName: String?
/// The resource type of the event.
public let resourceType: String?
/// The name of the service for which the event applies.
public let serviceName: String?
public init(eventTypeId: String? = nil, eventTypeName: String? = nil, resourceType: String? = nil, serviceName: String? = nil) {
self.eventTypeId = eventTypeId
self.eventTypeName = eventTypeName
self.resourceType = resourceType
self.serviceName = serviceName
}
private enum CodingKeys: String, CodingKey {
case eventTypeId = "EventTypeId"
case eventTypeName = "EventTypeName"
case resourceType = "ResourceType"
case serviceName = "ServiceName"
}
}
public struct ListEventTypesFilter: AWSEncodableShape {
/// The system-generated name of the filter type you want to filter by.
public let name: ListEventTypesFilterName
/// The name of the resource type (for example, pipeline) or service name (for example, CodePipeline) that you want to filter by.
public let value: String
public init(name: ListEventTypesFilterName, value: String) {
self.name = name
self.value = value
}
private enum CodingKeys: String, CodingKey {
case name = "Name"
case value = "Value"
}
}
public struct ListEventTypesRequest: AWSEncodableShape {
/// The filters to use to return information by service or resource type.
public let filters: [ListEventTypesFilter]?
/// A non-negative integer used to limit the number of returned results. The default number is 50. The maximum number of results that can be returned is 100.
public let maxResults: Int?
/// An enumeration token that, when provided in a request, returns the next batch of the results.
public let nextToken: String?
public init(filters: [ListEventTypesFilter]? = nil, maxResults: Int? = nil, nextToken: String? = nil) {
self.filters = filters
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^[\\w/+=]+$")
}
private enum CodingKeys: String, CodingKey {
case filters = "Filters"
case maxResults = "MaxResults"
case nextToken = "NextToken"
}
}
public struct ListEventTypesResult: AWSDecodableShape {
/// Information about each event, including service name, resource type, event ID, and event name.
public let eventTypes: [EventTypeSummary]?
/// An enumeration token that can be used in a request to return the next batch of the results.
public let nextToken: String?
public init(eventTypes: [EventTypeSummary]? = nil, nextToken: String? = nil) {
self.eventTypes = eventTypes
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case eventTypes = "EventTypes"
case nextToken = "NextToken"
}
}
public struct ListNotificationRulesFilter: AWSEncodableShape {
/// The name of the attribute you want to use to filter the returned notification rules.
public let name: ListNotificationRulesFilterName
/// The value of the attribute you want to use to filter the returned notification rules. For example, if you specify filtering by RESOURCE in Name, you might specify the ARN of a pipeline in AWS CodePipeline for the value.
public let value: String
public init(name: ListNotificationRulesFilterName, value: String) {
self.name = name
self.value = value
}
private enum CodingKeys: String, CodingKey {
case name = "Name"
case value = "Value"
}
}
public struct ListNotificationRulesRequest: AWSEncodableShape {
/// The filters to use to return information by service or resource type. For valid values, see ListNotificationRulesFilter. A filter with the same name can appear more than once when used with OR statements. Filters with different names should be applied with AND statements.
public let filters: [ListNotificationRulesFilter]?
/// A non-negative integer used to limit the number of returned results. The maximum number of results that can be returned is 100.
public let maxResults: Int?
/// An enumeration token that, when provided in a request, returns the next batch of the results.
public let nextToken: String?
public init(filters: [ListNotificationRulesFilter]? = nil, maxResults: Int? = nil, nextToken: String? = nil) {
self.filters = filters
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^[\\w/+=]+$")
}
private enum CodingKeys: String, CodingKey {
case filters = "Filters"
case maxResults = "MaxResults"
case nextToken = "NextToken"
}
}
public struct ListNotificationRulesResult: AWSDecodableShape {
/// An enumeration token that can be used in a request to return the next batch of the results.
public let nextToken: String?
/// The list of notification rules for the AWS account, by Amazon Resource Name (ARN) and ID.
public let notificationRules: [NotificationRuleSummary]?
public init(nextToken: String? = nil, notificationRules: [NotificationRuleSummary]? = nil) {
self.nextToken = nextToken
self.notificationRules = notificationRules
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case notificationRules = "NotificationRules"
}
}
public struct ListTagsForResourceRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) for the notification rule.
public let arn: String
public init(arn: String) {
self.arn = arn
}
public func validate(name: String) throws {
try self.validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
}
}
public struct ListTagsForResourceResult: AWSDecodableShape {
/// The tags associated with the notification rule.
public let tags: [String: String]?
public init(tags: [String: String]? = nil) {
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags = "Tags"
}
}
public struct ListTargetsFilter: AWSEncodableShape {
/// The name of the attribute you want to use to filter the returned targets.
public let name: ListTargetsFilterName
/// The value of the attribute you want to use to filter the returned targets. For example, if you specify SNS for the Target type, you could specify an Amazon Resource Name (ARN) for a topic as the value.
public let value: String
public init(name: ListTargetsFilterName, value: String) {
self.name = name
self.value = value
}
private enum CodingKeys: String, CodingKey {
case name = "Name"
case value = "Value"
}
}
public struct ListTargetsRequest: AWSEncodableShape {
/// The filters to use to return information by service or resource type. Valid filters include target type, target address, and target status. A filter with the same name can appear more than once when used with OR statements. Filters with different names should be applied with AND statements.
public let filters: [ListTargetsFilter]?
/// A non-negative integer used to limit the number of returned results. The maximum number of results that can be returned is 100.
public let maxResults: Int?
/// An enumeration token that, when provided in a request, returns the next batch of the results.
public let nextToken: String?
public init(filters: [ListTargetsFilter]? = nil, maxResults: Int? = nil, nextToken: String? = nil) {
self.filters = filters
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^[\\w/+=]+$")
}
private enum CodingKeys: String, CodingKey {
case filters = "Filters"
case maxResults = "MaxResults"
case nextToken = "NextToken"
}
}
public struct ListTargetsResult: AWSDecodableShape {
/// An enumeration token that can be used in a request to return the next batch of results.
public let nextToken: String?
/// The list of notification rule targets.
public let targets: [TargetSummary]?
public init(nextToken: String? = nil, targets: [TargetSummary]? = nil) {
self.nextToken = nextToken
self.targets = targets
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case targets = "Targets"
}
}
public struct NotificationRuleSummary: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the notification rule.
public let arn: String?
/// The unique ID of the notification rule.
public let id: String?
public init(arn: String? = nil, id: String? = nil) {
self.arn = arn
self.id = id
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case id = "Id"
}
}
public struct SubscribeRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the notification rule for which you want to create the association.
public let arn: String
/// An enumeration token that, when provided in a request, returns the next batch of the results.
public let clientRequestToken: String?
public let target: Target
public init(arn: String, clientRequestToken: String? = nil, target: Target) {
self.arn = arn
self.clientRequestToken = clientRequestToken
self.target = target
}
public func validate(name: String) throws {
try self.validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, max: 256)
try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, min: 1)
try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, pattern: "^[\\w:/-]+$")
try self.target.validate(name: "\(name).target")
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case clientRequestToken = "ClientRequestToken"
case target = "Target"
}
}
public struct SubscribeResult: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the notification rule for which you have created assocations.
public let arn: String?
public init(arn: String? = nil) {
self.arn = arn
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
}
}
public struct TagResourceRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the notification rule to tag.
public let arn: String
/// The list of tags to associate with the resource. Tag key names cannot start with "aws".
public let tags: [String: String]
public init(arn: String, tags: [String: String]) {
self.arn = arn
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
try self.tags.forEach {
try validate($0.key, name: "tags.key", parent: name, max: 128)
try validate($0.key, name: "tags.key", parent: name, min: 1)
try validate($0.key, name: "tags.key", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$")
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256)
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$")
}
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case tags = "Tags"
}
}
public struct TagResourceResult: AWSDecodableShape {
/// The list of tags associated with the resource.
public let tags: [String: String]?
public init(tags: [String: String]? = nil) {
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags = "Tags"
}
}
public struct Target: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the SNS topic.
public let targetAddress: String?
/// The target type. Can be an Amazon SNS topic.
public let targetType: String?
public init(targetAddress: String? = nil, targetType: String? = nil) {
self.targetAddress = targetAddress
self.targetType = targetType
}
public func validate(name: String) throws {
try self.validate(self.targetAddress, name: "targetAddress", parent: name, max: 320)
try self.validate(self.targetAddress, name: "targetAddress", parent: name, min: 1)
try self.validate(self.targetType, name: "targetType", parent: name, pattern: "^[A-Za-z]+$")
}
private enum CodingKeys: String, CodingKey {
case targetAddress = "TargetAddress"
case targetType = "TargetType"
}
}
public struct TargetSummary: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the SNS topic.
public let targetAddress: String?
/// The status of the target.
public let targetStatus: TargetStatus?
/// The type of the target (for example, SNS).
public let targetType: String?
public init(targetAddress: String? = nil, targetStatus: TargetStatus? = nil, targetType: String? = nil) {
self.targetAddress = targetAddress
self.targetStatus = targetStatus
self.targetType = targetType
}
private enum CodingKeys: String, CodingKey {
case targetAddress = "TargetAddress"
case targetStatus = "TargetStatus"
case targetType = "TargetType"
}
}
public struct UnsubscribeRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the notification rule.
public let arn: String
/// The ARN of the SNS topic to unsubscribe from the notification rule.
public let targetAddress: String
public init(arn: String, targetAddress: String) {
self.arn = arn
self.targetAddress = targetAddress
}
public func validate(name: String) throws {
try self.validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
try self.validate(self.targetAddress, name: "targetAddress", parent: name, max: 320)
try self.validate(self.targetAddress, name: "targetAddress", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case targetAddress = "TargetAddress"
}
}
public struct UnsubscribeResult: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the the notification rule from which you have removed a subscription.
public let arn: String
public init(arn: String) {
self.arn = arn
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
}
}
public struct UntagResourceRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the notification rule from which to remove the tags.
public let arn: String
/// The key names of the tags to remove.
public let tagKeys: [String]
public init(arn: String, tagKeys: [String]) {
self.arn = arn
self.tagKeys = tagKeys
}
public func validate(name: String) throws {
try self.validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
try self.tagKeys.forEach {
try validate($0, name: "tagKeys[]", parent: name, max: 128)
try validate($0, name: "tagKeys[]", parent: name, min: 1)
try validate($0, name: "tagKeys[]", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$")
}
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case tagKeys = "TagKeys"
}
}
public struct UntagResourceResult: AWSDecodableShape {
public init() {}
}
public struct UpdateNotificationRuleRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the notification rule.
public let arn: String
/// The level of detail to include in the notifications for this resource. BASIC will include only the contents of the event as it would appear in AWS CloudWatch. FULL will include any supplemental information provided by AWS CodeStar Notifications and/or the service for the resource for which the notification is created.
public let detailType: DetailType?
/// A list of event types associated with this notification rule.
public let eventTypeIds: [String]?
/// The name of the notification rule.
public let name: String?
/// The status of the notification rule. Valid statuses include enabled (sending notifications) or disabled (not sending notifications).
public let status: NotificationRuleStatus?
/// The address and type of the targets to receive notifications from this notification rule.
public let targets: [Target]?
public init(arn: String, detailType: DetailType? = nil, eventTypeIds: [String]? = nil, name: String? = nil, status: NotificationRuleStatus? = nil, targets: [Target]? = nil) {
self.arn = arn
self.detailType = detailType
self.eventTypeIds = eventTypeIds
self.name = name
self.status = status
self.targets = targets
}
public func validate(name: String) throws {
try self.validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
try self.eventTypeIds?.forEach {
try validate($0, name: "eventTypeIds[]", parent: name, max: 200)
try validate($0, name: "eventTypeIds[]", parent: name, min: 1)
}
try self.validate(self.name, name: "name", parent: name, max: 64)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9\\-_ ]+$")
try self.targets?.forEach {
try $0.validate(name: "\(name).targets[]")
}
try self.validate(self.targets, name: "targets", parent: name, max: 10)
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case detailType = "DetailType"
case eventTypeIds = "EventTypeIds"
case name = "Name"
case status = "Status"
case targets = "Targets"
}
}
public struct UpdateNotificationRuleResult: AWSDecodableShape {
public init() {}
}
}
| apache-2.0 | 7c3d1194d8eb0cb2a2e7ba186e22cc44 | 43.864935 | 429 | 0.620795 | 4.96636 | false | false | false | false |
donmccaughey/Lunch | LunchKit/LunchKit/Venue.swift | 1 | 5937 | //
// Venue.swift
// LunchKit
//
// Created by Don McCaughey on 4/19/16.
// Copyright © 2016 Don McCaughey. All rights reserved.
//
import Foundation
public class Venue {
public let id: String
public let name: String
public let categories: [Category]
public let contact: Contact?
public let location: Location
public let hasMenu: Bool
public let menu: Menu?
public var thumbsDown: Bool
public var review: Review?
public var hasReview: Bool {
return thumbsDown || review != nil
}
init(id: String, name: String, categories: [Category], contact: Contact?,
location: Location, hasMenu: Bool, menu: Menu?, thumbsDown: Bool,
review: Review?)
{
self.id = id
self.name = name
self.categories = categories
self.contact = contact
self.location = location
self.hasMenu = hasMenu
self.menu = menu
self.thumbsDown = thumbsDown
self.review = review
}
convenience init?(fromFoursquareJSONDictionary dictionary: [String : AnyObject]) {
guard
let id = dictionary["id"] as? String,
let name = dictionary["name"] as? String
else {
NSLog("Invalid Foursquare JSON for venue")
return nil
}
var categories: [Category] = []
if let categoryDictionaries = dictionary["categories"] as? [[String : AnyObject]] {
for categoryDictionary in categoryDictionaries {
if let category = Category(fromFoursquareJSONDictionary: categoryDictionary) {
categories.append(category)
}
}
}
var contact: Contact? = nil
if let contactDictionary = dictionary["contact"] as? [String : AnyObject] {
contact = Contact(fromFoursquareJSONDictionary: contactDictionary)
}
guard
let locationDictionary = dictionary["location"] as? [String : AnyObject],
let location = Location(fromFoursquareJSONDictionary: locationDictionary) else {
NSLog("Invalid Foursquare JSON for location of \(name)")
return nil
}
var hasMenu: Bool = false
if let hasMenuValue = dictionary["hasMenu"] as? Bool {
hasMenu = hasMenuValue
}
var menu: Menu? = nil
if let menuDictionary = dictionary["menu"] as? [String : AnyObject] {
menu = Menu(fromFoursquareJSONDictionary: menuDictionary)
}
self.init(id: id, name: name, categories: categories, contact: contact,
location: location, hasMenu: hasMenu, menu: menu,
thumbsDown: false, review: nil)
}
convenience init?(fromPlistDictionary dictionary: [String : AnyObject]) {
guard
let id = dictionary["id"] as? String,
let name = dictionary["name"] as? String,
let thumbsDown = dictionary["thumbsDown"] as? Bool
else {
return nil
}
var categories: [Category] = []
if let categoryDictionaries = dictionary["categories"] as? [[String : AnyObject]] {
for categoryDictionary in categoryDictionaries {
if let category = Category(fromPlistDictionary: categoryDictionary) {
categories.append(category)
}
}
}
var contact: Contact? = nil
if let contactDictionary = dictionary["contact"] as? [String : AnyObject] {
contact = Contact(fromPlistDictionary: contactDictionary)
}
guard
let locationDictionary = dictionary["location"] as? [String : AnyObject],
let location = Location(fromPlistDictionary: locationDictionary) else {
return nil
}
var hasMenu: Bool = false
if let hasMenuValue = dictionary["hasMenu"] as? Bool {
hasMenu = hasMenuValue
}
var menu: Menu? = nil
if let menuDictionary = dictionary["menu"] as? [String : AnyObject] {
menu = Menu(fromPlistDictionary: menuDictionary)
}
var review: Review? = nil
if let reviewDictionary = dictionary["review"] as? [String : AnyObject] {
review = Review(fromPlistDictionary: reviewDictionary)
}
self.init(id: id, name: name, categories: categories, contact: contact,
location: location, hasMenu: hasMenu, menu: menu,
thumbsDown: thumbsDown, review: review)
}
func asPlistDictionary() -> [String : AnyObject] {
var dictionary: [String : AnyObject] = [
"id": id,
"name": name,
"categories": categories.map({$0.asPlistDictionary()}),
"location": location.asPlistDictionary(),
"hasMenu": hasMenu,
"thumbsDown": thumbsDown,
]
if contact != nil {
dictionary["contact"] = contact!.asPlistDictionary()
}
if menu != nil {
dictionary["menu"] = menu!.asPlistDictionary()
}
if review != nil {
dictionary["review"] = review!.asPlistDictionary()
}
return dictionary
}
public func addOrUpdateReview(text: String) {
let trimmedText = text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
if review != nil {
if trimmedText.isEmpty {
review = nil
} else if trimmedText != review!.text {
review = Review(date: NSDate(), text: trimmedText)
}
} else {
if !trimmedText.isEmpty {
review = Review(date: NSDate(), text: trimmedText)
}
}
}
}
| bsd-2-clause | c0f5a31aef62e153c06c19156779f984 | 33.71345 | 103 | 0.561995 | 5.35257 | false | false | false | false |
becca9808/Hacktech2017 | Sample Project/CognitiveServices/CognitiveServices/Example Code/ComputerVision/OCRViewController.swift | 1 | 6407 | //
// OCRViewController.swift
// CognitiveServices
//
// Created by Vladimir Danila on 5/13/16.
// Copyright © 2016 Vladimir Danila. All rights reserved.
//
import UIKit
class OCRViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imagev: UIImageView!
@IBOutlet weak var urlTextField: UITextField!
@IBOutlet weak var resultTextView: UITextView!
// @interface OCRViewController : UIViewController <UIImagePickerControllerDelegate;UINavigationControllerDelegate>
let ocr = CognitiveServices.sharedInstance.ocr
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size
let widthRatio = targetSize.width / image.size.width
let heightRatio = targetSize.height / image.size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// The info dictionary may contain multiple representations of the image. You want to use the original.
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
<<<<<<< HEAD
imagev.image = selectedImage
let requestObject: OCRRequestObject = (resource: UIImagePNGRepresentation(selectedImage)!, language: .Automatic, detectOrientation: true)
try! ocr.recognizeCharactersWithRequestObject(requestObject, completion: { (response) in
self.resultTextView.text = response
let text = self.ocr.extractStringsFromDictionary(response!)
self.resultTextView.text = text[4]
})
//selected image is the one that you gott//
=======
//imagev.image = selectedImage
>>>>>>> f9c0cbfff3ebaf22768c68843c79832418789221
print(selectedImage.size.width*selectedImage.scale)
print(selectedImage.size.height*selectedImage.scale)
var resizedIm:UIImage
if selectedImage.size.width*selectedImage.scale>1480 || selectedImage.size.height*selectedImage.scale>1480
{
resizedIm = resizeImage(image: selectedImage, targetSize: CGSize(width: 1480, height: 1480))
}
else
{
resizedIm = selectedImage
}
print("imageresized")
imagev.image = resizedIm
var imgData: NSData = NSData(data: UIImageJPEGRepresentation((resizedIm
), 1)!)
// var imgData: NSData = UIImagePNGRepresentation(image)
// you can also replace UIImageJPEGRepresentation with UIImagePNGRepresentation.
var imageSize: Int = imgData.length
print("size of image in KB: " + String(imageSize/1024))
print(resizedIm.size.width*resizedIm.scale)
print(resizedIm.size.height*resizedIm.scale)
dismiss(animated: true, completion: nil)
let requestObject: OCRRequestObject = (resource: UIImagePNGRepresentation(resizedIm)!, language: .Automatic, detectOrientation: true)
try! ocr.recognizeCharactersWithRequestObject(requestObject, completion: { (response) in
print("printing response")
print(response!)
let text = self.ocr.extractStringFromDictionary(response!)
self.resultTextView.text = text
// Dismiss the picker.
})
}
@IBAction func textFromUrlDidPush(_ sender: UIButton) {
let requestObject: OCRRequestObject = (resource: urlTextField.text!, language: .Automatic, detectOrientation: true)
try! ocr.recognizeCharactersWithRequestObject(requestObject, completion: { (response) in
})
}
@IBAction func textFromImageDidPush(_ sender: UIButton) {
// Hide the keyboard.
//nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .photoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
@IBAction func textFromCameraRoll(_ sender: UIButton) {
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .camera
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
}
| apache-2.0 | 6d655bb7a4e9d5e413f82303919fa07f | 36.682353 | 145 | 0.655635 | 5.517657 | false | false | false | false |
troystribling/BlueCap | Examples/BlueCap/BlueCap/Peripheral/PeripheralManagerViewController.swift | 1 | 10455 | //
// PeripheralManagerViewController.swift
// BlueCapUI
//
// Created by Troy Stribling on 6/5/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import UIKit
import BlueCapKit
import CoreBluetooth
class PeripheralManagerViewController : UITableViewController, UITextFieldDelegate {
@IBOutlet var nameTextField: UITextField!
@IBOutlet var advertiseSwitch: UISwitch!
@IBOutlet var advertiseLabel: UILabel!
@IBOutlet var advertisedServicesLabel: UILabel!
@IBOutlet var advertisedServicesCountLabel: UILabel!
@IBOutlet var servicesLabel: UILabel!
@IBOutlet var servicesCountLabel: UILabel!
struct MainStoryboard {
static let peripheralManagerServicesSegue = "PeripheralManagerServices"
static let peripheralManagerAdvertisedServicesSegue = "PeripheralManagerAdvertisedServices"
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated:Bool) {
super.viewWillAppear(animated)
nameTextField.text = PeripheralStore.getPeripheralName()
let addServicesFuture = Singletons.peripheralManager.whenStateChanges().flatMap { [unowned self] state -> Future<[Void]> in
switch state {
case .poweredOn:
return self.loadPeripheralServicesFromConfig()
case .poweredOff:
throw AppError.poweredOff
case .unauthorized:
throw AppError.unauthorized
case .unknown:
throw AppError.unknown
case .unsupported:
throw AppError.unsupported
case .resetting:
throw AppError.resetting
}
}
addServicesFuture.onSuccess { [weak self] _ in
self?.setUIState()
}
addServicesFuture.onFailure { [weak self] error in
self.forEach { strongSelf in
switch error {
case AppError.poweredOff:
strongSelf.present(UIAlertController.alert(message: "Bluetooth powered off"), animated: true)
case AppError.resetting:
let message = "PeripheralManager state \"\(Singletons.peripheralManager.state)\". The connection with the system bluetooth service was momentarily lost.\n Restart advertising."
strongSelf.present(UIAlertController.alert(message: message) { _ in
Singletons.peripheralManager.reset()
}, animated: true)
case AppError.unsupported:
strongSelf.present(UIAlertController.alert(message: "Bluetooth not supported."), animated: true)
case AppError.unknown:
break;
default:
strongSelf.present(UIAlertController.alert(error: error) { _ in
Singletons.peripheralManager.reset()
}, animated: true, completion: nil)
}
strongSelf.setUIState()
}
}
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepare(for segue:UIStoryboardSegue, sender:Any!) {
if segue.identifier == MainStoryboard.peripheralManagerServicesSegue {
let viewController = segue.destination as! PeripheralManagerServicesViewController
viewController.peripheralManagerViewController = self
} else if segue.identifier == MainStoryboard.peripheralManagerAdvertisedServicesSegue {
let viewController = segue.destination as! PeripheralManagerAdvertisedServicesViewController
viewController.peripheralManagerViewController = self
}
}
override func shouldPerformSegue(withIdentifier identifier: String?, sender: Any?) -> Bool {
if let identifier = identifier {
if Singletons.peripheralManager.isAdvertising {
return identifier == MainStoryboard.peripheralManagerServicesSegue
} else if identifier == MainStoryboard.peripheralManagerAdvertisedServicesSegue {
return PeripheralStore.getSupportedPeripheralServices().count > 0
} else {
return true
}
} else {
return true
}
}
override func willMove(toParent parent: UIViewController?) {
if parent == nil {
Singletons.peripheralManager.invalidate()
}
}
@IBAction func toggleAdvertise(_ sender:AnyObject) {
if Singletons.peripheralManager.isAdvertising {
let stopAdvertisingFuture = Singletons.peripheralManager.stopAdvertising()
stopAdvertisingFuture.onSuccess { [weak self] _ in
self?.setUIState()
}
stopAdvertisingFuture.onFailure { [weak self] _ in
self?.present(UIAlertController.alert(message: "Failed to stop advertising."), animated: true)
}
return
}
guard let name = PeripheralStore.getPeripheralName() else {
return
}
let startAdvertiseFuture = loadPeripheralServicesFromConfig().flatMap { _ -> Future<Void> in
let advertisedServices = PeripheralStore.getAdvertisedPeripheralServices()
if advertisedServices.count > 0 {
return Singletons.peripheralManager.startAdvertising(name, uuids: advertisedServices)
} else {
return Singletons.peripheralManager.startAdvertising(name)
}
}
startAdvertiseFuture.onSuccess { [weak self] _ in
self?.setUIState()
self?.present(UIAlertController.alert(message: "Powered on and started advertising."), animated: true, completion: nil)
}
startAdvertiseFuture.onFailure { [weak self] error in
self.forEach { strongSelf in
switch error {
case AppError.poweredOff:
break
case AppError.resetting:
let message = "PeripheralManager state \"\(Singletons.peripheralManager.state)\". The connection with the system bluetooth service was momentarily lost.\n Restart advertising."
strongSelf.present(UIAlertController.alert(message: message) { _ in
Singletons.peripheralManager.reset()
}, animated: true)
case AppError.unsupported:
strongSelf.present(UIAlertController.alert(message: "Bluetooth not supported."), animated: true)
case AppError.unknown:
break;
default:
strongSelf.present(UIAlertController.alert(error: error) { _ in
Singletons.peripheralManager.reset()
}, animated: true, completion: nil)
}
let stopAdvertisingFuture = Singletons.peripheralManager.stopAdvertising()
stopAdvertisingFuture.onSuccess { _ in
strongSelf.setUIState()
}
stopAdvertisingFuture.onFailure { _ in
strongSelf.setUIState()
}
}
}
}
func loadPeripheralServicesFromConfig() -> Future<[Void]> {
let serviceUUIDs = PeripheralStore.getSupportedPeripheralServices()
let services = serviceUUIDs.reduce([MutableService]()){ services, uuid in
if let serviceProfile = Singletons.profileManager.services[uuid] {
let service = MutableService(profile: serviceProfile)
service.characteristicsFromProfiles()
return services + [service]
} else {
return services
}
}
Singletons.peripheralManager.removeAllServices()
return services.map { Singletons.peripheralManager.add($0) }.sequence()
}
func setUIState() {
let advertisedServicesCount = PeripheralStore.getAdvertisedPeripheralServices().count
let supportedServicesCount = PeripheralStore.getSupportedPeripheralServices().count
advertisedServicesCountLabel.text = "\(advertisedServicesCount)"
servicesCountLabel.text = "\(supportedServicesCount)"
if Singletons.peripheralManager.isAdvertising {
navigationItem.setHidesBackButton(true, animated:true)
advertiseSwitch.isOn = true
nameTextField.isEnabled = false
advertisedServicesLabel.textColor = UIColor.lightGray
} else {
nameTextField.isEnabled = true
navigationItem.setHidesBackButton(false, animated:true)
if canAdvertise() {
advertiseSwitch.isEnabled = true
advertiseLabel.textColor = UIColor.black
} else {
advertiseSwitch.isEnabled = false
advertiseLabel.textColor = UIColor.lightGray
}
if supportedServicesCount == 0 {
advertiseSwitch.isOn = false
advertisedServicesLabel.textColor = UIColor.lightGray
} else {
navigationItem.setHidesBackButton(false, animated:true)
advertiseSwitch.isOn = false
advertisedServicesLabel.textColor = UIColor.black
}
}
if !Singletons.peripheralManager.poweredOn {
advertiseSwitch.isEnabled = false
advertiseLabel.textColor = UIColor.lightGray
}
}
func alert(message: String) {
present(UIAlertController.alert(message: message), animated:true) { [weak self] () -> Void in
self.forEach { strongSelf in
Singletons.peripheralManager.reset()
}
}
}
func canAdvertise() -> Bool {
return PeripheralStore.getPeripheralName() != nil && PeripheralStore.getSupportedPeripheralServices().count > 0
}
// UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.nameTextField.resignFirstResponder()
if let enteredName = self.nameTextField.text, !enteredName.isEmpty {
PeripheralStore.setPeripheralName(enteredName)
}
self.setUIState()
return true
}
}
| mit | 8b18dd0ef7e588b43a408b6fd6d04aa2 | 40.987952 | 196 | 0.620373 | 6.260479 | false | false | false | false |
Narsail/relaykit | RelayKit/Shared/Logging.swift | 1 | 5198 | /// Copyright (c) 2017 David Moeller
///
/// 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.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// 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.
///
/// This Code is based and inspired upon https://github.com/bustoutsolutions/siesta/blob/ce4ff32618db5c950696e53b8e7818fa10a8d20a/Source/Siesta/Support/Logging.swift
/// Copyright © 2016 Bust Out Solutions. All rights reserved.
///
import Foundation
/**
Controls which message RelayKit will log. See `enabledLogCategories`.
*/
public enum RelayKitLogCategory {
/// Details of when a relay is set.
case configuration
/// Details of the actual messaging
case messages
/// Details of the Message Content
case messageContent
// MARK: Predefined subsets
/// The whole schebang!
public static let all: Set<RelayKitLogCategory> = [configuration, messages, messageContent]
/// The set of categories to log. Can be changed at runtime.
public static var enabled = Set<RelayKitLogCategory>()
}
private let maxCategoryNameLength = RelayKitLogCategory.all.map { Int(String(describing: $0).count) }.max() ?? 0
/// Inject your custom logger to do something other than print to stdout.
public var logger: (RelayKitLogCategory, String) -> Void = {
let paddedCategory = String(describing: $0).padding(toLength: maxCategoryNameLength, withPad: " ", startingAt: 0)
let prefix = "RelayKit:\(paddedCategory) │ "
let indentedMessage = $1.replacingOccurrences(of: "\n", with: "\n" + prefix)
print(prefix + indentedMessage)
}
internal func debugLog(_ category: RelayKitLogCategory, _ messageParts: @autoclosure () -> [Any?]) {
if RelayKitLogCategory.enabled.contains(category) {
logger(category, debugStr(messageParts()))
}
}
private let whitespacePat = try! NSRegularExpression(pattern: "\\s+")
internal func debugStr(_ x: Any?, consolidateWhitespace: Bool = false, truncate: Int? = 500) -> String {
guard let x = x else { return "nil" }
var s: String
if let debugPrintable = x as? CustomDebugStringConvertible {
s = debugPrintable.debugDescription
} else { s = "\(x)" }
if consolidateWhitespace {
s = s.replacing(regex: whitespacePat, with: " ")
}
if let truncate = truncate, s.count > truncate {
s = s.prefix(truncate) + "…"
}
return s
}
internal func debugStr(_ messageParts: [Any?], join: String = " ", consolidateWhitespace: Bool = true,
truncate: Int? = 300) -> String {
return messageParts.map {
($0 as? String)
?? debugStr($0, consolidateWhitespace: consolidateWhitespace, truncate: truncate)
}
.joined(separator: " ")
}
internal extension String {
func contains(regex: String) -> Bool {
return range(of: regex, options: .regularExpression) != nil
}
func replacing(regex: String, with replacement: String) -> String {
return replacingOccurrences(
of: regex, with: replacement, options: .regularExpression, range: nil)
}
func replacing(regex: NSRegularExpression, with template: String) -> String {
return regex.stringByReplacingMatches(in: self, options: [], range: fullRange, withTemplate: template)
}
fileprivate var fullRange: NSRange {
return NSRange(location: 0, length: (self as NSString).length)
}
}
internal extension NSRegularExpression {
func matches(_ string: String) -> Bool {
let match = firstMatch(in: string, options: [], range: string.fullRange)
return match != nil && match?.range.location != NSNotFound
}
}
| mit | 0037235822030c43c0a7c49928a64a0f | 37.466667 | 165 | 0.689775 | 4.511729 | false | false | false | false |
IAskWind/IAWExtensionTool | Pods/Easy/Easy/Classes/Core/EasyPopupMenu.swift | 1 | 4806 | //
// EasyPopupMenu.swift
// Easy
//
// Created by OctMon on 2018/10/15.
//
import UIKit
public extension Easy {
typealias PopMenu = EasyPopupMenu
}
public class EasyPopupMenu: UIView {
private lazy var menuTableView: UITableView = {
let tableView = UITableView(frame: EasyApp.screenBounds, style: .plain)
tableView.dataSource = self
tableView.delegate = self
tableView.layer.cornerRadius = 2
tableView.showsVerticalScrollIndicator = false
tableView.bounces = false
tableView.separatorInset = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
tableView.backgroundColor = .clear
var header = UIView()
header.frame.size.height = 6.5
tableView.tableHeaderView = header
return tableView
}()
private lazy var items: [String] = {
return []
}()
private var completion: ((Int) -> Void)?
private override init(frame: CGRect) {
super.init(frame: frame)
}
public convenience init() {
self.init(frame: EasyApp.screenBounds)
backgroundColor = .clear
let tapGestureRecognizer = UITapGestureRecognizer()
tapGestureRecognizer.delegate = self
tapGestureRecognizer.addTarget(self, action: #selector(close))
self.addGestureRecognizer(tapGestureRecognizer)
addSubview(menuTableView)
menuTableView.registerReusableCell(EasyPopupMenuCell.self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func close() {
UIView.animate(withDuration: 0.25, animations: { [weak self] in
guard let self = self else { return }
self.menuTableView.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
}) { (finish) in
self.subviews.forEach({ $0.removeFromSuperview() })
self.removeFromSuperview()
}
}
public func show(point: CGPoint, items: [String], backgroundImage: UIImage? = UIImage(for: EasyPopupMenu.self, forResource: "EasyCore", forImage: "bg_popup_menu"), completion: @escaping (Int) -> Void) {
menuTableView.backgroundView = UIImageView(image: backgroundImage)
self.completion = completion
menuTableView.layer.anchorPoint = CGPoint(x: 0.8, y: 0)
menuTableView.frame = CGRect(x: point.x, y: point.y, width: 113.5, height: 6.5 + 44 * CGFloat(items.count))
// menuTableView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
EasyApp.window?.addSubview(self)
addSubview(menuTableView)
self.items = items
self.menuTableView.reloadData()
self.menuTableView.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
UIView.animate(withDuration: 0.25) { [weak self] in
guard let self = self else { return }
self.menuTableView.transform = CGAffineTransform(scaleX: 1, y: 1)
}
}
}
extension EasyPopupMenu: UITableViewDataSource, UITableViewDelegate {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(with: EasyPopupMenuCell.self)
cell.titleLabel.text = items[indexPath.row]
return cell
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
completion?(indexPath.row)
close()
}
}
extension EasyPopupMenu: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if (touch.view?.isDescendant(of: menuTableView))! {
return false
}
return true
}
}
private class EasyPopupMenuCell: UITableViewCell {
lazy var titleLabel: UILabel = {
let label = UILabel()
addSubview(label)
label.textColor = .white
label.font = .size13
label.textAlignment = .center
label.snp.makeConstraints({ (make) in
make.edges.equalToSuperview()
make.height.equalTo(44)
})
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .clear
selectionStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 6c2b363d3835e07f0fbfb71ce33c20ff | 31.693878 | 206 | 0.638993 | 4.894094 | false | false | false | false |
tman94/eli | bfinterpreter/AppDelegate.swift | 1 | 2344 | //
// AppDelegate.swift
// bfinterpreter
//
// Created by Tielman Janse van Vuuren on 2015/11/28.
// Copyright © 2015 tman. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if(self.window == nil)
{
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
}
let vc = ViewController.init()
self.window!.rootViewController = vc
self.window!.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 70f21f7997e04faddda60fbc1f58f1c8 | 43.207547 | 285 | 0.733248 | 5.398618 | false | false | false | false |
softdevstory/yata | yata/Sources/Constants/TextStyles.swift | 1 | 6682 | //
// TextStyles.swift
// yata
//
// Created by HS Song on 2017. 7. 10..
// Copyright © 2017년 HS Song. All rights reserved.
//
import Cocoa
fileprivate struct ParagraphStyle {
static let title: NSParagraphStyle = {
let paragraph = NSMutableParagraphStyle()
paragraph.lineSpacing = 10
return paragraph
}()
static let header: NSParagraphStyle = {
let paragraph = NSMutableParagraphStyle()
paragraph.lineSpacing = 5
return paragraph
}()
static let body: NSParagraphStyle = {
let paragraph = NSMutableParagraphStyle()
return paragraph
}()
static let blockQuote: NSParagraphStyle = {
let paragraph = NSMutableParagraphStyle()
paragraph.firstLineHeadIndent = 10
paragraph.headIndent = 10
return paragraph
}()
static let pullQuote: NSParagraphStyle = {
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
return paragraph
}()
}
enum TextStyles {
case unknown
case title
case header
case body
case blockQuote
case pullQuote
init(attributes: [String: Any]) {
if TextStyles.isTitle(attributes: attributes) {
self = .title
return
}
if TextStyles.isHeader(attributes: attributes) {
self = .header
return
}
if TextStyles.isBody(attributes: attributes) {
self = .body
return
}
if TextStyles.isBlockQuote(attributes: attributes) {
self = .blockQuote
return
}
if TextStyles.isPullQuote(attributes: attributes) {
self = .pullQuote
return
}
self = .unknown
}
var attributes: [String: Any] {
switch self {
case .title:
return titleAttributes
case .header:
return headerAttributes
case .body:
return bodyAttributes
case .blockQuote:
return blockQuotationAttributes
case .pullQuote:
return pullQuoteAttributes
case .unknown:
Swift.print("Uknown Text Styles!!")
return bodyAttributes
}
}
}
extension TextStyles {
fileprivate var titleAttributes: [String: Any] {
let font = NSFont.boldSystemFont(ofSize: NSFont.systemFontSize() + 6)
return [
NSFontAttributeName: font,
NSParagraphStyleAttributeName: ParagraphStyle.title
]
}
fileprivate var headerAttributes: [String: Any] {
let font = NSFont.boldSystemFont(ofSize: NSFont.systemFontSize() + 3)
return [
NSFontAttributeName: font,
NSParagraphStyleAttributeName: ParagraphStyle.header
]
}
fileprivate var bodyAttributes: [String: Any] {
let font = NSFont.systemFont(ofSize: NSFont.systemFontSize())
return [
NSFontAttributeName: font,
NSParagraphStyleAttributeName: ParagraphStyle.body
]
}
fileprivate var blockQuotationAttributes: [String: Any] {
let font = NSFontManager.shared().convert(NSFont.systemFont(ofSize: NSFont.systemFontSize()), toHaveTrait: .italicFontMask)
return [
NSFontAttributeName: font,
NSParagraphStyleAttributeName: ParagraphStyle.blockQuote
]
}
fileprivate var pullQuoteAttributes: [String: Any] {
let font = NSFontManager.shared().convert(NSFont.systemFont(ofSize: NSFont.systemFontSize()), toHaveTrait: .italicFontMask)
return [
NSFontAttributeName: font,
NSParagraphStyleAttributeName: ParagraphStyle.pullQuote
]
}
fileprivate static func isTitle(attributes: [String: Any]) -> Bool {
guard let paragraph = attributes[NSParagraphStyleAttributeName] as? NSParagraphStyle else {
return false
}
guard let font = attributes[NSFontAttributeName] as? NSFont else {
return false
}
if paragraph != ParagraphStyle.title {
return false
}
if font.fontSize != NSFont.systemFontSize() + 6 {
return false
}
return true
}
fileprivate static func isHeader(attributes: [String: Any]) -> Bool {
guard let paragraph = attributes[NSParagraphStyleAttributeName] as? NSParagraphStyle else {
return false
}
guard let font = attributes[NSFontAttributeName] as? NSFont else {
return false
}
if paragraph != ParagraphStyle.header {
return false
}
if font.fontSize != NSFont.systemFontSize() + 3 {
return false
}
return true
}
fileprivate static func isBody(attributes: [String: Any]) -> Bool {
guard let paragraph = attributes[NSParagraphStyleAttributeName] as? NSParagraphStyle else {
return false
}
guard let font = attributes[NSFontAttributeName] as? NSFont else {
return false
}
if paragraph != ParagraphStyle.body {
return false
}
if font.fontSize != NSFont.systemFontSize() {
return false
}
return true
}
fileprivate static func isBlockQuote(attributes: [String: Any]) -> Bool {
guard let paragraph = attributes[NSParagraphStyleAttributeName] as? NSParagraphStyle else {
return false
}
guard let font = attributes[NSFontAttributeName] as? NSFont else {
return false
}
if paragraph != ParagraphStyle.blockQuote {
return false
}
if font.fontSize != NSFont.systemFontSize() {
return false
}
return true
}
fileprivate static func isPullQuote(attributes: [String: Any]) -> Bool {
guard let paragraph = attributes[NSParagraphStyleAttributeName] as? NSParagraphStyle else {
return false
}
guard let font = attributes[NSFontAttributeName] as? NSFont else {
return false
}
if paragraph != ParagraphStyle.pullQuote {
return false
}
if font.fontSize != NSFont.systemFontSize() {
return false
}
return true
}
}
| mit | e684c521e4b673552445e8524cb824c9 | 24.787645 | 131 | 0.569546 | 5.905393 | false | false | false | false |
DrGo/LearningSwift | PLAYGROUNDS/ExpressionParser/ExpressionParser/Parser.swift | 2 | 12093 | //
// Parser.swift
// ExpressionParser
//
// Created by Kyle Oba on 2/5/15.
// Copyright (c) 2015 Pas de Chocolat. All rights reserved.
//
import Foundation
/*---------------------------------------------------------/
// Extensions
/---------------------------------------------------------*/
public extension String {
var characters: [Character] {
var result: [Character] = []
for c in self {
result += [c]
}
return result
}
var slice: Slice<Character> {
let res = self.characters
return res[0..<res.count]
}
}
extension Slice {
var head: T? {
return self.isEmpty ? nil : self[0]
}
var tail: Slice<T> {
if (self.isEmpty) { return self }
return self[(self.startIndex+1)..<self.endIndex]
}
var decompose: (head: T, tail: Slice<T>)? {
return self.isEmpty ? nil : (self.head!, self.tail)
}
}
/*---------------------------------------------------------/
// Helpers
/---------------------------------------------------------*/
public func none<A>() -> SequenceOf<A> {
return SequenceOf(GeneratorOf { nil } )
}
public func one<A>(x: A) -> SequenceOf<A> {
return SequenceOf(GeneratorOfOne(x))
}
/*---------------------------------------------------------------------/
// Parser Type
// We use a struct because typealiases don't support generic types.
//
// “We define a parser as a function that takes a slice of tokens,
// processes some of these tokens, and returns a tuple of the result
// and the remainder of the tokens.”
// - Excerpt From: Chris Eidhof. “Functional Programming in Swift.” iBooks.
/---------------------------------------------------------------------*/
public struct Parser<Token, Result> {
public init(_ p: Slice<Token> -> SequenceOf<(Result, Slice<Token>)>) {
self.p = p
}
public let p: Slice<Token> -> SequenceOf<(Result, Slice<Token>)>
}
/*---------------------------------------------------------------------/
// Simple example: Just parse single character "a"
/---------------------------------------------------------------------*/
func parseA() -> Parser<Character, Character> {
let a: Character = "a"
return Parser { x in
if let (head, tail) = x.decompose {
if head == a {
return one((a, tail))
}
}
return none()
}
}
// Let's automate Parser testing
public func testParser<A>(parser: Parser<Character, A>, input: String) -> String {
var result: [String] = []
for (x, s) in parser.p(input.slice) {
result += ["Success, found \(x), remainder: \(Array(s))"]
}
return result.isEmpty ? "Parsing failed." : join("\n", result)
}
/*---------------------------------------------------------------------/
// Make generic over any kind of token
/---------------------------------------------------------------------*/
public func satisfy<Token>(condition: Token -> Bool) -> Parser<Token, Token> {
return Parser { x in
if let (head, tail) = x.decompose {
if condition(head) {
return one((head, tail))
}
}
return none()
}
}
// But we can make it shorter
public func token<Token: Equatable>(t: Token) -> Parser<Token, Token> {
return satisfy { $0 == t }
}
/*---------------------------------------------------------------------/
// Allow adding sequences
/---------------------------------------------------------------------*/
struct JoinedGenerator<A>: GeneratorType {
typealias Element = A
var generator: GeneratorOf<GeneratorOf<A>>
var current: GeneratorOf<A>?
init(_ g: GeneratorOf<GeneratorOf<A>>) {
generator = g
current = generator.next()
}
mutating func next() -> A? {
if var c = current {
if let x = c.next() {
return x
} else {
current = generator.next()
return next()
}
}
return nil
}
}
func map<A, B>(var g: GeneratorOf<A>, f: A -> B) -> GeneratorOf<B> {
return GeneratorOf { map(g.next(), f) }
}
func join<A>(s: SequenceOf<SequenceOf<A>>) -> SequenceOf<A> {
return SequenceOf {
JoinedGenerator(map(s.generate()) {
$0.generate()
})
}
}
func +<A>(l: SequenceOf<A>, r: SequenceOf<A>) -> SequenceOf<A> {
return join(SequenceOf([l, r]))
}
/*---------------------------------------------------------------------/
// Choice operator - Combining multiple parsers
/---------------------------------------------------------------------*/
infix operator <|> { associativity right precedence 130 }
public func <|> <Token, A>(l: Parser<Token, A>,
r: Parser<Token, A>) -> Parser<Token, A> {
return Parser { input in
return l.p(input) + r.p(input)
}
}
/*---------------------------------------------------------------------/
// Sequence the Parsers: The hard way
/---------------------------------------------------------------------*/
func map<A, B>(var s: SequenceOf<A>, f: A -> B) -> SequenceOf<B> {
return SequenceOf { map(s.generate(), f) }
}
func flatMap<A, B>(ls: SequenceOf<A>, f: A -> SequenceOf<B>)
-> SequenceOf<B> {
return join(map(ls, f))
}
// This is our first attempt. It's a little confusing, due to the nesting.
func sequence<Token, A, B>(l: Parser<Token, A>, r: Parser<Token, B>)
-> Parser<Token, (A, B)> {
return Parser { input in
let leftResults = l.p(input)
return flatMap(leftResults) { a, leftRest in
let rightResults = r.p(leftRest)
return map(rightResults, { b, rightRest in
((a, b), rightRest)
})
}
}
}
/*---------------------------------------------------------------------/
// Sequence the Parsers: The refined way
/---------------------------------------------------------------------*/
// The Combinator
func combinator<Token, A, B>(l: Parser<Token, A -> B>,
r: Parser<Token, A>)
-> Parser<Token, B> {
return Parser { input in
let leftResults = l.p(input)
return flatMap(leftResults) { f, leftRemainder in
let rightResults = r.p(leftRemainder)
return map(rightResults) { x, rightRemainder in
(f(x), rightRemainder)
}
}
}
}
/*---------------------------------------------------------------------/
// Pure - Returns a value in a default context
// pure :: a -> f a
/---------------------------------------------------------------------*/
public func pure<Token, A>(value: A) -> Parser<Token, A> {
return Parser { one((value, $0)) }
}
/*---------------------------------------------------------------------/
// Fail - Returns an unsuccessful parser
/---------------------------------------------------------------------*/
public func fail<Token, Result>() -> Parser<Token, Result> {
return Parser { _ in none() }
}
/*---------------------------------------------------------------------/
// <*>
//
// “for Maybe, <*> extracts the function from the left value if it’s
// a Just and maps it over the right value. If any of the parameters
// is Nothing, Nothing is the result.”
// - Excerpt From: Miran Lipovaca. “Learn You a Haskell for Great Good!.” iBooks.
/---------------------------------------------------------------------*/
infix operator <*> { associativity left precedence 150 }
public func <*><Token, A, B>(l: Parser<Token, A -> B>,
r: Parser<Token, A>)
-> Parser<Token, B> {
return combinator(l, r)
}
/*---------------------------------------------------------------------/
// Combine several existing strings
/---------------------------------------------------------------------*/
func string(characters: [Character]) -> String {
var s = ""
s.extend(characters)
return s
}
func combine(a: Character)(b: Character)(c: Character) -> String {
return string([a, b, c])
}
/*---------------------------------------------------------------------/
// Any character from a set
/---------------------------------------------------------------------*/
func member(set: NSCharacterSet, character: Character) -> Bool {
let unichar = (String(character) as NSString).characterAtIndex(0)
return set.characterIsMember(unichar)
}
public func characterFromSet(set: NSCharacterSet) -> Parser<Character, Character> {
return satisfy { return member(set, $0) }
}
let decimals = NSCharacterSet.decimalDigitCharacterSet()
let decimalDigit = characterFromSet(decimals)
/*---------------------------------------------------------------------/
// Zero or More
/---------------------------------------------------------------------*/
public func prepend<A>(l: A) -> [A] -> [A] {
return { (x: [A]) in [l] + x }
}
// So we use an autoclosure instead
public func lazy<Token, A>(@autoclosure f: () -> Parser<Token, A>) -> Parser<Token, A> {
return Parser { x in f().p(x) }
}
public func zeroOrMore<Token, A>(p: Parser<Token, A>) -> Parser<Token, [A]> {
return (pure(prepend) <*> p <*> lazy(zeroOrMore(p))) <|> pure([])
}
/*---------------------------------------------------------------------/
// One or More
/---------------------------------------------------------------------*/
public func oneOrMore<Token, A>(p: Parser<Token, A>) -> Parser<Token, [A]> {
return pure(prepend) <*> p <*> zeroOrMore(p)
}
/*---------------------------------------------------------------------/
// </> ==> pure(l) <*> r
//
// a.k.a Haskell's <$>
/---------------------------------------------------------------------*/
infix operator </> { precedence 170 }
public func </> <Token, A, B>(l: A -> B,
r: Parser<Token, A>) -> Parser<Token, B> {
return pure(l) <*> r
}
/*---------------------------------------------------------------------/
// Add two integers with "+"
//
// We'll see an easier way to "skip" the operator below (<*)
/---------------------------------------------------------------------*/
let plus: Character = "+"
func add(x: Int)(_: Character)(y: Int) -> Int {
return x + y
}
let number = { characters in string(characters).toInt()! } </> oneOrMore(decimalDigit)
/*---------------------------------------------------------------------/
// <* Throw away the right-hand result
/---------------------------------------------------------------------*/
infix operator <* { associativity left precedence 150 }
public func <* <Token, A, B>(p: Parser<Token, A>,
q: Parser<Token, B>)
-> Parser<Token, A> {
return {x in {_ in x} } </> p <*> q
}
/*---------------------------------------------------------------------/
// *> Throw away the left-hand result
/---------------------------------------------------------------------*/
infix operator *> { associativity left precedence 150 }
public func *> <Token, A, B>(p: Parser<Token, A>,
q: Parser<Token, B>) -> Parser<Token, B> {
return {_ in {y in y} } </> p <*> q
}
public func curry<A, B, C>(f: (A, B) -> C) -> A -> B -> C {
return { x in { y in f(x, y) } }
}
/*---------------------------------------------------------------------/
// </ Consumes, but doesn't use its right operand
/---------------------------------------------------------------------*/
infix operator </ { precedence 170 }
func </ <Token, A, B>(l: A, r: Parser<Token, B>) -> Parser<Token, A> {
return pure(l) <* r
}
func optionallyFollowed<A>(l: Parser<Character, A>,
r: Parser<Character, A -> A>)
-> Parser<Character, A> {
let apply: A -> (A -> A) -> A = { x in { f in f(x) } }
return apply </> l <*> (r <|> pure { $0 })
}
func flip<A, B, C>(f: (B, A) -> C) -> (A, B) -> C {
return { (x, y) in f(y, x) }
}
public typealias Calculator = Parser<Character, Int>
typealias Op = (Character, (Int, Int) -> Int)
let operatorTable: [Op] = [("*", *), ("/", /), ("+", +), ("-", -)]
func op(character: Character,
evaluate: (Int, Int) -> Int,
operand: Calculator) -> Calculator {
let withOperator = curry(flip(evaluate)) </ token(character) <*> operand
return optionallyFollowed(operand, withOperator)
}
public func eof<A>() -> Parser<A, ()> {
return Parser { stream in
if (stream.isEmpty) {
return one(((), stream))
}
return none()
}
}
| gpl-3.0 | fd9fb9463c382593ee07ffade41e641f | 27.613744 | 88 | 0.447205 | 4.31867 | false | false | false | false |
DanielTomlinson/Latch | Latch/Latch.swift | 2 | 9559 | //
// Latch.swift
// Latch
//
// Created by Danielle Lancashire on 02/09/2015.
// Copyright © 2015 Rocket Apps. All rights reserved.
//
import Foundation
import Security
/**
LatchAccessibility defines the access restrictions for the underlying
keychain items. It maps 1:1 with kSecAttrAccessible values.
*/
public enum LatchAccessibility: RawRepresentable {
/**
Data can only be accessed while the device is unlocked. This is recommended
for items that only need be accessible while the application is in the
foreground.
Data with this attribute will migrate to a new device when using encrypted
backups.
*/
case whenUnlocked
/**
Data can only be accessed once the device has been unlocked after a restart.
This is recommended for items that need to be accessible by background
applications.
Data with this attribute will migrate to a new device
when using encrypted backups.
*/
case afterFirstUnlock
/**
Data can always be accessed regardless of the lock state of the device.
This is **not recommended** for anything except system use.
Items with this attribute will migrate to a new device when using encrypted
backups.
*/
case always
/**
Data can only be accessed while the device is unlocked. This is recommended
for items that only need be accessible while the application is in the
foreground.
Items with this attribute will never migrate to a new device, so after
a backup is restored to a new device, these items will be missing.
*/
case whenUnlockedThisDeviceOnly
/**
Data can only be accessed once the device has been unlocked after a restart.
This is recommended for items that need to be accessible by background
applications.
Items with this attribute will never migrate to a new device, so after a
backup is restored to a new device these items will be missing.
*/
case afterFirstUnlockThisDeviceOnly
/**
Data can always be accessed regardless of the lock state of the device.
This option is not recommended for anything except system use.
Items with this attribute will never migrate to a new device, so after a
backup is restored to a new device, these items will be missing.
*/
case alwaysThisDeviceOnly
/**
Create a new LatchAccessibility value using a kSecAttrAccessible value.
:param: rawValue A CFString representing a kSecAttrAccessible value.
*/
public init?(rawValue: CFString) {
switch rawValue as NSString {
case kSecAttrAccessibleWhenUnlocked:
self = .whenUnlocked
case kSecAttrAccessibleAfterFirstUnlock:
self = .afterFirstUnlock
case kSecAttrAccessibleAlways:
self = .always
case kSecAttrAccessibleWhenUnlockedThisDeviceOnly:
self = .whenUnlockedThisDeviceOnly
case kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly:
self = .afterFirstUnlockThisDeviceOnly
case kSecAttrAccessibleAlwaysThisDeviceOnly:
self = .alwaysThisDeviceOnly
default:
return nil
}
}
/**
Get the rawValue of the current enum type. Will be a kSecAttrAccessible value.
*/
public var rawValue: CFString {
switch self {
case .whenUnlocked:
return kSecAttrAccessibleWhenUnlocked
case .afterFirstUnlock:
return kSecAttrAccessibleAfterFirstUnlock
case .always:
return kSecAttrAccessibleAlways
case .whenUnlockedThisDeviceOnly:
return kSecAttrAccessibleWhenUnlockedThisDeviceOnly
case .afterFirstUnlockThisDeviceOnly:
return kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
case .alwaysThisDeviceOnly:
return kSecAttrAccessibleAlwaysThisDeviceOnly
}
}
}
private struct LatchState {
var service: String
var accessGroup: String?
var accessibility: LatchAccessibility
}
/**
Latch is a simple abstraction around the iOS and OS X keychain API.
Multiple Latch instances can use the same service, accessGroup, and
accessibility attributes.
*/
public struct Latch {
fileprivate var state: LatchState
/**
Create a new instance of Latch with a service, accessGroup, and accessibility.
:param: service The keychain access service to use for records.
:param: accessGroup The keychain access group to use - ignored on the iOS simulator.
:param: accessibility The accessibility class to use for records.
:returns: An instance of Latch.
*/
public init(service: String, accessGroup: String? = nil, accessibility: LatchAccessibility = .afterFirstUnlockThisDeviceOnly) {
state = LatchState(service: service, accessGroup: accessGroup, accessibility: accessibility)
}
// MARK - Getters
/**
Retreives the data for a given key, or returns nil.
*/
public func data(forKey key: String) -> Data? {
var query = baseQuery(forKey: key)
query[kSecMatchLimit] = kSecMatchLimitOne
query[kSecReturnData] = true as AnyObject?
var dataRef: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &dataRef)
if status != errSecSuccess && status != errSecItemNotFound {
print("Latch failed to retrieve data for key '\(key)', error: \(status)")
}
return dataRef as? Data
}
/**
Retreives the string value for a given key. It will return nil if the data
is not a UTF8 encoded string.
*/
public func string(forKey key: String) -> String? {
guard let data = data(forKey: key) else { return nil }
return NSString(data: data, encoding: String.Encoding.utf8.rawValue) as? String
}
// MARK - Setters
/**
Set a string value for a given key.
*/
@discardableResult public func set(_ object: String, forKey key: String) -> Bool {
if let data = object.data(using: String.Encoding.utf8) {
return set(data, forKey: key)
}
return false
}
/**
Set an NSCoding compliant object for a given key.
*/
@discardableResult public func set(_ object: NSCoding, forKey key: String) -> Bool {
let data = NSKeyedArchiver.archivedData(withRootObject: object)
return set(data, forKey: key)
}
/**
Set an NSData blob for a given key.
*/
@discardableResult public func set(_ object: Data, forKey key: String) -> Bool {
var query = baseQuery(forKey: key)
var update = [NSString : AnyObject]()
update[kSecValueData] = object as AnyObject?
update[kSecAttrAccessible] = state.accessibility.rawValue
var status = errSecSuccess
if data(forKey: key) != nil { // Data already exists, we're updating not writing.
status = SecItemUpdate(query as CFDictionary, update as CFDictionary)
}
else { // No existing data, write a new item.
for (key, value) in update {
query[key] = value
}
status = SecItemAdd(query as CFDictionary, nil)
}
if status != errSecSuccess {
print("Latch failed to set data for key '\(key)', error: \(status)")
return false
}
return true
}
/**
Remove an object from the keychain for a given key.
*/
@discardableResult public func removeObject(forKey key: String) -> Bool {
let query = baseQuery(forKey: key)
if data(forKey: key) != nil {
let status = SecItemDelete(query as CFDictionary)
if status != errSecSuccess {
print("Latch failed to remove data for key '\(key)', error: \(status)")
return false
}
return true
}
return false
}
#if os(iOS) || os(watchOS)
/**
Remove all objects from the keychain for the current app. Only available on
iOS and watchOS.
*/
@discardableResult public func resetKeychain() -> Bool {
let query:[String: AnyObject] = [kSecClass as String : kSecClassGenericPassword]
let status = SecItemDelete(query as CFDictionary)
print("status: \(status)")
if status != errSecSuccess {
print("Latch failed to reset keychain, error: \(status)")
return false
}
return true
}
#endif
// MARK - Private
fileprivate func baseQuery(forKey key: String) -> [NSString : AnyObject] {
var query = [NSString : AnyObject]()
if !state.service.isEmpty {
query[kSecAttrService] = state.service as AnyObject?
}
query[kSecClass] = kSecClassGenericPassword
query[kSecAttrAccount] = key as AnyObject?
query[kSecAttrGeneric] = key as AnyObject?
#if TARGET_OS_IOS && !TARGET_OS_SIMULATOR
// Ignore the access group if running on the iPhone simulator.
//
// Apps that are built for the simulator aren't signed, so there's no keychain access group
// for the simulator to check. This means that all apps can see all keychain items when run
// on the simulator.
//
// If a SecItem contains an access group attribute, SecItemAdd and SecItemUpdate on the
// simulator will return -25243 (errSecNoAccessForItem).
if !state.accessGroup?.isEmpty {
query[kSecAttrAccessGroup] = state.accessGroup
}
#endif
return query
}
}
| mit | de13e0d00f09dd50dded419b4c3a3996 | 31.62116 | 131 | 0.655263 | 5.254535 | false | false | false | false |
russbishop/swift | test/Sema/diag_invalid_inout_captures.swift | 1 | 1134 | // RUN: %target-parse-verify-swift
func no_escape(_ you_say_price_of_my_love_is: @noescape () -> ()) {}
func do_escape(_ not_a_price_you_are_willing_to_pay: () -> ()) {}
struct you_cry_in_your_tea {
mutating func which_you_hurl_in_the_sea_when_you_see_me_go_by() {
no_escape { _ = self } // OK
do_escape { _ = self } // expected-error {{closure cannot implicitly capture a mutating self parameter}}
}
}
func why_so_sad(line: inout String) {
no_escape { line = "Remember we made an arrangement when you went away" } // OK
do_escape { line = "now you're making me mad" } // expected-error {{closure cannot implicitly capture an inout parameter unless @noescape}}
}
func remember(line: inout String) -> () -> Void {
func despite_our_estrangement() {
line = "I'm your man"
}
no_escape(despite_our_estrangement)
do_escape(despite_our_estrangement) // expected-error {{nested function with an implicitly captured inout parameter can only be used as a @noescape argument}}
return despite_our_estrangement // expected-error {{nested function cannot capture inout parameter and escape}}
}
| apache-2.0 | eaea77c434f1c27921f0c0252490afa6 | 41 | 162 | 0.679012 | 3.489231 | false | false | false | false |
mownier/photostream | Photostream/UI/Post Discovery/PostDiscoveryViewController.swift | 1 | 6954 | //
// PostDiscoveryViewController.swift
// Photostream
//
// Created by Mounir Ybanez on 20/12/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import UIKit
enum PostDiscoverySceneType {
case grid
case list
}
@objc protocol PostDiscoveryViewControllerAction: class {
func triggerRefresh()
func didTapBack()
}
class PostDiscoveryViewController: UICollectionViewController, PostDiscoveryViewControllerAction {
weak var scrollEventListener: ScrollEventListener?
var presenter: PostDiscoveryModuleInterface!
var isBackBarItemVisible: Bool = false
lazy var gridLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
lazy var listLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
lazy var prototype: PostListCollectionCell! = PostListCollectionCell()
lazy var emptyView: GhostView! = {
let view = GhostView()
view.titleLabel.text = "No posts"
return view
}()
lazy var loadingView: UIActivityIndicatorView! = {
let view = UIActivityIndicatorView(activityIndicatorStyle: .gray)
view.hidesWhenStopped = true
return view
}()
lazy var refreshView: UIRefreshControl! = {
let view = UIRefreshControl()
view.addTarget(
self,
action: #selector(self.triggerRefresh),
for: .valueChanged)
return view
}()
lazy var scrollHandler: ScrollHandler = {
var handler = ScrollHandler()
handler.scrollView = self.collectionView
return handler
}()
var sceneType: PostDiscoverySceneType = .list {
didSet {
guard sceneType != oldValue else {
return
}
reloadView()
collectionView!.collectionViewLayout.invalidateLayout()
switch sceneType {
case .grid:
collectionView!.setCollectionViewLayout(gridLayout, animated: false)
case .list:
collectionView!.setCollectionViewLayout(listLayout, animated: false)
}
}
}
var shouldShowLoadingView: Bool = false {
didSet {
guard shouldShowLoadingView != oldValue else {
return
}
if shouldShowLoadingView {
loadingView.startAnimating()
collectionView?.backgroundView = loadingView
} else {
loadingView.stopAnimating()
loadingView.removeFromSuperview()
collectionView?.backgroundView = nil
}
}
}
var shouldShowRefreshView: Bool = false {
didSet {
if refreshView.superview == nil {
collectionView?.addSubview(refreshView)
}
if shouldShowLoadingView {
refreshView.beginRefreshing()
} else {
refreshView.endRefreshing()
}
}
}
var shouldShowEmptyView: Bool = false {
didSet {
guard shouldShowEmptyView != oldValue, collectionView != nil else {
return
}
if shouldShowEmptyView {
emptyView.frame.size = collectionView!.frame.size
collectionView!.backgroundView = emptyView
} else {
collectionView!.backgroundView = nil
emptyView.removeFromSuperview()
}
}
}
convenience init(type: PostDiscoverySceneType) {
let layout = UICollectionViewFlowLayout()
self.init(collectionViewLayout: layout)
switch type {
case .grid:
self.gridLayout = layout
case .list:
self.listLayout = layout
}
self.sceneType = type
}
override func loadView() {
super.loadView()
collectionView!.alwaysBounceVertical = true
collectionView!.backgroundColor = UIColor.white
let size = collectionView!.frame.size
gridLayout.configure(with: size.width, columnCount: 3)
listLayout.configure(with: size.width, columnCount: 1)
listLayout.headerReferenceSize = CGSize(width: size.width, height: 48)
listLayout.sectionHeadersPinToVisibleBounds = false
PostGridCollectionCell.register(in: collectionView!)
PostListCollectionCell.register(in: collectionView!)
PostListCollectionHeader.register(in: collectionView!)
prototype.bounds.size.width = size.width
setupNavigationItem()
}
override func viewDidLoad() {
super.viewDidLoad()
presenter.viewDidLoad()
}
func triggerRefresh() {
presenter.refreshPosts()
}
func setupNavigationItem() {
navigationItem.title = "Discovery"
if isBackBarItemVisible {
let barItem = UIBarButtonItem(image: #imageLiteral(resourceName: "back_nav_icon"), style: .plain, target: self, action: #selector(self.didTapBack))
navigationItem.leftBarButtonItem = barItem
} else {
navigationItem.leftBarButtonItem = nil
}
}
func didTapBack() {
presenter.exit()
}
}
extension PostDiscoveryViewController: PostDiscoveryScene {
var controller: UIViewController? {
return self
}
func reloadView() {
collectionView?.reloadData()
}
func showEmptyView() {
shouldShowEmptyView = true
}
func showRefreshView() {
shouldShowRefreshView = true
}
func showInitialLoadView() {
shouldShowLoadingView = true
}
func hideEmptyView() {
shouldShowEmptyView = false
}
func hideRefreshView() {
shouldShowRefreshView = false
}
func hideInitialLoadView() {
shouldShowLoadingView = false
}
func showInitialPost(at index: Int) {
switch sceneType {
case .list:
let attributes = collectionView!.collectionViewLayout.layoutAttributesForSupplementaryView(
ofKind: UICollectionElementKindSectionHeader,
at: IndexPath(item: 0, section: index))
var offset = CGPoint.zero
offset.y = attributes!.frame.origin.y
offset.y -= collectionView!.contentInset.top
collectionView!.setContentOffset(offset, animated: false)
default:
break
}
}
func didRefresh(with error: String?) {
}
func didLoadMore(with error: String?) {
}
func didLike(with error: String?) {
}
func didUnlike(with error: String?) {
}
}
| mit | 710fdbf728fb82eab96efed10d80d657 | 26.374016 | 159 | 0.582051 | 6.169476 | false | false | false | false |
chrishannah/CHEssentials | CHEssentials/Preferences.swift | 1 | 5315 | //
// Preferences.swift
// CHEssentials
//
// Created by Christopher Hannah on 14/07/2017.
// Copyright © 2017 Chris Hannah. All rights reserved.
//
import Foundation
/// A basic class that simplifies the management of the standard UserDefaults.
public class Preferences {
/// Optional String value which will be applied to any Key used to Set, Get, or Remove an object.
///
/// A prefix "ABC" with the key "HelloWorld", will result in "ABC_HelloWorld".
/// Without a nil value for the prefix, it will result in just "HelloWorld".
var prefix: String? = nil
/// Optional String value which will be applied to any Key used to Set, Get, or Remove an object.
///
/// A suffix "ABC" with the key "HelloWorld", will result in "HelloWorld_ABC".
/// Without a nil value for the suffix, it will result in just "HelloWorld".
var suffix: String? = nil
/// The static instance of the Preferences class.
static let shared = Preferences()
/// When initialising, the standard UserDefaults are synchronised.
init() {
UserDefaults.standard.synchronize()
}
// MARK: Getting
/// Retrieves an object from the standard UserDefaults, which can of course be nil.
///
/// - Parameter forKey: The key for the object you wish to return
/// - Returns: Optional Any value, if it doesn't exists, nil is returned
///
func getObject(forKey key: String) -> Any? {
UserDefaults.standard.synchronize()
let realKey = self.formatKey(key)
return UserDefaults.standard.object(forKey: realKey)
}
/// Retrieves a Bool object from the standard UserDefaults, which can of course be nil.
///
/// - Parameter forKey: The key for the object you wish to return
/// - Returns: Optional Bool value, if it doesn't exists, nil is returned
///
func getBool(forKey key: String) -> Bool? {
UserDefaults.standard.synchronize()
let realKey = self.formatKey(key)
return UserDefaults.standard.object(forKey: realKey) as? Bool
}
/// Retrieves an Int object from the standard UserDefaults, which can of course be nil.
///
/// - Parameter forKey: The key for the object you wish to return
/// - Returns: Optional Int value, if it doesn't exists, nil is returned
///
func getInt(forKey key: String) -> Int? {
UserDefaults.standard.synchronize()
let realKey = self.formatKey(key)
return UserDefaults.standard.object(forKey: realKey) as? Int
}
/// Retrieves a String object from the standard UserDefaults, which can of course be nil.
///
/// - Parameter forKey: The key for the object you wish to return
/// - Returns: Optional String value, if it doesn't exists, nil is returned
///
func getString(forKey key: String) -> String? {
UserDefaults.standard.synchronize()
let realKey = self.formatKey(key)
return UserDefaults.standard.object(forKey: realKey) as? String
}
// MARK: Setting
/// Sets an object with a given key value to the standard UserDefaults.
///
/// - Parameter forKey: The key for the object you wish to set
/// - Parameter value: The value that you wish to set
///
func setValue(forKey key: String, value: Any) {
let realKey = self.formatKey(key)
UserDefaults.standard.set(value, forKey: realKey)
UserDefaults.standard.synchronize()
}
// MARK: Removing
/// Removes an object with a given key.
///
/// - Parameter forKey: The key for the object you wish to remove
///
func remove(forKey key: String) {
let realKey = self.formatKey(key)
UserDefaults.standard.synchronize()
UserDefaults.standard.removeObject(forKey: realKey)
UserDefaults.standard.synchronize()
}
// MARK: Misc
/// Checks whether there is an object stored in the standard UserDefaults
///
/// - Parameter forKey: The key for the object you wish to remove
/// - Returns: Bool value whether it exists or not
///
func objectExists(forKey key: String) -> Bool {
UserDefaults.standard.synchronize()
let realKey = self.formatKey(key)
return UserDefaults.standard.object(forKey: realKey) != nil
}
/// Just a simpler way to syncrhonize the standard UserDefaults
func synchronize() {
UserDefaults.standard.synchronize()
}
// MARK: Prefix and Suffix
/// If there is a prefix and/or a suffix, apply it to the given string and output the result
///
/// - Parameter key: The key that is to be formatted
/// - Returns: The key formatted with any set prefix and/or suffix
///
func formatKey(_ key: String) -> String {
let withPrefix = self.addPrefix(toKey: key)
let withPrefixAndSuffix = self.addSuffix(toKey: withPrefix)
return withPrefixAndSuffix
}
private func addPrefix(toKey key: String) -> String {
if let p = prefix {
return "\(p)_\(key)"
}
return "\(key)"
}
private func addSuffix(toKey key: String) -> String {
if let s = suffix {
return "\(key)_\(s)"
}
return "\(key)"
}
}
| mit | d8c5cfdda1ed27e4d40c7912f9bc461d | 34.192053 | 101 | 0.633798 | 4.588946 | false | false | false | false |
crypton-watanabe/morurun-ios | morurun/views/PostingView/PostingViewController_DKImagePicker.swift | 1 | 4485 | //
// PostingViewController_DKImagePicker.swift
// morurun
//
// Created by watanabe on 2016/11/07.
// Copyright © 2016年 Crypton Future Media, INC. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
import DKImagePickerController
import AVFoundation
import MobileCoreServices
extension PostingViewController {
private var pickerController: DKImagePickerController {
get {
let pickerController = DKImagePickerController()
pickerController.deselectAllAssets()
pickerController.singleSelect = true
let delegate = CustomUIDelegate()
delegate.image.asObservable()
.bindTo(self.postingViewModel.image)
.addDisposableTo(self.disposeBag)
delegate.movieUrl.asObservable()
.bindTo(self.postingViewModel.movieUrl)
.addDisposableTo(self.disposeBag)
pickerController.didSelectAssets = { (assets: [DKAsset]) in
guard let asset = assets.first else { return }
if !asset.isVideo {
asset.fetchOriginalImage(true) { image, info in
delegate.image.value = image
}
}
else {
asset.fetchAVAsset(true, options: nil) { avasset, info in
let url = (avasset as? AVURLAsset)?.url
delegate.movieUrl.value = url
}
}
}
pickerController.UIDelegate = delegate
return pickerController
}
}
func configureDKImagePicker() {
pickerController.singleSelect = true
let delegate = CustomUIDelegate()
delegate.image.asObservable()
.bindTo(self.postingViewModel.image)
.addDisposableTo(self.disposeBag)
delegate.movieUrl.asObservable()
.bindTo(self.postingViewModel.movieUrl)
.addDisposableTo(self.disposeBag)
pickerController.didSelectAssets = { (assets: [DKAsset]) in
guard let asset = assets.first else { return }
if !asset.isVideo {
asset.fetchOriginalImage(true) { image, info in
delegate.image.value = image
}
}
else {
asset.fetchAVAsset(true, options: nil) { avasset, info in
let url = (avasset as? AVURLAsset)?.url
delegate.movieUrl.value = url
}
}
}
pickerController.UIDelegate = delegate
self.pictureSelectButton
.rx
.tap
.bindNext {[unowned self] _ in self.present(self.pickerController, animated: true, completion: nil) }
.addDisposableTo(self.disposeBag)
}
}
class CustomUIDelegate: DKImagePickerControllerDefaultUIDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let image = Variable<UIImage?>(nil)
let movieUrl = Variable<URL?>(nil)
override func imagePickerControllerCreateCamera(_ imagePickerController: DKImagePickerController,
didCancel: @escaping (() -> Void),
didFinishCapturingImage: @escaping ((_ image: UIImage) -> Void),
didFinishCapturingVideo: @escaping ((_ videoURL: URL) -> Void)) -> UIViewController {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .camera
picker.mediaTypes = [kUTTypeImage as String, kUTTypeMovie as String]
return picker
}
// MARK: - UIImagePickerControllerDelegate methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! String
if mediaType == kUTTypeImage as String {
let image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.image.value = image
} else if mediaType == kUTTypeMovie as String {
let movieUrl = info[UIImagePickerControllerMediaURL] as? URL
self.movieUrl.value = movieUrl
}
self.imagePickerController.presentingViewController?.dismiss(animated: true, completion: nil)
}
}
| mit | b875632bbee942e7055cad262072e78b | 38.663717 | 137 | 0.590138 | 5.960106 | false | false | false | false |
CoderST/DYZB | DYZB/DYZB/Class/Profile/ViewModel/WatchHistoryVM.swift | 1 | 2820 | //
// WatchHistoryVM.swift
// DYZB
//
// Created by xiudou on 2017/6/22.
// Copyright © 2017年 xiudo. All rights reserved.
//
import UIKit
class WatchHistoryVM: NSObject {
// http://capi.douyucdn.cn/api/v1/history?aid=ios&client_sys=ios&time=1498807620&auth=fe73812c89c1a6fe5671cfc31a529331
lazy var watchHistoryModelFrameArray : [WatchHistoryModelFrame] = [WatchHistoryModelFrame]()
func loadWatchHistoryDatas(_ finishCallBack:@escaping ()->(), _ messageCallBack :@escaping (_ message : String)->(), _ failCallBack :@escaping ()->()){
// 2124270%2C1882763%2C2127419%2C573449%2C134000%2C796666
let nowDate = Date.getNowDate()
let urlString = "http://capi.douyucdn.cn/api/v1/history?aid=ios&client_sys=ios&time=\(nowDate)&auth=fe73812c89c1a6fe5671cfc31a529331"
// let ids = [2124270,1882763,2127419,573449,134000,796666]
let params = ["token" : TOKEN]
NetworkTools.requestData(.post, URLString: urlString, parameters: params) { (result) in
guard let resultDict = result as? [String : Any] else {
// messageCallBack(result["data"] as! String)
return }
print("resultttt = \(resultDict)")
guard let error = resultDict["error"] as? Int else{
return }
if error != 0 {
print("数据有错误!!",error,resultDict)
return
}
guard let dictArray = resultDict["data"] as? [[String : Any]] else {
return }
for dict in dictArray{
let watchHistoryModel = WatchHistoryModel(dict: dict)
let watchHistoryModelFrame = WatchHistoryModelFrame(watchHistoryModel)
self.watchHistoryModelFrameArray.append(watchHistoryModelFrame)
}
finishCallBack()
}
}
}
extension WatchHistoryVM{
// http://apiv2.douyucdn.cn/Livenc/User/clearViewHistory?token=94153348_11_cd79b4bb454aed7b_2_22753003&client_sys=ios
func clearHistory(_ finishCallBack : @escaping ()->()){
let urlString = "http://apiv2.douyucdn.cn/Livenc/User/clearViewHistory?token=\(TOKEN)&client_sys=ios"
NetworkTools.requestData(.get, URLString: urlString) { (result) in
guard let resultDict = result as? [String : Any] else {
return }
print(result,resultDict)
guard let error = resultDict["error"] as? Int else{
return }
if error != 0 {
print("数据有错误!!",error,resultDict)
return
}
guard let _ = resultDict["data"] as? String else { return }
self.watchHistoryModelFrameArray.removeAll()
finishCallBack()
}
}
}
| mit | d43fb02cf3858bb161a2f78f828405b5 | 39.536232 | 155 | 0.600644 | 4.187126 | false | false | false | false |
jeroen1985/iOS-course | ToDoList/ToDoList/FirstViewController.swift | 1 | 2111 | //
// FirstViewController.swift
// ToDoList
//
// Created by Jeroen Stevens on 2015-05-04.
// Copyright (c) 2015 fishsticks. All rights reserved.
//
import UIKit
var toDoList = [String]()
class FirstViewController: UIViewController, UITableViewDelegate {
@IBOutlet var toDoListTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
if NSUserDefaults.standardUserDefaults().objectForKey("toDoList") != nil {
toDoList = NSUserDefaults.standardUserDefaults().objectForKey("toDoList") as [String]
}
// 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.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return toDoList.count
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){
if editingStyle == UITableViewCellEditingStyle.Delete {
toDoList.removeAtIndex(indexPath.row)
NSUserDefaults.standardUserDefaults().setObject(toDoList, forKey: "toDoList")
toDoListTable.reloadData()
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
cell.textLabel?.text = toDoList[indexPath.row]
return cell
}
}
| mit | ae9dc03ff83d9e4f095c49533005c6e2 | 29.594203 | 188 | 0.664614 | 5.880223 | false | false | false | false |
denizztret/ObjectiveHexagon | ObjectiveHexagonDemo/ObjectiveHexagonDemo/CollectionViewLayout.swift | 1 | 2849 | //
// CollectionViewLayout.swift
// ObjectiveHexagonDemo
//
// Created by Denis Tretyakov on 17.03.15.
// Copyright (c) 2015 pythongem. All rights reserved.
//
import UIKit
import ObjectiveHexagonKit
class CollectionViewLayout: UICollectionViewLayout {
var grid: HKHexagonGrid { get { return (self.collectionView!.dataSource! as ViewController).itemsGrid } }
var items: [HKHexagon] { get { return (self.collectionView!.dataSource! as ViewController).items } }
var attributesByHash = [String : UICollectionViewLayoutAttributes]()
var needUpdate = true
override func prepareLayout() {
super.prepareLayout()
if needUpdate {
needUpdate = false
self.grid.position = CGPointZero
//MARK: Debug Draw Grid Frame
if DEBUG_DRAW {
self.collectionView!.DebugDrawRect(self.grid.frame, name: "frame", lineWidth: 1, strokeColor: UIColor.blueColor())
}
attributesByHash.removeAll(keepCapacity: false)
for (index, hex) in enumerate(items) {
let indexPath = NSIndexPath(forItem: index, inSection: 0)
let attributes = self.layoutAttributesForItemAtIndexPath(indexPath)
attributesByHash[hex.hashID] = attributes
}
}
}
override func collectionViewContentSize() -> CGSize {
return grid.contentSize
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
var visibleElements = [UICollectionViewLayoutAttributes]()
for (hashID, attributes) in attributesByHash {
if CGRectIntersectsRect(attributes.frame, rect) {
if let hex = grid.shapeByHashID(hashID) {
}
visibleElements.append(attributes)
}
}
return visibleElements
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
let hex = items[indexPath.item]
attributes.frame = hex.frame
attributes.center = hex.center
//MARK: Debug Draw Grid Cells
if DEBUG_DRAW {
self.collectionView!.DebugDrawPoly(hex.unwrappedVertices(), name: "Poly-\(hex.hashID)", lineWidth: 1, strokeColor: UIColor.brownColor())
}
return attributes
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
override func finalizeCollectionViewUpdates() {
needUpdate = true
self.collectionView!.setNeedsLayout()
}
}
| mit | cd827bfb5d49fc12b902bc445874f386 | 32.517647 | 148 | 0.618463 | 5.709419 | false | false | false | false |
benlangmuir/swift | validation-test/compiler_crashers_2_fixed/Inputs/sr11153_2_other.swift | 13 | 579 | protocol Snapshotting {
associatedtype NativeType: NativeInserting where NativeType.SnapshotType == Self
associatedtype ChangeType: SnapshotChange where ChangeType.SnapshotType == Self
}
protocol NativeInserting {
associatedtype SnapshotType : Snapshotting where SnapshotType.NativeType == Self
}
protocol SnapshotProperties : OptionSet where RawValue == Int {
static var all: Self { get }
}
protocol SnapshotChange {
associatedtype SnapshotType : Snapshotting where SnapshotType.ChangeType == Self
associatedtype PropertiesType : SnapshotProperties
}
| apache-2.0 | 069c3783cdaebc3216219713da2a3a67 | 33.058824 | 84 | 0.791019 | 5.79 | false | false | false | false |
jasonsturges/swift-prototypes | CollectionViewUsingClass/CollectionViewUsingClass/CollectionViewCell.swift | 2 | 882 | //
// CollectionViewCell.swift
// CollectionViewUsingClass
//
// Created by Jason Sturges on 10/29/15.
// Copyright © 2015 Jason Sturges. All rights reserved.
//
import UIKit
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var label: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
let label = UILabel(frame: CGRect.zero)
label.translatesAutoresizingMaskIntoConstraints = false;
contentView.addSubview(label)
self.label = label
label.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
label.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
self.backgroundColor = UIColor.lightGray
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 70a931e94a5599b919ead0047b2558d4 | 27.419355 | 84 | 0.677639 | 4.788043 | false | false | false | false |
square/Valet | Sources/Valet/MigratableKeyValuePair.swift | 1 | 3809 | // Created by Dan Federman on 5/20/20.
// Copyright © 2020 Square, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// A struct that represented a key:value pair that can be migrated.
public struct MigratableKeyValuePair<Key: Hashable>: Hashable {
// MARK: Initialization
/// Creates a migratable key:value pair with the provided inputs.
/// - Parameters:
/// - key: The key in the key:value pair.
/// - value: The value in the key:value pair.
public init(key: Key, value: Data) {
self.key = key
self.value = value
}
/// Creates a migratable key:value pair with the provided inputs.
/// - Parameters:
/// - key: The key in the key:value pair.
/// - value: The desired value in the key:value pair, represented as a String.
public init(key: Key, value: String) {
self.key = key
self.value = Data(value.utf8)
}
// MARK: Public
/// The key in the key:value pair.
public let key: Key
/// The value in the key:value pair.
public let value: Data
}
// MARK: - Objective-C Compatibility
@objc(VALMigratableKeyValuePairInput)
public final class ObjectiveCCompatibilityMigratableKeyValuePairInput: NSObject {
// MARK: Initialization
internal init(key: Any, value: Data) {
self.key = key
self.value = value
}
// MARK: Public
/// The key in the key:value pair.
@objc
public let key: Any
/// The value in the key:value pair.
@objc
public let value: Data
}
@objc(VALMigratableKeyValuePairOutput)
public class ObjectiveCCompatibilityMigratableKeyValuePairOutput: NSObject {
// MARK: Initialization
/// Creates a migratable key:value pair with the provided inputs.
/// - Parameters:
/// - key: The key in the key:value pair.
/// - value: The value in the key:value pair.
@objc
public init(key: String, value: Data) {
self.key = key
self.value = value
preventMigration = false
}
/// Creates a migratable key:value pair with the provided inputs.
/// - Parameters:
/// - key: The key in the key:value pair.
/// - stringValue: The desired value in the key:value pair, represented as a String.
@objc
public init(key: String, stringValue: String) {
self.key = key
self.value = Data(stringValue.utf8)
preventMigration = false
}
// MARK: Public Static Methods
/// A sentinal `ObjectiveCCompatibilityMigratableKeyValuePairOutput` that conveys that the migration should be prevented.
@available(swift, obsoleted: 1.0)
@objc
public static func preventMigration() -> ObjectiveCCompatibilityMigratableKeyValuePairOutput {
ObjectiveCCompatibilityPreventMigrationOutput()
}
// MARK: Public
/// The key in the key:value pair.
@objc
public let key: String
/// The value in the key:value pair.
@objc
public let value: Data
// MARK: Internal
internal fileprivate(set) var preventMigration: Bool
}
private final class ObjectiveCCompatibilityPreventMigrationOutput: ObjectiveCCompatibilityMigratableKeyValuePairOutput {
init() {
super.init(key: "", stringValue: "")
preventMigration = true
}
}
| apache-2.0 | 470b7d831acd1670883629321f3fbc7e | 28.261538 | 125 | 0.666667 | 4.293454 | false | false | false | false |
thomasvl/swift-protobuf | Sources/protoc-gen-swift/FileGenerator.swift | 2 | 8538 | // Sources/protoc-gen-swift/FileGenerator.swift - File-level generation logic
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// This provides the logic for each file that is stored in the plugin request.
/// In particular, generateOutputFile() actually builds a Swift source file
/// to represent a single .proto input. Note that requests typically contain
/// a number of proto files that are not to be generated.
///
// -----------------------------------------------------------------------------
import Foundation
import SwiftProtobufPluginLibrary
import SwiftProtobuf
class FileGenerator {
private let fileDescriptor: FileDescriptor
private let generatorOptions: GeneratorOptions
private let namer: SwiftProtobufNamer
var outputFilename: String {
let ext = ".pb.swift"
let pathParts = splitPath(pathname: fileDescriptor.name)
switch generatorOptions.outputNaming {
case .fullPath:
return pathParts.dir + pathParts.base + ext
case .pathToUnderscores:
let dirWithUnderscores =
pathParts.dir.replacingOccurrences(of: "/", with: "_")
return dirWithUnderscores + pathParts.base + ext
case .dropPath:
return pathParts.base + ext
}
}
init(fileDescriptor: FileDescriptor,
generatorOptions: GeneratorOptions) {
self.fileDescriptor = fileDescriptor
self.generatorOptions = generatorOptions
namer = SwiftProtobufNamer(currentFile: fileDescriptor,
protoFileToModuleMappings: generatorOptions.protoToModuleMappings)
}
/// Generate, if `errorString` gets filled in, then report error instead of using
/// what written into `printer`.
func generateOutputFile(printer p: inout CodePrinter, errorString: inout String?) {
guard fileDescriptor.options.swiftPrefix.isEmpty ||
isValidSwiftIdentifier(fileDescriptor.options.swiftPrefix,
allowQuoted: false) else {
errorString = "\(fileDescriptor.name) has an 'swift_prefix' that isn't a valid Swift identifier (\(fileDescriptor.options.swiftPrefix))."
return
}
p.print("""
// DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: \(fileDescriptor.name)
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
""")
// Attempt to bring over the comments at the top of the .proto file as
// they likely contain copyrights/preamble/etc.
//
// The C++ FileDescriptor::GetSourceLocation(), says the location for
// the file is an empty path. That never seems to have comments on it.
// https://github.com/protocolbuffers/protobuf/issues/2249 opened to
// figure out the right way to do this since the syntax entry is
// optional.
var comments = String()
let syntaxPath = IndexPath(index: Google_Protobuf_FileDescriptorProto.FieldNumbers.syntax)
if let syntaxLocation = fileDescriptor.sourceCodeInfoLocation(path: syntaxPath) {
comments = syntaxLocation.asSourceComment(commentPrefix: "///",
leadingDetachedPrefix: "//")
// If the was a leading or tailing comment it won't have a blank
// line, after it, so ensure there is one.
if !comments.isEmpty && !comments.hasSuffix("\n\n") {
comments.append("\n")
}
}
p.print("\(comments)import Foundation")
if !fileDescriptor.isBundledProto {
// The well known types ship with the runtime, everything else needs
// to import the runtime.
p.print("import \(namer.swiftProtobufModuleName)")
}
if let neededImports = generatorOptions.protoToModuleMappings.neededModules(forFile: fileDescriptor) {
p.print()
for i in neededImports {
p.print("import \(i)")
}
}
p.print()
generateVersionCheck(printer: &p)
let extensionSet =
ExtensionSetGenerator(fileDescriptor: fileDescriptor,
generatorOptions: generatorOptions,
namer: namer)
extensionSet.add(extensionFields: fileDescriptor.extensions)
let enums = fileDescriptor.enums.map {
return EnumGenerator(descriptor: $0, generatorOptions: generatorOptions, namer: namer)
}
let messages = fileDescriptor.messages.map {
return MessageGenerator(descriptor: $0,
generatorOptions: generatorOptions,
namer: namer,
extensionSet: extensionSet)
}
for e in enums {
e.generateMainEnum(printer: &p)
}
for m in messages {
m.generateMainStruct(printer: &p, parent: nil, errorString: &errorString)
}
var sendablePrinter = CodePrinter(p)
for m in messages {
m.generateSendable(printer: &sendablePrinter)
}
if !sendablePrinter.isEmpty {
p.print("", "#if swift(>=5.5) && canImport(_Concurrency)")
p.append(sendablePrinter)
p.print("#endif // swift(>=5.5) && canImport(_Concurrency)")
}
if !extensionSet.isEmpty {
let pathParts = splitPath(pathname: fileDescriptor.name)
let filename = pathParts.base + pathParts.suffix
p.print(
"",
"// MARK: - Extension support defined in \(filename).")
// Generate the Swift Extensions on the Messages that provide the api
// for using the protobuf extension.
extensionSet.generateMessageSwiftExtensions(printer: &p)
// Generate a registry for the file.
extensionSet.generateFileProtobufExtensionRegistry(printer: &p)
// Generate the Extension's declarations (used by the two above things).
//
// This is done after the other two as the only time developers will need
// these symbols is if they are manually building their own ExtensionMap;
// so the others are assumed more interesting.
extensionSet.generateProtobufExtensionDeclarations(printer: &p)
}
let protoPackage = fileDescriptor.package
let needsProtoPackage: Bool = !protoPackage.isEmpty && !messages.isEmpty
if needsProtoPackage || !enums.isEmpty || !messages.isEmpty {
p.print(
"",
"// MARK: - Code below here is support for the SwiftProtobuf runtime.")
if needsProtoPackage {
p.print(
"",
"fileprivate let _protobuf_package = \"\(protoPackage)\"")
}
for e in enums {
e.generateRuntimeSupport(printer: &p)
}
for m in messages {
m.generateRuntimeSupport(printer: &p, file: self, parent: nil)
}
}
}
private func generateVersionCheck(printer p: inout CodePrinter) {
let v = Version.compatibilityVersion
p.print("""
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: \(namer.swiftProtobufModulePrefix)ProtobufAPIVersionCheck {
""")
p.printIndented(
"struct _\(v): \(namer.swiftProtobufModulePrefix)ProtobufAPIVersion_\(v) {}",
"typealias Version = _\(v)")
p.print("}")
}
}
| apache-2.0 | 010cf1169740d1920b71bae4d0e2295a | 41.477612 | 147 | 0.595221 | 5.455591 | false | false | false | false |
i-schuetz/SwiftCharts | SwiftCharts/ChartCoordsSpace.swift | 1 | 23586 | //
// ChartCoordsSpace.swift
// SwiftCharts
//
// Created by ischuetz on 27/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
/**
A ChartCoordsSpace calculates the chart's inner frame and generates the axis layers based on given axis models, chart size and chart settings. In doing so it's able to calculate the frame for the inner area of the chart where points, bars, lines, etc. are drawn to represent data.
````
┌────────────────────────────────────────────────┐
│ ChartSettings.top │
│ ┌────┬────────────────────────────────┬────┐ │
│ │ │ X │ │ │
│ │ │ high │ │ │
│ ├────┼────────────────────────────────┼────┤ │
│ │ │ │ │ │
│ │ │ │ │ │
│ │ │ │ │ │
│ │ │ │ │ │
ChartSettings.leading ──┼▶ │ Y │ Chart Inner Frame │ Y │ ◀┼── ChartSettings.trailing
│ │low │ │high│ │
│ │ │ │ │ │
│ │ │ │ │ │
│ ├────┼────────────────────────────────┼────┤ │
│ │ │ X │ │ │
│ │ │ low │ │ │
│ └────┴────────────────────────────────┴────┘ │
│ ChartSettings.bottom │
└────────────────────────────────────────────────┘
│─────────────────── chartSize ──────────────────│
````
*/
open class ChartCoordsSpace {
public typealias ChartAxisLayerModel = (p1: CGPoint, p2: CGPoint, firstModelValue: Double, lastModelValue: Double, axisValuesGenerator: ChartAxisValuesGenerator, labelsGenerator: ChartAxisLabelsGenerator, axisTitleLabels: [ChartAxisLabel], settings: ChartAxisSettings, labelsConflictSolver: ChartAxisLabelsConflictSolver?, leadingPadding: ChartAxisPadding, trailingPadding: ChartAxisPadding, labelSpaceReservationMode: AxisLabelsSpaceReservationMode, clipContents: Bool)
public typealias ChartAxisLayerGenerator = (ChartAxisLayerModel) -> ChartAxisLayer
fileprivate let chartSettings: ChartSettings
fileprivate let chartSize: CGSize
open fileprivate(set) var chartInnerFrame: CGRect = CGRect.zero
fileprivate let yLowModels: [ChartAxisModel]
fileprivate let yHighModels: [ChartAxisModel]
fileprivate let xLowModels: [ChartAxisModel]
fileprivate let xHighModels: [ChartAxisModel]
fileprivate let yLowGenerator: ChartAxisLayerGenerator
fileprivate let yHighGenerator: ChartAxisLayerGenerator
fileprivate let xLowGenerator: ChartAxisLayerGenerator
fileprivate let xHighGenerator: ChartAxisLayerGenerator
open fileprivate(set) var yLowAxesLayers: [ChartAxisLayer] = []
open fileprivate(set) var yHighAxesLayers: [ChartAxisLayer] = []
open fileprivate(set) var xLowAxesLayers: [ChartAxisLayer] = []
open fileprivate(set) var xHighAxesLayers: [ChartAxisLayer] = []
/**
A convenience initializer with default axis layer generators
- parameter chartSettings: The chart layout settings
- parameter chartSize: The desired size of the chart
- parameter yLowModels: The chart axis model used to generate the Y low axis
- parameter yHighModels: The chart axis model used to generate the Y high axis
- parameter xLowModels: The chart axis model used to generate the X low axis
- parameter xHighModels: The chart axis model used to generate the X high axis
- returns: The coordinate space with generated axis layers
*/
public convenience init(chartSettings: ChartSettings, chartSize: CGSize, yLowModels: [ChartAxisModel] = [], yHighModels: [ChartAxisModel] = [], xLowModels: [ChartAxisModel] = [], xHighModels: [ChartAxisModel] = []) {
func calculatePaddingValues(_ axis: ChartAxis, model: ChartAxisLayerModel, dimensionExtractor: @escaping (CGSize) -> CGFloat) -> (CGFloat, CGFloat) {
func paddingForAxisValue(_ axisValueMaybe: Double?) -> CGFloat {
return axisValueMaybe.map{model.labelsGenerator.generate($0, axis: axis)}?.first.map{dimensionExtractor($0.textSize) / 2} ?? 0
}
func calculatePadding(_ padding: ChartAxisPadding, axisValueMaybe: Double?) -> CGFloat {
switch padding {
case .label: return paddingForAxisValue(axisValueMaybe)
case .labelPlus(let plus): return paddingForAxisValue(axisValueMaybe) + plus
case .maxLabelFixed(let length): return max(paddingForAxisValue(axisValueMaybe), length)
case .fixed(let length): return length
case .none: return 0
}
}
let axisValues: [Double] = {
switch (model.leadingPadding, model.trailingPadding) {
case (.label, _): fallthrough
case (_, .label): fallthrough
case (.labelPlus, _): fallthrough
case (_, .labelPlus): fallthrough
case (.maxLabelFixed(_), _): fallthrough
case (_, .maxLabelFixed(_)): return model.axisValuesGenerator.generate(axis)
default: return []
}
}()
return (
calculatePadding(model.leadingPadding, axisValueMaybe: axisValues.first),
calculatePadding(model.trailingPadding, axisValueMaybe: axisValues.last)
)
}
let yLowGenerator: ChartAxisLayerGenerator = {model in
let tmpAxis = ChartAxisY(first: model.firstModelValue, last: model.lastModelValue, firstScreen: model.p1.y, lastScreen: model.p2.y)
model.axisValuesGenerator.axisInitialized(tmpAxis)
let tmpAxis2 = ChartAxisY(first: model.axisValuesGenerator.first ?? model.firstModelValue, last: model.axisValuesGenerator.last ?? model.lastModelValue, firstScreen: model.p1.y, lastScreen: model.p2.y)
let (firstPadding, lastPadding) = calculatePaddingValues(tmpAxis2, model: model, dimensionExtractor: {$0.height})
let axis = ChartAxisY(first: model.axisValuesGenerator.first ?? model.firstModelValue, last: model.axisValuesGenerator.last ?? model.lastModelValue, firstScreen: model.p1.y, lastScreen: model.p2.y, paddingFirstScreen: firstPadding, paddingLastScreen: lastPadding)
return ChartAxisYLowLayerDefault(axis: axis, offset: model.p1.x, valuesGenerator: model.axisValuesGenerator, labelsGenerator: model.labelsGenerator, axisTitleLabels: model.axisTitleLabels, settings: model.settings, labelsConflictSolver: model.labelsConflictSolver, labelSpaceReservationMode: model.labelSpaceReservationMode, clipContents: model.clipContents)
}
let yHighGenerator: ChartAxisLayerGenerator = {model in
let tmpAxis = ChartAxisY(first: model.firstModelValue, last: model.lastModelValue, firstScreen: model.p1.y, lastScreen: model.p2.y)
model.axisValuesGenerator.axisInitialized(tmpAxis)
let tmpAxis2 = ChartAxisY(first: model.axisValuesGenerator.first ?? model.firstModelValue, last: model.axisValuesGenerator.last ?? model.lastModelValue, firstScreen: model.p1.y, lastScreen: model.p2.y)
let (firstPadding, lastPadding) = calculatePaddingValues(tmpAxis2, model: model, dimensionExtractor: {$0.height})
let axis = ChartAxisY(first: model.axisValuesGenerator.first ?? model.firstModelValue, last: model.axisValuesGenerator.last ?? model.lastModelValue, firstScreen: model.p1.y, lastScreen: model.p2.y, paddingFirstScreen: firstPadding, paddingLastScreen: lastPadding)
return ChartAxisYHighLayerDefault(axis: axis, offset: model.p1.x, valuesGenerator: model.axisValuesGenerator, labelsGenerator: model.labelsGenerator, axisTitleLabels: model.axisTitleLabels, settings: model.settings, labelsConflictSolver: model.labelsConflictSolver, labelSpaceReservationMode: model.labelSpaceReservationMode, clipContents: model.clipContents)
}
let xLowGenerator: ChartAxisLayerGenerator = {model in
let tmpAxis = ChartAxisX(first: model.firstModelValue, last: model.lastModelValue, firstScreen: model.p1.x, lastScreen: model.p2.x)
model.axisValuesGenerator.axisInitialized(tmpAxis)
let tmpAxis2 = ChartAxisX(first: model.axisValuesGenerator.first ?? model.firstModelValue, last: model.axisValuesGenerator.last ?? model.lastModelValue, firstScreen: model.p1.x, lastScreen: model.p2.x)
let (firstPadding, lastPadding) = calculatePaddingValues(tmpAxis2, model: model, dimensionExtractor: {$0.width})
let axis = ChartAxisX(first: model.axisValuesGenerator.first ?? model.firstModelValue, last: model.axisValuesGenerator.last ?? model.lastModelValue, firstScreen: model.p1.x, lastScreen: model.p2.x, paddingFirstScreen: firstPadding, paddingLastScreen: lastPadding)
return ChartAxisXLowLayerDefault(axis: axis, offset: model.p1.y, valuesGenerator: model.axisValuesGenerator, labelsGenerator: model.labelsGenerator, axisTitleLabels: model.axisTitleLabels, settings: model.settings, labelsConflictSolver: model.labelsConflictSolver, labelSpaceReservationMode: model.labelSpaceReservationMode, clipContents: model.clipContents)
}
let xHighGenerator: ChartAxisLayerGenerator = {model in
let tmpAxis = ChartAxisX(first: model.firstModelValue, last: model.lastModelValue, firstScreen: model.p1.x, lastScreen: model.p2.x)
model.axisValuesGenerator.axisInitialized(tmpAxis)
let tmpAxis2 = ChartAxisX(first: model.axisValuesGenerator.first ?? model.firstModelValue, last: model.axisValuesGenerator.last ?? model.lastModelValue, firstScreen: model.p1.x, lastScreen: model.p2.x)
let (firstPadding, lastPadding) = calculatePaddingValues(tmpAxis2, model: model, dimensionExtractor: {$0.width})
let axis = ChartAxisX(first: model.axisValuesGenerator.first ?? model.firstModelValue, last: model.axisValuesGenerator.last ?? model.lastModelValue, firstScreen: model.p1.x, lastScreen: model.p2.x, paddingFirstScreen: firstPadding, paddingLastScreen: lastPadding)
return ChartAxisXHighLayerDefault(axis: axis, offset: model.p1.y, valuesGenerator: model.axisValuesGenerator, labelsGenerator: model.labelsGenerator, axisTitleLabels: model.axisTitleLabels, settings: model.settings, labelsConflictSolver: model.labelsConflictSolver, labelSpaceReservationMode: model.labelSpaceReservationMode, clipContents: model.clipContents)
}
self.init(chartSettings: chartSettings, chartSize: chartSize, yLowModels: yLowModels, yHighModels: yHighModels, xLowModels: xLowModels, xHighModels: xHighModels, yLowGenerator: yLowGenerator, yHighGenerator: yHighGenerator, xLowGenerator: xLowGenerator, xHighGenerator: xHighGenerator)
}
public init(chartSettings: ChartSettings, chartSize: CGSize, yLowModels: [ChartAxisModel], yHighModels: [ChartAxisModel], xLowModels: [ChartAxisModel], xHighModels: [ChartAxisModel], yLowGenerator: @escaping ChartAxisLayerGenerator, yHighGenerator: @escaping ChartAxisLayerGenerator, xLowGenerator: @escaping ChartAxisLayerGenerator, xHighGenerator: @escaping ChartAxisLayerGenerator) {
self.chartSettings = chartSettings
self.chartSize = chartSize
self.yLowModels = yLowModels
self.yHighModels = yHighModels
self.xLowModels = xLowModels
self.xHighModels = xHighModels
self.yLowGenerator = yLowGenerator
self.yHighGenerator = yHighGenerator
self.xLowGenerator = xLowGenerator
self.xHighGenerator = xHighGenerator
chartInnerFrame = calculateChartInnerFrame()
self.yLowAxesLayers = generateYLowAxes()
self.yHighAxesLayers = generateYHighAxes()
self.xLowAxesLayers = generateXLowAxes()
self.xHighAxesLayers = generateXHighAxes()
}
fileprivate func generateYLowAxes() -> [ChartAxisLayer] {
return generateYAxisShared(axisModels: yLowModels, offset: chartSettings.leading, generator: yLowGenerator)
}
fileprivate func generateYHighAxes() -> [ChartAxisLayer] {
let chartFrame = chartInnerFrame
return generateYAxisShared(axisModels: yHighModels, offset: chartFrame.origin.x + chartFrame.width, generator: yHighGenerator)
}
fileprivate func generateXLowAxes() -> [ChartAxisLayer] {
let chartFrame = chartInnerFrame
let y = chartFrame.origin.y + chartFrame.height
return self.generateXAxesShared(axisModels: xLowModels, offset: y, generator: xLowGenerator)
}
fileprivate func generateXHighAxes() -> [ChartAxisLayer] {
return generateXAxesShared(axisModels: xHighModels, offset: chartSettings.top, generator: xHighGenerator)
}
/**
Uses a generator to make X axis layers from axis models. This method is used for both low and high X axes.
- parameter axisModels: The models used to generate the axis layers
- parameter offset: The offset in points for the generated layers
- parameter generator: The generator used to create the layers
- returns: An array of ChartAxisLayers
*/
fileprivate func generateXAxesShared(axisModels: [ChartAxisModel], offset: CGFloat, generator: ChartAxisLayerGenerator) -> [ChartAxisLayer] {
let chartFrame = chartInnerFrame
let chartSettings = self.chartSettings
let x = chartFrame.origin.x
let length = chartFrame.width
return generateAxisShared(axisModels: axisModels, offset: offset, boundingPointsCreator: {offset in
(p1: CGPoint(x: x, y: offset), p2: CGPoint(x: x + length, y: offset))
}, nextLayerOffset: {layer in
layer.frameWithoutLabels.height + chartSettings.spacingBetweenAxesX
}, generator: generator)
}
/**
Uses a generator to make Y axis layers from axis models. This method is used for both low and high Y axes.
- parameter axisModels: The models used to generate the axis layers
- parameter offset: The offset in points for the generated layers
- parameter generator: The generator used to create the layers
- returns: An array of ChartAxisLayers
*/
fileprivate func generateYAxisShared(axisModels: [ChartAxisModel], offset: CGFloat, generator: ChartAxisLayerGenerator) -> [ChartAxisLayer] {
let chartFrame = chartInnerFrame
let chartSettings = self.chartSettings
let y = chartFrame.origin.y
let length = chartFrame.height
return generateAxisShared(axisModels: axisModels, offset: offset, boundingPointsCreator: {offset in
(p1: CGPoint(x: offset, y: y + length), p2: CGPoint(x: offset, y: y))
}, nextLayerOffset: {layer in
layer.frameWithoutLabels.width + chartSettings.spacingBetweenAxesY
}, generator: generator)
}
/**
Uses a generator to make axis layers from axis models. This method is used for all axes.
- parameter axisModels: The models used to generate the axis layers
- parameter offset: The offset in points for the generated layers
- parameter boundingPointsCreator: A closure that creates a tuple containing the location of the smallest and largest values along the axis. For example, boundingPointsCreator for a Y axis might return a value like (p1: CGPoint(x, 0), p2: CGPoint(x, 100)), where x is the offset of the axis layer.
- parameter nextLayerOffset: A closure that returns the offset of the next axis layer relative to the current layer
- parameter generator: The generator used to create the layers
- returns: An array of ChartAxisLayers
*/
fileprivate func generateAxisShared(axisModels: [ChartAxisModel], offset: CGFloat, boundingPointsCreator: @escaping (_ offset: CGFloat) -> (p1: CGPoint, p2: CGPoint), nextLayerOffset: @escaping (ChartAxisLayer) -> CGFloat, generator: ChartAxisLayerGenerator) -> [ChartAxisLayer] {
let chartSettings = self.chartSettings
return axisModels.reduce((axes: Array<ChartAxisLayer>(), x: offset)) {tuple, chartAxisModel in
let layers = tuple.axes
let x: CGFloat = tuple.x
let axisSettings = ChartAxisSettings(chartSettings)
axisSettings.lineColor = chartAxisModel.lineColor
let points = boundingPointsCreator(x)
let layer = generator((p1: points.p1, p2: points.p2, firstModelValue: chartAxisModel.firstModelValue, lastModelValue: chartAxisModel.lastModelValue, axisValuesGenerator: chartAxisModel.axisValuesGenerator, labelsGenerator: chartAxisModel.labelsGenerator, axisTitleLabels: chartAxisModel.axisTitleLabels, settings: axisSettings, labelsConflictSolver: chartAxisModel.labelsConflictSolver, leadingPadding: chartAxisModel.leadingPadding, trailingPadding: chartAxisModel.trailingPadding, labelSpaceReservationMode: chartAxisModel.labelSpaceReservationMode, clipContents: chartAxisModel.clipContents))
return (
axes: layers + [layer],
x: x + nextLayerOffset(layer)
)
}.0
}
/**
Calculates the inner frame of the chart, which in short is the area where your points, bars, lines etc. are drawn. In order to calculate this frame the axes will be generated.
- returns: The inner frame as a CGRect
*/
fileprivate func calculateChartInnerFrame() -> CGRect {
let totalDim = {(axisLayers: [ChartAxisLayer], dimPicker: (ChartAxisLayer) -> CGFloat, spacingBetweenAxes: CGFloat) -> CGFloat in
return axisLayers.reduce((CGFloat(0), CGFloat(0))) {tuple, chartAxisLayer in
let totalDim = tuple.0 + tuple.1
return (totalDim + dimPicker(chartAxisLayer), spacingBetweenAxes)
}.0
}
func totalWidth(_ axisLayers: [ChartAxisLayer]) -> CGFloat {
return totalDim(axisLayers, {$0.frame.width}, chartSettings.spacingBetweenAxesY)
}
func totalHeight(_ axisLayers: [ChartAxisLayer]) -> CGFloat {
return totalDim(axisLayers, {$0.frame.height}, chartSettings.spacingBetweenAxesX)
}
let yLowWidth = totalWidth(generateYLowAxes())
let yHighWidth = totalWidth(generateYHighAxes())
let xLowHeight = totalHeight(generateXLowAxes())
let xHighHeight = totalHeight(generateXHighAxes())
let leftWidth = yLowWidth + chartSettings.leading
let topHeigth = xHighHeight + chartSettings.top
let rightWidth = yHighWidth + chartSettings.trailing
let bottomHeight = xLowHeight + chartSettings.bottom
return CGRect(
x: leftWidth,
y: topHeigth,
width: chartSize.width - leftWidth - rightWidth,
height: chartSize.height - topHeigth - bottomHeight
)
}
}
/// A ChartCoordsSpace subclass specifically for a chart with axes along the left and bottom edges
open class ChartCoordsSpaceLeftBottomSingleAxis {
public let yAxisLayer: ChartAxisLayer
public let xAxisLayer: ChartAxisLayer
public let chartInnerFrame: CGRect
public init(chartSettings: ChartSettings, chartFrame: CGRect, xModel: ChartAxisModel, yModel: ChartAxisModel) {
let coordsSpaceInitializer = ChartCoordsSpace(chartSettings: chartSettings, chartSize: chartFrame.size, yLowModels: [yModel], xLowModels: [xModel])
self.chartInnerFrame = coordsSpaceInitializer.chartInnerFrame
self.yAxisLayer = coordsSpaceInitializer.yLowAxesLayers[0]
self.xAxisLayer = coordsSpaceInitializer.xLowAxesLayers[0]
}
}
/// A ChartCoordsSpace subclass specifically for a chart with axes along the left and top edges
open class ChartCoordsSpaceLeftTopSingleAxis {
public let yAxisLayer: ChartAxisLayer
public let xAxisLayer: ChartAxisLayer
public let chartInnerFrame: CGRect
public init(chartSettings: ChartSettings, chartFrame: CGRect, xModel: ChartAxisModel, yModel: ChartAxisModel) {
let coordsSpaceInitializer = ChartCoordsSpace(chartSettings: chartSettings, chartSize: chartFrame.size, yLowModels: [yModel], xHighModels: [xModel])
self.chartInnerFrame = coordsSpaceInitializer.chartInnerFrame
self.yAxisLayer = coordsSpaceInitializer.yLowAxesLayers[0]
self.xAxisLayer = coordsSpaceInitializer.xHighAxesLayers[0]
}
}
/// A ChartCoordsSpace subclass specifically for a chart with axes along the right and bottom edges
open class ChartCoordsSpaceRightBottomSingleAxis {
public let yAxisLayer: ChartAxisLayer
public let xAxisLayer: ChartAxisLayer
public let chartInnerFrame: CGRect
public init(chartSettings: ChartSettings, chartFrame: CGRect, xModel: ChartAxisModel, yModel: ChartAxisModel) {
let coordsSpaceInitializer = ChartCoordsSpace(chartSettings: chartSettings, chartSize: chartFrame.size, yHighModels: [yModel], xLowModels: [xModel])
self.chartInnerFrame = coordsSpaceInitializer.chartInnerFrame
self.yAxisLayer = coordsSpaceInitializer.yHighAxesLayers[0]
self.xAxisLayer = coordsSpaceInitializer.xLowAxesLayers[0]
}
}
/// A ChartCoordsSpace subclass specifically for a chart with axes along the right and top edges
open class ChartCoordsSpaceRightTopSingleAxis {
public let yAxisLayer: ChartAxisLayer
public let xAxisLayer: ChartAxisLayer
public let chartInnerFrame: CGRect
public init(chartSettings: ChartSettings, chartFrame: CGRect, xModel: ChartAxisModel, yModel: ChartAxisModel) {
let coordsSpaceInitializer = ChartCoordsSpace(chartSettings: chartSettings, chartSize: chartFrame.size, yHighModels: [yModel], xHighModels: [xModel])
self.chartInnerFrame = coordsSpaceInitializer.chartInnerFrame
self.yAxisLayer = coordsSpaceInitializer.yHighAxesLayers[0]
self.xAxisLayer = coordsSpaceInitializer.xHighAxesLayers[0]
}
}
| apache-2.0 | a96858c3aa270b39425d274bde50a8fe | 61.4 | 607 | 0.674175 | 5.615385 | false | false | false | false |
CoreAnimationAsSwift/WZHQZhiBo | ZhiBo/ZhiBo/Home/View/AmuseMeunViewCell.swift | 1 | 1513 | //
// AmuseMeunViewCell.swift
// ZhiBo
//
// Created by mac on 16/11/5.
// Copyright © 2016年 mac. All rights reserved.
//
import UIKit
private let kGrameCellID = "kGrameCellID"
class AmuseMeunViewCell: UICollectionViewCell {
var groups : [AnchorGroup]?
@IBOutlet weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGrameCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let kItemW = collectionView.bounds.width / 4
let kItemH = collectionView.bounds.height / 2
layout.itemSize = CGSize(width: kItemW, height: kItemH)
}
}
extension AmuseMeunViewCell :UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return groups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier:kGrameCellID, for: indexPath) as! CollectionGameCell
// cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.purple : UIColor.yellow
cell.group = groups![indexPath.item]
// cell.clipsToBounds = true
return cell
}
}
| mit | 6d4b5d20ee53a305659d83715111aae8 | 35.829268 | 126 | 0.712583 | 4.95082 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.