repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
benlangmuir/swift | test/SILOptimizer/definite_init_extension.swift | 20 | 417 | // RUN: %target-swift-frontend -emit-sil -verify %s -o /dev/null
// RUN: %target-swift-frontend -emit-sil -verify %s -o /dev/null
struct S<T> {
let t: T // expected-note {{'self.t.1' not initialized}}
}
extension S where T == (Int, String) {
init(x: ()) {
t.0 = 1
t.1 = "hi"
}
init(y: ()) {
t.0 = 1
} // expected-error {{return from initializer without initializing all stored properties}}
}
| apache-2.0 | f63d12ca2c2bdf1a0aefecb3a6959689 | 23.529412 | 92 | 0.59952 | 2.895833 | false | false | false | false |
mozilla-mobile/firefox-ios | Tests/ClientTests/Frontend/Browser/Tab Management/TabManagerStoreTests.swift | 2 | 12765 | // 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
@testable import Client
import Shared
import Storage
import UIKit
import WebKit
import XCTest
class TabManagerStoreTests: XCTestCase {
private var profile: MockProfile!
private var fileManager: MockFileManager!
private var serialQueue: MockDispatchQueue!
override func setUp() {
super.setUp()
profile = MockProfile()
fileManager = MockFileManager()
serialQueue = MockDispatchQueue()
}
override func tearDown() {
super.tearDown()
profile = nil
fileManager = nil
serialQueue = nil
}
func testNoData() {
let manager = createManager()
let retrievedTabs = manager.testTabOnDisk()
XCTAssertEqual(retrievedTabs.count, 0, "Expected 0 tabs on disk")
XCTAssertFalse(manager.hasTabsToRestoreAtStartup)
}
// MARK: Preserve
func testPreserve_withNoTabs() {
let manager = createManager()
manager.preserveTabs([], selectedTab: nil)
let retrievedTabs = manager.testTabOnDisk()
XCTAssertEqual(retrievedTabs.count, 0, "Expected 0 tabs on disk")
XCTAssertFalse(manager.hasTabsToRestoreAtStartup)
}
func testPreserveTabs_noSelectedTab() {
let manager = createManager()
let tabs = createTabs(tabNumber: 3)
manager.preserveTabs(tabs, selectedTab: nil)
let retrievedTabs = manager.testTabOnDisk()
XCTAssertEqual(retrievedTabs.count, 3, "Expected 3 tabs on disk")
XCTAssertEqual(retrievedTabs[0].title, "Title 0 isPrivate: false")
XCTAssertEqual(retrievedTabs[1].title, "Title 1 isPrivate: false")
XCTAssertEqual(retrievedTabs[2].title, "Title 2 isPrivate: false")
XCTAssertTrue(manager.hasTabsToRestoreAtStartup)
}
func testPreserveTabs_withSelectedNormalTab() {
let manager = createManager()
let tabs = createTabs(tabNumber: 3)
manager.preserveTabs(tabs, selectedTab: tabs[0])
let retrievedTabs = manager.testTabOnDisk()
XCTAssertEqual(retrievedTabs.count, 3, "Expected 3 tabs on disk")
XCTAssertEqual(retrievedTabs[0].title, "Title 0 isPrivate: false")
XCTAssertEqual(retrievedTabs[1].title, "Title 1 isPrivate: false")
XCTAssertEqual(retrievedTabs[2].title, "Title 2 isPrivate: false")
XCTAssertTrue(manager.hasTabsToRestoreAtStartup)
}
func testPreserveTabs_withSelectedPrivateTab() {
let manager = createManager()
let tabs = createTabs(tabNumber: 3, isPrivate: true)
manager.preserveTabs(tabs, selectedTab: tabs[0])
let retrievedTabs = manager.testTabOnDisk()
XCTAssertEqual(retrievedTabs.count, 3, "Expected 3 tabs on disk")
XCTAssertEqual(retrievedTabs[0].title, "Title 0 isPrivate: true")
XCTAssertEqual(retrievedTabs[1].title, "Title 1 isPrivate: true")
XCTAssertEqual(retrievedTabs[2].title, "Title 2 isPrivate: true")
XCTAssertTrue(manager.hasTabsToRestoreAtStartup)
}
func testPreserveTabs_clearAddAgain() {
let manager = createManager()
let threeTabs = createTabs(tabNumber: 3)
manager.preserveTabs(threeTabs, selectedTab: threeTabs[0])
manager.clearArchive()
let twoTabs = createTabs(tabNumber: 2)
manager.preserveTabs(twoTabs, selectedTab: nil)
let retrievedTabs = manager.testTabOnDisk()
XCTAssertEqual(retrievedTabs.count, 2, "Expected 2 tabs on disk")
XCTAssertEqual(retrievedTabs[0].title, "Title 0 isPrivate: false")
XCTAssertEqual(retrievedTabs[1].title, "Title 1 isPrivate: false")
XCTAssertTrue(manager.hasTabsToRestoreAtStartup)
XCTAssertEqual(fileManager.remoteItemCalledCount, 4)
XCTAssertEqual(fileManager.fileExistsCalledCount, 2)
}
// MARK: Restore
func testRestoreEmptyTabs() {
let manager = createManager()
let tabToSelect = manager.restoreStartupTabs(clearPrivateTabs: false,
addTabClosure: { isPrivate in
XCTFail("Should not be called since there's no tabs to restore")
return createTab(isPrivate: isPrivate)
})
XCTAssertNil(tabToSelect, "There's no tabs to restore, so nothing is selected")
let retrievedTabs = manager.testTabOnDisk()
XCTAssertEqual(retrievedTabs.count, 0, "Expected 0 tabs on disk")
XCTAssertFalse(manager.hasTabsToRestoreAtStartup)
}
func testRestoreNormalTabs_noSelectedTab() {
let manager = createManager()
let tabs = createTabs(tabNumber: 3)
manager.preserveTabs(tabs, selectedTab: nil)
let tabToSelect = manager.restoreStartupTabs(clearPrivateTabs: false,
addTabClosure: { isPrivate in
XCTAssertFalse(isPrivate)
return createTab(isPrivate: isPrivate)
})
XCTAssertNil(tabToSelect, "No tab was selected in restore, tab manager is expected to select one")
let retrievedTabs = manager.testTabOnDisk()
XCTAssertEqual(retrievedTabs.count, 3, "Expected 3 tabs on disk")
XCTAssertTrue(manager.hasTabsToRestoreAtStartup)
}
func testRestoreNormalTabs_selectedTabIsReselected() {
let manager = createManager()
let tabs = createTabs(tabNumber: 3)
manager.preserveTabs(tabs, selectedTab: tabs[0])
let tabToSelect = manager.restoreStartupTabs(clearPrivateTabs: false,
addTabClosure: { isPrivate in
XCTAssertFalse(isPrivate)
return createTab(isPrivate: isPrivate)
})
XCTAssertNotNil(tabToSelect, "Tab was selected in restore")
XCTAssertEqual(tabToSelect?.lastTitle, tabs[0].lastTitle, "Selected tab is same that was previously selected")
let retrievedTabs = manager.testTabOnDisk()
XCTAssertEqual(retrievedTabs.count, 3, "Expected 3 tabs on disk")
XCTAssertTrue(manager.hasTabsToRestoreAtStartup)
}
func testRestorePrivateTabs_noSelectedTab() {
let manager = createManager()
let tabs = createTabs(tabNumber: 3, isPrivate: true)
manager.preserveTabs(tabs, selectedTab: nil)
let tabToSelect = manager.restoreStartupTabs(clearPrivateTabs: false,
addTabClosure: { isPrivate in
XCTAssertTrue(isPrivate)
return createTab(isPrivate: isPrivate)
})
XCTAssertNil(tabToSelect, "No tab was selected in restore, tab manager is expected to select one")
let retrievedTabs = manager.testTabOnDisk()
XCTAssertEqual(retrievedTabs.count, 3, "Expected 3 tabs on disk")
XCTAssertTrue(manager.hasTabsToRestoreAtStartup)
}
func testRestorePrivateTabs_selectedTabIsReselected() {
let manager = createManager()
let tabs = createTabs(tabNumber: 3, isPrivate: true)
manager.preserveTabs(tabs, selectedTab: tabs[0])
let tabToSelect = manager.restoreStartupTabs(clearPrivateTabs: false,
addTabClosure: { isPrivate in
XCTAssertTrue(isPrivate)
return createTab(isPrivate: isPrivate)
})
XCTAssertNotNil(tabToSelect, "Tab was selected in restore")
XCTAssertEqual(tabToSelect?.lastTitle, tabs[0].lastTitle, "Selected tab is same that was previously selected")
let retrievedTabs = manager.testTabOnDisk()
XCTAssertEqual(retrievedTabs.count, 3, "Expected 3 tabs on disk")
XCTAssertTrue(manager.hasTabsToRestoreAtStartup)
}
func testRestorePrivateTabs_clearPrivateTabs() {
let manager = createManager()
let tabs = createTabs(tabNumber: 3, isPrivate: true)
manager.preserveTabs(tabs, selectedTab: tabs[0])
let tabToSelect = manager.restoreStartupTabs(clearPrivateTabs: true,
addTabClosure: { isPrivate in
XCTFail("Shouldn't be called as there's no more tabs after clear private tabs is done")
return createTab(isPrivate: isPrivate)
})
XCTAssertNil(tabToSelect, "No tab is selected since all tabs were removed (since they were private)")
}
func testRestoreNormalAndPrivateTabs_clearPrivateTabs() {
let manager = createManager()
let normalTabs = createTabs(tabNumber: 2)
let privateTabs = createTabs(tabNumber: 3, isPrivate: true)
let allTabs = normalTabs + privateTabs
manager.preserveTabs(allTabs, selectedTab: privateTabs[0])
let tabToSelect = manager.restoreStartupTabs(clearPrivateTabs: true,
addTabClosure: { isPrivate in
XCTAssertFalse(isPrivate)
return createTab(isPrivate: isPrivate)
})
XCTAssertNil(tabToSelect, "No tab selected since the selected one was deleted, tab manager will deal with it")
}
// MARK: Migration
func testMigrationForward_savingOnlyWithDeprecatedMethod() {
let manager = createManager()
let tabs = createTabs(tabNumber: 2)
// Save tabs only with deprecated method, as if we're in v105
manager.preserveTabs(tabs, selectedTab: nil)
// Retrieve tabs as if we're in v106
let tabToSelect = manager.restoreStartupTabs(clearPrivateTabs: false,
addTabClosure: { isPrivate in
XCTAssertFalse(isPrivate)
return createTab(isPrivate: isPrivate)
})
XCTAssertNil(tabToSelect, "No tab was selected in restore, tab manager is expected to select one")
let retrievedTabs = manager.testTabOnDisk()
XCTAssertEqual(retrievedTabs.count, 2, "Expected 2 tabs on disk")
XCTAssertTrue(manager.hasTabsToRestoreAtStartup)
}
}
// MARK: - Helper methods
private extension TabManagerStoreTests {
func createManager(file: StaticString = #file,
line: UInt = #line) -> TabManagerStoreImplementation {
let manager = TabManagerStoreImplementation(prefs: profile.prefs,
imageStore: nil,
fileManager: fileManager,
serialQueue: serialQueue)
manager.clearArchive()
trackForMemoryLeaks(manager, file: file, line: line)
return manager
}
func createConfiguration(file: StaticString = #file,
line: UInt = #line) -> WKWebViewConfiguration {
let configuration = WKWebViewConfiguration()
configuration.processPool = WKProcessPool()
trackForMemoryLeaks(configuration, file: file, line: line)
return configuration
}
func createTabs(tabNumber: Int,
isPrivate: Bool = false,
file: StaticString = #file,
line: UInt = #line) -> [Tab] {
var tabs = [Tab]()
(0..<tabNumber).forEach { index in
let tab = createTab(title: "Title \(index) isPrivate: \(isPrivate)",
isPrivate: isPrivate,
file: file,
line: line)
tabs.append(tab)
}
return tabs
}
// Without session data, a Tab can't become a SavedTab and get archived
func createTab(title: String? = nil,
isPrivate: Bool = false,
file: StaticString = #file,
line: UInt = #line) -> Tab {
let configuration = createConfiguration(file: file, line: line)
let tab = Tab(profile: profile, configuration: configuration, isPrivate: isPrivate)
tab.url = URL(string: "http://yahoo.com/")!
tab.lastTitle = title
tab.sessionData = SessionData(currentPage: 0, urls: [tab.url!], lastUsedTime: Date.now())
return tab
}
}
class MockFileManager: TabFileManager {
var remoteItemCalledCount = 0
func removeItem(at URL: URL) throws {
remoteItemCalledCount += 1
try FileManager.default.removeItem(at: URL)
}
var fileExistsCalledCount = 0
func fileExists(atPath path: String) -> Bool {
fileExistsCalledCount += 1
return FileManager.default.fileExists(atPath: tabPath!)
}
var tabPath: String? {
return FileManager.default.temporaryDirectory.path
}
}
| mpl-2.0 | b30e7b36cef1ed8983adbdacb2c2dd9c | 39.015674 | 118 | 0.639875 | 5.029551 | false | true | false | false |
Farteen/ios-charts | Charts/Classes/Charts/PieRadarChartViewBase.swift | 1 | 27332 | //
// PieRadarChartViewBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
/// Base class of PieChartView and RadarChartView.
public class PieRadarChartViewBase: ChartViewBase
{
/// holds the normalized version of the current rotation angle of the chart
private var _rotationAngle = CGFloat(270.0)
/// holds the raw version of the current rotation angle of the chart
private var _rawRotationAngle = CGFloat(270.0)
/// flag that indicates if rotation is enabled or not
public var rotationEnabled = true
private var _rotationWithTwoFingers = false
private var _tapGestureRecognizer: UITapGestureRecognizer!
private var _rotationGestureRecognizer: UIRotationGestureRecognizer!
public override init(frame: CGRect)
{
super.init(frame: frame);
}
public required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder);
}
deinit
{
stopDeceleration();
}
internal override func initialize()
{
super.initialize();
_tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:"));
_rotationGestureRecognizer = UIRotationGestureRecognizer(target: self, action: Selector("rotationGestureRecognized:"));
self.addGestureRecognizer(_tapGestureRecognizer);
self.addGestureRecognizer(_rotationGestureRecognizer);
_rotationGestureRecognizer.enabled = rotationWithTwoFingers;
}
internal override func calcMinMax()
{
_deltaX = CGFloat(_data.xVals.count - 1);
}
public override func notifyDataSetChanged()
{
if (_dataNotSet)
{
return;
}
calcMinMax();
if (_legend !== nil)
{
_legendRenderer.computeLegend(_data);
}
calculateOffsets();
setNeedsDisplay();
}
internal override func calculateOffsets()
{
var legendLeft = CGFloat(0.0);
var legendRight = CGFloat(0.0);
var legendBottom = CGFloat(0.0);
var legendTop = CGFloat(0.0);
if (_legend != nil && _legend.enabled)
{
var fullLegendWidth = min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent);
fullLegendWidth += _legend.formSize + _legend.formToTextSpace;
if (_legend.position == .RightOfChartCenter)
{
// this is the space between the legend and the chart
let spacing = CGFloat(13.0);
legendRight = fullLegendWidth + spacing;
}
else if (_legend.position == .RightOfChart)
{
// this is the space between the legend and the chart
let spacing = CGFloat(8.0);
var legendWidth = fullLegendWidth + spacing;
var legendHeight = _legend.neededHeight + _legend.textHeightMax;
var c = self.midPoint;
var bottomRight = CGPoint(x: self.bounds.width - legendWidth + 15.0, y: legendHeight + 15);
var distLegend = distanceToCenter(x: bottomRight.x, y: bottomRight.y);
var reference = getPosition(center: c, dist: self.radius,
angle: angleForPoint(x: bottomRight.x, y: bottomRight.y));
var distReference = distanceToCenter(x: reference.x, y: reference.y);
var minOffset = CGFloat(5.0);
if (distLegend < distReference)
{
var diff = distReference - distLegend;
legendRight = minOffset + diff;
}
if (bottomRight.y >= c.y && self.bounds.height - legendWidth > self.bounds.width)
{
legendRight = legendWidth;
}
}
else if (_legend.position == .LeftOfChartCenter)
{
// this is the space between the legend and the chart
let spacing = CGFloat(13.0);
legendLeft = fullLegendWidth + spacing;
}
else if (_legend.position == .LeftOfChart)
{
// this is the space between the legend and the chart
let spacing = CGFloat(8.0);
var legendWidth = fullLegendWidth + spacing;
var legendHeight = _legend.neededHeight + _legend.textHeightMax;
var c = self.midPoint;
var bottomLeft = CGPoint(x: legendWidth - 15.0, y: legendHeight + 15);
var distLegend = distanceToCenter(x: bottomLeft.x, y: bottomLeft.y);
var reference = getPosition(center: c, dist: self.radius,
angle: angleForPoint(x: bottomLeft.x, y: bottomLeft.y));
var distReference = distanceToCenter(x: reference.x, y: reference.y);
var min = CGFloat(5.0);
if (distLegend < distReference)
{
var diff = distReference - distLegend;
legendLeft = min + diff;
}
if (bottomLeft.y >= c.y && self.bounds.height - legendWidth > self.bounds.width)
{
legendLeft = legendWidth;
}
}
else if (_legend.position == .BelowChartLeft
|| _legend.position == .BelowChartRight
|| _legend.position == .BelowChartCenter)
{
var yOffset = self.requiredBottomOffset; // It's possible that we do not need this offset anymore as it is available through the extraOffsets
legendBottom = min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent);
}
legendLeft += self.requiredBaseOffset;
legendRight += self.requiredBaseOffset;
legendTop += self.requiredBaseOffset;
}
legendTop += self.extraTopOffset;
legendRight += self.extraRightOffset;
legendBottom += self.extraBottomOffset;
legendLeft += self.extraLeftOffset;
var minOffset = CGFloat(10.0);
if (self.isKindOfClass(RadarChartView))
{
let x = (self as! RadarChartView).xAxis;
if (x.isEnabled)
{
minOffset = max(10.0, x.labelWidth);
}
}
var offsetLeft = max(minOffset, legendLeft);
var offsetTop = max(minOffset, legendTop);
var offsetRight = max(minOffset, legendRight);
var offsetBottom = max(minOffset, max(self.requiredBaseOffset, legendBottom));
_viewPortHandler.restrainViewPort(offsetLeft: offsetLeft, offsetTop: offsetTop, offsetRight: offsetRight, offsetBottom: offsetBottom);
}
/// returns the angle relative to the chart center for the given point on the chart in degrees.
/// The angle is always between 0 and 360°, 0° is NORTH, 90° is EAST, ...
public func angleForPoint(#x: CGFloat, y: CGFloat) -> CGFloat
{
var c = centerOffsets;
var tx = Double(x - c.x);
var ty = Double(y - c.y);
var length = sqrt(tx * tx + ty * ty);
var r = acos(ty / length);
var angle = r * ChartUtils.Math.RAD2DEG;
if (x > c.x)
{
angle = 360.0 - angle;
}
// add 90° because chart starts EAST
angle = angle + 90.0;
// neutralize overflow
if (angle > 360.0)
{
angle = angle - 360.0;
}
return CGFloat(angle);
}
/// Calculates the position around a center point, depending on the distance
/// from the center, and the angle of the position around the center.
internal func getPosition(#center: CGPoint, dist: CGFloat, angle: CGFloat) -> CGPoint
{
var a = cos(angle * ChartUtils.Math.FDEG2RAD);
return CGPoint(x: center.x + dist * cos(angle * ChartUtils.Math.FDEG2RAD),
y: center.y + dist * sin(angle * ChartUtils.Math.FDEG2RAD));
}
/// Returns the distance of a certain point on the chart to the center of the chart.
public func distanceToCenter(#x: CGFloat, y: CGFloat) -> CGFloat
{
var c = self.centerOffsets;
var dist = CGFloat(0.0);
var xDist = CGFloat(0.0);
var yDist = CGFloat(0.0);
if (x > c.x)
{
xDist = x - c.x;
}
else
{
xDist = c.x - x;
}
if (y > c.y)
{
yDist = y - c.y;
}
else
{
yDist = c.y - y;
}
// pythagoras
dist = sqrt(pow(xDist, 2.0) + pow(yDist, 2.0));
return dist;
}
/// Returns the xIndex for the given angle around the center of the chart.
/// Returns -1 if not found / outofbounds.
public func indexForAngle(angle: CGFloat) -> Int
{
fatalError("indexForAngle() cannot be called on PieRadarChartViewBase");
}
/// current rotation angle of the pie chart
/// :returns will always return a normalized value, which will be between 0.0 < 360.0
/// :default: 270 --> top (NORTH)
public var rotationAngle: CGFloat
{
get
{
return _rotationAngle;
}
set
{
_rawRotationAngle = newValue;
_rotationAngle = ChartUtils.normalizedAngleFromAngle(newValue);
setNeedsDisplay();
}
}
/// gets the raw version of the current rotation angle of the pie chart the returned value could be any value, negative or positive, outside of the 360 degrees.
/// this is used when working with rotation direction, mainly by gestures and animations.
public var rawRotationAngle: CGFloat
{
return _rawRotationAngle;
}
/// returns the diameter of the pie- or radar-chart
public var diameter: CGFloat
{
var content = _viewPortHandler.contentRect;
return min(content.width, content.height);
}
/// Returns the radius of the chart in pixels.
public var radius: CGFloat
{
fatalError("radius cannot be called on PieRadarChartViewBase");
}
/// Returns the required bottom offset for the chart.
internal var requiredBottomOffset: CGFloat
{
fatalError("requiredBottomOffset cannot be called on PieRadarChartViewBase");
}
/// Returns the base offset needed for the chart without calculating the
/// legend size.
internal var requiredBaseOffset: CGFloat
{
fatalError("requiredBaseOffset cannot be called on PieRadarChartViewBase");
}
public override var chartXMax: Double
{
return 0.0;
}
public override var chartXMin: Double
{
return 0.0;
}
/// Returns an array of SelectionDetail objects for the given x-index.
/// The SelectionDetail objects give information about the value at the selected index and the DataSet it belongs to.
public func getSelectionDetailsAtIndex(xIndex: Int) -> [ChartSelectionDetail]
{
var vals = [ChartSelectionDetail]();
for (var i = 0; i < _data.dataSetCount; i++)
{
var dataSet = _data.getDataSetByIndex(i);
if (dataSet === nil || !dataSet.isHighlightEnabled)
{
continue;
}
// extract all y-values from all DataSets at the given x-index
var yVal = dataSet!.yValForXIndex(xIndex);
if (!isnan(yVal))
{
vals.append(ChartSelectionDetail(value: yVal, dataSetIndex: i, dataSet: dataSet!));
}
}
return vals;
}
public var isRotationEnabled: Bool { return rotationEnabled; }
/// flag that indicates if rotation is done with two fingers or one.
/// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events.
/// :default: false
public var rotationWithTwoFingers: Bool
{
get
{
return _rotationWithTwoFingers;
}
set
{
_rotationWithTwoFingers = newValue;
_rotationGestureRecognizer.enabled = _rotationWithTwoFingers;
}
}
/// flag that indicates if rotation is done with two fingers or one.
/// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events.
/// :default: false
public var isRotationWithTwoFingers: Bool
{
return _rotationWithTwoFingers;
}
// MARK: - Animation
private var _spinAnimator: ChartAnimator!;
/// Applys a spin animation to the Chart.
public func spin(#duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easing: ChartEasingFunctionBlock?)
{
if (_spinAnimator != nil)
{
_spinAnimator.stop();
}
_spinAnimator = ChartAnimator();
_spinAnimator.updateBlock = {
self.rotationAngle = (toAngle - fromAngle) * self._spinAnimator.phaseX + fromAngle;
};
_spinAnimator.stopBlock = { self._spinAnimator = nil; };
_spinAnimator.animate(xAxisDuration: duration, easing: easing);
}
public func spin(#duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easingOption: ChartEasingOption)
{
spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: easingFunctionFromOption(easingOption));
}
public func spin(#duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat)
{
spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: nil);
}
public func stopSpinAnimation()
{
if (_spinAnimator != nil)
{
_spinAnimator.stop();
}
}
// MARK: - Gestures
private var _touchStartPoint: CGPoint!
private var _isRotating = false
private var _defaultTouchEventsWereEnabled = false
private var _startAngle = CGFloat(0.0)
private struct AngularVelocitySample
{
var time: NSTimeInterval;
var angle: CGFloat;
}
private var _velocitySamples = [AngularVelocitySample]();
private var _decelerationLastTime: NSTimeInterval = 0.0
private var _decelerationDisplayLink: CADisplayLink!
private var _decelerationAngularVelocity: CGFloat = 0.0
public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)
{
// if rotation by touch is enabled
if (rotationEnabled)
{
stopDeceleration();
if (!rotationWithTwoFingers)
{
var touch = touches.first as! UITouch!;
var touchLocation = touch.locationInView(self);
self.resetVelocity();
if (rotationEnabled)
{
self.sampleVelocity(touchLocation: touchLocation);
}
self.setGestureStartAngle(x: touchLocation.x, y: touchLocation.y);
_touchStartPoint = touchLocation;
}
}
if (!_isRotating)
{
super.touchesBegan(touches, withEvent: event);
}
}
public override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent)
{
if (rotationEnabled && !rotationWithTwoFingers)
{
var touch = touches.first as! UITouch!;
var touchLocation = touch.locationInView(self);
if (isDragDecelerationEnabled)
{
sampleVelocity(touchLocation: touchLocation);
}
if (!_isRotating && distance(eventX: touchLocation.x, startX: _touchStartPoint.x, eventY: touchLocation.y, startY: _touchStartPoint.y) > CGFloat(8.0))
{
_isRotating = true;
}
else
{
self.updateGestureRotation(x: touchLocation.x, y: touchLocation.y);
setNeedsDisplay();
}
}
if (!_isRotating)
{
super.touchesMoved(touches, withEvent: event);
}
}
public override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent)
{
if (!_isRotating)
{
super.touchesEnded(touches, withEvent: event);
}
if (rotationEnabled && !rotationWithTwoFingers)
{
var touch = touches.first as! UITouch!;
var touchLocation = touch.locationInView(self);
if (isDragDecelerationEnabled)
{
stopDeceleration();
sampleVelocity(touchLocation: touchLocation);
_decelerationAngularVelocity = calculateVelocity();
if (_decelerationAngularVelocity != 0.0)
{
_decelerationLastTime = CACurrentMediaTime();
_decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop"));
_decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes);
}
}
}
if (_isRotating)
{
_isRotating = false;
}
}
public override func touchesCancelled(touches: Set<NSObject>, withEvent event: UIEvent)
{
super.touchesCancelled(touches, withEvent: event);
if (_isRotating)
{
_isRotating = false;
}
}
private func resetVelocity()
{
_velocitySamples.removeAll(keepCapacity: false);
}
private func sampleVelocity(#touchLocation: CGPoint)
{
var currentTime = CACurrentMediaTime();
_velocitySamples.append(AngularVelocitySample(time: currentTime, angle: angleForPoint(x: touchLocation.x, y: touchLocation.y)));
// Remove samples older than our sample time - 1 seconds
for (var i = 0, count = _velocitySamples.count; i < count - 2; i++)
{
if (currentTime - _velocitySamples[i].time > 1.0)
{
_velocitySamples.removeAtIndex(0);
i--;
count--;
}
else
{
break;
}
}
}
private func calculateVelocity() -> CGFloat
{
if (_velocitySamples.isEmpty)
{
return 0.0;
}
var firstSample = _velocitySamples[0];
var lastSample = _velocitySamples[_velocitySamples.count - 1];
// Look for a sample that's closest to the latest sample, but not the same, so we can deduce the direction
var beforeLastSample = firstSample;
for (var i = _velocitySamples.count - 1; i >= 0; i--)
{
beforeLastSample = _velocitySamples[i];
if (beforeLastSample.angle != lastSample.angle)
{
break;
}
}
// Calculate the sampling time
var timeDelta = lastSample.time - firstSample.time;
if (timeDelta == 0.0)
{
timeDelta = 0.1;
}
// Calculate clockwise/ccw by choosing two values that should be closest to each other,
// so if the angles are two far from each other we know they are inverted "for sure"
var clockwise = lastSample.angle >= beforeLastSample.angle;
if (abs(lastSample.angle - beforeLastSample.angle) > 270.0)
{
clockwise = !clockwise;
}
// Now if the "gesture" is over a too big of an angle - then we know the angles are inverted, and we need to move them closer to each other from both sides of the 360.0 wrapping point
if (lastSample.angle - firstSample.angle > 180.0)
{
firstSample.angle += 360.0;
}
else if (firstSample.angle - lastSample.angle > 180.0)
{
lastSample.angle += 360.0;
}
// The velocity
var velocity = abs((lastSample.angle - firstSample.angle) / CGFloat(timeDelta));
// Direction?
if (!clockwise)
{
velocity = -velocity;
}
return velocity;
}
/// sets the starting angle of the rotation, this is only used by the touch listener, x and y is the touch position
private func setGestureStartAngle(#x: CGFloat, y: CGFloat)
{
_startAngle = angleForPoint(x: x, y: y);
// take the current angle into consideration when starting a new drag
_startAngle -= _rotationAngle;
}
/// updates the view rotation depending on the given touch position, also takes the starting angle into consideration
private func updateGestureRotation(#x: CGFloat, y: CGFloat)
{
self.rotationAngle = angleForPoint(x: x, y: y) - _startAngle;
}
public func stopDeceleration()
{
if (_decelerationDisplayLink !== nil)
{
_decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes);
_decelerationDisplayLink = nil;
}
}
@objc private func decelerationLoop()
{
var currentTime = CACurrentMediaTime();
_decelerationAngularVelocity *= self.dragDecelerationFrictionCoef;
var timeInterval = CGFloat(currentTime - _decelerationLastTime);
self.rotationAngle += _decelerationAngularVelocity * timeInterval;
_decelerationLastTime = currentTime;
if(abs(_decelerationAngularVelocity) < 0.001)
{
stopDeceleration();
}
}
/// returns the distance between two points
private func distance(#eventX: CGFloat, startX: CGFloat, eventY: CGFloat, startY: CGFloat) -> CGFloat
{
var dx = eventX - startX;
var dy = eventY - startY;
return sqrt(dx * dx + dy * dy);
}
/// returns the distance between two points
private func distance(#from: CGPoint, to: CGPoint) -> CGFloat
{
var dx = from.x - to.x;
var dy = from.y - to.y;
return sqrt(dx * dx + dy * dy);
}
/// reference to the last highlighted object
private var _lastHighlight: ChartHighlight!;
@objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Ended)
{
var location = recognizer.locationInView(self);
var distance = distanceToCenter(x: location.x, y: location.y);
// check if a slice was touched
if (distance > self.radius)
{
// if no slice was touched, highlight nothing
self.highlightValues(nil);
_lastHighlight = nil;
_lastHighlight = nil;
}
else
{
var angle = angleForPoint(x: location.x, y: location.y);
if (self.isKindOfClass(PieChartView))
{
angle /= _animator.phaseY;
}
var index = indexForAngle(angle);
// check if the index could be found
if (index < 0)
{
self.highlightValues(nil);
_lastHighlight = nil;
}
else
{
var valsAtIndex = getSelectionDetailsAtIndex(index);
var dataSetIndex = 0;
// get the dataset that is closest to the selection (PieChart only has one DataSet)
if (self.isKindOfClass(RadarChartView))
{
dataSetIndex = ChartUtils.closestDataSetIndex(valsAtIndex, value: Double(distance / (self as! RadarChartView).factor), axis: nil);
}
if (dataSetIndex < 0)
{
self.highlightValues(nil);
_lastHighlight = nil;
}
else
{
var h = ChartHighlight(xIndex: index, dataSetIndex: dataSetIndex);
if (_lastHighlight !== nil && h == _lastHighlight)
{
self.highlightValue(highlight: nil, callDelegate: true);
_lastHighlight = nil;
}
else
{
self.highlightValue(highlight: h, callDelegate: true);
_lastHighlight = h;
}
}
}
}
}
}
@objc private func rotationGestureRecognized(recognizer: UIRotationGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began)
{
stopDeceleration();
_startAngle = self.rawRotationAngle;
}
if (recognizer.state == UIGestureRecognizerState.Began || recognizer.state == UIGestureRecognizerState.Changed)
{
var angle = ChartUtils.Math.FRAD2DEG * recognizer.rotation;
self.rotationAngle = _startAngle + angle;
setNeedsDisplay();
}
else if (recognizer.state == UIGestureRecognizerState.Ended)
{
var angle = ChartUtils.Math.FRAD2DEG * recognizer.rotation;
self.rotationAngle = _startAngle + angle;
setNeedsDisplay();
if (isDragDecelerationEnabled)
{
stopDeceleration();
_decelerationAngularVelocity = ChartUtils.Math.FRAD2DEG * recognizer.velocity;
if (_decelerationAngularVelocity != 0.0)
{
_decelerationLastTime = CACurrentMediaTime();
_decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop"));
_decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes);
}
}
}
}
} | apache-2.0 | 16f0368b284c9c1ac6aaf50e84fe3916 | 32.206561 | 191 | 0.551669 | 5.503021 | false | false | false | false |
david1mdavis/IOS-nRF-Toolbox | nRF Toolbox/BluetoothManager/NORBluetoothManager.swift | 1 | 19109 | //
// NORBluetoothManager.swift
// nRF Toolbox
//
// Created by Mostafa Berg on 06/05/16.
// Copyright © 2016 Nordic Semiconductor. All rights reserved.
//
import UIKit
import CoreBluetooth
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
protocol NORBluetoothManagerDelegate {
func didConnectPeripheral(deviceName aName : String?)
func didDisconnectPeripheral()
func peripheralReady()
func peripheralNotSupported()
}
class NORBluetoothManager: NSObject, CBPeripheralDelegate, CBCentralManagerDelegate {
//MARK: - Delegate Properties
var delegate : NORBluetoothManagerDelegate?
var logger : NORLogger?
var cameradata :NSMutableData?
var imageByteCount : Int
//MARK: - Class Properties
fileprivate let MTU = 20
fileprivate let UARTServiceUUID : CBUUID
fileprivate let UARTRXCharacteristicUUID : CBUUID
fileprivate let UARTTXCharacteristicUUID : CBUUID
fileprivate var centralManager : CBCentralManager
fileprivate var bluetoothPeripheral : CBPeripheral?
fileprivate var uartRXCharacteristic : CBCharacteristic?
fileprivate var uartTXCharacteristic : CBCharacteristic?
fileprivate var connected = false
//MARK: - BluetoothManager API
required init(withManager aManager : CBCentralManager) {
centralManager = aManager
imageByteCount = 0;
cameradata = NSMutableData()
// self.imagedata?.init
UARTServiceUUID = CBUUID(string: NORServiceIdentifiers.uartServiceUUIDString)
UARTTXCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.uartTXCharacteristicUUIDString)
UARTRXCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.uartRXCharacteristicUUIDString)
super.init()
centralManager.delegate = self
}
/**
* Connects to the given peripheral.
*
* - parameter aPeripheral: target peripheral to connect to
*/
func connectPeripheral(peripheral aPeripheral : CBPeripheral) {
bluetoothPeripheral = aPeripheral
// we assign the bluetoothPeripheral property after we establish a connection, in the callback
if let name = aPeripheral.name {
log(withLevel: .verboseLogLevel, andMessage: "Connecting to: \(name)...")
} else {
log(withLevel: .verboseLogLevel, andMessage: "Connecting to device...")
}
log(withLevel: .debugLogLevel, andMessage: "centralManager.connect(peripheral, options:nil)")
centralManager.connect(aPeripheral, options: nil)
}
/**
* Disconnects or cancels pending connection.
* The delegate's didDisconnectPeripheral() method will be called when device got disconnected.
*/
func cancelPeripheralConnection() {
guard bluetoothPeripheral != nil else {
log(withLevel: .warningLogLevel, andMessage: "Peripheral not set")
return
}
if connected {
log(withLevel: .verboseLogLevel, andMessage: "Disconnecting...")
} else {
log(withLevel: .verboseLogLevel, andMessage: "Cancelling connection...")
}
log(withLevel: .debugLogLevel, andMessage: "centralManager.cancelPeripheralConnection(peripheral)")
centralManager.cancelPeripheralConnection(bluetoothPeripheral!)
// In case the previous connection attempt failed before establishing a connection
if !connected {
bluetoothPeripheral = nil
delegate?.didDisconnectPeripheral()
}
}
/**
* Returns true if the peripheral device is connected, false otherwise
* - returns: true if device is connected
*/
func isConnected() -> Bool {
return connected
}
/**
* This method sends the given test to the UART RX characteristic.
* Depending on whether the characteristic has the Write Without Response or Write properties the behaviour is different.
* In the latter case the Long Write may be used. To enable it you have to change the flag below in the code.
* Otherwise, in both cases, texts longer than 20 (MTU) bytes (not characters) will be splitted into up-to 20-byte packets.
*
* - parameter aText: text to be sent to the peripheral using Nordic UART Service
*/
func send(text aText : String) {
guard self.uartRXCharacteristic != nil else {
log(withLevel: .warningLogLevel, andMessage: "UART RX Characteristic not found")
return
}
// Check what kind of Write Type is supported. By default it will try Without Response.
// If the RX charactereisrtic have Write property the Write Request type will be used.
var type = CBCharacteristicWriteType.withoutResponse
if (self.uartRXCharacteristic!.properties.rawValue & CBCharacteristicProperties.write.rawValue) > 0 {
type = CBCharacteristicWriteType.withResponse
}
// In case of Write Without Response the text needs to be splited in up-to 20-bytes packets.
// When Write Request (with response) is used, the Long Write may be used.
// It will be handled automatically by the iOS, but must be supported on the device side.
// If your device does support Long Write, change the flag below to true.
let longWriteSupported = false
// The following code will split the text to packets
let textData = aText.data(using: String.Encoding.utf8)!
textData.withUnsafeBytes { (u8Ptr: UnsafePointer<CChar>) in
var buffer = UnsafeMutableRawPointer(mutating: UnsafeRawPointer(u8Ptr))
var len = textData.count
while(len != 0){
var part : String
if len > MTU && (type == CBCharacteristicWriteType.withoutResponse || longWriteSupported == false) {
// If the text contains national letters they may be 2-byte long.
// It may happen that only 19 (MTU) bytes can be send so that not of them is splited into 2 packets.
var builder = NSMutableString(bytes: buffer, length: MTU, encoding: String.Encoding.utf8.rawValue)
if builder != nil {
// A 20-byte string has been created successfully
buffer = buffer + MTU
len = len - MTU
} else {
// We have to create 19-byte string. Let's ignore some stranger UTF-8 characters that have more than 2 bytes...
builder = NSMutableString(bytes: buffer, length: (MTU - 1), encoding: String.Encoding.utf8.rawValue)
buffer = buffer + (MTU - 1)
len = len - (MTU - 1)
}
part = String(describing: builder!)
} else {
let builder = NSMutableString(bytes: buffer, length: len, encoding: String.Encoding.utf8.rawValue)
part = String(describing: builder!)
len = 0
}
send(text: part, withType: type)
}
}
}
/**
* Sends the given text to the UART RX characteristic using the given write type.
* This method does not split the text into parts. If the given write type is withResponse
* and text is longer than 20-bytes the long write will be used.
*
* - parameters:
* - aText: text to be sent to the peripheral using Nordic UART Service
* - aType: write type to be used
*/
func send(text aText : String, withType aType : CBCharacteristicWriteType) {
guard self.uartRXCharacteristic != nil else {
log(withLevel: .warningLogLevel, andMessage: "UART RX Characteristic not found")
return
}
let typeAsString = aType == .withoutResponse ? ".withoutResponse" : ".withResponse"
let data = aText.data(using: String.Encoding.utf8)!
//do some logging
log(withLevel: .verboseLogLevel, andMessage: "Writing to characteristic: \(uartRXCharacteristic!.uuid.uuidString)")
log(withLevel: .debugLogLevel, andMessage: "peripheral.writeValue(0x\(data.hexString), for: \(uartRXCharacteristic!.uuid.uuidString), type: \(typeAsString))")
self.bluetoothPeripheral!.writeValue(data, for: self.uartRXCharacteristic!, type: aType)
// The transmitted data is not available after the method returns. We have to log the text here.
// The callback peripheral:didWriteValueForCharacteristic:error: is called only when the Write Request type was used,
// but even if, the data is not available there.
log(withLevel: .appLogLevel, andMessage: "\"\(aText)\" sent")
}
//MARK: - Logger API
func log(withLevel aLevel : NORLOGLevel, andMessage aMessage : String) {
logger?.log(level: aLevel,message: aMessage)
}
func logError(error anError : Error) {
if let e = anError as? CBError {
logger?.log(level: .errorLogLevel, message: "Error \(e.code): \(e.localizedDescription)")
} else {
logger?.log(level: .errorLogLevel, message: "Error \(anError.localizedDescription)")
}
}
//MARK: - CBCentralManagerDelegate
func centralManagerDidUpdateState(_ central: CBCentralManager) {
var state : String
switch(central.state){
case .poweredOn:
state = "Powered ON"
break
case .poweredOff:
state = "Powered OFF"
break
case .resetting:
state = "Resetting"
break
case .unauthorized:
state = "Unautthorized"
break
case .unsupported:
state = "Unsupported"
break
case .unknown:
state = "Unknown"
break
}
log(withLevel: .debugLogLevel, andMessage: "[Callback] Central Manager did update state to: \(state)")
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
log(withLevel: .debugLogLevel, andMessage: "[Callback] Central Manager did connect peripheral")
if let name = peripheral.name {
log(withLevel: .infoLogLevel, andMessage: "Connected to: \(name)")
} else {
log(withLevel: .infoLogLevel, andMessage: "Connected to device")
}
imageByteCount = 0;
connected = true
bluetoothPeripheral = peripheral
bluetoothPeripheral!.delegate = self
delegate?.didConnectPeripheral(deviceName: peripheral.name)
log(withLevel: .verboseLogLevel, andMessage: "Discovering services...")
log(withLevel: .debugLogLevel, andMessage: "peripheral.discoverServices([\(UARTServiceUUID.uuidString)])")
peripheral.discoverServices([UARTServiceUUID])
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
guard error == nil else {
log(withLevel: .debugLogLevel, andMessage: "[Callback] Central Manager did disconnect peripheral")
logError(error: error!)
return
}
log(withLevel: .debugLogLevel, andMessage: "[Callback] Central Manager did disconnect peripheral successfully")
log(withLevel: .infoLogLevel, andMessage: "Disconnected")
connected = false
delegate?.didDisconnectPeripheral()
bluetoothPeripheral!.delegate = nil
bluetoothPeripheral = nil
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
guard error == nil else {
log(withLevel: .debugLogLevel, andMessage: "[Callback] Central Manager did fail to connect to peripheral")
logError(error: error!)
return
}
log(withLevel: .debugLogLevel, andMessage: "[Callback] Central Manager did fail to connect to peripheral without errors")
log(withLevel: .infoLogLevel, andMessage: "Failed to connect")
connected = false
delegate?.didDisconnectPeripheral()
bluetoothPeripheral!.delegate = nil
bluetoothPeripheral = nil
}
//MARK: - CBPeripheralDelegate
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
guard error == nil else {
log(withLevel: .warningLogLevel, andMessage: "Service discovery failed")
logError(error: error!)
//TODO: Disconnect?
return
}
log(withLevel: .infoLogLevel, andMessage: "Services discovered")
for aService: CBService in peripheral.services! {
if aService.uuid.isEqual(UARTServiceUUID) {
log(withLevel: .verboseLogLevel, andMessage: "Nordic UART Service found")
log(withLevel: .verboseLogLevel, andMessage: "Discovering characteristics...")
log(withLevel: .debugLogLevel, andMessage: "peripheral.discoverCharacteristics(nil, for: \(aService.uuid.uuidString))")
bluetoothPeripheral!.discoverCharacteristics(nil, for: aService)
return
}
}
//No UART service discovered
log(withLevel: .warningLogLevel, andMessage: "UART Service not found. Try to turn bluetooth Off and On again to clear the cache.")
delegate?.peripheralNotSupported()
cancelPeripheralConnection()
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard error == nil else {
log(withLevel: .warningLogLevel, andMessage: "Characteristics discovery failed")
logError(error: error!)
return
}
log(withLevel: .infoLogLevel, andMessage: "Characteristics discovered")
if service.uuid.isEqual(UARTServiceUUID) {
for aCharacteristic : CBCharacteristic in service.characteristics! {
if aCharacteristic.uuid.isEqual(UARTTXCharacteristicUUID) {
log(withLevel: .verboseLogLevel, andMessage: "TX Characteristic found")
uartTXCharacteristic = aCharacteristic
} else if aCharacteristic.uuid.isEqual(UARTRXCharacteristicUUID) {
log(withLevel: .verboseLogLevel, andMessage: "RX Characteristic found")
uartRXCharacteristic = aCharacteristic
}
}
//Enable notifications on TX Characteristic
if (uartTXCharacteristic != nil && uartRXCharacteristic != nil) {
log(withLevel: .verboseLogLevel, andMessage: "Enabling notifications for \(uartTXCharacteristic!.uuid.uuidString)")
log(withLevel: .debugLogLevel, andMessage: "peripheral.setNotifyValue(true, for: \(uartTXCharacteristic!.uuid.uuidString))")
bluetoothPeripheral!.setNotifyValue(true, for: uartTXCharacteristic!)
} else {
log(withLevel: .warningLogLevel, andMessage: "UART service does not have required characteristics. Try to turn Bluetooth Off and On again to clear cache.")
delegate?.peripheralNotSupported()
cancelPeripheralConnection()
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
guard error == nil else {
log(withLevel: .warningLogLevel, andMessage: "Enabling notifications failed")
logError(error: error!)
return
}
if characteristic.isNotifying {
log(withLevel: .infoLogLevel, andMessage: "Notifications enabled for characteristic: \(characteristic.uuid.uuidString)")
} else {
log(withLevel: .infoLogLevel, andMessage: "Notifications disabled for characteristic: \(characteristic.uuid.uuidString)")
}
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
guard error == nil else {
log(withLevel: .warningLogLevel, andMessage: "Writing value to characteristic has failed")
logError(error: error!)
return
}
log(withLevel: .infoLogLevel, andMessage: "Data written to characteristic: \(characteristic.uuid.uuidString)")
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?) {
guard error == nil else {
log(withLevel: .warningLogLevel, andMessage: "Writing value to descriptor has failed")
logError(error: error!)
return
}
log(withLevel: .infoLogLevel, andMessage: "Data written to descriptor: \(descriptor.uuid.uuidString)")
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
guard error == nil else {
log(withLevel: .warningLogLevel, andMessage: "Updating characteristic has failed")
logError(error: error!)
return
}
// try to print a friendly string of received bytes if they can be parsed as UTF8
guard let bytesReceived = characteristic.value else {
log(withLevel: .infoLogLevel, andMessage: "Notification received from: \(characteristic.uuid.uuidString), with empty value")
log(withLevel: .appLogLevel, andMessage: "Empty packet received")
return
}
bytesReceived.withUnsafeBytes { (utf8Bytes: UnsafePointer<CChar>) in
var len = bytesReceived.count
if utf8Bytes[len - 1] == 0 {
len -= 1 // if the string is null terminated, don't pass null terminator into NSMutableString constructor
}
cameradata?.append(utf8Bytes, length: len)
// log(withLevel: .infoLogLevel, andMessage: "Notification received from: \(characteristic.uuid.uuidString), with value: 0x\(bytesReceived.hexString)")
/* if let validUTF8String = String(utf8String: utf8Bytes) {// NSMutableString(bytes: utf8Bytes, length: len, encoding: String.Encoding.utf8.rawValue) {
log(withLevel: .minLogLevel, andMessage: "\"\(validUTF8String)\" ")
} else {
log(withLevel: .minLogLevel, andMessage: "\"0x\(bytesReceived.hexString)\" ")
}
*/ }
}
}
| bsd-3-clause | a9b37eb1d95c6b9cf69be92281d7ca90 | 44.172577 | 171 | 0.631516 | 5.210799 | false | false | false | false |
apple/swift-nio-ssl | Sources/NIOSSLPerformanceTester/BenchManyWrites.swift | 1 | 2956 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import NIOSSL
final class BenchManyWrites: Benchmark {
let clientContext: NIOSSLContext
let serverContext: NIOSSLContext
let dummyAddress: SocketAddress
let backToBack: BackToBackEmbeddedChannel
let loopCount: Int
let writeSize: Int
var buffer: ByteBuffer?
init(loopCount: Int, writeSizeInBytes writeSize: Int) throws {
self.loopCount = loopCount
self.writeSize = writeSize
self.serverContext = try NIOSSLContext(configuration: .makeServerConfiguration(
certificateChain: [.certificate(.forTesting())],
privateKey: .privateKey(.forTesting())
))
var clientConfig = TLSConfiguration.makeClientConfiguration()
clientConfig.trustRoots = try .certificates([.forTesting()])
self.clientContext = try NIOSSLContext(configuration: clientConfig)
self.dummyAddress = try SocketAddress(ipAddress: "1.2.3.4", port: 5678)
self.backToBack = BackToBackEmbeddedChannel()
}
func setUp() throws {
let serverHandler = NIOSSLServerHandler(context: self.serverContext)
let clientHandler = try NIOSSLClientHandler(context: self.clientContext, serverHostname: "localhost")
try self.backToBack.client.pipeline.addHandler(clientHandler).wait()
try self.backToBack.server.pipeline.addHandler(serverHandler).wait()
// To trigger activation of both channels we use connect().
try self.backToBack.client.connect(to: dummyAddress).wait()
try self.backToBack.server.connect(to: dummyAddress).wait()
try self.backToBack.interactInMemory()
self.buffer = self.backToBack.client.allocator.buffer(capacity: self.writeSize)
self.buffer!.writeBytes(repeatElement(0, count: self.writeSize))
}
func tearDown() { }
func run() throws -> Int {
guard let buffer = self.buffer else {
fatalError("Couldn't get buffer")
}
for _ in 0..<self.loopCount {
// A vector of 100 writes.
for _ in 0..<100 {
self.backToBack.client.write(buffer, promise: nil)
}
self.backToBack.client.flush()
try self.backToBack.interactInMemory()
// Pull any data out of the server to avoid ballooning in memory.
while let _ = try self.backToBack.server.readInbound(as: ByteBuffer.self) { }
}
return self.loopCount
}
}
| apache-2.0 | 433f90e164967a64c7413317953eb456 | 35.493827 | 109 | 0.636671 | 4.775444 | false | true | false | false |
codepgq/WeiBoDemo | PQWeiboDemo/PQWeiboDemo/classes/Index 首页/popver/PQPopverPresentationController.swift | 1 | 1922 | //
// PQPopverPresentationController.swift
// PQWeiboDemo
//
// Created by ios on 16/9/19.
// Copyright © 2016年 ios. All rights reserved.
//
import UIKit
class PQPopverPresentationController: UIPresentationController {
/// 定义属性保存菜单的大小
var presentFrame = CGRect.zero
/**
初始化方法,用于创建负责转场动画的对象
- parameter presentedViewController: 被展现的控制器
- parameter presentingViewController: 发起的控制器
- returns: 返回负责转场动画的对象
*/
override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) {
super.init(presentedViewController: presentedViewController, presenting : presentingViewController)
}
/**
即将布局转场子视图时调用
*/
override func containerViewWillLayoutSubviews() {
// 1、修改弹出视图的大小
if presentFrame == CGRect.zero {
presentedView?.frame = CGRect(x: 100, y: 56, width: 200, height: 200)
}else{
presentedView?.frame = presentFrame
}
// 2、在容器上添加一个蒙版,插入到图层最底层
containerView?.insertSubview(coverView, at: 0)
}
private lazy var coverView : UIView = {
// 1、创建View
let view = UIView()
view.backgroundColor = UIColor(white: 0, alpha: 0.2)
view.frame = UIScreen.main.bounds
//2、添加监听
let tap = UITapGestureRecognizer(target: self, action: #selector(PQPopverPresentationController.close))
view.addGestureRecognizer(tap)
return view
}()
@objc private func close(){
//presentedViewController 当前弹出的控制器
presentedViewController.dismiss(animated: true, completion: nil)
}
}
| mit | e0f14880bf9f62b0784e0ef87fcc9a96 | 27.25 | 118 | 0.641298 | 4.695291 | false | false | false | false |
jzarakas/tsp-ios | tsp/tsp/ViewController.swift | 1 | 3148 | //
// ViewController.swift
// tsp
//
// Created by James Zarakas on 8/8/14.
// Copyright (c) 2014 Labs FunWare. All rights reserved.
//
import UIKit
//urinal pin 1
//toilet pin 2
class ViewController: UIViewController {
@IBOutlet weak var toiletView: UIView!
@IBOutlet weak var toiletLabel: UILabel!
@IBOutlet weak var urinalView: UIView!
@IBOutlet weak var urinalLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
refresh()
var timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: Selector("refresh"), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func refresh() {
NSLog("refreshing/..")
let url = "https://agent.electricimp.com/vfR-e76MntZb"
var request = NSMutableURLRequest()
request.URL = NSURL(string: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
if jsonResult {
dispatch_async(dispatch_get_main_queue(), {
NSLog("json: %@, %@", jsonResult.objectForKey("pin1") as String, jsonResult.objectForKey("pin2") as String)
let toilet = jsonResult.objectForKey("pin2") as String
let urinal = jsonResult.objectForKey("pin1") as String
if (toilet.toInt() > 30000) {
//toilet is free
self.toiletLabel.text = "VACANT (" + toilet + ")"
self.toiletView.backgroundColor = UIColor.greenColor()
} else {
//toilet is occupied
self.toiletLabel.text = "OCCUPIED (" + toilet + ")"
self.toiletView.backgroundColor = UIColor.redColor()
}
if (urinal.toInt() > 42000) {
//urinal is free
self.urinalLabel.text = "VACANT (" + urinal + ")"
self.urinalView.backgroundColor = UIColor.greenColor()
} else {
//urinal is occupied
self.urinalLabel.text = "OCCUPIED (" + urinal + ")"
self.urinalView.backgroundColor = UIColor.redColor()
}
})
} else {
// couldn't load JSON, look at error
}
})
}
@IBAction func refreshButton(sender: AnyObject) {
refresh()
}
}
| mit | ae5469c5b5ffce27e40eb4d1f2407a38 | 33.593407 | 172 | 0.546696 | 5.160656 | false | false | false | false |
qkrqjadn/SoonChat | source/Extension/Extensions.swift | 1 | 4145 | //
// Extensions.swift
//
//
//
//
//
import UIKit
extension UIColor{
static func rgb(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor {
return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 1)
}
}
extension UIView {
func anchorToTop(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil) {
anchorWithConstantsToTop(top, left: left, bottom: bottom, right: right, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0)
}
func anchorWithConstantsToTop(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0) {
_ = anchor(top, left: left, bottom: bottom, right: right, topConstant: topConstant, leftConstant: leftConstant, bottomConstant: bottomConstant, rightConstant: rightConstant)
}
func anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let top = top {
anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
}
if let left = left {
anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
}
if let bottom = bottom {
anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
}
if let right = right {
anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
}
if widthConstant > 0 {
anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
}
if heightConstant > 0 {
anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
}
anchors.forEach({$0.isActive = true})
return anchors
}
}
extension UIView {
func addConstraintsWithFormat(format:String , views: UIView...)
{
var viewsDictionary = [String:UIView]()
for (index,view) in views.enumerated(){
view.translatesAutoresizingMaskIntoConstraints = false
let key = "v\(index)"
viewsDictionary[key] = view
}
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
}
}
extension UIView {
func addsubview(_ view:UIView...)
{
view.forEach { (view) in
self.addSubview(view)
}
}
}
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView {
func loadImageUsingCacheWithUrlString(urlString:String){
//check cache for image first
if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = cachedImage
return
}
let unwrapurl = URL(string: urlString)
guard let url = unwrapurl else {return}
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if error != nil
{
print(error)
}
DispatchQueue.main.async {
if let downloadedImage = UIImage(data: data!){
imageCache.setObject(downloadedImage, forKey: urlString as AnyObject)
}
self.image = UIImage(data: data!)
}
}).resume()
}
}
| mit | d8c9146405fd3afee564ba8d09ab3769 | 34.127119 | 348 | 0.608926 | 5.123609 | false | false | false | false |
emilstahl/swift | test/Interpreter/protocol_extensions.swift | 9 | 5887 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// Extend a protocol with a property.
extension SequenceType {
final var myCount: Int {
var result = 0
for _ in self {
++result
}
return result
}
}
// CHECK: 4
print(["a", "b", "c", "d"].myCount)
// Extend a protocol with a function.
extension CollectionType {
final var myIndices: Range<Index> {
return Range(start: startIndex, end: endIndex)
}
func clone() -> Self {
return self
}
}
// CHECK: 4
print(["a", "b", "c", "d"].clone().myCount)
extension CollectionType {
final func indexMatching(fn: Generator.Element -> Bool) -> Index? {
for i in myIndices {
if fn(self[i]) { return i }
}
return nil
}
}
// CHECK: 2
print(["a", "b", "c", "d"].indexMatching({$0 == "c"})!)
// Extend certain instances of a collection (those that have equatable
// element types) with another algorithm.
extension CollectionType where Self.Generator.Element : Equatable {
final func myIndexOf(element: Generator.Element) -> Index? {
for i in self.indices {
if self[i] == element { return i }
}
return nil
}
}
// CHECK: 3
print(["a", "b", "c", "d", "e"].myIndexOf("d")!)
extension SequenceType {
final public func myEnumerate() -> EnumerateSequence<Self> {
return EnumerateSequence(self)
}
}
// CHECK: (0, a)
// CHECK-NEXT: (1, b)
// CHECK-NEXT: (2, c)
for (index, element) in ["a", "b", "c"].myEnumerate() {
print("(\(index), \(element))")
}
extension SequenceType {
final public func myReduce<T>(
initial: T, @noescape combine: (T, Self.Generator.Element) -> T
) -> T {
var result = initial
for value in self {
result = combine(result, value)
}
return result
}
}
// CHECK: 15
print([1, 2, 3, 4, 5].myReduce(0, combine: +))
extension SequenceType {
final public func myZip<S : SequenceType>(s: S) -> Zip2Sequence<Self, S> {
return Zip2Sequence(self, s)
}
}
// CHECK: (1, a)
// CHECK-NEXT: (2, b)
// CHECK-NEXT: (3, c)
for (a, b) in [1, 2, 3].myZip(["a", "b", "c"]) {
print("(\(a), \(b))")
}
// Mutating algorithms.
extension MutableCollectionType
where Self.Index: RandomAccessIndexType, Self.Generator.Element : Comparable {
public final mutating func myPartition(range: Range<Index>) -> Index {
return self.partition(range)
}
}
// CHECK: 4 3 1 2 | 5 9 8 6 7 6
var evenOdd = [5, 3, 6, 2, 4, 9, 8, 1, 7, 6]
var evenOddSplit = evenOdd.myPartition(evenOdd.myIndices)
for i in evenOdd.myIndices {
if i == evenOddSplit { print(" |", terminator: "") }
if i > 0 { print(" ", terminator: "") }
print(evenOdd[i], terminator: "")
}
print("")
extension RangeReplaceableCollectionType {
public final func myJoin<S : SequenceType where S.Generator.Element == Self>(
elements: S
) -> Self {
var result = Self()
var gen = elements.generate()
if let first = gen.next() {
result.appendContentsOf(first)
while let next = gen.next() {
result.appendContentsOf(self)
result.appendContentsOf(next)
}
}
return result
}
}
// CHECK: a,b,c
print(
String(
",".characters.myJoin(["a".characters, "b".characters, "c".characters])
)
)
// Constrained extensions for specific types.
extension CollectionType where Self.Generator.Element == String {
final var myCommaSeparatedList: String {
if startIndex == endIndex { return "" }
var result = ""
var first = true
for x in self {
if first { first = false }
else { result += ", " }
result += x
}
return result
}
}
// CHECK: x, y, z
print(["x", "y", "z"].myCommaSeparatedList)
// CHECK: {{[tuv], [tuv], [tuv]}}
print((["t", "u", "v"] as Set).myCommaSeparatedList)
// Existentials
protocol ExistP1 {
func existP1()
}
extension ExistP1 {
final func runExistP1() {
print("runExistP1")
self.existP1()
}
}
struct ExistP1_Struct : ExistP1 {
func existP1() {
print(" - ExistP1_Struct")
}
}
class ExistP1_Class : ExistP1 {
func existP1() {
print(" - ExistP1_Class")
}
}
// CHECK: runExistP1
// CHECK-NEXT: - ExistP1_Struct
var existP1: ExistP1 = ExistP1_Struct()
existP1.runExistP1()
// CHECK: runExistP1
// CHECK-NEXT: - ExistP1_Class
existP1 = ExistP1_Class()
existP1.runExistP1()
protocol P {
mutating func setValue(b: Bool)
func getValue() -> Bool
}
extension P {
final var extValue: Bool {
get { return getValue() }
set(newValue) { setValue(newValue) }
}
}
extension Bool : P {
mutating func setValue(b: Bool) { self = b }
func getValue() -> Bool { return self }
}
class C : P {
var theValue: Bool = false
func setValue(b: Bool) { theValue = b }
func getValue() -> Bool { return theValue }
}
func toggle(inout value: Bool) {
value = !value
}
var p: P = true
// CHECK: Bool
print("Bool")
// CHECK: true
p.extValue = true
print(p.extValue)
// CHECK: false
p.extValue = false
print(p.extValue)
// CHECK: true
toggle(&p.extValue)
print(p.extValue)
// CHECK: C
print("C")
p = C()
// CHECK: true
p.extValue = true
print(p.extValue)
// CHECK: false
p.extValue = false
print(p.extValue)
// CHECK: true
toggle(&p.extValue)
print(p.extValue)
// Logical lvalues of existential type.
struct HasP {
var _p: P
var p: P {
get { return _p }
set { _p = newValue }
}
}
var hasP = HasP(_p: false)
// CHECK: true
hasP.p.extValue = true
print(hasP.p.extValue)
// CHECK: false
toggle(&hasP.p.extValue)
print(hasP.p.extValue)
// rdar://problem/20739719
class Super: Init {
required init(x: Int) { print("\(x) \(self.dynamicType)") }
}
class Sub: Super {}
protocol Init { init(x: Int) }
extension Init { init() { self.init(x: 17) } }
// CHECK: 17 Super
_ = Super()
// CHECK: 17 Sub
_ = Sub()
// CHECK: 17 Super
var sup: Super.Type = Super.self
_ = sup.init()
// CHECK: 17 Sub
sup = Sub.self
_ = sup.init()
// CHECK: DONE
print("DONE")
| apache-2.0 | de30c639c2385e00460dfe9311a7e33d | 18.429043 | 80 | 0.621709 | 3.104958 | false | false | false | false |
ben-ng/swift | test/SILGen/witness_tables.swift | 4 | 39270 | // RUN: %target-swift-frontend -emit-silgen -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module > %t.sil
// RUN: %FileCheck -check-prefix=TABLE -check-prefix=TABLE-ALL %s < %t.sil
// RUN: %FileCheck -check-prefix=SYMBOL %s < %t.sil
// RUN: %target-swift-frontend -emit-silgen -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-testing > %t.testable.sil
// RUN: %FileCheck -check-prefix=TABLE-TESTABLE -check-prefix=TABLE-ALL %s < %t.testable.sil
// RUN: %FileCheck -check-prefix=SYMBOL-TESTABLE %s < %t.testable.sil
import witness_tables_b
struct Arg {}
@objc class ObjCClass {}
infix operator <~> {}
protocol AssocReqt {
func requiredMethod()
}
protocol ArchetypeReqt {
func requiredMethod()
}
protocol AnyProtocol {
associatedtype AssocType
associatedtype AssocWithReqt: AssocReqt
func method(x x: Arg, y: Self)
func generic<A: ArchetypeReqt>(x x: A, y: Self)
func assocTypesMethod(x x: AssocType, y: AssocWithReqt)
static func staticMethod(x x: Self)
func <~>(x: Self, y: Self)
}
protocol ClassProtocol : class {
associatedtype AssocType
associatedtype AssocWithReqt: AssocReqt
func method(x x: Arg, y: Self)
func generic<B: ArchetypeReqt>(x x: B, y: Self)
func assocTypesMethod(x x: AssocType, y: AssocWithReqt)
static func staticMethod(x x: Self)
func <~>(x: Self, y: Self)
}
@objc protocol ObjCProtocol {
func method(x x: ObjCClass)
static func staticMethod(y y: ObjCClass)
}
class SomeAssoc {}
struct ConformingAssoc : AssocReqt {
func requiredMethod() {}
}
// TABLE-LABEL: sil_witness_table hidden ConformingAssoc: AssocReqt module witness_tables {
// TABLE-TESTABLE-LABEL: sil_witness_table [fragile] ConformingAssoc: AssocReqt module witness_tables {
// TABLE-ALL-NEXT: method #AssocReqt.requiredMethod!1: @_TTWV14witness_tables15ConformingAssocS_9AssocReqtS_FS1_14requiredMethod{{.*}}
// TABLE-ALL-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables15ConformingAssocS_9AssocReqtS_FS1_14requiredMethod{{.*}} : $@convention(witness_method) (@in_guaranteed ConformingAssoc) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables15ConformingAssocS_9AssocReqtS_FS1_14requiredMethod{{.*}} : $@convention(witness_method) (@in_guaranteed ConformingAssoc) -> ()
struct ConformingStruct : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ConformingStruct) {}
func generic<D: ArchetypeReqt>(x x: D, y: ConformingStruct) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: ConformingStruct) {}
}
func <~>(x: ConformingStruct, y: ConformingStruct) {}
// TABLE-LABEL: sil_witness_table hidden ConformingStruct: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_7generic{{.*}}: ArchetypeReqt> (@in τ_0_0, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformingStruct, @thick ConformingStruct.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingStruct) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformingStruct, @thick ConformingStruct.Type) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> ()
protocol AddressOnly {}
struct ConformingAddressOnlyStruct : AnyProtocol {
var p: AddressOnly // force address-only layout with a protocol-type field
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ConformingAddressOnlyStruct) {}
func generic<E: ArchetypeReqt>(x x: E, y: ConformingAddressOnlyStruct) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: ConformingAddressOnlyStruct) {}
}
func <~>(x: ConformingAddressOnlyStruct, y: ConformingAddressOnlyStruct) {}
// TABLE-LABEL: sil_witness_table hidden ConformingAddressOnlyStruct: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformingAddressOnlyStruct, @in_guaranteed ConformingAddressOnlyStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformingAddressOnlyStruct, @in_guaranteed ConformingAddressOnlyStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingAddressOnlyStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformingAddressOnlyStruct, @thick ConformingAddressOnlyStruct.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformingAddressOnlyStruct, @in ConformingAddressOnlyStruct, @thick ConformingAddressOnlyStruct.Type) -> ()
class ConformingClass : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ConformingClass) {}
func generic<F: ArchetypeReqt>(x x: F, y: ConformingClass) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
class func staticMethod(x x: ConformingClass) {}
}
func <~>(x: ConformingClass, y: ConformingClass) {}
// TABLE-LABEL: sil_witness_table hidden ConformingClass: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformingClass, @in_guaranteed ConformingClass) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformingClass, @in_guaranteed ConformingClass) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingClass) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformingClass, @thick ConformingClass.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformingClass, @in ConformingClass, @thick ConformingClass.Type) -> ()
struct ConformsByExtension {}
extension ConformsByExtension : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ConformsByExtension) {}
func generic<G: ArchetypeReqt>(x x: G, y: ConformsByExtension) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: ConformsByExtension) {}
}
func <~>(x: ConformsByExtension, y: ConformsByExtension) {}
// TABLE-LABEL: sil_witness_table hidden ConformsByExtension: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformsByExtension, @in_guaranteed ConformsByExtension) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformsByExtension, @in_guaranteed ConformsByExtension) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformsByExtension) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformsByExtension, @thick ConformsByExtension.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformsByExtension, @in ConformsByExtension, @thick ConformsByExtension.Type) -> ()
extension OtherModuleStruct : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: OtherModuleStruct) {}
func generic<H: ArchetypeReqt>(x x: H, y: OtherModuleStruct) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: OtherModuleStruct) {}
}
func <~>(x: OtherModuleStruct, y: OtherModuleStruct) {}
// TABLE-LABEL: sil_witness_table hidden OtherModuleStruct: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_ZFS2_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_ZFS2_oi3ltg{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_6method{{.*}} : $@convention(witness_method) (Arg, @in OtherModuleStruct, @in_guaranteed OtherModuleStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_7generic{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in OtherModuleStruct, @in_guaranteed OtherModuleStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed OtherModuleStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_ZFS2_12staticMethod{{.*}} : $@convention(witness_method) (@in OtherModuleStruct, @thick OtherModuleStruct.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_ZFS2_oi3ltg{{.*}} : $@convention(witness_method) (@in OtherModuleStruct, @in OtherModuleStruct, @thick OtherModuleStruct.Type) -> ()
protocol OtherProtocol {}
struct ConformsWithMoreGenericWitnesses : AnyProtocol, OtherProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method<I, J>(x x: I, y: J) {}
func generic<K, L>(x x: K, y: L) {}
func assocTypesMethod<M, N>(x x: M, y: N) {}
static func staticMethod<O>(x x: O) {}
}
func <~> <P: OtherProtocol>(x: P, y: P) {}
// TABLE-LABEL: sil_witness_table hidden ConformsWithMoreGenericWitnesses: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformsWithMoreGenericWitnesses, @in_guaranteed ConformsWithMoreGenericWitnesses) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformsWithMoreGenericWitnesses, @in_guaranteed ConformsWithMoreGenericWitnesses) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformsWithMoreGenericWitnesses) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformsWithMoreGenericWitnesses, @thick ConformsWithMoreGenericWitnesses.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformsWithMoreGenericWitnesses, @in ConformsWithMoreGenericWitnesses, @thick ConformsWithMoreGenericWitnesses.Type) -> ()
class ConformingClassToClassProtocol : ClassProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ConformingClassToClassProtocol) {}
func generic<Q: ArchetypeReqt>(x x: Q, y: ConformingClassToClassProtocol) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
class func staticMethod(x x: ConformingClassToClassProtocol) {}
}
func <~>(x: ConformingClassToClassProtocol,
y: ConformingClassToClassProtocol) {}
// TABLE-LABEL: sil_witness_table hidden ConformingClassToClassProtocol: ClassProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #ClassProtocol.method!1: @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #ClassProtocol.generic!1: @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #ClassProtocol.assocTypesMethod!1: @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #ClassProtocol.staticMethod!1: @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #ClassProtocol."<~>"!1: @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @owned ConformingClassToClassProtocol, @guaranteed ConformingClassToClassProtocol) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @owned ConformingClassToClassProtocol, @guaranteed ConformingClassToClassProtocol) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @guaranteed ConformingClassToClassProtocol) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@owned ConformingClassToClassProtocol, @thick ConformingClassToClassProtocol.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@owned ConformingClassToClassProtocol, @owned ConformingClassToClassProtocol, @thick ConformingClassToClassProtocol.Type) -> ()
class ConformingClassToObjCProtocol : ObjCProtocol {
@objc func method(x x: ObjCClass) {}
@objc class func staticMethod(y y: ObjCClass) {}
}
// TABLE-NOT: sil_witness_table hidden ConformingClassToObjCProtocol
struct ConformingGeneric<R: AssocReqt> : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = R
func method(x x: Arg, y: ConformingGeneric) {}
func generic<Q: ArchetypeReqt>(x x: Q, y: ConformingGeneric) {}
func assocTypesMethod(x x: SomeAssoc, y: R) {}
static func staticMethod(x x: ConformingGeneric) {}
}
func <~> <R: AssocReqt>(x: ConformingGeneric<R>, y: ConformingGeneric<R>) {}
// TABLE-LABEL: sil_witness_table hidden <R where R : AssocReqt> ConformingGeneric<R>: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: R
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): dependent
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWuRx14witness_tables9AssocReqtrGVS_17ConformingGenericx_S_11AnyProtocolS_FS2_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWuRx14witness_tables9AssocReqtrGVS_17ConformingGenericx_S_11AnyProtocolS_FS2_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWuRx14witness_tables9AssocReqtrGVS_17ConformingGenericx_S_11AnyProtocolS_FS2_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWuRx14witness_tables9AssocReqtrGVS_17ConformingGenericx_S_11AnyProtocolS_ZFS2_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWuRx14witness_tables9AssocReqtrGVS_17ConformingGenericx_S_11AnyProtocolS_ZFS2_oi3ltg{{.*}}
// TABLE-NEXT: }
protocol AnotherProtocol {}
struct ConformingGenericWithMoreGenericWitnesses<S: AssocReqt>
: AnyProtocol, AnotherProtocol
{
typealias AssocType = SomeAssoc
typealias AssocWithReqt = S
func method<T, U>(x x: T, y: U) {}
func generic<V, W>(x x: V, y: W) {}
func assocTypesMethod<X, Y>(x x: X, y: Y) {}
static func staticMethod<Z>(x x: Z) {}
}
func <~> <AA: AnotherProtocol, BB: AnotherProtocol>(x: AA, y: BB) {}
// TABLE-LABEL: sil_witness_table hidden <S where S : AssocReqt> ConformingGenericWithMoreGenericWitnesses<S>: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: S
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): dependent
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWuRx14witness_tables9AssocReqtrGVS_41ConformingGenericWithMoreGenericWitnessesx_S_11AnyProtocolS_FS2_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWuRx14witness_tables9AssocReqtrGVS_41ConformingGenericWithMoreGenericWitnessesx_S_11AnyProtocolS_FS2_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWuRx14witness_tables9AssocReqtrGVS_41ConformingGenericWithMoreGenericWitnessesx_S_11AnyProtocolS_FS2_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWuRx14witness_tables9AssocReqtrGVS_41ConformingGenericWithMoreGenericWitnessesx_S_11AnyProtocolS_ZFS2_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWuRx14witness_tables9AssocReqtrGVS_41ConformingGenericWithMoreGenericWitnessesx_S_11AnyProtocolS_ZFS2_oi3ltg{{.*}}
// TABLE-NEXT: }
protocol InheritedProtocol1 : AnyProtocol {
func inheritedMethod()
}
protocol InheritedProtocol2 : AnyProtocol {
func inheritedMethod()
}
protocol InheritedClassProtocol : class, AnyProtocol {
func inheritedMethod()
}
struct InheritedConformance : InheritedProtocol1 {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: InheritedConformance) {}
func generic<H: ArchetypeReqt>(x x: H, y: InheritedConformance) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: InheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: InheritedConformance, y: InheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden InheritedConformance: InheritedProtocol1 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: InheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: @_TTWV14witness_tables20InheritedConformanceS_18InheritedProtocol1S_FS1_15inheritedMethod{{.*}}
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden InheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables20InheritedConformanceS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables20InheritedConformanceS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables20InheritedConformanceS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables20InheritedConformanceS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables20InheritedConformanceS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
struct RedundantInheritedConformance : InheritedProtocol1, AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: RedundantInheritedConformance) {}
func generic<H: ArchetypeReqt>(x x: H, y: RedundantInheritedConformance) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: RedundantInheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: RedundantInheritedConformance, y: RedundantInheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden RedundantInheritedConformance: InheritedProtocol1 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: RedundantInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_18InheritedProtocol1S_FS1_15inheritedMethod{{.*}}
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden RedundantInheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
struct DiamondInheritedConformance : InheritedProtocol1, InheritedProtocol2 {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: DiamondInheritedConformance) {}
func generic<H: ArchetypeReqt>(x x: H, y: DiamondInheritedConformance) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: DiamondInheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: DiamondInheritedConformance, y: DiamondInheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: InheritedProtocol1 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: DiamondInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_18InheritedProtocol1S_FS1_15inheritedMethod{{.*}}
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: InheritedProtocol2 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: DiamondInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol2.inheritedMethod!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_18InheritedProtocol2S_FS1_15inheritedMethod{{.*}}
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
class ClassInheritedConformance : InheritedClassProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ClassInheritedConformance) {}
func generic<H: ArchetypeReqt>(x x: H, y: ClassInheritedConformance) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
class func staticMethod(x x: ClassInheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: ClassInheritedConformance, y: ClassInheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden ClassInheritedConformance: InheritedClassProtocol module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: ClassInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedClassProtocol.inheritedMethod!1: @_TTWC14witness_tables25ClassInheritedConformanceS_22InheritedClassProtocolS_FS1_15inheritedMethod{{.*}}
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden ClassInheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
// -- Witnesses have the 'self' abstraction level of their protocol.
// AnyProtocol has no class bound, so its witnesses treat Self as opaque.
// InheritedClassProtocol has a class bound, so its witnesses treat Self as
// a reference value.
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables25ClassInheritedConformanceS_22InheritedClassProtocolS_FS1_15inheritedMethod{{.*}} : $@convention(witness_method) (@guaranteed ClassInheritedConformance) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ClassInheritedConformance, @in_guaranteed ClassInheritedConformance) -> ()
struct GenericAssocType<T> : AssocReqt {
func requiredMethod() {}
}
protocol AssocTypeWithReqt {
associatedtype AssocType : AssocReqt
}
struct ConformsWithDependentAssocType1<CC: AssocReqt> : AssocTypeWithReqt {
typealias AssocType = CC
}
// TABLE-LABEL: sil_witness_table hidden <CC where CC : AssocReqt> ConformsWithDependentAssocType1<CC>: AssocTypeWithReqt module witness_tables {
// TABLE-NEXT: associated_type AssocType: CC
// TABLE-NEXT: associated_type_protocol (AssocType: AssocReqt): dependent
// TABLE-NEXT: }
struct ConformsWithDependentAssocType2<DD> : AssocTypeWithReqt {
typealias AssocType = GenericAssocType<DD>
}
// TABLE-LABEL: sil_witness_table hidden <DD> ConformsWithDependentAssocType2<DD>: AssocTypeWithReqt module witness_tables {
// TABLE-NEXT: associated_type AssocType: GenericAssocType<DD>
// TABLE-NEXT: associated_type_protocol (AssocType: AssocReqt): GenericAssocType<DD>: specialize <DD> (<T> GenericAssocType<T>: AssocReqt module witness_tables)
// TABLE-NEXT: }
protocol InheritedFromObjC : ObjCProtocol {
func inheritedMethod()
}
class ConformsInheritedFromObjC : InheritedFromObjC {
@objc func method(x x: ObjCClass) {}
@objc class func staticMethod(y y: ObjCClass) {}
func inheritedMethod() {}
}
// TABLE-LABEL: sil_witness_table hidden ConformsInheritedFromObjC: InheritedFromObjC module witness_tables {
// TABLE-NEXT: method #InheritedFromObjC.inheritedMethod!1: @_TTWC14witness_tables25ConformsInheritedFromObjCS_17InheritedFromObjCS_FS1_15inheritedMethod{{.*}}
// TABLE-NEXT: }
protocol ObjCAssoc {
associatedtype AssocType : ObjCProtocol
}
struct HasObjCAssoc : ObjCAssoc {
typealias AssocType = ConformsInheritedFromObjC
}
// TABLE-LABEL: sil_witness_table hidden HasObjCAssoc: ObjCAssoc module witness_tables {
// TABLE-NEXT: associated_type AssocType: ConformsInheritedFromObjC
// TABLE-NEXT: }
protocol Initializer {
init(arg: Arg)
}
// TABLE-LABEL: sil_witness_table hidden HasInitializerStruct: Initializer module witness_tables {
// TABLE-NEXT: method #Initializer.init!allocator.1: @_TTWV14witness_tables20HasInitializerStructS_11InitializerS_FS1_C{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables20HasInitializerStructS_11InitializerS_FS1_C{{.*}} : $@convention(witness_method) (Arg, @thick HasInitializerStruct.Type) -> @out HasInitializerStruct
struct HasInitializerStruct : Initializer {
init(arg: Arg) { }
}
// TABLE-LABEL: sil_witness_table hidden HasInitializerClass: Initializer module witness_tables {
// TABLE-NEXT: method #Initializer.init!allocator.1: @_TTWC14witness_tables19HasInitializerClassS_11InitializerS_FS1_C{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables19HasInitializerClassS_11InitializerS_FS1_C{{.*}} : $@convention(witness_method) (Arg, @thick HasInitializerClass.Type) -> @out HasInitializerClass
class HasInitializerClass : Initializer {
required init(arg: Arg) { }
}
// TABLE-LABEL: sil_witness_table hidden HasInitializerEnum: Initializer module witness_tables {
// TABLE-NEXT: method #Initializer.init!allocator.1: @_TTWO14witness_tables18HasInitializerEnumS_11InitializerS_FS1_C{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWO14witness_tables18HasInitializerEnumS_11InitializerS_FS1_C{{.*}} : $@convention(witness_method) (Arg, @thick HasInitializerEnum.Type) -> @out HasInitializerEnum
enum HasInitializerEnum : Initializer {
case A
init(arg: Arg) { self = .A }
}
| apache-2.0 | 2eb9b921b4f3ec71a2ad57e3e29ca68c | 70.36 | 312 | 0.770689 | 3.754712 | false | false | false | false |
luispadron/GradePoint | GradePoint/Models/Main/Grade.swift | 1 | 1380 | //
// Grade.swift
// GradePoint
//
// Created by Luis Padron on 4/26/17.
// Copyright © 2017 Luis Padron. All rights reserved.
//
import Foundation
import RealmSwift
/// Data model which represents a score for a Class object
class Grade: Object {
// MARK: Properties
/// The id of the score in Realm
@objc dynamic var id = UUID().uuidString
/// The score
@objc dynamic var score: Double = 0.0
/// The grade letter
@objc dynamic var gradeLetter: String = "F"
// MARK: Initializers & Overrides
/// Used when creating a new class which will be tracked and saved
convenience init(score: Double) {
self.init()
self.score = score
self.gradeLetter = Grade.gradeLetter(for: score)
}
/// Used when creating a Previous class
convenience init(gradeLetter: String) {
self.init()
self.gradeLetter = gradeLetter
}
override class func primaryKey() -> String? {
return "id"
}
// MARK: Helper Methods
/// Returns a string representation of the score object, the grade letter
/// NOTE: This function will only work properly when called on grade objects that belong to in-progress classes
static func gradeLetter(for score: Double) -> String {
return GradeRubric.shared.letterGrade(for: score) ?? "?"
}
}
| apache-2.0 | 4eed2e4e9e2e5ebf81e2b0d48309497b | 25.018868 | 115 | 0.633067 | 4.405751 | false | false | false | false |
RxSwiftCommunity/RxWebKit | RxWebKitTests/HasEventsBehavior.swift | 1 | 2074 | import Foundation
import Quick
import Nimble
import RxSwift
import RxCocoa
import RxTest
import WebKit
@testable import RxWebKit
struct HasEventsBehaviorContext<T: Equatable> {
let scheduler: TestScheduler
let observable: Observable<T>
let expected: T?
init(_ scheduler: TestScheduler, _ observable: Observable<T>, _ expected: T?) {
self.scheduler = scheduler
self.observable = observable
self.expected = expected
}
}
class HasEventsBehavior<T: Equatable>: Quick.Behavior<HasEventsBehaviorContext<T>> {
override class func spec(_ context: @escaping () -> HasEventsBehaviorContext<T>) {
var scheduler: TestScheduler!
var observable: Observable<T>!
var expected: T?
beforeEach {
let cxt = context()
scheduler = cxt.scheduler
observable = cxt.observable
expected = cxt.expected
}
afterEach {
scheduler = nil
observable = nil
}
describe("Has Events Behavior") {
it("Actually got the event") {
SharingScheduler.mock(scheduler: scheduler) {
let recorded = scheduler.record(source: observable)
scheduler.start()
expect(recorded.events.count).to(equal(1))
expect(recorded.events[0].value.element).to(equal(expected))
}
}
}
}
}
extension TestScheduler {
/// Builds testable observer for s specific observable sequence, binds it's results and sets up disposal.
/// parameter source: Observable sequence to observe.
/// returns: Observer that records all events for observable sequence.
func record<O: ObservableConvertibleType>(source: O) -> TestableObserver<O.Element> {
let observer = self.createObserver(O.Element.self)
let disposable = source.asObservable().bind(to: observer)
self.scheduleAt(100000) {
disposable.dispose()
}
return observer
}
}
| mit | e5ba5cf2e03bf956c42f0aa8fc327439 | 31.40625 | 109 | 0.614754 | 4.973621 | false | true | false | false |
mapsme/omim | iphone/Maps/TipsAndTricks/TutorialViewController.swift | 5 | 5145 | @objc(MWMTutorialType)
enum TutorialType: Int {
case search = 0
case discovery
case bookmarks
case subway
case isolines
}
@objc(MWMTutorialViewControllerDelegate)
protocol TutorialViewControllerDelegate: AnyObject {
func didPressTarget(_ viewController: TutorialViewController)
func didPressCancel(_ viewController: TutorialViewController)
func didPressOnScreen(_ viewController: TutorialViewController)
}
fileprivate struct TargetAction {
let target: Any
let action: Selector
}
@objc(MWMTutorialViewController)
@objcMembers
class TutorialViewController: UIViewController {
var targetView: UIControl?
var customAction: (() -> Void)?
weak var delegate: TutorialViewControllerDelegate?
private var targetViewActions: [TargetAction] = []
var tutorialView: TutorialBlurView {
return view as! TutorialBlurView
}
override func viewDidLoad() {
super.viewDidLoad()
tutorialView.targetView = targetView
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
overrideTargetAction()
tutorialView.animateAppearance(kDefaultAnimationDuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
restoreTargetAction()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
tutorialView.animateSizeChange(coordinator.transitionDuration)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { }
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { }
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
delegate?.didPressOnScreen(self)
}
func fadeOut(withCompletion completion: (() -> Void)?) {
tutorialView.animateFadeOut(kDefaultAnimationDuration) {
completion?()
}
}
@objc func onTap(_ sender: UIControl) {
customAction?()
delegate?.didPressTarget(self)
}
@IBAction func onCancel(_ sender: UIButton) {
delegate?.didPressCancel(self)
}
private func overrideTargetAction() {
if customAction != nil {
let targets = targetView?.allTargets
targets?.forEach({ target in
let actions = targetView?.actions(forTarget: target, forControlEvent: .touchUpInside)
actions?.forEach({ action in
let actionSelector = NSSelectorFromString(action)
targetViewActions.append(TargetAction(target: target, action: actionSelector))
targetView?.removeTarget(target, action: actionSelector, for: .touchUpInside)
})
})
}
targetView?.addTarget(self, action: #selector(onTap(_:)), for: .touchUpInside)
}
private func restoreTargetAction() {
targetView?.removeTarget(self, action: #selector(onTap(_:)), for: .touchUpInside)
targetViewActions.forEach { targetAction in
targetView?.addTarget(targetAction.target, action: targetAction.action, for: .touchUpInside)
}
}
}
extension TutorialViewController {
@objc static func tutorial(_ type: TutorialType,
target: UIControl,
delegate: TutorialViewControllerDelegate) -> TutorialViewController {
let result: TutorialViewController
switch type {
case .search:
result = searchTutorialBlur()
case .discovery:
result = discoveryTutorialBlur()
case .subway:
result = subwayTutorialBlur()
case .isolines:
result = isolinesTutorialBlur()
case .bookmarks:
result = bookmarksTutorialBlur()
}
result.targetView = target
result.delegate = delegate
return result
}
private static func bookmarksTutorial() -> TutorialViewController {
return TutorialViewController(nibName: "BookmarksTutorial", bundle: nil)
}
private static func bookmarksTutorialBlur() -> TutorialViewController {
let result = TutorialViewController(nibName: "BookmarksTutorialBlur", bundle: nil)
result.customAction = {
MapViewController.shared().openCatalog(animated: true, utm: .tipsAndTricks)
}
return result
}
private static func searchTutorialBlur() -> TutorialViewController {
let result = TutorialViewController(nibName: "SearchTutorialBlur", bundle: nil)
result.customAction = {
MapViewController.shared().searchText(L("hotel").appending(" "))
}
return result
}
private static func discoveryTutorialBlur() -> TutorialViewController {
let result = TutorialViewController(nibName: "DiscoveryTutorialBlur", bundle: nil)
return result
}
private static func subwayTutorialBlur() -> TutorialViewController {
let result = TutorialViewController(nibName: "SubwayTutorialBlur", bundle: nil)
result.customAction = {
MapOverlayManager.setTransitEnabled(true)
}
return result
}
private static func isolinesTutorialBlur() -> TutorialViewController {
let result = TutorialViewController(nibName: "IsolinesTutorialBlur", bundle: nil)
result.customAction = {
MapOverlayManager.setIsoLinesEnabled(true)
}
return result
}
}
| apache-2.0 | 910fefbcaafc5c46c20a13fbb22ce62b | 30.564417 | 110 | 0.721088 | 4.904671 | false | false | false | false |
cplaverty/KeitaiWaniKani | AlliCrab/ViewControllers/SubjectSummaryCollectionViewController.swift | 1 | 2971 | //
// SubjectSummaryCollectionViewController.swift
// AlliCrab
//
// Copyright © 2019 Chris Laverty. All rights reserved.
//
import os
import UIKit
import WaniKaniKit
class SubjectSummaryCollectionViewController: UICollectionViewController {
private enum ReuseIdentifier: String {
case subject = "Subject"
}
private enum SegueIdentifier: String {
case subjectDetail = "SubjectDetail"
}
// MARK: - Properties
private var cachingSubjectLoader: CachingSubjectLoader!
var repositoryReader: ResourceRepositoryReader! {
didSet {
cachingSubjectLoader = CachingSubjectLoader(repositoryReader: repositoryReader)
}
}
var subjectIDs: [Int] {
get { return cachingSubjectLoader.subjectIDs }
set {
cachingSubjectLoader.subjectIDs = newValue
collectionView.reloadData()
}
}
private var contentSizeChangedObserver: NSObjectProtocol?
// MARK: - UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return subjectIDs.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ReuseIdentifier.subject.rawValue, for: indexPath) as! SubjectCollectionViewCell
let subjectID = subjectIDs[indexPath.row]
let subject = cachingSubjectLoader.subject(at: indexPath.row)
cell.setSubject(subject, id: subjectID)
return cell
}
// MARK: - UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
}
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
contentSizeChangedObserver = collectionView.observe(\.contentSize) { [weak self] collectionView, _ in
self?.preferredContentSize = collectionView.contentSize
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let identifier = segue.identifier, let segueIdentifier = SegueIdentifier(rawValue: identifier) else {
return
}
os_log("Preparing segue %@", type: .debug, identifier)
switch segueIdentifier {
case .subjectDetail:
let vc = segue.destination as! SubjectDetailViewController
let cell = sender as! SubjectCollectionViewCell
vc.repositoryReader = repositoryReader
vc.subjectID = cell.subjectID
}
}
}
| mit | 6f2f05ce6c0d1d62ad1b12cb8af0b31b | 30.595745 | 154 | 0.664983 | 5.834971 | false | false | false | false |
coderZsq/coderZsq.target.swift | StudyNotes/Foundation/Algorithm4Swift/Algorithm4Swift/DataStructure/Other/Queue_.swift | 1 | 1423 | //
// Queue.swift
// DataStructure
//
// Created by 朱双泉 on 04/01/2018.
// Copyright © 2018 Castie!. All rights reserved.
//
import Foundation
class Queue_<Element> {
private var capacity: Int
private lazy var head: Int = 0
private lazy var tail: Int = 0
private lazy var length: Int = 0
private lazy var queue: [Element] = [Element]()
init(_ queueCapacity: Int = 16) {
capacity = queueCapacity
}
func clear() {
head = 0
tail = 0
length = 0
}
func isEmpty() -> Bool {
return length == 0 ? true : false
}
func isFull() -> Bool {
return length == capacity ? true : false
}
func size() -> Int {
return length
}
@discardableResult func entry(_ element: Element) -> Bool {
guard !isFull() else { return false }
queue.append(element)
queue[tail] = element
tail += 1
tail %= capacity
length += 1
return true
}
@discardableResult func depart() -> Element? {
guard !isEmpty() else { return nil }
let element = queue[head]
head += 1
head %= capacity
length -= 1
return element
}
func traverse() {
print("︵")
for i in head..<length + head {
print(queue[i % capacity])
}
print("︶")
}
}
| mit | fb3b326a93f59e93b92a8c99072b1630 | 20.074627 | 63 | 0.511331 | 4.371517 | false | false | false | false |
pmhicks/Spindle-Player | Spindle Player/ModuleInfo.swift | 1 | 5717 | // Spindle Player
// Copyright (C) 2015 Mike Hicks
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
struct ModuleInfo {
let comment:String
let volumeBase:Int
let sequenceCount:Int
let md5:String
let name:String
let format:String
var simpleFormat:String {
//has to be a better way than this
get {
if format.hasSuffix("M.K.") { //standard 4-chan
return "MOD"
}
if format.hasSuffix("2CHN") {
return "MOD"
}
if format.hasSuffix("6CHN") {
return "MOD"
}
if format.hasSuffix("8CHN") {
return "MOD"
}
if format.hasSuffix("FLT4") { //Startrekker
return "MOD"
}
if format.hasSuffix("FLT8") { //Startrekker
return "MOD"
}
if format.hasSuffix("CD81") {
return "MOD"
}
if format.hasSuffix("M!K!") {
return "MOD"
}
if format.hasSuffix("669") {
return "669"
}
if format.hasSuffix("MTM") {
return "MTM"
}
if format.hasSuffix("S3M") { //scream tracker 3
return "S3M"
}
if format == "Soundtracker IX" {
return "MOD"
}
if format == "Ultimate Soundtracker" {
return "MOD"
}
if format.hasPrefix("D.O.C Soundtracker") {
return "MOD"
}
if format.hasPrefix("OctaMED") {
return "MED"
}
if format.hasPrefix("Ulta Tracker") {
return "ULT"
}
if format.hasPrefix("Poly Tracker") {
return "PTM"
}
if format.rangeOfString("PTM") != nil {
return "PTM"
}
if format.rangeOfString("XM") != nil {
return "XM"
}
if format.rangeOfString("IT") != nil {
return "IT"
}
return " "
}
}
let patternCount:Int
let trackCount:Int
let channelCount:Int
let instrumentCount:Int
let sampleCount:Int
let initialSpeed:Int
let initialBPM:Int
let lengthInPatterns:Int
let restartPosition:Int
let globalVolume:Int
let instruments:[String]
let samples:[String]
let duration:Int //duration of the first sequence in ms
let durationSeconds:Int
init(info:xmp_module_info) {
self.comment = String.fromCString(info.comment) ?? ""
self.volumeBase = Int(info.vol_base)
self.sequenceCount = Int(info.num_sequences)
self.md5 = md5UInt8ToString(info.md5)
var mod = info.mod.memory
//println(mod.name)
self.name = int8TupleToString(mod.name)
self.format = int8TupleToString(mod.type)
self.patternCount = Int(mod.pat)
self.trackCount = Int(mod.trk)
self.channelCount = Int(mod.chn)
self.instrumentCount = Int(mod.ins)
self.sampleCount = Int(mod.smp)
self.initialSpeed = Int(mod.spd)
self.initialBPM = Int(mod.bpm)
self.lengthInPatterns = Int(mod.len)
self.restartPosition = Int(mod.rst)
self.globalVolume = Int(mod.gvl)
let seq = info.seq_data
self.duration = Int(seq.memory.duration) //
self.durationSeconds = self.duration / 1000
if sampleCount > 0 {
var index = 0
var sampleArray:[String] = []
var samplePtr = mod.xxs
while index < sampleCount {
let sample = samplePtr.memory
sampleArray.append(int8TupleToString(sample.name))
samplePtr = samplePtr.advancedBy(1)
index++
}
self.samples = sampleArray
} else {
self.samples = []
}
if instrumentCount > 0 {
var iindex = 0
var instArray:[String] = []
var instPtr = mod.xxi
while iindex < instrumentCount {
let inst = instPtr.memory
instArray.append(int8TupleToString(inst.name))
instPtr = instPtr.advancedBy(1)
iindex++
}
self.instruments = instArray
} else {
self.instruments = []
}
}
}
| mit | 5a8c92ffd955d61cc2c45d0ec8c1065d | 30.761111 | 80 | 0.534021 | 4.522943 | false | false | false | false |
li13418801337/DouyuTV | DouyuZB/DouyuZB/Classes/Home/View/RecommendCycleView.swift | 1 | 4033 | //
// RecommendCycleView.swift
// DouyuZB
//
// Created by work on 16/11/4.
// Copyright © 2016年 xiaosi. All rights reserved.
//
import UIKit
private let kCycleCellID = "kCycleCellID"
class RecommendCycleView: UIView {
@IBOutlet weak var collectionView:
UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
var cycleTimeer : Timer?
var cycleModels : [CycleModel]?{
didSet{
//刷新collectionview
collectionView.reloadData()
//设置pagecontroll个数
pageControl.numberOfPages = cycleModels?.count ?? 0
//默认滚动到中间某一个位置
let indexPath = IndexPath(item: (cycleModels?.count ?? 0 * 10), section: 0)
collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
//添加定时器
remoCycleTimer()
addCycleTimer()
}
}
//MARK: 系统回调
override func awakeFromNib() {
super.awakeFromNib()
//设置该控件不随主控件的拉伸而拉伸
autoresizingMask = UIViewAutoresizing()
//注册cell
collectionView.register(UINib(nibName: "CollectionCycleCell",bundle: nil), forCellWithReuseIdentifier: kCycleCellID)
collectionView.dataSource = self
collectionView.delegate = self
}
override func layoutSubviews(){
super.layoutSubviews()
//设置collectionview的layout
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
}
}
//MARK: 提供快速创建view的方法
extension RecommendCycleView{
class func recommendCycleView() -> RecommendCycleView{
return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)?.first as! RecommendCycleView
}
}
//MARK: 遵守uicollticonview数据源
extension RecommendCycleView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (cycleModels?.count ?? 0) * 10000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath) as! CollectionCycleCell
cell.cycleModel = cycleModels![(indexPath as NSIndexPath).item % cycleModels!.count]
return cell
}
}
//MARK: 遵守uicollticonview代理
extension RecommendCycleView : UICollectionViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//获取滚动的偏移量
let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
//计算index
pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels!.count )
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
remoCycleTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
addCycleTimer()
}
}
//MARK: 定时器的操作方法
extension RecommendCycleView{
fileprivate func addCycleTimer(){
cycleTimeer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollTONext), userInfo: nil, repeats: true)
RunLoop.main.add(cycleTimeer!, forMode: RunLoopMode.commonModes)
}
fileprivate func remoCycleTimer(){
cycleTimeer?.invalidate()
cycleTimeer = nil
}
@objc fileprivate func scrollTONext(){
let currentOffsetX = collectionView.contentOffset.x
let offsetX = currentOffsetX + collectionView.bounds.width
collectionView.setContentOffset(CGPoint(x: offsetX,y: 0), animated: true)
}
}
| mit | 32bc7c07f3d5515a30b4b12cb5d06aff | 28.480916 | 130 | 0.648887 | 5.356449 | false | false | false | false |
inkyfox/SwiftySQL | Tests/PrefixUnaryExprTests.swift | 1 | 1806 | //
// PrefixUnaryExprTests.swift
// SwiftySQLTests
//
// Created by Yongha Yoo (inkyfox) on 2016. 10. 26..
// Copyright © 2016년 Gen X Hippies Company. All rights reserved.
//
import XCTest
@testable import SwiftySQL
class PrefixUnaryExprTests: XCTestCase {
override func setUp() {
super.setUp()
student = Student()
teature = Teature()
lecture = Lecture()
attending = Attending()
}
override func tearDown() {
super.tearDown()
student = nil
teature = nil
lecture = nil
attending = nil
}
func testNot() {
XCTAssertSQL(!(student.id == attending.studentID), "NOT (stu.id = atd.student_id)")
XCTAssertSQL(!student.name.hasPrefix("Yoo"), "NOT (stu.name LIKE 'Yoo%')")
XCTAssertSQL(!1, "NOT 1")
}
func testMinus() {
XCTAssertSQL(-student.grade, "-stu.grade")
XCTAssertSQL(-1 + 2, "1")
XCTAssertSQL(2 + -1, "1")
XCTAssertSQL(-SQL.select(student.grade).from(student).limit(1)
,
"-(SELECT stu.grade FROM student AS stu LIMIT 1)"
)
}
func testBitwiseNot() {
XCTAssertSQL(~student.grade, "~stu.grade")
XCTAssertSQL(~SQLHex(0x123), "~0x123")
}
func testExists() {
XCTAssertSQL(
exists(SQL.select()
.from(student)
.where(student.grade >= 3)),
"EXISTS (SELECT * FROM student AS stu WHERE stu.grade >= 3)")
}
func testNotExists() {
XCTAssertSQL(
notExists(SQL.select()
.from(student)
.where(student.grade >= 3)),
"NOT EXISTS (SELECT * FROM student AS stu WHERE stu.grade >= 3)")
}
}
| mit | 68a528823157f64abc05ba93fcb13cf8 | 25.130435 | 91 | 0.535774 | 4.212617 | false | true | false | false |
khizkhiz/swift | benchmark/single-source/DictionaryLiteral.swift | 2 | 808 | //===--- DictionaryLiteral.swift ------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Dictionary creation from literals benchmark
// rdar://problem/19804127
import TestsUtils
@inline(never)
func makeDictionary() -> [Int: Int] {
return [1: 3, 2: 2, 3: 1]
}
@inline(never)
public func run_DictionaryLiteral(N: Int) {
for _ in 1...10000*N {
makeDictionary()
}
}
| apache-2.0 | 2f392dd6427562f0f9cd29265c7478ad | 28.925926 | 80 | 0.591584 | 4.275132 | false | false | false | false |
ProjectDent/ARKit-CoreLocation | ARKit+CoreLocation/NotSupportedViewController.swift | 1 | 739 | //
// NotSupportedViewController.swift
// ARKit+CoreLocation
//
// Created by Vihan Bhargava on 9/2/17.
// Copyright © 2017 Project Dent. All rights reserved.
//
import UIKit
class NotSupportedViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
let label = UILabel()
label.textAlignment = .center
label.text = "iOS 11+ required"
self.view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
}
}
| mit | c0780178d8c369f0a51e508fdde8c0a5 | 25.357143 | 88 | 0.695122 | 4.555556 | false | false | false | false |
cwnidog/PhotoFilters | PhotoFilters/GalleryCell.swift | 1 | 1220 | //
// GalleryCell.swift
// PhotoFilters
//
// Created by John Leonard on 1/12/15.
// Copyright (c) 2015 John Leonard. All rights reserved.
//
import UIKit
class GalleryCell: UICollectionViewCell {
let imageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(self.imageView)
// set image attributes
imageView.frame = self.bounds
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.layer.masksToBounds = true
let views = ["imageView" : self.imageView]
imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
let imageViewConstraintsHorizontal = NSLayoutConstraint.constraintsWithVisualFormat("H:|[imageView]|", options: nil, metrics: nil, views: views)
let imageViewConstraintsVertical = NSLayoutConstraint.constraintsWithVisualFormat("V:|[imageView]|", options: nil, metrics: nil, views: views)
self.addConstraints(imageViewConstraintsHorizontal)
self.addConstraints(imageViewConstraintsVertical)
} // override init()
// we gotta do this to keep Xcode happy
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
} // required init()
} // GalleryCell
| gpl-2.0 | c75099250346010e2b2f6d8d6a5c3a11 | 31.972973 | 148 | 0.733607 | 4.728682 | false | false | false | false |
Sharelink/Bahamut | Bahamut/Persistents/iCloud/iCloudExtension.swift | 1 | 1489 | //
// iCloudDocumentManager.swift
// iDiaries
//
// Created by AlexChow on 15/12/8.
// Copyright © 2015年 GStudio. All rights reserved.
//
import Foundation
import iCloudDocumentSync
//MARK: PersistentsManger extension
extension PersistentManager
{
func useiCloudExtension(iCloudContainerIdentifier:String){
self.useExtension(iCloudExtension()) { (ext) -> Void in
iCloudExtension.defaultInstance = ext
ext.iCloudManager.setupiCloudDocumentSyncWithUbiquityContainer(iCloudContainerIdentifier)
ext.iCloudManager.verboseLogging = true
ext.iCloudManager.verboseAvailabilityLogging = true
ext.iCloudManager.checkCloudAvailability()
ext.iCloudManager.checkCloudUbiquityContainer()
}
}
}
class iCloudExtension:NSObject,iCloudDocumentDelegate,iCloudDelegate,PersistentExtensionProtocol
{
private(set) static var defaultInstance:iCloudExtension!
private(set) var iCloudManager = iCloud.sharedCloud(){
didSet{
iCloud.sharedCloud().delegate = self
}
}
func resetExtension(){
}
func destroyExtension() {
}
func releaseExtension() {
iCloud.sharedCloud().delegate = nil
iCloudManager = nil
iCloudExtension.defaultInstance = nil
}
func storeImmediately() {
}
func iCloudDocumentErrorOccured(error: NSError!) {
NSLog("iCloud", error.description)
}
} | mit | 65734e1000556be65a2f9bf6fba02e25 | 25.553571 | 101 | 0.676985 | 4.840391 | false | false | false | false |
devpunk/velvet_room | Source/Model/Vita/MVitaLinkStrategyCloseSession.swift | 1 | 804 | import Foundation
class MVitaLinkStrategyCloseSession:MVitaLinkStrategyProtocol
{
private(set) var model:MVitaLink?
required init(model:MVitaLink)
{
self.model = model
}
//MARK: protocol
func commandReceived(
header:MVitaPtpMessageInHeader,
data:Data)
{
guard
let confirm:MVitaPtpMessageInConfirm = MVitaPtpMessageInConfirm(
header:header,
data:data),
header.type == MVitaPtpType.commandAccepted,
confirm.code == MVitaPtpCommand.success
else
{
failed()
return
}
success()
}
//MARK: internal
func failed() { }
func success() { }
}
| mit | 43ae90fb745fccaa1c9da5e37cfce4ef | 19.1 | 76 | 0.521144 | 4.757396 | false | false | false | false |
dcunited001/SpectraNu | Spectra/Classes/Scene.swift | 1 | 2782 | //
// SpectraScene.swift
// Spectra
//
// Created by David Conner on 9/29/15.
// Copyright © 2015 Spectra. All rights reserved.
//
import QuartzCore
import Metal
import simd
// SpectraScene
// - render is called
// - sets up render pass descriptor
// - mutating state between renderers in the collection
// - passes renderEncoder into encode(renderEncoder) for each renderer
//TODO: explore using a state machine for RenderStrategy, where states are dynamically defined for each renderer type, a default state transition is defined which calls endEncoding() and creates a new renderEncoder and custom state transitions can be defined to transition renderEncoders without creating new ones
//TODO: exploring using a similar map for Update Objects, so top level controller can easily specify dynamic object behaviors without needing to subclass
//use enums descending from String for id's!
public typealias RendererMap = [String:Renderer]
public typealias RenderPipelineStateMap = [String:MTLRenderPipelineState]
public typealias RenderPipelineDescriptorMap = [String:MTLRenderPipelineDescriptor]
public typealias DepthStencilStateMap = [String:MTLDepthStencilState]
public typealias DepthStencilDescriptorMap = [String:MTLDepthStencilDescriptor]
public typealias ComputePipelineStateMap = [String:MTLComputePipelineState]
public typealias VertexDescriptorMap = [String:MTLVertexDescriptor]
public class Scene: RenderDelegate, UpdateDelegate {
public var pipelineStateMap: RenderPipelineStateMap = [:]
public var depthStencilStateMap: DepthStencilStateMap = [:]
public var rendererMap: RendererMap = [:]
public var nodeMap: SceneNodeMap = [:]
public var sceneGraph: SceneGraph?
public var activeCamera: Camable = BaseCamera()
public var worldUniforms: Uniformable = BaseUniforms()
public var mvpInput: BaseEncodableInput<float4x4>?
public init() {
updateMvp()
}
// func setupRenderStrategy
// for RenderStrategy, need to be able to:
// - specify the objects to render
// - acquire or create a renderEncoder
// - pass in objects & renderEncoder to an encode block for the renderer
public func renderObjects(drawable: CAMetalDrawable, renderPassDescriptor: MTLRenderPassDescriptor, commandBuffer: MTLCommandBuffer, inflightResourcesIndex: Int) {
// pass commandBuffer & renderPassDescriptor to renderStrategy
// - to create renderEncoder
}
public func updateObjects(timeSinceLastUpdate: CFTimeInterval, inflightResourcesIndex: Int) {
}
}
extension Scene: HasMVPInput {
public func calcMvp() -> float4x4 {
return float4x4()
// return calcPerspectiveMatrix() * calcProjectionMatrix() * calcUniformMatrix()
}
}
| mit | 1269766d5ab811ce1c61b7a8a1338f44 | 38.728571 | 313 | 0.755484 | 4.904762 | false | false | false | false |
LesCoureurs/Courir | Courir/Courir/GameNetworkPortal.swift | 1 | 7983 | //
// GameNetworkPortal.swift
// Courir
//
// Created by Hieu Giang on 20/3/16.
// Copyright © 2016 NUS CS3217. All rights reserved.
//
import Coulomb
import MultipeerConnectivity
protocol GameNetworkPortalConnectionDelegate: class {
func foundHostsChanged(foundHosts: [MCPeerID])
func playerWantsToJoinRoom(peer: MCPeerID, acceptGuest: (Bool) -> Void)
func playersInRoomChanged(peerIDs: [MCPeerID])
func gameStartSignalReceived(data: AnyObject?, peer: MCPeerID)
func connectedToRoom(peer: MCPeerID)
func disconnectedFromRoom(peer: MCPeerID)
}
protocol GameNetworkPortalGameStateDelegate: class {
func gameReadySignalReceived(data: AnyObject?, peer: MCPeerID)
func playerLostSignalReceived(data: AnyObject?, peer: MCPeerID)
func jumpActionReceived(data: AnyObject?, peer: MCPeerID)
func duckActionReceived(data: AnyObject?, peer: MCPeerID)
func collideActionReceived(data: AnyObject?, peer: MCPeerID)
func floatingObstacleReceived(data: AnyObject?, peer: MCPeerID)
func nonfloatingObstacleReceived(data: AnyObject?, peer: MCPeerID)
func disconnectedFromGame(peer: MCPeerID)
}
class GameNetworkPortal {
static let _instance = GameNetworkPortal(playerName: me.name ?? me.deviceName)
var semaphore: dispatch_semaphore_t?
let semaphoreTimeout: Int64 = 200
let serviceType = "courir"
var isMovingToRoomView = false
weak var connectionDelegate: GameNetworkPortalConnectionDelegate?
weak var gameStateDelegate: GameNetworkPortalGameStateDelegate? {
didSet {
while !messageBacklog.isEmpty {
let message = messageBacklog.removeAtIndex(0)
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { self.handleDataPacket(message.data, peerID: message.peer) })
}
}
}
let coulombNetwork: CoulombNetwork!
private var messageBacklog = [(data: NSData, peer: MCPeerID)]()
private init(playerName deviceId: String) {
// NOTE: coulombNetwork.autoAcceptGuests is defaulted to true
// If autoAcceptGuests is set to false, implement
// CoulombNetworkDelegate.invitationToConnectReceived to handle invitation properly
coulombNetwork = CoulombNetwork(serviceType: serviceType, myPeerId: me.peerID)
coulombNetwork.delegate = self
coulombNetwork.debugMode = true
createSemaphore()
}
deinit {
coulombNetwork.stopAdvertisingHost()
coulombNetwork.stopSearchingForHosts()
}
// MARK: Hosting
/// Call library function to start hosting
func beginHosting() {
coulombNetwork.startAdvertisingHost()
}
/// Call library function to stop hosting
func stopHosting() {
coulombNetwork.stopAdvertisingHost()
}
// MARK: Looking for hosts
/// Call library function to start looking for host
func beginSearchingForHosts() {
coulombNetwork.startSearchingForHosts()
}
/// Call library function to stop looking for host
func stopSearchingForHosts() {
coulombNetwork.stopSearchingForHosts()
}
/// Attempt to connect to host
func connectToHost(host: MCPeerID) {
coulombNetwork.connectToHost(host)
}
/// Get the currently discoverable hosts
func getFoundHosts() -> [MCPeerID] {
return coulombNetwork.getFoundHosts()
}
// MARK: Common methods
/// Called when own device wants to deliberately exit a room
func disconnectFromRoom() {
let group = dispatch_group_create()
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
self.stopHosting()
self.beginSearchingForHosts()
})
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
self.coulombNetwork.disconnect()
})
}
/// Return peer id of own device
func getMyPeerID() -> MCPeerID {
return coulombNetwork.getMyPeerID()
}
// MARK: Data transfer
/// Send data to everyone in the session
func send(event: GameEvent, data: AnyObject = "No data", mode: MCSessionSendDataMode = .Reliable) {
let standardData = ["event": event.rawValue, "data": data]
let encodedData = NSKeyedArchiver.archivedDataWithRootObject(standardData)
coulombNetwork.sendData(encodedData, mode: mode)
}
// MARK: Semaphore
func createSemaphore() {
semaphore = dispatch_semaphore_create(0)
}
}
extension GameNetworkPortal: CoulombNetworkDelegate {
func foundHostsChanged(foundHosts: [MCPeerID]) {
connectionDelegate?.foundHostsChanged(foundHosts)
}
func invitationToConnectReceived(peer: MCPeerID, handleInvitation: (Bool) -> Void) {
// If autoAcceptGuests is true, this method won't be called.
// Else, call connectionDelegate method to handle
connectionDelegate?.playerWantsToJoinRoom(peer, acceptGuest: handleInvitation)
}
/// Wait for semaphore to make sure the correct delegate is assigned
func connectedPeersInSessionChanged(peers: [MCPeerID]) {
// Only wait when connecting
if isMovingToRoomView && semaphore != nil {
dispatch_semaphore_wait(semaphore!, DISPATCH_TIME_FOREVER)
isMovingToRoomView = false
}
connectionDelegate?.playersInRoomChanged(peers)
}
func connectedToPeer(peer: MCPeerID) {
isMovingToRoomView = true
connectionDelegate?.connectedToRoom(peer)
}
func connectingToPeer(peer: MCPeerID) {
createSemaphore()
}
/// Called when self is disconnected from a session
/// Stop hosting (if applicable) and begin searching for host again
/// Call delegate to take further actions e.g. segue
func disconnectedFromSession(peer: MCPeerID) {
isMovingToRoomView = false
if gameStateDelegate != nil {
gameStateDelegate?.disconnectedFromGame(peer)
} else {
connectionDelegate?.disconnectedFromRoom(peer)
}
}
/// Receives NSData and converts it into a dictionary of type [String: AnyObject]
/// All data packets must contain an event number which is keyed with the string
/// "event"
func handleDataPacket(data: NSData, peerID: MCPeerID) {
if let parsedData = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [String: AnyObject], eventNumber = parsedData["event"] as? Int, event = GameEvent(rawValue: eventNumber) {
if gameStateDelegate == nil && event != .GameDidStart {
messageBacklog.append((data: data, peer: peerID))
return
}
switch event {
case GameEvent.GameDidStart:
connectionDelegate?.gameStartSignalReceived(parsedData["data"], peer: peerID)
case GameEvent.GameReady:
gameStateDelegate?.gameReadySignalReceived(parsedData["data"], peer: peerID)
case GameEvent.PlayerLost:
gameStateDelegate?.playerLostSignalReceived(parsedData["data"], peer: peerID)
case GameEvent.PlayerDidJump:
gameStateDelegate?.jumpActionReceived(parsedData["data"], peer: peerID)
case GameEvent.PlayerDidDuck:
gameStateDelegate?.duckActionReceived(parsedData["data"], peer: peerID)
case GameEvent.PlayerDidCollide:
gameStateDelegate?.collideActionReceived(parsedData["data"], peer: peerID)
case GameEvent.FloatingObstacleGenerated:
gameStateDelegate?.floatingObstacleReceived(parsedData["data"], peer: peerID)
case GameEvent.NonFloatingObstacleGenerated:
gameStateDelegate?.nonfloatingObstacleReceived(parsedData["data"], peer: peerID)
default:
break
}
}
}
}
| mit | 9a3811e770a9e338b8e7822c9c822948 | 37.375 | 186 | 0.671887 | 4.692534 | false | false | false | false |
glock45/swifter | Sources/Swifter/Scopes.swift | 1 | 32265 | //
// HttpHandlers+Scopes.swift
// Swifter
//
// Copyright © 2014-2016 Damian Kołakowski. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Foundation
#endif
public func scopes(_ scope: @escaping Closure) -> ((HttpRequest) -> HttpResponse) {
return { r in
ScopesBuffer[Process.tid] = ""
scope()
return .raw(200, "OK", ["Content-Type": "text/html"], {
try? $0.write([UInt8](("<!DOCTYPE html>" + (ScopesBuffer[Process.tid] ?? "")).utf8))
})
}
}
public typealias Closure = (Void) -> Void
public var idd: String? = nil
public var dir: String? = nil
public var rel: String? = nil
public var rev: String? = nil
public var alt: String? = nil
public var forr: String? = nil
public var src: String? = nil
public var type: String? = nil
public var href: String? = nil
public var text: String? = nil
public var abbr: String? = nil
public var size: String? = nil
public var face: String? = nil
public var char: String? = nil
public var cite: String? = nil
public var span: String? = nil
public var data: String? = nil
public var axis: String? = nil
public var Name: String? = nil
public var name: String? = nil
public var code: String? = nil
public var link: String? = nil
public var lang: String? = nil
public var cols: String? = nil
public var rows: String? = nil
public var ismap: String? = nil
public var shape: String? = nil
public var style: String? = nil
public var alink: String? = nil
public var width: String? = nil
public var rules: String? = nil
public var align: String? = nil
public var frame: String? = nil
public var vlink: String? = nil
public var deferr: String? = nil
public var color: String? = nil
public var media: String? = nil
public var title: String? = nil
public var scope: String? = nil
public var classs: String? = nil
public var value: String? = nil
public var clear: String? = nil
public var start: String? = nil
public var label: String? = nil
public var action: String? = nil
public var height: String? = nil
public var method: String? = nil
public var acceptt: String? = nil
public var object: String? = nil
public var scheme: String? = nil
public var coords: String? = nil
public var usemap: String? = nil
public var onblur: String? = nil
public var nohref: String? = nil
public var nowrap: String? = nil
public var hspace: String? = nil
public var border: String? = nil
public var valign: String? = nil
public var vspace: String? = nil
public var onload: String? = nil
public var target: String? = nil
public var prompt: String? = nil
public var onfocus: String? = nil
public var enctype: String? = nil
public var onclick: String? = nil
public var onkeyup: String? = nil
public var profile: String? = nil
public var version: String? = nil
public var onreset: String? = nil
public var charset: String? = nil
public var standby: String? = nil
public var colspan: String? = nil
public var charoff: String? = nil
public var classid: String? = nil
public var compact: String? = nil
public var declare: String? = nil
public var rowspan: String? = nil
public var checked: String? = nil
public var archive: String? = nil
public var bgcolor: String? = nil
public var content: String? = nil
public var noshade: String? = nil
public var summary: String? = nil
public var headers: String? = nil
public var onselect: String? = nil
public var readonly: String? = nil
public var tabindex: String? = nil
public var onchange: String? = nil
public var noresize: String? = nil
public var disabled: String? = nil
public var longdesc: String? = nil
public var codebase: String? = nil
public var language: String? = nil
public var datetime: String? = nil
public var selected: String? = nil
public var hreflang: String? = nil
public var onsubmit: String? = nil
public var multiple: String? = nil
public var onunload: String? = nil
public var codetype: String? = nil
public var scrolling: String? = nil
public var onkeydown: String? = nil
public var maxlength: String? = nil
public var valuetype: String? = nil
public var accesskey: String? = nil
public var onmouseup: String? = nil
public var autofocus: String? = nil
public var onkeypress: String? = nil
public var ondblclick: String? = nil
public var onmouseout: String? = nil
public var httpEquiv: String? = nil
public var background: String? = nil
public var onmousemove: String? = nil
public var onmouseover: String? = nil
public var cellpadding: String? = nil
public var onmousedown: String? = nil
public var frameborder: String? = nil
public var marginwidth: String? = nil
public var cellspacing: String? = nil
public var placeholder: String? = nil
public var marginheight: String? = nil
public var acceptCharset: String? = nil
public var inner: String? = nil
public func a(_ c: Closure) { element("a", c) }
public func b(_ c: Closure) { element("b", c) }
public func i(_ c: Closure) { element("i", c) }
public func p(_ c: Closure) { element("p", c) }
public func q(_ c: Closure) { element("q", c) }
public func s(_ c: Closure) { element("s", c) }
public func u(_ c: Closure) { element("u", c) }
public func br(_ c: Closure) { element("br", c) }
public func dd(_ c: Closure) { element("dd", c) }
public func dl(_ c: Closure) { element("dl", c) }
public func dt(_ c: Closure) { element("dt", c) }
public func em(_ c: Closure) { element("em", c) }
public func hr(_ c: Closure) { element("hr", c) }
public func li(_ c: Closure) { element("li", c) }
public func ol(_ c: Closure) { element("ol", c) }
public func rp(_ c: Closure) { element("rp", c) }
public func rt(_ c: Closure) { element("rt", c) }
public func td(_ c: Closure) { element("td", c) }
public func th(_ c: Closure) { element("th", c) }
public func tr(_ c: Closure) { element("tr", c) }
public func tt(_ c: Closure) { element("tt", c) }
public func ul(_ c: Closure) { element("ul", c) }
public func ul<T: Sequence>(_ collection: T, _ c: @escaping (T.Iterator.Element) -> Void) {
element("ul", {
for item in collection {
c(item)
}
})
}
public func h1(_ c: Closure) { element("h1", c) }
public func h2(_ c: Closure) { element("h2", c) }
public func h3(_ c: Closure) { element("h3", c) }
public func h4(_ c: Closure) { element("h4", c) }
public func h5(_ c: Closure) { element("h5", c) }
public func h6(_ c: Closure) { element("h6", c) }
public func bdi(_ c: Closure) { element("bdi", c) }
public func bdo(_ c: Closure) { element("bdo", c) }
public func big(_ c: Closure) { element("big", c) }
public func col(_ c: Closure) { element("col", c) }
public func del(_ c: Closure) { element("del", c) }
public func dfn(_ c: Closure) { element("dfn", c) }
public func dir(_ c: Closure) { element("dir", c) }
public func div(_ c: Closure) { element("div", c) }
public func img(_ c: Closure) { element("img", c) }
public func ins(_ c: Closure) { element("ins", c) }
public func kbd(_ c: Closure) { element("kbd", c) }
public func map(_ c: Closure) { element("map", c) }
public func nav(_ c: Closure) { element("nav", c) }
public func pre(_ c: Closure) { element("pre", c) }
public func rtc(_ c: Closure) { element("rtc", c) }
public func sub(_ c: Closure) { element("sub", c) }
public func sup(_ c: Closure) { element("sup", c) }
public func varr(_ c: Closure) { element("var", c) }
public func wbr(_ c: Closure) { element("wbr", c) }
public func xmp(_ c: Closure) { element("xmp", c) }
public func abbr(_ c: Closure) { element("abbr", c) }
public func area(_ c: Closure) { element("area", c) }
public func base(_ c: Closure) { element("base", c) }
public func body(_ c: Closure) { element("body", c) }
public func cite(_ c: Closure) { element("cite", c) }
public func code(_ c: Closure) { element("code", c) }
public func data(_ c: Closure) { element("data", c) }
public func font(_ c: Closure) { element("font", c) }
public func form(_ c: Closure) { element("form", c) }
public func head(_ c: Closure) { element("head", c) }
public func html(_ c: Closure) { element("html", c) }
public func link(_ c: Closure) { element("link", c) }
public func main(_ c: Closure) { element("main", c) }
public func mark(_ c: Closure) { element("mark", c) }
public func menu(_ c: Closure) { element("menu", c) }
public func meta(_ c: Closure) { element("meta", c) }
public func nobr(_ c: Closure) { element("nobr", c) }
public func ruby(_ c: Closure) { element("ruby", c) }
public func samp(_ c: Closure) { element("samp", c) }
public func span(_ c: Closure) { element("span", c) }
public func time(_ c: Closure) { element("time", c) }
public func aside(_ c: Closure) { element("aside", c) }
public func audio(_ c: Closure) { element("audio", c) }
public func blink(_ c: Closure) { element("blink", c) }
public func embed(_ c: Closure) { element("embed", c) }
public func frame(_ c: Closure) { element("frame", c) }
public func image(_ c: Closure) { element("image", c) }
public func input(_ c: Closure) { element("input", c) }
public func label(_ c: Closure) { element("label", c) }
public func meter(_ c: Closure) { element("meter", c) }
public func param(_ c: Closure) { element("param", c) }
public func small(_ c: Closure) { element("small", c) }
public func style(_ c: Closure) { element("style", c) }
public func table(_ c: Closure) { element("table", c) }
public func table<T: Sequence>(_ collection: T, c: @escaping (T.Iterator.Element) -> Void) {
element("table", {
for item in collection {
c(item)
}
})
}
public func tbody(_ c: Closure) { element("tbody", c) }
public func tbody<T: Sequence>(_ collection: T, c: @escaping (T.Iterator.Element) -> Void) {
element("tbody", {
for item in collection {
c(item)
}
})
}
public func tfoot(_ c: Closure) { element("tfoot", c) }
public func thead(_ c: Closure) { element("thead", c) }
public func title(_ c: Closure) { element("title", c) }
public func track(_ c: Closure) { element("track", c) }
public func video(_ c: Closure) { element("video", c) }
public func applet(_ c: Closure) { element("applet", c) }
public func button(_ c: Closure) { element("button", c) }
public func canvas(_ c: Closure) { element("canvas", c) }
public func center(_ c: Closure) { element("center", c) }
public func dialog(_ c: Closure) { element("dialog", c) }
public func figure(_ c: Closure) { element("figure", c) }
public func footer(_ c: Closure) { element("footer", c) }
public func header(_ c: Closure) { element("header", c) }
public func hgroup(_ c: Closure) { element("hgroup", c) }
public func iframe(_ c: Closure) { element("iframe", c) }
public func keygen(_ c: Closure) { element("keygen", c) }
public func legend(_ c: Closure) { element("legend", c) }
public func object(_ c: Closure) { element("object", c) }
public func option(_ c: Closure) { element("option", c) }
public func output(_ c: Closure) { element("output", c) }
public func script(_ c: Closure) { element("script", c) }
public func select(_ c: Closure) { element("select", c) }
public func shadow(_ c: Closure) { element("shadow", c) }
public func source(_ c: Closure) { element("source", c) }
public func spacer(_ c: Closure) { element("spacer", c) }
public func strike(_ c: Closure) { element("strike", c) }
public func strong(_ c: Closure) { element("strong", c) }
public func acronym(_ c: Closure) { element("acronym", c) }
public func address(_ c: Closure) { element("address", c) }
public func article(_ c: Closure) { element("article", c) }
public func bgsound(_ c: Closure) { element("bgsound", c) }
public func caption(_ c: Closure) { element("caption", c) }
public func command(_ c: Closure) { element("command", c) }
public func content(_ c: Closure) { element("content", c) }
public func details(_ c: Closure) { element("details", c) }
public func elementt(_ c: Closure) { element("element", c) }
public func isindex(_ c: Closure) { element("isindex", c) }
public func listing(_ c: Closure) { element("listing", c) }
public func marquee(_ c: Closure) { element("marquee", c) }
public func noembed(_ c: Closure) { element("noembed", c) }
public func picture(_ c: Closure) { element("picture", c) }
public func section(_ c: Closure) { element("section", c) }
public func summary(_ c: Closure) { element("summary", c) }
public func basefont(_ c: Closure) { element("basefont", c) }
public func colgroup(_ c: Closure) { element("colgroup", c) }
public func datalist(_ c: Closure) { element("datalist", c) }
public func fieldset(_ c: Closure) { element("fieldset", c) }
public func frameset(_ c: Closure) { element("frameset", c) }
public func menuitem(_ c: Closure) { element("menuitem", c) }
public func multicol(_ c: Closure) { element("multicol", c) }
public func noframes(_ c: Closure) { element("noframes", c) }
public func noscript(_ c: Closure) { element("noscript", c) }
public func optgroup(_ c: Closure) { element("optgroup", c) }
public func progress(_ c: Closure) { element("progress", c) }
public func template(_ c: Closure) { element("template", c) }
public func textarea(_ c: Closure) { element("textarea", c) }
public func plaintext(_ c: Closure) { element("plaintext", c) }
public func javascript(_ c: Closure) { element("script", ["type": "text/javascript"], c) }
public func blockquote(_ c: Closure) { element("blockquote", c) }
public func figcaption(_ c: Closure) { element("figcaption", c) }
public func stylesheet(_ c: Closure) { element("link", ["rel": "stylesheet", "type": "text/css"], c) }
public func element(_ node: String, _ c: Closure) { evaluate(node, [:], c) }
public func element(_ node: String, _ attrs: [String: String?] = [:], _ c: Closure) { evaluate(node, attrs, c) }
var ScopesBuffer = [UInt64: String]()
private func evaluate(_ node: String, _ attrs: [String: String?] = [:], _ c: Closure) {
// Push the attributes.
let stackid = idd
let stackdir = dir
let stackrel = rel
let stackrev = rev
let stackalt = alt
let stackfor = forr
let stacksrc = src
let stacktype = type
let stackhref = href
let stacktext = text
let stackabbr = abbr
let stacksize = size
let stackface = face
let stackchar = char
let stackcite = cite
let stackspan = span
let stackdata = data
let stackaxis = axis
let stackName = Name
let stackname = name
let stackcode = code
let stacklink = link
let stacklang = lang
let stackcols = cols
let stackrows = rows
let stackismap = ismap
let stackshape = shape
let stackstyle = style
let stackalink = alink
let stackwidth = width
let stackrules = rules
let stackalign = align
let stackframe = frame
let stackvlink = vlink
let stackdefer = deferr
let stackcolor = color
let stackmedia = media
let stacktitle = title
let stackscope = scope
let stackclass = classs
let stackvalue = value
let stackclear = clear
let stackstart = start
let stacklabel = label
let stackaction = action
let stackheight = height
let stackmethod = method
let stackaccept = acceptt
let stackobject = object
let stackscheme = scheme
let stackcoords = coords
let stackusemap = usemap
let stackonblur = onblur
let stacknohref = nohref
let stacknowrap = nowrap
let stackhspace = hspace
let stackborder = border
let stackvalign = valign
let stackvspace = vspace
let stackonload = onload
let stacktarget = target
let stackprompt = prompt
let stackonfocus = onfocus
let stackenctype = enctype
let stackonclick = onclick
let stackonkeyup = onkeyup
let stackprofile = profile
let stackversion = version
let stackonreset = onreset
let stackcharset = charset
let stackstandby = standby
let stackcolspan = colspan
let stackcharoff = charoff
let stackclassid = classid
let stackcompact = compact
let stackdeclare = declare
let stackrowspan = rowspan
let stackchecked = checked
let stackarchive = archive
let stackbgcolor = bgcolor
let stackcontent = content
let stacknoshade = noshade
let stacksummary = summary
let stackheaders = headers
let stackonselect = onselect
let stackreadonly = readonly
let stacktabindex = tabindex
let stackonchange = onchange
let stacknoresize = noresize
let stackdisabled = disabled
let stacklongdesc = longdesc
let stackcodebase = codebase
let stacklanguage = language
let stackdatetime = datetime
let stackselected = selected
let stackhreflang = hreflang
let stackonsubmit = onsubmit
let stackmultiple = multiple
let stackonunload = onunload
let stackcodetype = codetype
let stackscrolling = scrolling
let stackonkeydown = onkeydown
let stackmaxlength = maxlength
let stackvaluetype = valuetype
let stackaccesskey = accesskey
let stackonmouseup = onmouseup
let stackonkeypress = onkeypress
let stackondblclick = ondblclick
let stackonmouseout = onmouseout
let stackhttpEquiv = httpEquiv
let stackbackground = background
let stackonmousemove = onmousemove
let stackonmouseover = onmouseover
let stackcellpadding = cellpadding
let stackonmousedown = onmousedown
let stackframeborder = frameborder
let stackmarginwidth = marginwidth
let stackcellspacing = cellspacing
let stackplaceholder = placeholder
let stackmarginheight = marginheight
let stackacceptCharset = acceptCharset
let stackinner = inner
// Reset the values before a nested scope evalutation.
idd = nil
dir = nil
rel = nil
rev = nil
alt = nil
forr = nil
src = nil
type = nil
href = nil
text = nil
abbr = nil
size = nil
face = nil
char = nil
cite = nil
span = nil
data = nil
axis = nil
Name = nil
name = nil
code = nil
link = nil
lang = nil
cols = nil
rows = nil
ismap = nil
shape = nil
style = nil
alink = nil
width = nil
rules = nil
align = nil
frame = nil
vlink = nil
deferr = nil
color = nil
media = nil
title = nil
scope = nil
classs = nil
value = nil
clear = nil
start = nil
label = nil
action = nil
height = nil
method = nil
acceptt = nil
object = nil
scheme = nil
coords = nil
usemap = nil
onblur = nil
nohref = nil
nowrap = nil
hspace = nil
border = nil
valign = nil
vspace = nil
onload = nil
target = nil
prompt = nil
onfocus = nil
enctype = nil
onclick = nil
onkeyup = nil
profile = nil
version = nil
onreset = nil
charset = nil
standby = nil
colspan = nil
charoff = nil
classid = nil
compact = nil
declare = nil
rowspan = nil
checked = nil
archive = nil
bgcolor = nil
content = nil
noshade = nil
summary = nil
headers = nil
onselect = nil
readonly = nil
tabindex = nil
onchange = nil
noresize = nil
disabled = nil
longdesc = nil
codebase = nil
language = nil
datetime = nil
selected = nil
hreflang = nil
onsubmit = nil
multiple = nil
onunload = nil
codetype = nil
scrolling = nil
onkeydown = nil
maxlength = nil
valuetype = nil
accesskey = nil
onmouseup = nil
onkeypress = nil
ondblclick = nil
onmouseout = nil
httpEquiv = nil
background = nil
onmousemove = nil
onmouseover = nil
cellpadding = nil
onmousedown = nil
frameborder = nil
placeholder = nil
marginwidth = nil
cellspacing = nil
marginheight = nil
acceptCharset = nil
inner = nil
ScopesBuffer[Process.tid] = (ScopesBuffer[Process.tid] ?? "") + "<" + node
// Save the current output before the nested scope evalutation.
var output = ScopesBuffer[Process.tid] ?? ""
// Clear the output buffer for the evalutation.
ScopesBuffer[Process.tid] = ""
// Evaluate the nested scope.
c()
// Render attributes set by the evalutation.
var mergedAttributes = [String: String?]()
if let idd = idd { mergedAttributes["id"] = idd }
if let dir = dir { mergedAttributes["dir"] = dir }
if let rel = rel { mergedAttributes["rel"] = rel }
if let rev = rev { mergedAttributes["rev"] = rev }
if let alt = alt { mergedAttributes["alt"] = alt }
if let forr = forr { mergedAttributes["for"] = forr }
if let src = src { mergedAttributes["src"] = src }
if let type = type { mergedAttributes["type"] = type }
if let href = href { mergedAttributes["href"] = href }
if let text = text { mergedAttributes["text"] = text }
if let abbr = abbr { mergedAttributes["abbr"] = abbr }
if let size = size { mergedAttributes["size"] = size }
if let face = face { mergedAttributes["face"] = face }
if let char = char { mergedAttributes["char"] = char }
if let cite = cite { mergedAttributes["cite"] = cite }
if let span = span { mergedAttributes["span"] = span }
if let data = data { mergedAttributes["data"] = data }
if let axis = axis { mergedAttributes["axis"] = axis }
if let Name = Name { mergedAttributes["Name"] = Name }
if let name = name { mergedAttributes["name"] = name }
if let code = code { mergedAttributes["code"] = code }
if let link = link { mergedAttributes["link"] = link }
if let lang = lang { mergedAttributes["lang"] = lang }
if let cols = cols { mergedAttributes["cols"] = cols }
if let rows = rows { mergedAttributes["rows"] = rows }
if let ismap = ismap { mergedAttributes["ismap"] = ismap }
if let shape = shape { mergedAttributes["shape"] = shape }
if let style = style { mergedAttributes["style"] = style }
if let alink = alink { mergedAttributes["alink"] = alink }
if let width = width { mergedAttributes["width"] = width }
if let rules = rules { mergedAttributes["rules"] = rules }
if let align = align { mergedAttributes["align"] = align }
if let frame = frame { mergedAttributes["frame"] = frame }
if let vlink = vlink { mergedAttributes["vlink"] = vlink }
if let deferr = deferr { mergedAttributes["defer"] = deferr }
if let color = color { mergedAttributes["color"] = color }
if let media = media { mergedAttributes["media"] = media }
if let title = title { mergedAttributes["title"] = title }
if let scope = scope { mergedAttributes["scope"] = scope }
if let classs = classs { mergedAttributes["class"] = classs }
if let value = value { mergedAttributes["value"] = value }
if let clear = clear { mergedAttributes["clear"] = clear }
if let start = start { mergedAttributes["start"] = start }
if let label = label { mergedAttributes["label"] = label }
if let action = action { mergedAttributes["action"] = action }
if let height = height { mergedAttributes["height"] = height }
if let method = method { mergedAttributes["method"] = method }
if let acceptt = acceptt { mergedAttributes["accept"] = acceptt }
if let object = object { mergedAttributes["object"] = object }
if let scheme = scheme { mergedAttributes["scheme"] = scheme }
if let coords = coords { mergedAttributes["coords"] = coords }
if let usemap = usemap { mergedAttributes["usemap"] = usemap }
if let onblur = onblur { mergedAttributes["onblur"] = onblur }
if let nohref = nohref { mergedAttributes["nohref"] = nohref }
if let nowrap = nowrap { mergedAttributes["nowrap"] = nowrap }
if let hspace = hspace { mergedAttributes["hspace"] = hspace }
if let border = border { mergedAttributes["border"] = border }
if let valign = valign { mergedAttributes["valign"] = valign }
if let vspace = vspace { mergedAttributes["vspace"] = vspace }
if let onload = onload { mergedAttributes["onload"] = onload }
if let target = target { mergedAttributes["target"] = target }
if let prompt = prompt { mergedAttributes["prompt"] = prompt }
if let onfocus = onfocus { mergedAttributes["onfocus"] = onfocus }
if let enctype = enctype { mergedAttributes["enctype"] = enctype }
if let onclick = onclick { mergedAttributes["onclick"] = onclick }
if let onkeyup = onkeyup { mergedAttributes["onkeyup"] = onkeyup }
if let profile = profile { mergedAttributes["profile"] = profile }
if let version = version { mergedAttributes["version"] = version }
if let onreset = onreset { mergedAttributes["onreset"] = onreset }
if let charset = charset { mergedAttributes["charset"] = charset }
if let standby = standby { mergedAttributes["standby"] = standby }
if let colspan = colspan { mergedAttributes["colspan"] = colspan }
if let charoff = charoff { mergedAttributes["charoff"] = charoff }
if let classid = classid { mergedAttributes["classid"] = classid }
if let compact = compact { mergedAttributes["compact"] = compact }
if let declare = declare { mergedAttributes["declare"] = declare }
if let rowspan = rowspan { mergedAttributes["rowspan"] = rowspan }
if let checked = checked { mergedAttributes["checked"] = checked }
if let archive = archive { mergedAttributes["archive"] = archive }
if let bgcolor = bgcolor { mergedAttributes["bgcolor"] = bgcolor }
if let content = content { mergedAttributes["content"] = content }
if let noshade = noshade { mergedAttributes["noshade"] = noshade }
if let summary = summary { mergedAttributes["summary"] = summary }
if let headers = headers { mergedAttributes["headers"] = headers }
if let onselect = onselect { mergedAttributes["onselect"] = onselect }
if let readonly = readonly { mergedAttributes["readonly"] = readonly }
if let tabindex = tabindex { mergedAttributes["tabindex"] = tabindex }
if let onchange = onchange { mergedAttributes["onchange"] = onchange }
if let noresize = noresize { mergedAttributes["noresize"] = noresize }
if let disabled = disabled { mergedAttributes["disabled"] = disabled }
if let longdesc = longdesc { mergedAttributes["longdesc"] = longdesc }
if let codebase = codebase { mergedAttributes["codebase"] = codebase }
if let language = language { mergedAttributes["language"] = language }
if let datetime = datetime { mergedAttributes["datetime"] = datetime }
if let selected = selected { mergedAttributes["selected"] = selected }
if let hreflang = hreflang { mergedAttributes["hreflang"] = hreflang }
if let onsubmit = onsubmit { mergedAttributes["onsubmit"] = onsubmit }
if let multiple = multiple { mergedAttributes["multiple"] = multiple }
if let onunload = onunload { mergedAttributes["onunload"] = onunload }
if let codetype = codetype { mergedAttributes["codetype"] = codetype }
if let scrolling = scrolling { mergedAttributes["scrolling"] = scrolling }
if let onkeydown = onkeydown { mergedAttributes["onkeydown"] = onkeydown }
if let maxlength = maxlength { mergedAttributes["maxlength"] = maxlength }
if let valuetype = valuetype { mergedAttributes["valuetype"] = valuetype }
if let accesskey = accesskey { mergedAttributes["accesskey"] = accesskey }
if let onmouseup = onmouseup { mergedAttributes["onmouseup"] = onmouseup }
if let onkeypress = onkeypress { mergedAttributes["onkeypress"] = onkeypress }
if let ondblclick = ondblclick { mergedAttributes["ondblclick"] = ondblclick }
if let onmouseout = onmouseout { mergedAttributes["onmouseout"] = onmouseout }
if let httpEquiv = httpEquiv { mergedAttributes["http-equiv"] = httpEquiv }
if let background = background { mergedAttributes["background"] = background }
if let onmousemove = onmousemove { mergedAttributes["onmousemove"] = onmousemove }
if let onmouseover = onmouseover { mergedAttributes["onmouseover"] = onmouseover }
if let cellpadding = cellpadding { mergedAttributes["cellpadding"] = cellpadding }
if let onmousedown = onmousedown { mergedAttributes["onmousedown"] = onmousedown }
if let frameborder = frameborder { mergedAttributes["frameborder"] = frameborder }
if let marginwidth = marginwidth { mergedAttributes["marginwidth"] = marginwidth }
if let cellspacing = cellspacing { mergedAttributes["cellspacing"] = cellspacing }
if let placeholder = placeholder { mergedAttributes["placeholder"] = placeholder }
if let marginheight = marginheight { mergedAttributes["marginheight"] = marginheight }
if let acceptCharset = acceptCharset { mergedAttributes["accept-charset"] = acceptCharset }
for item in attrs.enumerated() {
mergedAttributes.updateValue(item.element.1, forKey: item.element.0)
}
output = output + mergedAttributes.reduce("") {
if let value = $0.1.1 {
return $0.0 + " \($0.1.0)=\"\(value)\""
} else {
return $0.0
}
}
if let inner = inner {
ScopesBuffer[Process.tid] = output + ">" + (inner) + "</" + node + ">"
} else {
let current = ScopesBuffer[Process.tid] ?? ""
ScopesBuffer[Process.tid] = output + ">" + current + "</" + node + ">"
}
// Pop the attributes.
idd = stackid
dir = stackdir
rel = stackrel
rev = stackrev
alt = stackalt
forr = stackfor
src = stacksrc
type = stacktype
href = stackhref
text = stacktext
abbr = stackabbr
size = stacksize
face = stackface
char = stackchar
cite = stackcite
span = stackspan
data = stackdata
axis = stackaxis
Name = stackName
name = stackname
code = stackcode
link = stacklink
lang = stacklang
cols = stackcols
rows = stackrows
ismap = stackismap
shape = stackshape
style = stackstyle
alink = stackalink
width = stackwidth
rules = stackrules
align = stackalign
frame = stackframe
vlink = stackvlink
deferr = stackdefer
color = stackcolor
media = stackmedia
title = stacktitle
scope = stackscope
classs = stackclass
value = stackvalue
clear = stackclear
start = stackstart
label = stacklabel
action = stackaction
height = stackheight
method = stackmethod
acceptt = stackaccept
object = stackobject
scheme = stackscheme
coords = stackcoords
usemap = stackusemap
onblur = stackonblur
nohref = stacknohref
nowrap = stacknowrap
hspace = stackhspace
border = stackborder
valign = stackvalign
vspace = stackvspace
onload = stackonload
target = stacktarget
prompt = stackprompt
onfocus = stackonfocus
enctype = stackenctype
onclick = stackonclick
onkeyup = stackonkeyup
profile = stackprofile
version = stackversion
onreset = stackonreset
charset = stackcharset
standby = stackstandby
colspan = stackcolspan
charoff = stackcharoff
classid = stackclassid
compact = stackcompact
declare = stackdeclare
rowspan = stackrowspan
checked = stackchecked
archive = stackarchive
bgcolor = stackbgcolor
content = stackcontent
noshade = stacknoshade
summary = stacksummary
headers = stackheaders
onselect = stackonselect
readonly = stackreadonly
tabindex = stacktabindex
onchange = stackonchange
noresize = stacknoresize
disabled = stackdisabled
longdesc = stacklongdesc
codebase = stackcodebase
language = stacklanguage
datetime = stackdatetime
selected = stackselected
hreflang = stackhreflang
onsubmit = stackonsubmit
multiple = stackmultiple
onunload = stackonunload
codetype = stackcodetype
scrolling = stackscrolling
onkeydown = stackonkeydown
maxlength = stackmaxlength
valuetype = stackvaluetype
accesskey = stackaccesskey
onmouseup = stackonmouseup
onkeypress = stackonkeypress
ondblclick = stackondblclick
onmouseout = stackonmouseout
httpEquiv = stackhttpEquiv
background = stackbackground
onmousemove = stackonmousemove
onmouseover = stackonmouseover
cellpadding = stackcellpadding
onmousedown = stackonmousedown
frameborder = stackframeborder
placeholder = stackplaceholder
marginwidth = stackmarginwidth
cellspacing = stackcellspacing
marginheight = stackmarginheight
acceptCharset = stackacceptCharset
inner = stackinner
}
| bsd-3-clause | 561a19be47ca9457631660c96d756124 | 35.914188 | 112 | 0.660912 | 4.043489 | false | false | false | false |
aleufms/JeraUtils | JeraUtils/HUD/HudManager.swift | 1 | 4876 | //
// HudManager.swift
// Jera
//
// Created by Alessandro Nakamuta on 9/16/15.
// Copyright © 2015 Jera. All rights reserved.
//
import UIKit
import RxSwift
struct Hud {
let customView: UIView
let dismissAfter: Double?
let userInteractionEnabled: Bool
let customLayout: ((containerView: UIView, customView: UIView) -> ())?
}
public class HudManager {
public static var sharedManager = HudManager()
private var hudWindow: UIWindow?
private var currentView: UIView?
private var viewQueue = [Hud]()
/**
Shows a custom view popup
- parameter customView: The view to be shown
- parameter dismissAfter: Seconds before the view is dismissed. If nil the dismissing should be handled by your code.
- parameter userInteractionEnabled: Whether the user can interact with the view or not. Set true by default.
- parameter customLayout: A block with a custom container view and a custom view with their constrains and layout alreay set. By default it will layout in the middle of the screen.
*/
public func showCustomView(customView: UIView, dismissAfter: Double? = nil, userInteractionEnabled: Bool = true, customLayout: ((containerView: UIView, customView: UIView) -> ())? = nil) {
if hudWindow == nil {
hudWindow = UIWindow(frame: UIScreen.mainScreen().bounds)
if let hudWindow = hudWindow {
currentView = customView
let hudViewController = HudViewController()
if let customLayout = customLayout {
hudViewController.customViewLayout = customLayout
}
hudViewController.customView = customView
hudWindow.userInteractionEnabled = userInteractionEnabled
hudWindow.rootViewController = hudViewController
hudWindow.windowLevel = UIWindowLevelAlert + 1
hudWindow.makeKeyAndVisible()
//Animation
customView.transform = CGAffineTransformMakeScale(0.8, 0.8)
let initialHudAlpha = customView.alpha
customView.alpha = 0
hudViewController.view.backgroundColor = UIColor(white: 0, alpha: 0)
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: [], animations: { () -> Void in
if userInteractionEnabled {
hudViewController.view.backgroundColor = UIColor(white: 0, alpha: 0.5)
}
customView.alpha = initialHudAlpha
customView.transform = CGAffineTransformIdentity
}, completion: nil)
if let dismissAfter = dismissAfter {
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(dismissAfter * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) { [weak self] in
self?.dismissHudView(customView)
}
}
}
} else {
viewQueue.append(Hud(customView: customView, dismissAfter: dismissAfter, userInteractionEnabled: userInteractionEnabled, customLayout: customLayout))
}
}
/**
Dismiss a view being or about to be shown by the HUDManager
- parameter hudView: The view to be dismissed
*/
public func dismissHudView(hudView: UIView?) {
guard let hudView = hudView else {
return
}
if hudView == currentView {
dismissCurrentView()
} else {
if let customViewIndex = viewQueue.map({ return $0.customView }).indexOf(hudView) {
viewQueue.removeAtIndex(customViewIndex)
}
}
}
public func dismissCurrentView(completion: ((finished: Bool) -> Void)? = nil) {
if let hudWindow = hudWindow {
UIView.animateWithDuration(0.25, animations: { () -> Void in
hudWindow.alpha = 0
}, completion: { [weak self] (finished) -> Void in
if let strongSelf = self {
hudWindow.resignKeyWindow()
strongSelf.hudWindow = nil
if let hudToPresent = strongSelf.viewQueue.first {
strongSelf.showCustomView(hudToPresent.customView, dismissAfter: hudToPresent.dismissAfter, userInteractionEnabled: hudToPresent.userInteractionEnabled, customLayout: hudToPresent.customLayout)
strongSelf.viewQueue.removeAtIndex(0)
}
completion?(finished: finished)
}
})
}
}
public func dismissAllAlerts() {
viewQueue = []
dismissCurrentView()
}
}
| mit | daa941642e1e546de9934aa23c3d820d | 38.314516 | 221 | 0.598359 | 5.459127 | false | false | false | false |
wayfair/brickkit-ios | Source/Models/BrickDimension.swift | 1 | 8389 | //
// BrickDimension.swift
// BrickKit
//
// Created by Ruben Cagnie on 9/20/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
import Foundation
public struct BrickSize {
public var width: BrickDimension
public var height: BrickDimension
public init(width: BrickDimension, height: BrickDimension) {
self.width = width
self.height = height
}
}
extension BrickSize: Equatable {
public static func ==(lhs: BrickSize, rhs: BrickSize) -> Bool {
return lhs.height == rhs.height && lhs.width == rhs.width
}
}
public enum RestrictedSize {
case minimumSize(size: BrickDimension)
case maximumSize(size: BrickDimension)
}
public typealias RangeDimensionPair = (dimension: BrickDimension, minimumSize: CGFloat)
public struct BrickRangeDimension {
internal var defaultPair : RangeDimensionPair
internal var additionalPairs : [RangeDimensionPair]
public init(default dimension: BrickDimension, additionalRangePairs: [RangeDimensionPair] = []) {
defaultPair = (dimension, 0)
additionalPairs = additionalRangePairs
}
public func dimension(forWidth width: CGFloat?) -> BrickDimension {
guard let width = width else {
return defaultPair.dimension
}
var dimension = defaultPair.dimension
for RangeDimensionPair in additionalPairs {
if RangeDimensionPair.minimumSize > width {
break
}
else {
dimension = RangeDimensionPair.dimension
}
}
return dimension
}
}
internal func almostEqualRelative(first: CGFloat, second: CGFloat, maxRelDiff: CGFloat = CGFloat.ulpOfOne) -> Bool
{
// Calculate the difference.
let diff = abs(first - second);
let a = abs(first)
let b = abs(second)
// Find the largest
let largest = (b > a) ? b : a
if diff <= largest * maxRelDiff {
return true
}
return false
}
public func ==(lhs: RangeDimensionPair, rhs: RangeDimensionPair) -> Bool {
return lhs.dimension == rhs.dimension && almostEqualRelative(first: lhs.minimumSize, second: rhs.minimumSize)
}
public func ==(lhs: BrickRangeDimension, rhs: BrickRangeDimension) -> Bool {
if lhs.additionalPairs.count != rhs.additionalPairs.count {
return false
}
if lhs.defaultPair != rhs.defaultPair {
return false
}
for (index, value) in lhs.additionalPairs.enumerated() {
if value != rhs.additionalPairs[index] {
return false
}
}
return true
}
public enum BrickDimension {
case ratio(ratio: CGFloat)
case fixed(size: CGFloat)
case fill
indirect case auto(estimate: BrickDimension)
indirect case orientation(landscape: BrickDimension, portrait: BrickDimension)
indirect case horizontalSizeClass(regular: BrickDimension, compact: BrickDimension)
indirect case verticalSizeClass(regular: BrickDimension, compact: BrickDimension)
indirect case dimensionRange(default: BrickDimension, additionalRangePairs: [RangeDimensionPair] )
indirect case restricted(size: BrickDimension, restrictedSize: RestrictedSize)
public func isEstimate(withValue value: CGFloat?) -> Bool {
switch self.dimension(withValue: value) {
case .auto(_): return true
case .restricted(let size, _): return size.isEstimate(withValue: value)
default: return false
}
}
func dimension(withValue value: CGFloat? = nil) -> BrickDimension {
switch self {
case .orientation(let landScape, let portrait):
return (BrickDimension.isPortrait ? portrait : landScape).dimension(withValue: value)
case .horizontalSizeClass(let regular, let compact):
let isRegular = BrickDimension.horizontalInterfaceSizeClass == .regular
return (isRegular ? regular : compact).dimension(withValue: value)
case .verticalSizeClass(let regular, let compact):
let isRegular = BrickDimension.verticalInterfaceSizeClass == .regular
return (isRegular ? regular : compact).dimension(withValue: value)
case .dimensionRange(let defaultValue, let additionalRanges):
return BrickRangeDimension(default: defaultValue, additionalRangePairs: additionalRanges).dimension(forWidth:value)
default: return self
}
}
func value(for otherDimension: CGFloat, startingAt origin: CGFloat) -> CGFloat {
let actualDimension = dimension(withValue: otherDimension)
switch actualDimension {
case .auto(let dimension): return dimension.value(for: otherDimension, startingAt: origin)
case .restricted(let size, _): return size.value(for: otherDimension, startingAt: origin)
default: return BrickDimension._rawValue(for: otherDimension, startingAt: origin, with: actualDimension)
}
}
func isRatio() -> Bool {
if case BrickDimension.ratio = self.dimension(withValue: nil) {
return true
}
return false
}
/// Function that gets the raw value of a BrickDimension. As of right now, only Ratio, Fixed and Fill are allowed
static func _rawValue(for otherDimension: CGFloat, startingAt origin: CGFloat, with dimension: BrickDimension) -> CGFloat {
switch dimension {
case .ratio(let ratio): return ratio * otherDimension
case .fixed(let size): return size
case .fill:
guard otherDimension > origin else {
// If the origin is bigger than the actual dimension, just return the whole dimension
return otherDimension
}
return otherDimension - origin
default: fatalError("Only Ratio, Fixed and Fill are allowed")
}
}
internal static func restrictedValue(for cellHeight: CGFloat, width: CGFloat, restrictedSize: RestrictedSize) -> CGFloat {
switch restrictedSize {
case .minimumSize(let minimumDimension):
return max(cellHeight, minimumDimension.dimension(withValue: cellHeight).value(for: width, startingAt: 0))
case .maximumSize(let maximumDimension):
return min(cellHeight, maximumDimension.dimension(withValue: cellHeight).value(for: width, startingAt: 0))
}
}
}
extension BrickDimension {
static var isPortrait: Bool {
return UIScreen.main.bounds.width <= UIScreen.main.bounds.height
}
static var horizontalInterfaceSizeClass: UIUserInterfaceSizeClass {
return UIScreen.main.traitCollection.horizontalSizeClass
}
static var verticalInterfaceSizeClass: UIUserInterfaceSizeClass {
return UIScreen.main.traitCollection.verticalSizeClass
}
}
extension BrickDimension: Equatable {
public static func ==(lhs: BrickDimension, rhs: BrickDimension) -> Bool {
switch (lhs, rhs) {
case (let .auto(estimate1), let .auto(estimate2)):
return estimate1 == estimate2
case (let .ratio(ratio1), let .ratio(ratio2)):
return ratio1 == ratio2
case (let .fixed(size1), let .fixed(size2)):
return size1 == size2
case (let .orientation(landscape1, portrait1), let .orientation(landscape2, portrait2)):
return landscape1 == landscape2 && portrait1 == portrait2
case (let .horizontalSizeClass(regular1, compact1), let .horizontalSizeClass(regular2, compact2)):
return regular1 == regular2 && compact1 == compact2
case (let .verticalSizeClass(regular1, compact1), let .verticalSizeClass(regular2, compact2)):
return regular1 == regular2 && compact1 == compact2
case (.fill, .fill):
return true
case (let .dimensionRange(range1, addtionalRanges1), let .dimensionRange(range2, addtionalRanges2)):
if range1 != range2 || addtionalRanges1.count != addtionalRanges2.count {
return false
}
for (index, value) in addtionalRanges1.enumerated() {
if addtionalRanges2[index] != value {
return false
}
}
return true
default:
return false
}
}
}
| apache-2.0 | 46cff826f2ea2a3c9178757d3da1827c | 35.469565 | 127 | 0.650691 | 4.83737 | false | false | false | false |
marklin2012/iOS_Animation | Section3/Chapter13/O2Multiplayer_challenge/O2Multiplayer/ViewController.swift | 1 | 2749 | //
// ViewController.swift
// O2Multiplayer
//
// Created by O2.LinYi on 16/3/17.
// Copyright © 2016年 jd.com. All rights reserved.
//
import UIKit
//
// Util delay function
//
func delay(seconds seconds: Double, completion:()->()) {
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( Double(NSEC_PER_SEC) * seconds ))
dispatch_after(popTime, dispatch_get_main_queue()) {
completion()
}
}
class ViewController: UIViewController {
@IBOutlet weak var myAvatar: AvatarView!
@IBOutlet weak var opponentAvatar: AvatarView!
@IBOutlet weak var status: UILabel!
@IBOutlet weak var vs: UILabel!
@IBOutlet weak var searchAgain: UIButton!
// MARK: - Life Cycle
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
searchForOpponent()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func actionSearchAgain() {
UIApplication.sharedApplication().keyWindow?.rootViewController = storyboard!.instantiateViewControllerWithIdentifier("ViewController") as UIViewController
}
// MARK: - further methods
func searchForOpponent() {
let avatarSize = myAvatar.frame.size
let bounceXOffset: CGFloat = avatarSize.width/1.9
let morphSize = CGSize(width: avatarSize.width * 0.85, height: avatarSize.height * 1.1)
let rightBouncePoint = CGPoint(x: view.frame.size.width/2.0 + bounceXOffset, y: myAvatar.center.y)
let leftBouncePoint = CGPoint(x: view.frame.size.width/2.0 - bounceXOffset, y: myAvatar.center.y)
myAvatar.bounceOffPoint(rightBouncePoint, morphSize: morphSize)
opponentAvatar.bounceOffPoint(leftBouncePoint, morphSize: morphSize)
delay(seconds: 4) { () -> () in
self.foundOpponent()
}
}
func foundOpponent() {
status.text = "Connectiong..."
opponentAvatar.image = UIImage(named: "avatar-2")
opponentAvatar.name = "Ray"
delay(seconds: 4) { () -> () in
self.connectedToOpponent()
}
}
func connectedToOpponent() {
myAvatar.shouldTransitionToFinishedState = true
opponentAvatar.shouldTransitionToFinishedState = true
delay(seconds: 1) { () -> () in
self.completed()
}
}
func completed() {
status.text = "Ready to play"
UIView.animateWithDuration(0.2, animations: { _ in
self.vs.alpha = 1
self.searchAgain.alpha = 1
})
}
}
| mit | 8ddff9035e172716af5bc38b62e83317 | 26.46 | 163 | 0.611435 | 4.414791 | false | false | false | false |
apple/swift-experimental-string-processing | Sources/_StringProcessing/Utility/ASTBuilder.swift | 1 | 12441 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 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
//
//===----------------------------------------------------------------------===//
/*
These functions are temporary AST construction helpers. As
the AST gets more and more source-location tracking, we'll
want easier migration paths for our parser tests (which
construct and compare location-less AST nodes) as well as the
result builder DSL (which has a different notion of location).
Without real namespaces and `using`, attempts at
pseudo-namespaces tie the use site to being nested inside a
type. So for now, these are global, but they will likely be
namespaced in the future if/when clients are weaned off the
AST.
*/
@_implementationOnly import _RegexParser
func alt(_ asts: [AST.Node]) -> AST.Node {
return .alternation(
.init(asts, pipes: Array(repeating: .fake, count: asts.count - 1))
)
}
func alt(_ asts: AST.Node...) -> AST.Node {
alt(asts)
}
func concat(_ asts: [AST.Node]) -> AST.Node {
.concatenation(.init(asts, .fake))
}
func concat(_ asts: AST.Node...) -> AST.Node {
concat(asts)
}
func empty() -> AST.Node {
.empty(.init(.fake))
}
func ast(_ root: AST.Node, opts: [AST.GlobalMatchingOption.Kind]) -> AST {
.init(root, globalOptions: .init(opts.map { .init($0, .fake) }), diags: Diagnostics())
}
func ast(_ root: AST.Node, opts: AST.GlobalMatchingOption.Kind...) -> AST {
ast(root, opts: opts)
}
func group(
_ kind: AST.Group.Kind, _ child: AST.Node
) -> AST.Node {
.group(.init(.init(faking: kind), child, .fake))
}
func capture(
_ child: AST.Node
) -> AST.Node {
group(.capture, child)
}
func nonCapture(
_ child: AST.Node
) -> AST.Node {
group(.nonCapture, child)
}
func namedCapture(
_ name: String,
_ child: AST.Node
) -> AST.Node {
group(.namedCapture(.init(faking: name)), child)
}
func balancedCapture(
name: String?, priorName: String, _ child: AST.Node
) -> AST.Node {
group(.balancedCapture(
.init(name: name.map { .init(faking: $0) }, dash: .fake,
priorName: .init(faking: priorName))
), child)
}
func nonCaptureReset(
_ child: AST.Node
) -> AST.Node {
group(.nonCaptureReset, child)
}
func atomicNonCapturing(
_ child: AST.Node
) -> AST.Node {
group(.atomicNonCapturing, child)
}
func lookahead(_ child: AST.Node) -> AST.Node {
group(.lookahead, child)
}
func lookbehind(_ child: AST.Node) -> AST.Node {
group(.lookbehind, child)
}
func negativeLookahead(_ child: AST.Node) -> AST.Node {
group(.negativeLookahead, child)
}
func negativeLookbehind(_ child: AST.Node) -> AST.Node {
group(.negativeLookbehind, child)
}
func nonAtomicLookahead(_ child: AST.Node) -> AST.Node {
group(.nonAtomicLookahead, child)
}
func nonAtomicLookbehind(_ child: AST.Node) -> AST.Node {
group(.nonAtomicLookbehind, child)
}
func scriptRun(_ child: AST.Node) -> AST.Node {
group(.scriptRun, child)
}
func atomicScriptRun(_ child: AST.Node) -> AST.Node {
group(.atomicScriptRun, child)
}
func changeMatchingOptions(
_ seq: AST.MatchingOptionSequence, _ child: AST.Node
) -> AST.Node {
group(.changeMatchingOptions(seq), child)
}
func changeMatchingOptions(
_ seq: AST.MatchingOptionSequence
) -> AST.Node {
atom(.changeMatchingOptions(seq))
}
func matchingOptions(
adding: [AST.MatchingOption.Kind] = [],
removing: [AST.MatchingOption.Kind] = []
) -> AST.MatchingOptionSequence {
.init(caretLoc: nil, adding: adding.map { .init($0, location: .fake) },
minusLoc: nil, removing: removing.map { .init($0, location: .fake)})
}
func matchingOptions(
adding: AST.MatchingOption.Kind...,
removing: AST.MatchingOption.Kind...
) -> AST.MatchingOptionSequence {
matchingOptions(adding: adding, removing: removing)
}
func unsetMatchingOptions(
adding: [AST.MatchingOption.Kind]
) -> AST.MatchingOptionSequence {
.init(caretLoc: .fake, adding: adding.map { .init($0, location: .fake) },
minusLoc: nil, removing: [])
}
func unsetMatchingOptions(
adding: AST.MatchingOption.Kind...
) -> AST.MatchingOptionSequence {
unsetMatchingOptions(adding: adding)
}
func ref(_ n: Int?) -> AST.Reference.Kind {
.absolute(.init(n, at: .fake))
}
func ref(plus n: Int?) -> AST.Reference.Kind {
.relative(.init(n, at: .fake))
}
func ref(minus n: Int?) -> AST.Reference.Kind {
.relative(.init(n.map { x in -x }, at: .fake))
}
func ref(named n: String) -> AST.Reference.Kind {
.named(n)
}
func ref(_ n: Int?, recursionLevel: Int? = nil) -> AST.Reference {
.init(
ref(n), recursionLevel: recursionLevel.map { .init($0, at: .fake) },
innerLoc: .fake
)
}
func ref(plus n: Int?, recursionLevel: Int? = nil) -> AST.Reference {
.init(
ref(plus: n), recursionLevel: recursionLevel.map { .init($0, at: .fake) },
innerLoc: .fake
)
}
func ref(minus n: Int?, recursionLevel: Int? = nil) -> AST.Reference {
.init(
ref(minus: n), recursionLevel: recursionLevel.map { .init($0, at: .fake) },
innerLoc: .fake
)
}
func ref(_ s: String, recursionLevel: Int? = nil) -> AST.Reference {
.init(.named(s), recursionLevel: recursionLevel.map { .init($0, at: .fake) },
innerLoc: .fake)
}
func conditional(
_ cond: AST.Conditional.Condition.Kind, trueBranch: AST.Node,
falseBranch: AST.Node
) -> AST.Node {
.conditional(.init(.init(cond, .fake), trueBranch: trueBranch, pipe: .fake,
falseBranch: falseBranch, .fake))
}
func pcreVersionCheck(
_ kind: AST.Conditional.Condition.PCREVersionCheck.Kind,
_ major: Int?, _ minor: Int?
) -> AST.Conditional.Condition.Kind {
.pcreVersionCheck(.init(
.init(faking: kind), .init(major: .init(major, at: .fake),
minor: .init(minor, at: .fake), .fake)
))
}
func groupCondition(
_ kind: AST.Group.Kind, _ child: AST.Node
) -> AST.Conditional.Condition.Kind {
.group(.init(.init(faking: kind), child, .fake))
}
func pcreCallout(number: Int?) -> AST.Node {
atom(.callout(.pcre(.init(.init(faking: .number(.init(number, at: .fake)))))))
}
func pcreCallout(string: String) -> AST.Node {
atom(.callout(.pcre(.init(.init(faking: .string(string))))))
}
func absentRepeater(_ child: AST.Node) -> AST.Node {
.absentFunction(.init(.repeater(child), start: .fake, location: .fake))
}
func absentExpression(_ absentee: AST.Node, _ child: AST.Node) -> AST.Node {
.absentFunction(.init(
.expression(absentee: absentee, pipe: .fake, expr: child),
start: .fake, location: .fake
))
}
func absentStopper(_ absentee: AST.Node) -> AST.Node {
.absentFunction(.init(.stopper(absentee), start: .fake, location: .fake))
}
func absentRangeClear() -> AST.Node {
.absentFunction(.init(.clearer, start: .fake, location: .fake))
}
func onigurumaNamedCallout(
_ name: String, tag: String? = nil, args: String...
) -> AST.Node {
atom(.callout(.onigurumaNamed(.init(
.init(faking: name),
tag: tag.map { .init(.fake, .init(faking: $0), .fake) },
args: args.isEmpty ? nil : .init(.fake, args.map { .init(faking: $0) }, .fake)
))))
}
func onigurumaCalloutOfContents(
_ contents: String, tag: String? = nil,
direction: AST.Atom.Callout.OnigurumaOfContents.Direction = .inProgress
) -> AST.Node {
atom(.callout(.onigurumaOfContents(.init(
.fake, .init(faking: contents), .fake,
tag: tag.map { .init(.fake, .init(faking: $0), .fake) },
direction: .init(faking: direction)
))))
}
func backtrackingDirective(
_ kind: AST.Atom.BacktrackingDirective.Kind, name: String? = nil
) -> AST.Node {
atom(.backtrackingDirective(
.init(.init(faking: kind), name: name.map { .init(faking: $0) })
))
}
func quant(
_ amount: AST.Quantification.Amount,
_ kind: AST.Quantification.Kind = .eager,
_ child: AST.Node
) -> AST.Node {
.quantification(.init(
.init(faking: amount), .init(faking: kind), child, .fake, trivia: []))
}
func zeroOrMore(
_ kind: AST.Quantification.Kind = .eager,
of child: AST.Node
) -> AST.Node {
quant(.zeroOrMore, kind, child)
}
func zeroOrOne(
_ kind: AST.Quantification.Kind = .eager,
of child: AST.Node
) -> AST.Node {
quant(.zeroOrOne, kind, child)
}
func oneOrMore(
_ kind: AST.Quantification.Kind = .eager,
of child: AST.Node
) -> AST.Node {
quant(.oneOrMore, kind, child)
}
func exactly(
_ i: Int?,
_ kind: AST.Quantification.Kind = .eager,
of child: AST.Node
) -> AST.Node {
quant(.exactly(.init(i, at: .fake)), kind, child)
}
func nOrMore(
_ i: Int?,
_ kind: AST.Quantification.Kind = .eager,
of child: AST.Node
) -> AST.Node {
quant(.nOrMore(.init(i, at: .fake)), kind, child)
}
func upToN(
_ i: Int?,
_ kind: AST.Quantification.Kind = .eager,
of child: AST.Node
) -> AST.Node {
quant(.upToN(.init(i, at: .fake)), kind, child)
}
func quantRange(
_ r: ClosedRange<Int>,
_ kind: AST.Quantification.Kind = .eager,
of child: AST.Node
) -> AST.Node {
quant(.range(
.init(r.lowerBound, at: .fake), .init(r.upperBound, at: .fake)
), kind, child)
}
func charClass(
_ members: AST.CustomCharacterClass.Member...,
inverted: Bool = false
) -> AST.Node {
let cc = AST.CustomCharacterClass(
.init(faking: inverted ? .inverted : .normal),
members,
.fake)
return .customCharacterClass(cc)
}
func charClass(
_ members: AST.CustomCharacterClass.Member...,
inverted: Bool = false
) -> AST.CustomCharacterClass.Member {
let cc = AST.CustomCharacterClass(
.init(faking: inverted ? .inverted : .normal),
members,
.fake)
return .custom(cc)
}
func setOp(
_ lhs: AST.CustomCharacterClass.Member...,
op: AST.CustomCharacterClass.SetOp,
_ rhs: AST.CustomCharacterClass.Member...
) -> AST.CustomCharacterClass.Member {
.setOperation(lhs, .init(faking: op), rhs)
}
func quote(_ s: String) -> AST.Node {
.quote(.init(s, .fake))
}
func quote_m(_ s: String) -> AST.CustomCharacterClass.Member {
.quote(.init(s, .fake))
}
// MARK: - Atoms
func atom(_ k: AST.Atom.Kind) -> AST.Node {
.atom(.init(k, .fake))
}
func escaped(
_ e: AST.Atom.EscapedBuiltin
) -> AST.Node {
atom(.escaped(e))
}
func scalar(_ s: Unicode.Scalar) -> AST.Node {
.atom(scalar_a(s))
}
func scalar_a(_ s: Unicode.Scalar) -> AST.Atom {
atom_a(.scalar(.init(s, .fake)))
}
func scalar_m(_ s: Unicode.Scalar) -> AST.CustomCharacterClass.Member {
.atom(scalar_a(s))
}
func scalarSeq(_ s: Unicode.Scalar...) -> AST.Node {
.atom(scalarSeq_a(s))
}
func scalarSeq_a(_ s: Unicode.Scalar...) -> AST.Atom {
scalarSeq_a(s)
}
func scalarSeq_a(_ s: [Unicode.Scalar]) -> AST.Atom {
atom_a(.scalarSequence(.init(s.map { .init($0, .fake) }, trivia: [])))
}
func scalarSeq_m(_ s: Unicode.Scalar...) -> AST.CustomCharacterClass.Member {
.atom(scalarSeq_a(s))
}
func backreference(_ r: AST.Reference.Kind, recursionLevel: Int? = nil) -> AST.Node {
atom(.backreference(.init(
r, recursionLevel: recursionLevel.map { .init($0, at: .fake) }, innerLoc: .fake
)))
}
func subpattern(_ r: AST.Reference.Kind) -> AST.Node {
atom(.subpattern(.init(r, innerLoc: .fake)))
}
func prop(
_ kind: AST.Atom.CharacterProperty.Kind,
inverted: Bool = false
) -> AST.Node {
atom(.property(.init(kind, isInverted: inverted, isPOSIX: false)))
}
func posixProp(
_ kind: AST.Atom.CharacterProperty.Kind, inverted: Bool = false
) -> AST.Node {
atom(.property(.init(kind, isInverted: inverted, isPOSIX: true)))
}
// Raw atom constructing variant
func atom_a(
_ k: AST.Atom.Kind
) -> AST.Atom {
AST.Atom(k, .fake)
}
// CustomCC member variant
func atom_m(
_ k: AST.Atom.Kind
) -> AST.CustomCharacterClass.Member {
.atom(atom_a(k))
}
func posixProp_m(
_ kind: AST.Atom.CharacterProperty.Kind, inverted: Bool = false
) -> AST.CustomCharacterClass.Member {
atom_m(.property(.init(kind, isInverted: inverted, isPOSIX: true)))
}
func prop_m(
_ kind: AST.Atom.CharacterProperty.Kind,
inverted: Bool = false
) -> AST.CustomCharacterClass.Member {
atom_m(.property(.init(kind, isInverted: inverted, isPOSIX: false)))
}
func range_m(
_ lower: AST.Atom, _ upper: AST.Atom
) -> AST.CustomCharacterClass.Member {
.range(.init(lower, .fake, upper, trivia: []))
}
func range_m(
_ lower: AST.Atom.Kind, _ upper: AST.Atom.Kind
) -> AST.CustomCharacterClass.Member {
range_m(atom_a(lower), atom_a(upper))
}
| apache-2.0 | 36ae66f1fdd7b5fbdc1e43ad530e4005 | 26.770089 | 88 | 0.654449 | 3.132964 | false | false | false | false |
kinetic-fit/sensors-swift | Sources/SwiftySensors/HeartRateSerializer.swift | 1 | 2347 | //
// HeartRateSerializer.swift
// SwiftySensors
//
// https://github.com/kinetic-fit/sensors-swift
//
// Copyright © 2017 Kinetic. All rights reserved.
//
import Foundation
/// :nodoc:
open class HeartRateSerializer {
public struct MeasurementData {
public enum ContactStatus {
case notSupported
case notDetected
case detected
}
public var heartRate: UInt16 = 0
public var contactStatus: ContactStatus = .notSupported
public var energyExpended: UInt16?
public var rrInterval: UInt16?
}
public enum BodySensorLocation: UInt8 {
case other = 0
case chest = 1
case wrist = 2
case finger = 3
case hand = 4
case earLobe = 5
case foot = 6
}
public static func readMeasurement(_ data: Data) -> MeasurementData {
var measurement = MeasurementData()
let bytes = data.map { $0 }
if bytes.count < 2 {
return measurement
}
var index: Int = 0
let flags = bytes[index++=];
if flags & 0x01 == 0 {
measurement.heartRate = UInt16(bytes[index++=])
} else if bytes.count > index + 1 {
measurement.heartRate = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
let contactStatusBits = (flags | 0x06) >> 1
if contactStatusBits == 2 {
measurement.contactStatus = .notDetected
} else if contactStatusBits == 3 {
measurement.contactStatus = .detected
}
if flags & 0x08 == 0x08 && bytes.count > index + 1 {
measurement.energyExpended = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
if flags & 0x10 == 0x10 && bytes.count > index + 1 {
measurement.rrInterval = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
return measurement
}
public static func readSensorLocation(_ data: Data) -> BodySensorLocation? {
let bytes = data.map { $0 }
if bytes.count == 0 { return nil }
return BodySensorLocation(rawValue: bytes[0])
}
public static func writeResetEnergyExpended() -> [UInt8] {
return [0x01]
}
}
| mit | 07943f7fd84dc3773514f7487f26fefd | 28.325 | 95 | 0.548593 | 4.25 | false | false | false | false |
stuartbreckenridge/SelfSizingCells | XMLExample/AppCell.swift | 1 | 2817 | //
// SongCell.swift
// XMLExample
//
// Created by Stuart Breckenridge on 14/8/14.
// Copyright (c) 2014 Stuart Breckenridge. All rights reserved.
//
import UIKit
class AppCell: UITableViewCell {
@IBOutlet weak var appName: UILabel!
@IBOutlet weak var appPrice: UILabel!
@IBOutlet weak var appSummary: UILabel!
@IBOutlet weak var appRights: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
// MARK: Required for self-sizing cells.
self.appName.preferredMaxLayoutWidth = CGRectGetWidth(UIApplication.sharedApplication().keyWindow!.frame)
self.appRights.preferredMaxLayoutWidth = CGRectGetWidth(UIApplication.sharedApplication().keyWindow!.frame)
self.appPrice.preferredMaxLayoutWidth = CGRectGetWidth(UIApplication.sharedApplication().keyWindow!.frame)
self.appSummary.preferredMaxLayoutWidth = CGRectGetWidth(UIApplication.sharedApplication().keyWindow!.frame)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func layoutSubviews() {
super.layoutSubviews()
// MARK: Required for self-sizing cells and device orientation
self.appName.preferredMaxLayoutWidth = CGRectGetWidth(UIApplication.sharedApplication().keyWindow!.frame)
self.appRights.preferredMaxLayoutWidth = CGRectGetWidth(UIApplication.sharedApplication().keyWindow!.frame)
self.appPrice.preferredMaxLayoutWidth = CGRectGetWidth(UIApplication.sharedApplication().keyWindow!.frame)
self.appSummary.preferredMaxLayoutWidth = CGRectGetWidth(UIApplication.sharedApplication().keyWindow!.frame)
}
func populateCell(#appData:App)
{
self.appName.text = appData.appName
self.appName.accessibilityLabel = "Application Name"
self.appName.accessibilityValue = appData.appName
self.appName.isAccessibilityElement = true
self.appPrice.text = appData.appPrice
self.appPrice.accessibilityLabel = "Application Price in U.S. Dollars"
self.appPrice.accessibilityValue = appData.appPrice
self.appPrice.isAccessibilityElement = true
self.appRights.text = appData.appRights
self.appRights.accessibilityLabel = "Application Rights Holder"
self.appRights.accessibilityValue = appData.appRights
self.appRights.isAccessibilityElement = true
self.appSummary.text = appData.appSummary
self.appSummary.accessibilityLabel = "Application Description"
self.appSummary.accessibilityValue = appData.appSummary
self.appSummary.isAccessibilityElement = true
}
}
| mit | 7d540afc887ec5da11a1d504a7bbb565 | 41.044776 | 116 | 0.71743 | 5.345351 | false | false | false | false |
Diederia/project | Pods/JTAppleCalendar/Sources/CalendarStructs.swift | 1 | 14795 | //
// CalendarStructs.swift
// JTAppleCalendar
//
// Created by JayT on 2016-10-02.
//
//
/// Describes which month the cell belongs to
/// - ThisMonth: Cell belongs to the current month
/// - PreviousMonthWithinBoundary: Cell belongs to the previous month.
/// Previous month is included in the date boundary you have set in your
/// delegate - PreviousMonthOutsideBoundary: Cell belongs to the previous
/// month. Previous month is not included in the date boundary you have set
/// in your delegate - FollowingMonthWithinBoundary: Cell belongs to the
/// following month. Following month is included in the date boundary you have
/// set in your delegate - FollowingMonthOutsideBoundary: Cell belongs to the
/// following month. Following month is not included in the date boundary you
/// have set in your delegate You can use these cell states to configure how
/// you want your date cells to look. Eg. you can have the colors belonging
/// to the month be in color black, while the colors of previous months be in
/// color gray.
public struct CellState {
/// returns true if a cell is selected
public let isSelected: Bool
/// returns the date as a string
public let text: String
/// returns the a description of which month owns the date
public let dateBelongsTo: DateOwner
/// returns the date
public let date: Date
/// returns the day
public let day: DaysOfWeek
/// returns the row in which the date cell appears visually
public let row: () -> Int
/// returns the column in which the date cell appears visually
public let column: () -> Int
/// returns the section the date cell belongs to
public let dateSection: () ->
(range: (start: Date, end: Date), month: Int, rowsForSection: Int)
/// returns the position of a selection in the event you wish to do range selection
public let selectedPosition: () -> SelectionRangePosition
/// returns the cell frame.
/// Useful if you wish to display something at the cell's frame/position
public var cell: () -> JTAppleDayCell?
}
/// Defines the parameters which configures the calendar.
public struct ConfigurationParameters {
/// The start date boundary of your calendar
var startDate: Date
/// The end-date boundary of your calendar
var endDate: Date
/// Number of rows you want to calendar to display per date section
var numberOfRows: Int
/// Your calendar() Instance
var calendar: Calendar
/// Describes the types of in-date cells to be generated.
var generateInDates: InDateCellGeneration
/// Describes the types of out-date cells to be generated.
var generateOutDates: OutDateCellGeneration
/// Sets the first day of week
var firstDayOfWeek: DaysOfWeek
/// Determine if dates of a month should stay in its section
/// or if it can flow into another months section. This value is ignored
/// if your calendar has registered headers
var hasStrictBoundaries: Bool
/// init-function
public init(startDate: Date,
endDate: Date,
numberOfRows: Int? = nil,
calendar: Calendar? = nil,
generateInDates: InDateCellGeneration? = nil,
generateOutDates: OutDateCellGeneration? = nil,
firstDayOfWeek: DaysOfWeek? = nil,
hasStrictBoundaries: Bool? = nil) {
self.startDate = startDate
self.endDate = endDate
self.numberOfRows = 6
if let validNumberOfRows = numberOfRows {
switch validNumberOfRows {
case 1, 2, 3:
self.numberOfRows = validNumberOfRows
default:
break
}
}
if let nonNilHasStrictBoundaries = hasStrictBoundaries {
self.hasStrictBoundaries = nonNilHasStrictBoundaries
} else {
self.hasStrictBoundaries = self.numberOfRows > 1 ? true : false
}
self.calendar = calendar ?? Calendar.current
self.generateInDates = generateInDates ?? .forAllMonths
self.generateOutDates = generateOutDates ?? .tillEndOfGrid
self.firstDayOfWeek = firstDayOfWeek ?? .sunday
}
}
struct CalendarData {
var months: [Month]
var totalSections: Int
var sectionToMonthMap: [Int: Int]
var totalDays: Int
}
/// Defines a month structure.
public struct Month {
/// Start index day for the month.
/// The start is total number of days of previous months
let startDayIndex: Int
/// Start cell index for the month.
/// The start is total number of cells of previous months
let startCellIndex: Int
/// The total number of items in this array are the total number
/// of sections. The actual number is the number of items in each section
let sections: [Int]
/// Number of inDates for this month
let inDates: Int
/// Number of outDates for this month
let outDates: Int
// Maps a section to the index in the total number of sections
let sectionIndexMaps: [Int: Int]
// Number of rows for the month
let rows: Int
// Return the total number of days for the represented month
var numberOfDaysInMonth: Int {
get {
return numberOfDaysInMonthGrid - inDates - outDates
}
}
// Return the total number of day cells
// to generate for the represented month
var numberOfDaysInMonthGrid: Int {
get {
return sections.reduce(0, +)
}
}
var startSection: Int {
return sectionIndexMaps.keys.min()!
}
// func firstIndexPathForExternal(section: Int) -> IndexPath? {
// guard let internalSection = sectionIndexMaps[section] else {
// return nil
// }
// if internalSection == 0 {
// // Then we need to consider predates
// return indexPath(forDay: 1 - inDates)
// } else {
// let startDay = startDayFor(section: internalSection)!
// let path = indexPath(forDay: startDay)
// return path
// }
// }
// Return the section in which a day is contained
func indexPath(forDay number: Int) -> IndexPath? {
let sectionInfo = sectionFor(day: number)
let externalSection = sectionInfo.externalSection
let internalSection = sectionInfo.internalSection
let dateOfStartIndex = sections[0..<internalSection].reduce(0, +) - inDates + 1
let itemIndex = number - dateOfStartIndex
return IndexPath(item: itemIndex, section: externalSection)
}
private func sectionFor(day: Int) -> (externalSection: Int, internalSection: Int) {
var variableNumber = day
let possibleSection = sections.index {
let retval = variableNumber + inDates <= $0
variableNumber -= $0
return retval
}!
return (sectionIndexMaps.key(for: possibleSection)!, possibleSection)
}
// Return the number of rows for a section in the month
func numberOfRows(for section: Int, developerSetRows: Int) -> Int {
var retval: Int
guard let theSection = sectionIndexMaps[section] else {
return 0
}
let fullRows = rows / developerSetRows
let partial = sections.count - fullRows
if theSection + 1 <= fullRows {
retval = developerSetRows
} else if fullRows == 0 && partial > 0 {
retval = rows
} else {
retval = 1
}
return retval
}
// Returns the maximum number of a rows for a completely full section
func maxNumberOfRowsForFull(developerSetRows: Int) -> Int {
var retval: Int
let fullRows = rows / developerSetRows
if fullRows < 1 {
retval = rows
} else {
retval = developerSetRows
}
return retval
}
func boundaryIndicesFor(section: Int) -> (startIndex: Int, endIndex: Int)? {
// Check internal sections to see
if !(0..<sections.count ~= section) {
return nil
}
let startIndex = section == 0 ? inDates : 0
var endIndex = sections[section] - 1
if section + 1 == sections.count {
endIndex -= inDates + 1
}
return (startIndex: startIndex, endIndex: endIndex)
}
// func startDayFor(section: Int) -> Int? {
// var retval: Int?
//
// if !(0..<sections.count ~= section) {
// return nil
// }
// if section == 0 {
// retval = 1
// } else {
// var diff: Int = 0
// for (index, _) in sections.enumerated() {
// guard let bounds = boundaryIndicesFor(section: index), index < section else {
// break
// }
// diff += bounds.endIndex - bounds.startIndex + 1
// }
// retval = diff + 1
// }
// return retval
// }
}
struct JTAppleDateConfigGenerator {
weak var delegate: JTAppleCalendarDelegateProtocol?
init(delegate: JTAppleCalendarDelegateProtocol) {
self.delegate = delegate
}
mutating func setupMonthInfoDataForStartAndEndDate(_ parameters: ConfigurationParameters)
-> (months: [Month], monthMap: [Int: Int], totalSections: Int, totalDays: Int) {
let differenceComponents = parameters.calendar.dateComponents([.month], from: parameters.startDate, to: parameters.endDate)
let numberOfMonths = differenceComponents.month! + 1
// if we are for example on the same month
// and the difference is 0 we still need 1 to display it
var monthArray: [Month] = []
var monthIndexMap: [Int: Int] = [:]
var section = 0
var startIndexForMonth = 0
var startCellIndexForMonth = 0
var totalDays = 0
let numberOfRowsPerSectionThatUserWants = parameters.numberOfRows
// Section represents # of months. section is used as an offset
// to determine which month to calculate
guard let nonNilDelegate = delegate else {
return ([], [:], 0, 0 )
}
for monthIndex in 0 ..< numberOfMonths {
if let currentMonth = parameters.calendar.date(byAdding: .month, value: monthIndex, to: parameters.startDate) {
var numberOfDaysInMonthVariable = parameters.calendar.range(of: .day, in: .month, for: currentMonth)!.count
let numberOfDaysInMonthFixed = numberOfDaysInMonthVariable
var numberOfRowsToGenerateForCurrentMonth = 0
var numberOfPreDatesForThisMonth = 0
let predatesGeneration = nonNilDelegate.preDatesAreGenerated()
if predatesGeneration != .off {
numberOfPreDatesForThisMonth = nonNilDelegate.numberOfPreDatesForMonth(currentMonth)
numberOfDaysInMonthVariable += numberOfPreDatesForThisMonth
if predatesGeneration == .forFirstMonthOnly && monthIndex != 0 {
numberOfDaysInMonthVariable -= numberOfPreDatesForThisMonth
numberOfPreDatesForThisMonth = 0
}
}
if parameters.generateOutDates == .tillEndOfGrid {
numberOfRowsToGenerateForCurrentMonth = maxNumberOfRowsPerMonth
} else {
let actualNumberOfRowsForThisMonth = Int(ceil(Float(numberOfDaysInMonthVariable) / Float(maxNumberOfDaysInWeek)))
numberOfRowsToGenerateForCurrentMonth = actualNumberOfRowsForThisMonth
}
var numberOfPostDatesForThisMonth = 0
let postGeneration = nonNilDelegate.postDatesAreGenerated()
switch postGeneration {
case .tillEndOfGrid, .tillEndOfRow:
numberOfPostDatesForThisMonth =
maxNumberOfDaysInWeek * numberOfRowsToGenerateForCurrentMonth - (numberOfDaysInMonthFixed + numberOfPreDatesForThisMonth)
numberOfDaysInMonthVariable += numberOfPostDatesForThisMonth
default:
break
}
var sectionsForTheMonth: [Int] = []
var sectionIndexMaps: [Int: Int] = [:]
for index in 0..<6 {
// Max number of sections in the month
if numberOfDaysInMonthVariable < 1 {
break
}
monthIndexMap[section] = monthIndex
sectionIndexMaps[section] = index
var numberOfDaysInCurrentSection = numberOfRowsPerSectionThatUserWants * maxNumberOfDaysInWeek
if numberOfDaysInCurrentSection > numberOfDaysInMonthVariable {
numberOfDaysInCurrentSection = numberOfDaysInMonthVariable
// assert(false)
}
totalDays += numberOfDaysInCurrentSection
sectionsForTheMonth.append(numberOfDaysInCurrentSection)
numberOfDaysInMonthVariable -= numberOfDaysInCurrentSection
section += 1
}
monthArray.append(Month(
startDayIndex: startIndexForMonth,
startCellIndex: startCellIndexForMonth,
sections: sectionsForTheMonth,
inDates: numberOfPreDatesForThisMonth,
outDates: numberOfPostDatesForThisMonth,
sectionIndexMaps: sectionIndexMaps,
rows: numberOfRowsToGenerateForCurrentMonth
))
startIndexForMonth += numberOfDaysInMonthFixed
startCellIndexForMonth += numberOfDaysInMonthFixed + numberOfPreDatesForThisMonth + numberOfPostDatesForThisMonth
}
}
return (monthArray, monthIndexMap, section, totalDays)
}
}
/// Contains the information for visible dates of the calendar.
public struct DateSegmentInfo {
/// Visible pre-dates
public let indates: [Date]
/// Visible month-dates
public let monthDates: [Date]
/// Visible post-dates
public let outdates: [Date]
internal let indateIndexes: [IndexPath]
internal let monthDateIndexes: [IndexPath]
internal let outdateIndexes: [IndexPath]
}
| mit | 2836c6a405029d1393c161d7e5fca64e | 39.757576 | 149 | 0.606016 | 5.218695 | false | false | false | false |
Webtrekk/webtrekk-ios-sdk | Source/Internal/Utility/String.swift | 1 | 2935 | import Foundation
// import CryptoSwift -> currently included, TODO: but kept here to find the dependent files back when stable version is ready
internal extension String {
func firstMatchForRegularExpression(_ regularExpression: NSRegularExpression) -> [String]? {
guard let match = regularExpression.firstMatch(in: self, options: [], range: NSMakeRange(0, utf16.count)) else {
return nil
}
return (0 ..< match.numberOfRanges).map { String(self[match.range(at: $0).rangeInString(self)!]) }
}
func firstMatchForRegularExpression(_ regularExpressionPattern: String) -> [String]? {
do {
let regularExpression = try NSRegularExpression(pattern: regularExpressionPattern, options: [])
return firstMatchForRegularExpression(regularExpression)
} catch let error {
fatalError("Invalid regular expression pattern: \(error)")
}
}
//check if string is matched to expression
func isMatchForRegularExpression(_ expression: String) -> Bool? {
do {
let regularExpression = try NSRegularExpression(pattern: expression, options: [])
return regularExpression.numberOfMatches(in: self, options: [], range: NSMakeRange(0, utf16.count)) == 1
} catch let error {
WebtrekkTracking.defaultLogger.logError("Error: \(error) for incorrect regular expression: \(expression)")
return nil
}
}
var nonEmpty: String? {
if isEmpty {
return nil
}
return self
}
var simpleDescription: String {
return "\"\(self)\""
}
func isValidURL() -> Bool {
if let url = URL(string: self), url.host != nil {
return true
} else {
return false
}
}
func isTrackIdFormat() -> Bool {
let trackIds = self.replacingOccurrences(of: " ", with: "").components(separatedBy: ",")
guard trackIds.isEmpty else {
return false
}
for trackId in trackIds {
if !CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: trackId)) || trackId.utf8.count != 15 {
return false
}
}
return true
}
func sha256() -> String {
return self.utf8.lazy.map({ $0 as UInt8 }).sha256().toHexString()
}
func md5() -> String {
return self.utf8.lazy.map({ $0 as UInt8 }).md5().toHexString()
}
var coded: String {
let codedChar = "$',/:?@=&+"
var csValue = CharacterSet.urlQueryAllowed
codedChar.forEach { (ch) in
csValue.remove(ch.unicodeScalars.first!)
}
return self.addingPercentEncoding(withAllowedCharacters: csValue)!
}
}
internal extension _Optional where Wrapped == String {
var simpleDescription: String {
return self.value?.simpleDescription ?? "<nil>"
}
}
| mit | 8ed8b681e36ee739a402881f75523533 | 28.94898 | 126 | 0.607496 | 4.86733 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV | PopcornTime/UI/Shared/View Controllers/DownloadViewController.swift | 1 | 3876 |
import Foundation
import class PopcornTorrent.PTTorrentDownloadManager
import enum PopcornTorrent.PTTorrentDownloadStatus
import class PopcornTorrent.PTTorrentDownload
import protocol PopcornTorrent.PTTorrentDownloadManagerListener
import PopcornKit
import MediaPlayer.MPMediaItem
#if os(iOS)
typealias UIDownloadViewController = UITableViewController
#elseif os(tvOS)
typealias UIDownloadViewController = UIViewController
#endif
class DownloadViewController: UIDownloadViewController, PTTorrentDownloadManagerListener {
@IBOutlet var segmentedControl: UISegmentedControl!
#if os(tvOS)
@IBOutlet var tableView: UITableView?
#endif
var completedEpisodes: [PTTorrentDownload] {
return filter(downloads: PTTorrentDownloadManager.shared().completedDownloads, through: .episode)
}
var completedMovies: [PTTorrentDownload] {
return filter(downloads: PTTorrentDownloadManager.shared().completedDownloads, through: .movie)
}
var downloadingEpisodes: [PTTorrentDownload] {
return filter(downloads: PTTorrentDownloadManager.shared().activeDownloads, through: .episode)
}
var downloadingMovies: [PTTorrentDownload] {
return filter(downloads: PTTorrentDownloadManager.shared().activeDownloads, through: .movie)
}
private func filter(downloads: [PTTorrentDownload], through predicate: MPMediaType) -> [PTTorrentDownload] {
return downloads.filter { download in
guard let rawValue = download.mediaMetadata[MPMediaItemPropertyMediaType] as? NSNumber else { return false }
let type = MPMediaType(rawValue: rawValue.uintValue)
return type == predicate
}.sorted { (first, second) in
guard
let firstTitle = first.mediaMetadata[MPMediaItemPropertyTitle] as? String,
let secondTitle = second.mediaMetadata[MPMediaItemPropertyTitle] as? String
else {
return false
}
return firstTitle > secondTitle
}
}
func activeDataSource(in section: Int) -> [AnyHashable] {
switch (segmentedControl.selectedSegmentIndex, section) {
case (0, 0):
return downloadingMovies
case (0, 1):
return downloadingEpisodes
case (1, 0):
return completedMovies
case (1, 1):
var shows = [Show]()
completedEpisodes.forEach {
guard let show = Episode($0.mediaMetadata)?.show, !shows.contains(show) else { return }
shows.append(show)
}
return shows
default:
fatalError()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
reloadData()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedSetup()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
sharedSetup()
}
#if os(iOS)
override init(style: UITableView.Style) {
super.init(style: style)
sharedSetup()
}
#endif
func sharedSetup() {
PTTorrentDownloadManager.shared().add(self)
}
deinit {
PTTorrentDownloadManager.shared().remove(self)
}
@IBAction func changeSegment(_ sender: UISegmentedControl) {
reloadData()
}
func downloadStatusDidChange(_ downloadStatus: PTTorrentDownloadStatus, for download: PTTorrentDownload) {
reloadData()
}
func downloadDidFail(_ download: PTTorrentDownload, withError error: Error) {
reloadData()
AppDelegate.shared.download(download, failedWith: error)
}
}
| gpl-3.0 | 07765f5f9f5cd5ae74147ff4f04ef9f1 | 31.033058 | 120 | 0.653767 | 5.295082 | false | false | false | false |
iOS-Swift-Developers/Swift | UIKit/读取json文件&重载/SwiftJsonTest/SwiftJsonTest/ViewController.swift | 1 | 4023 | //
// ViewController.swift
// SwiftJsonTest
//
// Created by 韩俊强 on 2017/8/14.
// Copyright © 2017年 HaRi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
/*
swift支持方法的重载;
方法的重载:方法名称相同,但是参数不同.包括:
1.参数的类型不同;
2.参数的个数不同.
*/
// 1.获取json文件路径
guard let jsonPath = Bundle.main.path(forResource: "MainVCSettings.json", ofType: nil) else {
print("没有获取到对应的文件路径")
return
}
// 2.读取json文件中的内容
guard let jsonData = NSData.init(contentsOfFile: jsonPath) else {
print("没有获取到json文件中的数据")
return
}
// 3.将Data转成数组
// 如果在调用系统某个方法时,该方法最后有一个throws,说明该方法会抛出异常,那么需要对该异常进行处理
guard let anyObject = try? JSONSerialization.jsonObject(with: jsonData as Data, options: .mutableContainers) else {
return
}
guard let dicArray = anyObject as?[[String : AnyObject]] else {
return
}
// 4.遍历字典, 获取对应信息
for dict in dicArray {
// 4.1.获取控制器对应的字符串
guard let vcName = dict["vcName"] as? String else {
continue
}
// 4.2.获取控制器显示的title
guard let title = dict["title"] as? String else {
continue
}
// 4.3.获取控制器显示的图标名称
guard let imageName = dict["imageName"] as? String else {
continue
}
// 4.4.添加子控制器
addChildViewController(childVCName: vcName, title: title, imageName: imageName)
}
}
// 方法重载
private func addChildViewController(childVCName : String, title : String, imageName : String) {
// NSClassFromString("这里的名字是SwiftJsonTest.HomeViewController") // 根据字符串获取对应的Class:命名空间+.ViewController的名字
// 如何修改命名空间 Target -> Build Settings -> Product Name, 可以在这里修改命名空间的名称,但是要注意,新修改的命名空间不能有中文,不能以数字开头并且不能包含"-"符号
// 1.获取命名空间
guard let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else {
print("没有命名空间")
return
}
// 2.根据字符串获取对应的Class
guard let childVCClass = NSClassFromString(nameSpace + "." + childVCName) else {
print("没有获取到字符串对应的Class")
return
}
// 3.将对应的AnyObject转成控制器的类型
guard let childVCType = childVCClass as? UIViewController.Type else {
print("没有获取到对应控制器的类型")
return
}
// 4.创建对应的控制器对象
let childVC = childVCType.init()
// 5.设置子控制器的属性
childVC.title = title
childVC.tabBarItem.image = UIImage(named: "\(imageName)_unselected")
childVC.tabBarItem.selectedImage = UIImage(named: "\(imageName)_selected")
// 6.包装导航控制器
let childNav = UINavigationController(rootViewController: childVC)
// 7.添加控制器
addChildViewController(childNav)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | d9b86905c9522589b3180d216fd56800 | 27.689655 | 123 | 0.553786 | 4.667602 | false | false | false | false |
episquare/CollectionInTable | CollectionInTable/Controller/CollectionInTableVC.swift | 1 | 3318 | //
// CollectionInTableVC.swift
// CollectionInTable
//
// Created by Andrian Yohanes on 7/25/17.
// Copyright © 2017 episquare. All rights reserved.
//
import UIKit
class CollectionInTableVC: UIViewController {
/// TableView properties.
let tableView: UITableView = {
let myTableView = UITableView()
myTableView.showsVerticalScrollIndicator = false
myTableView.allowsSelection = false
myTableView.estimatedRowHeight = 44
myTableView.backgroundColor = .white
return myTableView
}()
/// Set cell id for tableViewCell and tableViewCellWithCollectionView
let tableViewCell = "tableViewCellID"
let tableViewCellWithCollectionViewID = "tableViewCellWithCollectionViewID"
/// Setup myCellData
var myCellData = [TableWithCollectionData]()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
navigationItem.title = "CollectionInTable"
tableView.register(TableViewCell.self, forCellReuseIdentifier: tableViewCell)
tableView.register(TableViewCellWithCollectionView.self, forCellReuseIdentifier: tableViewCellWithCollectionViewID)
tableView.dataSource = self
tableView.delegate = self
tableView.tableFooterView = UIView()
setupViewsForVC()
// Get data myCellData
myCellData = TableWithCollectionData.getTableWithCollectionData()
// Reload tableView
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
/// Setup layout for TableView.
func setupViewsForVC() {
// Add tableView as a subview
view.addSubview(tableView)
// Setup tableView layout
tableView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
}
}
extension CollectionInTableVC: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myCellData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellData = myCellData[indexPath.row]
// Setup tableViewCellWithCollectionView in row 3
if indexPath.row == 2 {
let cell = tableView.dequeueReusableCell(withIdentifier: tableViewCellWithCollectionViewID, for: indexPath) as! TableViewCellWithCollectionView
cell.myCustomCollectionCellData = cellData
return cell
}
// Setup tableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: tableViewCell, for: indexPath) as! TableViewCell
cell.myCustomCellData = cellData
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.row {
// Row height tableViewCellWithCollectionView
case 2:
return 200
// Row height for tableViewCell
default:
return 150
}
}
}
| mit | d5a10da0e13ef5d18f3b11ea46c4df01 | 31.519608 | 222 | 0.662948 | 5.7487 | false | false | false | false |
apple/swift-syntax | Tests/SwiftParserTest/SyntaxTransformVisitorTest.swift | 1 | 3356 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import XCTest
import SwiftParser
import SwiftSyntax
final class SyntaxTransformVisitorTest: XCTestCase {
public func testFunctionCounter() {
struct FuncCounter: SyntaxTransformVisitor {
public func visitAny(_ node: Syntax) -> Int {
visitChildren(node).reduce(0, +)
}
public func visit(_ node: FunctionDeclSyntax) -> Int {
visitChildren(node).reduce(1, +)
}
}
_ = {
let parsed = Parser.parse(source: """
func foo() {
public func foo() {
func foo() {
/*Unknown token */0xG
}
func bar() {
/*Unknown token */0xG
}
}
}
""")
let count = FuncCounter().visit(parsed)
XCTAssertEqual(count, 4)
}()
}
public func testPrintFunctionType() {
/// Assuming there is a single functioned declaration in the source file, print the type of that function.
struct PrintFunctionType: SyntaxTransformVisitor {
func visitAny(_ node: SwiftSyntax.Syntax) -> String {
fatalError("Not implemented")
}
public func visit(_ node: CodeBlockItemSyntax) -> String { visit(node.item) }
public func visit(_ node: SourceFileSyntax) -> String {
assert(node.statements.count == 1)
return visit(node.statements.first!.item)
}
public func visit(_ node: FunctionDeclSyntax) -> String {
let argStrings = node.signature.input.parameterList
.compactMap { $0.type }
.compactMap(visit)
let resultString: String
if let out = node.signature.output {
resultString = visit(out.returnType)
} else {
resultString = "Void"
}
return "(" + argStrings.joined(separator: ", ") + ") -> " + resultString
}
public func visit(_ node: SimpleTypeIdentifierSyntax) -> String {
node.name.text
}
public func visit(_ node: ArrayTypeSyntax) -> String {
"[" + visit(node.elementType) + "]"
}
}
_ = {
let parsed = Parser.parse(source: """
func foo(a: Int, b: Foo, c: [Int]) -> Result {
}
""")
let stringified = PrintFunctionType().visit(parsed)
XCTAssertEqual(stringified, "(Int, Foo, [Int]) -> Result")
}()
_ = {
let parsed = Parser.parse(source: """
func foo() {
}
""")
let stringified = PrintFunctionType().visit(parsed)
XCTAssertEqual(stringified, "() -> Void")
}()
_ = {
let parsed = Parser.parse(source: """
func foo(a: Int) -> [Result] {
}
""")
let stringified = PrintFunctionType().visit(parsed)
XCTAssertEqual(stringified, "(Int) -> [Result]")
}()
}
}
| apache-2.0 | 3978cfa4040794268fde80475d824c24 | 30.074074 | 110 | 0.537247 | 4.726761 | false | false | false | false |
apple/swift-tools-support-core | Tests/TSCBasicTests/RegExTests.swift | 1 | 922 | /*
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 XCTest
import TSCBasic
class RegExTests: XCTestCase {
func testErrors() {
// https://bugs.swift.org/browse/SR-5557
#if canImport(Darwin)
XCTAssertThrowsError(try RegEx(pattern: "("))
#endif
}
func testMatchGroups() throws {
try XCTAssert(RegEx(pattern: "([a-z]+)([0-9]+)").matchGroups(in: "foo1 bar2 baz3") == [["foo", "1"], ["bar", "2"], ["baz", "3"]])
try XCTAssert(RegEx(pattern: "[0-9]+").matchGroups(in: "foo bar baz") == [])
try XCTAssert(RegEx(pattern: "[0-9]+").matchGroups(in: "1") == [[]])
}
}
| apache-2.0 | 86d89e0f030246c03ee8842b5754c193 | 31.928571 | 137 | 0.633406 | 3.717742 | false | true | false | false |
giangbvnbgit128/AnViet | AnViet/Class/ViewControllers/HomeViewController/Cell/AVNewFeedOneImageTableViewCell.swift | 1 | 2298 | //
// AVNewFeedOneImageTableViewCell.swift
// AnViet
//
// Created by Bui Giang on 5/30/17.
// Copyright © 2017 Bui Giang. All rights reserved.
//
import UIKit
import SDWebImage
import SKPhotoBrowser
class AVNewFeedOneImageTableViewCell: AVBaseNewFeedTableViewCell {
@IBOutlet weak var imgAvarta: UIImageView!
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var lblDetail: UILabel!
@IBOutlet weak var lblDescription: UILabel!
@IBOutlet weak var img1: UIImageView!
@IBOutlet weak var btnLike: UIButton!
@IBOutlet weak var btnShare: UIButton!
var supperViewVC:UIViewController?
var urlImage1:String = ""
var images = [SKPhoto]()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let tapRecognizer = UITapGestureRecognizer( target: self, action: #selector(self.tapImg1))
self.img1.addGestureRecognizer(tapRecognizer)
}
func tapImg1() {
let browser = SKPhotoBrowser(photos: images)
let b = SKPhotoBrowser()
browser.initializePageIndex(0)
self.supperViewVC?.present(browser, animated: true, completion: {})
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func configCell(data: DataForItem, host: String, vc: UIViewController) {
self.images.removeAll()
self.supperViewVC = vc
self.lblTitle.text = data.post.title
self.lblDetail.text = data.post.createdDate
self.lblDescription.text = data.post.content
self.btnLike.setTitle(data.post.userLike, for: .normal)
self.imgAvarta.sd_setImage(with: URL(string: host + data.user.avartar), placeholderImage: UIImage(named: "icon_avatar.png"))
self.img1.sd_setImage(with: URL(string: host + data.post.image[0].urlImage), placeholderImage: UIImage(named: "no_image.png"), options: []) { (someImage, someError, type, urlImage) in
var photo:SKPhoto?
if someImage != nil {
photo = SKPhoto.photoWithImage(someImage!)
} else {
photo = SKPhoto.photoWithImage(UIImage(named: "no_image.png")!)
}
self.images.append(photo!)
}
}
}
| apache-2.0 | 06c564ad5a9ca6817f97608b88ca4eab | 35.460317 | 191 | 0.660862 | 4.176364 | false | false | false | false |
iziz/libPhoneNumber-iOS | libPhoneNumber-Demo/libPhoneNumber-Demo/GeocodingSearchView.swift | 1 | 2125 | //
// GeocodingSearchView.swift
// libPhoneNumber-Demo
//
// Created by Rastaar Haghi on 7/17/20.
// Copyright © 2020 Google LLC. All rights reserved.
//
import SwiftUI
import libPhoneNumberGeocoding
import libPhoneNumber_iOS
struct GeocodingSearchView: View {
@State private var localeSelection = 0
@State private var phoneNumber: String = ""
@State private var regionDescription: String = ""
private let geocoder = NBPhoneNumberOfflineGeocoder()
private let phoneUtil = NBPhoneNumberUtil()
var body: some View {
VStack {
Form {
Section(header: Text("Locale Options")) {
Picker("Locale Options", selection: $localeSelection) {
ForEach(0..<locales.count) { index in
Text(locales[index].language)
.tag(index)
}
}
}
Section(header: Text("Phone Number")) {
TextField("Ex: 19098611234", text: $phoneNumber)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
}
Button(
action: {
self.regionDescription = self.searchPhoneNumber()
},
label: {
Text("Search for Region Description")
.multilineTextAlignment(.center)
})
}
Text(regionDescription)
.bold()
}
.navigationBarTitle(Text("Search for Region Description"))
}
}
extension GeocodingSearchView {
func searchPhoneNumber() -> String {
do {
let parsedPhoneNumber: NBPhoneNumber =
try phoneUtil.parse(phoneNumber, defaultRegion: Locale.current.regionCode!)
if localeSelection == 0 {
return geocoder.description(for: parsedPhoneNumber) ?? "Unknown Region"
} else {
return geocoder.description(
for: parsedPhoneNumber,
withLanguageCode: locales[localeSelection].localeCode)
?? "Unknown Region"
}
} catch {
print(error)
return "Error parsing phone number."
}
}
}
struct GeocodingSearchView_Previews: PreviewProvider {
static var previews: some View {
GeocodingSearchView()
}
}
| apache-2.0 | 7ebdee3d4092cc05f8fab16858bb88d1 | 26.584416 | 83 | 0.622411 | 4.647702 | false | false | false | false |
TrustWallet/trust-wallet-ios | TrustTests/EtherClient/TypedMessageEncodingTests.swift | 1 | 10363 | // Copyright DApps Platform Inc. All rights reserved.
import XCTest
@testable import Trust
import TrustCore
import TrustKeystore
import KeychainSwift
class TypedMessageEncodingTests: XCTestCase {
let keystore = FakeEtherKeystore()
func testValue_none() {
let account = importAccount()
let typedData = EthTypedData(type: "string", name: "test test", value: .none)
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0xd8cb0766acdfeb460b3e88173d71e223e31a442d468a6ceec85eb60b2cdf69dd62cc0a14e8c205eed582d47fac726850e43149844c81965a18ddee7a627c6ffb1b")
}
func testValues() {
let account = importAccount()
let typedData = EthTypedData(type: "string", name: "Message", value: .string(value: "Hi, Alice!"))
let typedData2 = EthTypedData(type: "uint8", name: "value", value: .uint(value: 10))
let signResult = keystore.signTypedMessage([typedData, typedData2], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0xfff29ccbfcd4a2a19fc43fbb803a09facaf3c6363f017cc57201b71a96facbc25200460d266b6a5ec0e42a79271593b95faf067f25a569e7465a169240fac0b91b")
}
func testType_uint_Value_uint() {
let account = importAccount()
// from https://beta.adex.network/
let typedData = EthTypedData(type: "uint", name: "Auth token", value: .uint(value: 1498316044249108))
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0xa1f639ae9e97401030fb4205749fe8b8e72602624aa92aa0558129b345e9546c42f3bcb7b71c83b7474cb93d83913249708570af9120cf9655775fea9571e0481b")
}
func testType_uint_Value_string() {
let account = importAccount()
// from https://beta.adex.network/
let typedData = EthTypedData(type: "uint", name: "Auth token", value: .string(value: "1498316044249108"))
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0xa1f639ae9e97401030fb4205749fe8b8e72602624aa92aa0558129b345e9546c42f3bcb7b71c83b7474cb93d83913249708570af9120cf9655775fea9571e0481b")
}
func testType_bool_Value_bool() {
let account = importAccount()
let typedData = EthTypedData(type: "bool", name: "email valid", value: .bool(value: false))
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0x1df23825a6c4ea9b1782754da23c21c6af1732fe614cbcdf34a4daefbaddf47c444891aad02c2d4bab0df228fb4852d6620d624a9848e432f7141fe5a89e7e171c")
}
func testType_address_Value_string() {
let account = importAccount()
let typedData = EthTypedData(type: "address", name: "my address", value: .address(value: "0x2c7536e3605d9c16a7a3d7b1898e529396a65c23"))
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0xe218514cddfeba69a1fe7fac5af54193e357e8fb5644239045ed65e4e950d564412c6bf6d571fafb73bdd23ef71e8269242b001ca3ecb1a6661fcb70eaacf25c1b")
}
func testType_string_Value_string() {
let account = importAccount()
let typedData = EthTypedData(type: "string", name: "This is a message", value: .string(value: "hello bob"))
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0x8b5194f65b8f2fb8ef110391bcecde9bc97a41dae833c69aa1f6486d910a7d870056f784a386d7a9416315692e0da7a78702d95d308b4381c21d60d93dbc7e061c")
}
func testType_string_Value_emptyString() {
let account = importAccount()
let typedData = EthTypedData(type: "string", name: "empty string here!", value: .string(value: ""))
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0xbf9ee06fd0f62fd385d5eeb091efaa636c808cc315f40c48f945138ed4cd1458547cdaf8a4cd8ddd4949a5441910a94cd2a18e9dbc4183c93804299a79335e451c")
}
func testType_int_Value_int() {
let account = importAccount()
let typedData = EthTypedData(type: "int32", name: "how much?", value: .int(value: 1200))
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0xe6d4d981485013055ee978c39cf9c18096b4e05bc0471de72377db9b392c7582276d2d8e7b6329f784aac8fbd42417c74906285e072019e025883e52f94a169d1c")
}
func testType_int_Value_bigInt() {
let account = importAccount()
// from https://like.co/
let typedData = EthTypedData(type: "int256", name: "how much?", value: .string(value: "-57896044618658097711785492504343953926634992332820282019728792003956564819968"))
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0xa1cd93b6dd2a18748993c727c8c9be20a784504b7f1fc9eece228bc5004e805d6a0bcabce62994881b562243ace5cc3ce18bd41302c793dce38c301036af01761c")
}
func testType_int_Value_bigUInt() {
let account = importAccount()
// from https://like.co/
let typedData = EthTypedData(type: "uint256", name: "how much?", value: .string(value: "6739986666787659948666753771754907668409286105635143120275902562304"))
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0xb88c74fd791b6f1e201c8bb08ff977a938d9ca379f83fd00140f683f3a04fcf6220db28ff750efafc642b525d00d0e3e37d2a1af8cd50940306e690f5b93c8d81c")
}
func testType_bytes_Value_hexString() {
let account = importAccount()
let typedData = EthTypedData(type: "bytes", name: "your address", value: .string(value: "0x2c7536e3605d9c16a7a3d7b1898e529396a65c23"))
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0x5da07ffb693a23caced43cb9056667a32078d64b24aa2591d2b9c56527b6556e29fbe0807dee0d55c16e85d83edc7bbe972234fa5580a4f4f23f0280c875c8461c")
}
func testType_bytes_Value_hexShortString() {
let account = importAccount()
let typedData = EthTypedData(type: "bytes", name: "short hex", value: .string(value: "0xdeadbeaf"))
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0x740a918cfbfe75a38634a84f2e2c7f33698465ff0332290d5df9b021cbf336cb2593dd11708cdba302d3281223a5db148eda61ef6bd8a32a9f3f2daaa064e72b1c")
}
func testType_bytes_Value_hexEmptyString() {
let account = importAccount()
let typedData = EthTypedData(type: "bytes", name: "empty hex", value: .string(value: "0x"))
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0x342400b5d6a29da301b207df4aab507006ca093cf6d3a690c450524272cf647e0dc013fd29ce1b3fb1292c8af16fc4f1c38777c3acf4a1019c1b7d400aabd1941c")
}
func testType_bytes_Value_string() {
let account = importAccount()
let typedData = EthTypedData(type: "bytes", name: "+bytes in string", value: .string(value: "this is a raw string"))
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0x6f3dc47a034c49f235998b2d460b0bcee7b01fe02d90841bfc2962fb6ec27d003e16fd619f69c85c9360fbe39b2232e5ab8e313c2074bf8c358feade940d289c1b")
}
func testType_bytes_Value_emptyString() {
let account = importAccount()
let typedData = EthTypedData(type: "bytes", name: "nothing here", value: .string(value: ""))
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0x30c390c4579cf166d2b61b7ec7b776219ff6ef44c5171d831b258614e9b00cf14f4ecc01c322cd94c3ef277252a4664f458eaba09e0e91bc63f4eedb145ff8851c")
}
func testType_bytes_Value_int() {
let account = importAccount()
let typedData = EthTypedData(type: "bytes", name: "a number?", value: .uint(value: 1100))
let signResult = keystore.signTypedMessage([typedData], for: account)
guard case let .success(data) = signResult else {
return XCTFail()
}
XCTAssertEqual(data.hexEncoded, "0xd90e257771b64fbc4ecd963f27ea371eb6a656c1912afda8a9184a4b81130dd71487f525d1ecca0d6008530c1bfcf5afc0c2224670ae68080d264ec96468c9bb1c")
}
private func importAccount() -> Account {
let privateKey = PrivateKey(data: Data(hexString: "0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318")!)!
let result = keystore.importPrivateKey(privateKey: privateKey, password: TestKeyStore.password, coin: .ethereum)
guard case let .success(account1) = result else {
return .make()
}
return account1.currentAccount
}
}
| gpl-3.0 | 990eddbed4db763a11b3530505ac8421 | 49.79902 | 176 | 0.713403 | 3.146023 | false | true | false | false |
blinksh/blink | SSH/SSHError.swift | 1 | 4238 | //////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2021 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink 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.
//
// Blink 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 Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
import Combine
import Foundation
import LibSSH
public enum SSHError: Error, Equatable {
public static func == (lhs: SSHError, rhs: SSHError) -> Bool {
switch (lhs,rhs) {
case (.again, .again):
return true
case (.connError(msg: _),.connError(msg: _)):
return true
case (.notImplemented(let message1),.notImplemented(let message2)):
if message1 == message2 {
return true
}
return true
case (.authFailed(methods: let methods1), .authFailed(methods: let methods2)):
if methods1.elementsEqual(methods2, by: { $0.name() == $1.name() }) {
return true
}
return false
case (.authError(msg: _), .authError(msg: _)):
return true
default:
return false
}
}
case again
/// Errors related to the connection and may have state from the session attached.
case connError(msg: String)
/// Errors related to operations in the library, no communication involved
case operationError(msg: String)
case notImplemented(_: String)
/// Fails either when the username or password are incorrect
case authFailed(methods: [AuthMethod])
/// Tried to authenticate using a method that's not allowed
case authError(msg: String)
public var description: String {
switch self {
case .again:
return "Retry"
case .connError(let msg):
return "Connection Error: \(msg)"
case .operationError(let msg):
return "Operation Error: \(msg)"
case .notImplemented(let msg):
return "Not implemented: \(msg)"
case .authFailed(let methods):
let names = Set(methods.map { $0.name() })
return "Could not authenticate. Tried \(names.joined(separator: ", "))"
case .authError(let msg):
return "Authentication error: \(msg)"
}
}
}
extension SSHError {
init(title: String, forSession session: ssh_session?=nil) {
if let session = session {
let error = SSHError.getErrorDescription(session)
self = .connError(msg: "\(title) - \(error)")
} else {
self = .operationError(msg: title)
}
}
// Should we permit nil too?
init(_ rc: Int32, forSession session: ssh_session) {
switch rc {
case SSH_AGAIN:
self = .again
default:
let msg = SSHError.getErrorDescription(session)
self = .connError(msg: msg)
}
}
init(auth rc: ssh_auth_e, forSession session: ssh_session?=nil, message: String="Auth Error") {
switch rc {
case SSH_AUTH_AGAIN:
self = .again
default:
if let session = session {
let msg = SSHError.getErrorDescription(session)
self = .authError(msg: msg)
} else {
self = .authError(msg: message)
}
}
}
static func getErrorDescription(_ session: ssh_session) -> String {
let pErr = UnsafeMutableRawPointer(session)
guard let pErrMsg = ssh_get_error(pErr) else {
return "Unknown Error"
}
let errMsg = String(cString: pErrMsg)
return errMsg
}
}
| gpl-3.0 | 7da176a34ca822e8cb2fd1ae2e6e7a8c | 30.626866 | 97 | 0.63379 | 4.183613 | false | false | false | false |
rdgborges/twitch-top50 | TwitchTop50/TwitchTop50/Classes/AppDelegate/AppDelegate.swift | 1 | 3226 | //
// AppDelegate.swift
// TwitchTop50
//
// Created by Rodrigo Soares on 24/08/15.
// Copyright © 2015 Rodrigo Borges. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Initializes NSManagedObjectContext on ViewController
let navigationControler = self.window!.rootViewController
let rootViewController = navigationControler?.childViewControllers[0] as! ViewController
rootViewController.managedObjectContext = self.managedObjectContext;
return true
}
func applicationWillTerminate(application: UIApplication) {
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = NSBundle.mainBundle().URLForResource("TwitchTop50", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// TODO: Handle error
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 35f1e7e161d99e4e612b1e0ca909ecfe | 33.308511 | 127 | 0.664806 | 6.237911 | false | false | false | false |
huonw/swift | test/NameBinding/named_lazy_member_loading_objc_interface.swift | 14 | 1269 | // REQUIRES: objc_interop
// REQUIRES: OS=macosx
// RUN: rm -rf %t && mkdir -p %t/stats-pre && mkdir -p %t/stats-post
//
// Prime module cache
// RUN: %target-swift-frontend -typecheck -I %S/Inputs/NamedLazyMembers -typecheck -primary-file %s %S/Inputs/NamedLazyMembers/NamedLazyMembersExt.swift
//
// Check that named-lazy-member-loading reduces the number of Decls deserialized
// RUN: %target-swift-frontend -typecheck -I %S/Inputs/NamedLazyMembers -disable-named-lazy-member-loading -stats-output-dir %t/stats-pre -primary-file %s %S/Inputs/NamedLazyMembers/NamedLazyMembersExt.swift
// RUN: %target-swift-frontend -typecheck -I %S/Inputs/NamedLazyMembers -stats-output-dir %t/stats-post -primary-file %s %S/Inputs/NamedLazyMembers/NamedLazyMembersExt.swift
// RUN: %{python} %utils/process-stats-dir.py --evaluate-delta 'NumTotalClangImportedEntities < -10' %t/stats-pre %t/stats-post
import NamedLazyMembers
public func bar(d: SimpleDoerSubclass) {
let _ = d.simplyDoVeryImportantWork(speed: 10, motivation: 42)
}
public func foo(d: SimpleDoer) {
let _ = d.simplyDoSomeWork()
let _ = d.simplyDoSomeWork(withSpeed:10)
let _ = d.simplyDoVeryImportantWork(speed:10, thoroughness:12)
let _ = d.simplyDoSomeWorkWithSpeed(speed:10, levelOfAlacrity:12)
}
| apache-2.0 | f8e88dbd36cd9dd1a37aed395f477465 | 51.875 | 207 | 0.754137 | 3.072639 | false | false | false | false |
steven7/ParkingApp | MapboxNavigation/Style.swift | 1 | 10884 | import UIKit
fileprivate extension CGFloat {
fileprivate static var defaultManeuverViewHeight: CGFloat = 115
}
extension UIColor {
class var defaultRouteCasing: UIColor { get { return .defaultTintStroke } }
class var defaultRouteLayer: UIColor { get { return UIColor.defaultTintStroke.withAlphaComponent(0.6) } }
class var defaultArrowStroke: UIColor { get { return .defaultTint } }
}
fileprivate extension UIColor {
// General styling
fileprivate class var defaultTint: UIColor { get { return #colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1) } }
fileprivate class var defaultTintStroke: UIColor { get { return #colorLiteral(red: 0.05882352963, green: 0.180392161, blue: 0.2470588237, alpha: 1) } }
fileprivate class var defaultPrimaryText: UIColor { get { return #colorLiteral(red: 45.0/255.0, green: 45.0/255.0, blue: 45.0/255.0, alpha: 1) } }
fileprivate class var defaultSecondaryText: UIColor { get { return #colorLiteral(red: 0.4509803922, green: 0.4509803922, blue: 0.4509803922, alpha: 1) } }
fileprivate class var defaultLine: UIColor { get { return #colorLiteral(red: 0.7825912237, green: 0.7776457667, blue: 0.7863886952, alpha: 0.7) } }
// Maneuver view (Page view)
fileprivate class var defaultManeuverViewBackground: UIColor { get { return #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) } }
// Table view (Drawer)
fileprivate class var defaultHeaderBackground: UIColor { get { return #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) } }
fileprivate class var defaultHeaderTitleLabel: UIColor { get { return defaultPrimaryText } }
fileprivate class var defaultHeaderSubtitleLabel: UIColor { get { return defaultSecondaryText } }
}
fileprivate extension UIFont {
// General styling
fileprivate class var defaultPrimaryText: UIFont { get { return UIFont.systemFont(ofSize: 16) } }
fileprivate class var defaultSecondaryText: UIFont { get { return UIFont.systemFont(ofSize: 16) } }
fileprivate class var defaultCellTitleLabel: UIFont { get { return UIFont.systemFont(ofSize: 28, weight: UIFontWeightMedium) } }
// Table view (drawer)
fileprivate class var defaultHeaderTitleLabel: UIFont { get { return UIFont.preferredFont(forTextStyle: .headline) } }
}
/**
`Style` is a convenient wrapper for styling the appearance of various interface
components throughout the Navigation UI.
*/
@objc(MBStyle)
public class Style: NSObject {
public var traitCollection: UITraitCollection
/**
Initializes a style that will be applied for any system traits of an
interface’s environment.
*/
convenience override public init() {
self.init(traitCollection: UITraitCollection())
}
/**
Initializes a style for a specific system trait(s) of an interface’s
environment.
*/
required public init(traitCollection: UITraitCollection) {
self.traitCollection = traitCollection
super.init()
}
/// General styling
/**
`tintColor` is used for guidance arrow, highlighted text, progress bar and
more.
*/
public var tintColor: UIColor?
/**
`primaryTextColor` sets the color for titles and other prominent information.
*/
public var primaryTextColor: UIColor?
/**
`secondaryTextColor` sets the color for subtitles and other subtle
information.
*/
public var secondaryTextColor: UIColor?
/**
`buttonTextColor` sets the text color on buttons for normal state.
*/
public var buttonTextColor: UIColor?
/**
`lineColor` sets the color of dividers and separators.
*/
public var lineColor: UIColor?
/// Maneuver view (Page view)
/**
`maneuverViewBackgroundColor` sets the background color of the maneuver
view, positioned at the top.
*/
public var maneuverViewBackgroundColor: UIColor?
/**
`maneuverViewHeight` sets the height of the maneuver view.
*/
public var maneuverViewHeight: CGFloat?
/// Table view (Drawer)
/**
`headerBackgroundColor` sets the color of the drawer header, positioned at
the bottom.
*/
public var headerBackgroundColor: UIColor?
/**
`cellTitleLabelFont` sets the font of the title labels in table views.
*/
public var cellTitleLabelFont: UIFont?
/**
`cellTitleLabelTextColor` sets the title text color in table views.
*/
public var cellTitleLabelTextColor: UIColor?
/**
`cellSubtitleLabelFont` sets the font of the subtitle label in table views.
*/
public var cellSubtitleLabelFont: UIFont?
/**
`cellSubtitleLabelTextColor` sets the text color of the subtitle label in
table views.
*/
public var cellSubtitleLabelTextColor: UIColor?
/**
`wayNameTextColor` sets the color for the current way name label.
*/
public var wayNameTextColor: UIColor?
/**
`wayNameLabelFont` sets the font of the current way name label.
*/
public var wayNameLabelFont: UIFont?
/**
`defaultStyle` returns the default style for Mapbox Navigation SDK.
*/
public class var defaultStyle: Style {
let style = Style(traitCollection: UITraitCollection())
// General styling
if let tintColor = UIApplication.shared.delegate?.window??.tintColor {
style.tintColor = tintColor
} else {
style.tintColor = .defaultTint
}
style.primaryTextColor = .defaultPrimaryText
style.secondaryTextColor = .defaultSecondaryText
style.buttonTextColor = .defaultPrimaryText
style.lineColor = .defaultLine
// Maneuver view (Page view)
style.maneuverViewBackgroundColor = .defaultManeuverViewBackground
style.maneuverViewHeight = .defaultManeuverViewHeight
// Table view (Drawer)
style.headerBackgroundColor = .defaultHeaderBackground
style.cellTitleLabelFont = .defaultPrimaryText
style.cellTitleLabelTextColor = .defaultPrimaryText
style.cellSubtitleLabelFont = .defaultSecondaryText
style.cellSubtitleLabelTextColor = .defaultSecondaryText
return style
}
/**
Applies the style for all changed properties.
*/
public func apply() {
// General styling
if let color = tintColor {
NavigationMapView.appearance(for: traitCollection).tintColor = color
ProgressBar.appearance(for: traitCollection).backgroundColor = color
Button.appearance(for: traitCollection).tintColor = color
HighlightedButton.appearance(for: traitCollection).setTitleColor(color, for: .normal)
}
if let color = primaryTextColor {
TitleLabel.appearance(for: traitCollection).textColor = color
CellTitleLabel.appearance(for: traitCollection).textColor = color
}
if let color = secondaryTextColor {
SubtitleLabel.appearance(for: traitCollection).textColor = color
CellSubtitleLabel.appearance(for: traitCollection).textColor = color
}
if let color = buttonTextColor {
Button.appearance(for: traitCollection).textColor = color
}
if let color = lineColor {
// Line view can be a dashed line view so we add a lineColor to avoid changing the background.
LineView.appearance(for: traitCollection).lineColor = color
// Separator view can also be a divider (vertical/horizontal) with a solid background color.
SeparatorView.appearance(for: traitCollection).backgroundColor = color
}
// Maneuver page view controller
if let color = maneuverViewBackgroundColor {
ManeuverView.appearance(for: traitCollection).backgroundColor = color
}
if let height = maneuverViewHeight {
ManeuverView.appearance(for: traitCollection).height = height
}
// Table view (drawer)
if let color = headerBackgroundColor {
RouteTableViewHeaderView.appearance(for: traitCollection).backgroundColor = color
}
if let font = cellTitleLabelFont {
CellTitleLabel.appearance(for: traitCollection).font = font
}
if let color = cellTitleLabelTextColor {
CellTitleLabel.appearance(for: traitCollection).textColor = color
}
if let font = cellSubtitleLabelFont {
CellSubtitleLabel.appearance(for: traitCollection).font = font
}
if let color = cellSubtitleLabelTextColor {
CellSubtitleLabel.appearance(for: traitCollection).textColor = color
}
if let color = wayNameTextColor {
WayNameLabel.appearance(for: traitCollection).textColor = color
}
if let font = wayNameLabelFont {
WayNameLabel.appearance(for: traitCollection).font = font
}
}
}
/**
`MBButton` sets the tintColor according to the style.
*/
@objc(MBButton)
public class Button: StylableButton { }
/**
`MBHighlightedButton` sets the button’s titleColor for normal control state
according to the style in addition to the styling behavior inherited from
`MBButton`.
*/
@objc(MBHighlightedButton)
public class HighlightedButton: Button { }
@objc(MBStylableLabel)
public class StylableLabel : UILabel { }
@objc(MBTitleLabel)
public class TitleLabel: StylableLabel { }
@objc(MBSubtitleLabel)
public class SubtitleLabel: StylableLabel { }
@objc(MBCellTitleLabel)
public class CellTitleLabel: StylableLabel { }
@objc(MBCellSubtitleLabel)
public class CellSubtitleLabel: StylableLabel { }
@objc(MBWayNameLabel)
public class WayNameLabel: StylableLabel { }
@objc(MBProgressBar)
public class ProgressBar: UIView { }
@objc(MBLineView)
public class LineView: UIView {
dynamic var lineColor: UIColor = .defaultLine {
didSet {
setNeedsDisplay()
setNeedsLayout()
}
}
}
@objc(MBSeparatorView)
public class SeparatorView: UIView { }
@objc(MBStylableButton)
public class StylableButton: UIButton {
dynamic var textColor: UIColor = .defaultPrimaryText {
didSet {
setTitleColor(textColor, for: .normal)
}
}
}
@objc(MBManeuverView)
class ManeuverView: UIView {
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
dynamic var height: CGFloat = .defaultManeuverViewHeight {
didSet {
heightConstraint.constant = height
setNeedsUpdateConstraints()
}
}
}
| isc | 6aa5c0dc0406c98a671c01099294c220 | 32.782609 | 158 | 0.666115 | 4.913279 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/SensorData/SensorData.swift | 1 | 6236 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import CoreData
import Foundation
/// A Science Journal sensor data model object that is stored in Core Data.
final class SensorData: NSManagedObject {
/// The sensor tag of the sensor that this data was recored by.
@NSManaged var sensor: String
/// The timestamp this sensor data was recorded at.
@NSManaged var timestamp: Int64
/// The value of the sensor data.
@NSManaged var value: Double
/// The resolution tier of the data.
@NSManaged var resolutionTier: Int16
/// The ID of the trial this sensor data is associated with.
@NSManaged var trialID: String
/// Inserts a new sensor data object into Core Data.
///
/// - Parameters:
/// - dataPoint: The data point to store.
/// - sensorID: The ID of the sensor the data was recorded by.
/// - trialID: The ID of the trial this data was recored for.
/// - resolutionTier: The resolution tier to which the data point belongs.
/// - context: The managed object context to perform the insert on. If nil it will use the main
/// context.
@discardableResult static func insert(dataPoint: DataPoint,
forSensorID sensorID: String,
trialID: String,
resolutionTier: Int16,
context: NSManagedObjectContext) -> SensorData {
let sensorData: SensorData = context.insertObject()
sensorData.value = dataPoint.y
sensorData.timestamp = dataPoint.x
sensorData.sensor = sensorID
sensorData.trialID = trialID
sensorData.resolutionTier = resolutionTier
return sensorData
}
/// Returns a fetch request for all sensor data with unique sensor IDs in a trial. If timestamps
/// are given there must be both start and end timestamps, not just one.
///
/// - Parameters:
/// - trialID: The trial ID.
/// - startTimestamp: The earliest timestamp to fetch.
/// - endTimestamp: The latest timestamp to fetch.
/// - Returns: The fetch request.
static func fetchRequest(withTrialID trialID: String,
startTimestamp: Int64? = nil,
endTimestamp: Int64? = nil) -> NSFetchRequest<SensorData> {
let fetchRequest = sortedFetchRequest
if let startTimestamp = startTimestamp, let endTimestamp = endTimestamp {
let format = "trialID = %@ AND resolutionTier = 0 AND timestamp BETWEEN { %@, %@ }"
fetchRequest.predicate = NSPredicate(format: format,
argumentArray: [trialID, startTimestamp, endTimestamp])
} else {
fetchRequest.predicate = NSPredicate(format: "trialID = %@ AND resolutionTier = 0", trialID)
}
return fetchRequest
}
/// Returns a fetch request for all sensor data with unique sensor IDs in a trial, at all
/// resolution tiers.
///
/// - Parameter trialID: The trial ID.
/// - Returns: The fetch request.
static func fetchAllRequest(withTrialID trialID: String) -> NSFetchRequest<SensorData> {
let fetchRequest = sortedFetchRequest
fetchRequest.predicate = NSPredicate(format: "trialID = %@", trialID)
return fetchRequest
}
/// Returns a fetch request for the count of all sensor data with unique sensor IDs in a trial, at
/// all resolution tiers.
///
/// - Parameter trialID: The trial ID.
/// - Returns: The fetch request.
static func countOfAllRequest(withTrialID trialID: String) -> NSFetchRequest<SensorData> {
let fetchRequest = NSFetchRequest<SensorData>(entityName: entityName)
fetchRequest.predicate = NSPredicate(format: "trialID = %@", trialID)
fetchRequest.resultType = .countResultType
return fetchRequest
}
/// Returns a fetch request for all data points for a sensor in a trial. If timestamps
/// are given there must be both start and end timestamps, not just one.
///
/// - Parameters:
/// - sensorID: The sensor ID.
/// - trialID: The trial ID.
/// - resolutionTier: The resolution tier to fetch, defaults to 0.
/// - startTimestamp: The earliest timestamp to fetch.
/// - endTimestamp: The latest timestamp to fetch.
/// - Returns: The fetch request.
static func fetchRequest(for sensorID: String,
trialID: String,
resolutionTier: Int = 0,
startTimestamp: Int64? = nil,
endTimestamp: Int64? = nil) -> NSFetchRequest<SensorData> {
let fetchRequest = SensorData.sortedFetchRequest
if let startTimestamp = startTimestamp, let endTimestamp = endTimestamp {
let format =
"sensor = %@ AND trialID = %@ AND resolutionTier = %@ AND timestamp BETWEEN { %@, %@ }"
fetchRequest.predicate = NSPredicate(
format: format,
argumentArray: [sensorID, trialID, resolutionTier, startTimestamp, endTimestamp])
} else {
fetchRequest.predicate =
NSPredicate(format: "sensor = %@ AND trialID = %@ AND resolutionTier = %d",
sensorID,
trialID,
resolutionTier)
}
return fetchRequest
}
}
extension SensorData: Managed {
static var entityName: String {
return "SensorData"
}
static var defaultSortDescriptors: [NSSortDescriptor] {
return [NSSortDescriptor(key: "timestamp", ascending: true)]
}
}
extension Array where Element:SensorData {
/// Returns an array, `[DataPoint]` (one for each `SensorData` object.
var dataPoints: [DataPoint] {
return map { DataPoint(x: $0.timestamp, y: $0.value) }
}
}
| apache-2.0 | e31c8ff2d299fe3199393be8807802d9 | 39.75817 | 100 | 0.652662 | 4.738602 | false | false | false | false |
mleiv/IBStyler | Initial Code Files/IBStyles/IBStyleProperty.swift | 2 | 2969 | //
// IBStyleProperty.swift
// MEGameTracker
//
// Created by Emily Ivie on 3/10/17.
// Copyright © 2017 Emily Ivie. All rights reserved.
//
import UIKit
/// All the current possible IBStyle options.
/// Note: neither StateX or IPad|IPhoneStyles are properly visible in Interface Builder.
/// Use the @IBInspectable properties in IBStyledButton and IBStyledRootView to set them.
public enum IBStyleProperty {
public typealias List = [IBStyleProperty: Any]
public typealias Group = [String: List]
/// Expects string of IBStyle names. Applies them in order listed, with current styles taking precedence.
case inherit //[String]
/// UIColor
case backgroundColor
/// IBGradient. Ex: IBGradient(direction:.Vertical, colors:[UIColor.red,UIColor.black]).
case backgroundGradient
/// UIColor
case borderColor
/// Double
case borderWidth
/// UIImage?
case buttonImage
/// Double
case cornerRadius
/// IBFont. Add new fonts to IBFont enum. This field will only accept IBFont enum values.
case font
/// Bool
case hasAdjustableFontSize
/// Array (v, h) or (t, l, r, b). NOTE: Currently only works for button and textview.
case padding
/// IBStyleProperty.List to only apply when button is active.
case stateActive
/// IBStyleProperty.List to only apply when button is pressed.
case statePressed
/// IBStyleProperty.List to only apply when button is disabled.
case stateDisabled
/// IBStyleProperty.List to only apply when button is selected.
case stateSelected
/// IBTextAlignment
case textAlign
/// UIColor
case textColor
/// A custom string property - more risky than other options, but provides unlimited functionality.
case custom(String)
/// All the options, in order of precedent.
static var orderedList: [IBStyleProperty: Int] = [
.inherit: 0,
.backgroundGradient: 32,
.buttonImage: 9,
.stateActive: 10,
.statePressed: 11,
.stateDisabled: 12,
.stateSelected: 13,
.hasAdjustableFontSize: 20,
.font: 21,
.textColor: 22,
.textAlign: 23,
.padding: 30,
.backgroundColor: 31,
.cornerRadius: 40,
.borderWidth: 41,
.borderColor: 42
]
/// Sort a list of properties by order of precedent.
public static func sort(_ first: IBStyleProperty, _ second: IBStyleProperty) -> Bool {
return first.sortIndex < second.sortIndex
}
/// Order of precedent.
public var sortIndex: Int {
return IBStyleProperty.orderedList[self] ?? 100
}
}
// MARK: IBStyles.Property Extensions
extension IBStyleProperty: Hashable {
public func hash(into hasher: inout Hasher) {
switch self {
case (.custom(let v1)):
hasher.combine(v1)
default:
break
}
}
}
// MARK: Property Equatable Protocol
extension IBStyleProperty: Equatable {}
public func == (lhs: IBStyleProperty, rhs: IBStyleProperty) -> Bool {
switch (lhs, rhs) {
case (.custom(let value1), .custom(let value2)):
return value1 == value2
default:
return "\(lhs)" == "\(rhs)"
}
}
| mit | c24f7168670fc24ec46a585595db3959 | 26.738318 | 106 | 0.707547 | 3.623932 | false | false | false | false |
yangboz/SwiftSteeringBehavior | SwiftSteeringBehaviorDemo/SwiftSteeringBehaviorDemo/ViewController.swift | 1 | 1403 | //
// ViewController.swift
// SwiftSteeringBehaviorDemo
//
// Created by yangboz on 14-8-7.
// Copyright (c) 2014年 GODPAPER. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let square = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100));
square.backgroundColor = UIColor.gray;
view.addSubview(square);
//
var animator:UIDynamicAnimator!;
var gravity:UIGravityBehavior!;
//
animator = UIDynamicAnimator(referenceView: view);
gravity = UIGravityBehavior(items: [square]);
animator.addBehavior(gravity);
//
let barrier = UIView(frame: CGRect(x: 0, y: 300, width: 130, height: 20));
barrier.backgroundColor = UIColor.red;
view.addSubview(barrier);
//Handle collision
var collision:UICollisionBehavior!;
collision = UICollisionBehavior(items: [square,barrier]);
collision.translatesReferenceBoundsIntoBoundary = true;
animator.addBehavior(collision);
//
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 6595f216c62158878b6bb4ead59f2099 | 29.456522 | 84 | 0.62955 | 4.797945 | false | false | false | false |
RobotsAndPencils/Scythe | Scythe/AppDelegate.swift | 1 | 1581 | //
// AppDelegate.swift
// Scythe
//
// Created by Brandon Evans on 2017-01-04.
// Copyright © 2017 Robots and Pencils. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var credentialsViewController: CredentialsViewController?
var timersViewController: TimersViewController?
func applicationDidFinishLaunching(_ aNotification: Notification) {
let storyboard = NSStoryboard(name: "Main", bundle: nil)
credentialsViewController = NSApplication.shared().windows.first?.contentViewController as? CredentialsViewController
timersViewController = storyboard.instantiateController(withIdentifier: "TimersViewController") as? TimersViewController
credentialsViewController?.signInHandler = { [weak self] credentials in
let service = HarvestService(credentials: credentials)
service.verifyCredentials { result in
switch result {
case .success:
self?.timersViewController?.service = service
NSApplication.shared().mainWindow?.contentViewController = self?.timersViewController
case .failure(let error):
NSAlert(error: error).runModal()
self?.credentialsViewController?.signInButton.isEnabled = true
}
}
}
timersViewController?.signOutHandler = { [weak self] in
NSApplication.shared().mainWindow?.contentViewController = self?.credentialsViewController
}
}
}
| mit | f133ea028f9a96dae284780ea4e11544 | 40.578947 | 128 | 0.678481 | 5.851852 | false | false | false | false |
cabarique/TheProposalGame | MyProposalGame/Components/ParallaxComponent.swift | 1 | 2443 | /*
* Copyright (c) 2015 Neil North.
*
* 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 SpriteKit
import GameplayKit
class ParallaxComponent: GKComponent {
var movementFactor = CGPointZero
var pointOfOrigin = CGPointZero
var resetLocation = false
var spriteComponent: SpriteComponent {
guard let spriteComponent = entity?.componentForClass(SpriteComponent.self) else { fatalError("SpriteComponent Missing") }
return spriteComponent
}
init(entity: GKEntity, movementFactor factor:CGPoint, spritePosition:CGPoint, reset:Bool) {
super.init()
movementFactor = factor
pointOfOrigin = spritePosition
resetLocation = reset
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateWithDeltaTime(seconds: NSTimeInterval) {
super.updateWithDeltaTime(seconds)
//Move Sprite
spriteComponent.node.position += CGPoint(x: movementFactor.x, y: movementFactor.y)
//Check location
if (spriteComponent.node.position.x <= (spriteComponent.node.size.width * -1)) && resetLocation == true {
spriteComponent.node.position = CGPoint(x: spriteComponent.node.size.width, y: 0)
}
//Add other directions if required.
}
}
| mit | 6c0619e58f8d051c5a0874502348c93e | 36.584615 | 130 | 0.698731 | 4.780822 | false | false | false | false |
jpsim/CardsAgainst | CardsAgainst/Views/WhiteCardCell.swift | 1 | 1482 | //
// WhiteCardCell.swift
// CardsAgainst
//
// Created by JP Simard on 11/3/14.
// Copyright (c) 2014 JP Simard. All rights reserved.
//
import UIKit
import Cartography
final class WhiteCardCell: UICollectionViewCell {
class var reuseID: String { return "WhiteCardCell" }
let label = UILabel()
override var isHighlighted: Bool {
get {
return super.isHighlighted
}
set {
contentView.backgroundColor = newValue ? .gray : lightColor
super.isHighlighted = newValue
}
}
override init(frame: CGRect) {
super.init(frame: frame)
// Background
contentView.backgroundColor = lightColor
contentView.layer.cornerRadius = 8
// Label
setupLabel()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupLabel() {
// Label
contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.font = .whiteCardFont
label.textColor = darkColor
// Layout
constrain(label) { label in
label.edges == inset(label.superview!.edges, 15, 10)
}
}
override func layoutSubviews() {
super.layoutSubviews()
label.preferredMaxLayoutWidth = label.frame.size.width
}
}
| mit | 85c431afeebcd7c955c5b495c984f4f5 | 23.295082 | 71 | 0.617409 | 4.956522 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/Requests/Hashtag/SuggestedHashtagsFetchResponseHandler.swift | 1 | 2384 | //
// SuggestedHashtagsFetchResponseHandler.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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 UIKit
import ObjectMapper
class SuggestedHashtagsFetchResponseHandler: ResponseHandler
{
fileprivate let completion: HashtagsClosure?
init(completion: HashtagsClosure?)
{
self.completion = completion
}
override func handleResponse(_ response: Dictionary<String, AnyObject>?, error: Error?)
{
if let response = response,
let mappers = Mapper<HashtagMapper>().mapArray(JSONObject: response["data"])
{
let metadata = MappingUtils.metadataFromResponse(response)
let pageInfo = MappingUtils.pagingInfoFromResponse(response)
let dataMapper = MappingUtils.dataIncludeMapperFromResponse(response, metadata: metadata)
let hashtags = mappers.map({ Hashtag(mapper: $0, dataMapper: dataMapper, metadata: metadata) })
executeOnMainQueue { self.completion?(hashtags, pageInfo, ErrorTransformer.errorFromResponse(response, error: error)) }
}
else
{
executeOnMainQueue { self.completion?(nil, nil, ErrorTransformer.errorFromResponse(response, error: error)) }
}
}
}
| mit | 5c806a03ebc075f0396ae0bca9bc1e69 | 41.571429 | 131 | 0.716023 | 4.825911 | false | false | false | false |
DavadDi/flatbuffers | grpc/examples/swift/Greeter/Sources/client/main.swift | 2 | 3318 | /*
* Copyright 2021 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import FlatBuffers
import GRPC
import Logging
import Model
import NIO
// Quieten the logs.
LoggingSystem.bootstrap {
var handler = StreamLogHandler.standardOutput(label: $0)
handler.logLevel = .critical
return handler
}
func greet(name: String, client greeter: models_GreeterServiceClient) {
// Form the request with the name, if one was provided.
var builder = FlatBufferBuilder()
let nameOff = builder.create(string: name)
let root = models_HelloRequest.createHelloRequest(
&builder,
nameOffset: nameOff)
builder.finish(offset: root)
// Make the RPC call to the server.
let sayHello = greeter.SayHello(Message<models_HelloRequest>(builder: &builder))
// wait() on the response to stop the program from exiting before the response is received.
do {
let response = try sayHello.response.wait()
print("Greeter SayHello received: \(response.object.message ?? "Unknown")")
} catch {
print("Greeter failed: \(error)")
}
let surname = builder.create(string: name)
let manyRoot = models_HelloRequest.createHelloRequest(
&builder,
nameOffset: surname)
builder.finish(offset: manyRoot)
let call = greeter.SayManyHellos(Message(builder: &builder)) { message in
print("Greeter SayManyHellos received: \(message.object.message ?? "Unknown")")
}
let status = try! call.status.recover { _ in .processingError }.wait()
if status.code != .ok {
print("RPC failed: \(status)")
}
}
func main(args: [String]) {
// arg0 (dropped) is the program name. We expect arg1 to be the port, and arg2 (optional) to be
// the name sent in the request.
let arg1 = args.dropFirst(1).first
let arg2 = args.dropFirst(2).first
switch (arg1.flatMap(Int.init), arg2) {
case (.none, _):
print("Usage: PORT [NAME]")
exit(1)
case let (.some(port), name):
// Setup an `EventLoopGroup` for the connection to run on.
//
// See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
// Make sure the group is shutdown when we're done with it.
defer {
try! group.syncShutdownGracefully()
}
// Configure the channel, we're not using TLS so the connection is `insecure`.
let channel = ClientConnection.insecure(group: group)
.connect(host: "localhost", port: port)
// Close the connection when we're done with it.
defer {
try! channel.close().wait()
}
// Provide the connection to the generated client.
let greeter = models_GreeterServiceClient(channel: channel)
// Do the greeting.
greet(name: name ?? "FlatBuffers!", client: greeter)
}
}
main(args: CommandLine.arguments)
| apache-2.0 | 08e3692093c2548affabd25bcb2015c2 | 30.6 | 97 | 0.701025 | 3.889801 | false | false | false | false |
zyuanming/EffectDesignerX | EffectDesignerX/ViewController.swift | 1 | 12946 | //
// ViewController.swift
// EffectDesignerX
//
// Created by Zhang Yuanming on 10/11/16.
// Copyright © 2016 Zhang Yuanming. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
var switchingTab: Bool = false
var previousTitle: String = ""
var items: [Item] = []
var saveFilePath: String?
var selectedLayerIndex: Int = 0
var effectModels: [EffectModel] = EffectModel.getEffectModels()
var effectModel: EffectModel {
return effectModels[selectedLayerIndex]
}
let selectedCellModel: BindingModel = BindingModel()
var effectView: UIEffectView?
@IBOutlet weak var effectBox: NSBox!
@IBOutlet weak var tabsControl: TabsControl!
@IBOutlet weak var textureButton: FileButton!
@IBOutlet weak var tableView: NSTableView!
let kEmitterMode = EffectModel.kEmitterMode.map{ $0.1 }
let kRenderMode = EffectModel.kRenderMode.map{ $0.1 }
let kEmitterShape = EffectModel.kEmitterShape.map{ $0.1 }
override func viewDidLoad() {
super.viewDidLoad()
updateBindingModel(cellIndex: 0)
effectView = UIEffectView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
effectView?.reload(effectModels)
effectBox.addSubview(effectView!)
for propertyName in selectedCellModel.allPropertyNames() {
selectedCellModel.addObserver(self, forKeyPath: propertyName, options: .new, context: nil)
}
for cellModel in effectModel.cellModels {
let item = Item(title: cellModel.name, icon: cellModel.contentsImage)
items.append(item)
}
tabsControl.dataSource = self
tabsControl.delegate = self
tabsControl.reloadTabs()
tabsControl.selectItemAtIndex(0)
textureButton.dragFileHandler = ({[weak self] (filePath) in
self?.loadImage(forFile: filePath)
})
}
deinit {
for propertyName in effectModel.allPropertyNames() {
effectModel.removeObserver(self, forKeyPath: propertyName)
}
for propertyName in selectedCellModel.allPropertyNames() {
selectedCellModel.removeObserver(self, forKeyPath: propertyName)
}
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
refreshUI()
}
@IBAction func saveDocument(_ sender: AnyObject) {
print("Button was clicked", sender)
if let saveFilePath = saveFilePath {
(EffectModel.toArray(models: effectModels) as NSArray).write(toFile: saveFilePath, atomically: true)
} else {
saveDocumentAs(sender)
}
}
@IBAction func saveDocumentAs(_ sender: AnyObject) {
print("Button was clicked", sender)
let savePanel = NSSavePanel()
savePanel.allowedFileTypes = ["plist"]
savePanel.beginSheetModal(for: view.window!) { (result) in
if result == 1 {
let filePath = savePanel.url!.path
self.saveFilePath = filePath
(EffectModel.toArray(models: self.effectModels) as NSArray).write(toFile: filePath, atomically: true)
self.view.window?.title = (filePath as NSString).lastPathComponent
}
}
}
@IBAction func addNewTab(_ sender: AnyObject) {
let cellModel = effectModel.cellModels.last!
let newModel = EmitterCellModel()
newModel.update(from: cellModel)
newModel.name = newModel.name + "1"
effectModel.cellModels.append(newModel)
effectView?.reload(effectModels)
effectView?.needsDisplay = true
let item = Item(title: newModel.name, icon: newModel.contentsImage)
items.append(item)
tabsControl.reloadTabs()
}
@IBAction func addEmitterLayer(_ sender: Any) {
switchingTab = true
effectModels.append(effectModel.copy() as! EffectModel)
switchingTab = false
}
@IBAction func deleteEmitterLayer(_ sender: Any) {
guard effectModels.count > 1 else {return }
let currentRow = selectedLayerIndex
var targetNewRow = currentRow
if currentRow == 0 {
targetNewRow = 1
} else {
targetNewRow = currentRow - 1
}
switchToEmitterLayer(at: targetNewRow)
switchingTab = true
effectModels.remove(at: currentRow)
tableView.removeRows(at: [currentRow], withAnimation: [])
if effectModels.count == 1 {
targetNewRow = 0
}
selectedLayerIndex = targetNewRow
switchingTab = false
}
func loadImage(forFile filePath: String) {
self.selectedCellModel.contentsImage = NSImage(contentsOfFile: filePath)
self.refreshUI()
}
func loadFile(filePath: String) {
switchingTab = true
effectModels = EffectModel.getEffectModels(filePath: filePath)
updateBindingModel(cellIndex: 0)
tableView.reloadData()
effectView?.reload(effectModels)
effectView?.needsDisplay = true
switchingTab = false
items.removeAll()
for cellModel in effectModel.cellModels {
let item = Item(title: cellModel.name, icon: cellModel.contentsImage)
items.append(item)
}
tabsControl.reloadTabs()
tabsControl.selectItemAtIndex(0)
}
private func refreshUI() {
if let selectedIndex = tabsControl.selectedButtonIndex, !switchingTab, effectModel.cellModels.count > selectedIndex {
updateFromBindingModel(cellIndex: selectedIndex)
}
effectView?.reload(effectModels)
effectView?.needsDisplay = true
}
func updateBindingModel(cellIndex: Int) {
selectedCellModel.update(from: effectModel.cellModels[cellIndex])
selectedCellModel.emitterShape = effectModel.emitterShape
selectedCellModel.emitterMode = effectModel.emitterMode
selectedCellModel.renderMode = effectModel.renderMode
selectedCellModel.preservesDepth = effectModel.preservesDepth
selectedCellModel.width = effectModel.width
selectedCellModel.height = effectModel.height
}
func updateFromBindingModel(cellIndex: Int) {
effectModel.cellModels[cellIndex].update2(from: selectedCellModel)
effectModel.emitterShape = selectedCellModel.emitterShape
effectModel.emitterMode = selectedCellModel.emitterMode
effectModel.renderMode = selectedCellModel.renderMode
effectModel.preservesDepth = selectedCellModel.preservesDepth
effectModel.width = selectedCellModel.width
effectModel.height = selectedCellModel.height
}
}
extension ViewController: NSTableViewDataSource, NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cellView: EmitterTableCellView = tableView.make(withIdentifier: "EmitterLayerColumn", owner: self) as! EmitterTableCellView
cellView.titleLabel.stringValue = "EmitterLayer \(row)"
cellView.buttonHandler = {[weak self] button in
guard let strongSelf = self else { return }
let selectedRow = tableView.row(for: button)
print(selectedRow)
strongSelf.effectView?.setEmitterLayer(Int32(selectedRow), hidden: button.state != NSOnState)
}
return cellView
}
func numberOfRows(in tableView: NSTableView) -> Int {
return effectModels.count
}
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
if let cellView = tableView.rowView(atRow: selectedLayerIndex, makeIfNecessary: false) {
cellView.backgroundColor = NSColor.clear
}
if let cellView = tableView.rowView(atRow: row, makeIfNecessary: true) {
cellView.backgroundColor = NSColor.lightGray.withAlphaComponent(0.5)
}
return true
}
func tableViewSelectionDidChange(_ notification: Notification) {
switchToEmitterLayer(at: (notification.object as! NSTableView).selectedRow)
}
func switchToEmitterLayer(at row: Int) {
switchingTab = true
let tagIndex = tabsControl.selectedButtonIndex!
updateFromBindingModel(cellIndex: tagIndex)
previousTitle = items[tagIndex].title
let _ = tableView(tableView, shouldSelectRow: row)
selectedLayerIndex = row
updateBindingModel(cellIndex: 0)
items.removeAll()
for cellModel in effectModel.cellModels {
let item = Item(title: cellModel.name, icon: cellModel.contentsImage)
items.append(item)
}
tabsControl.reloadTabs()
tabsControl.selectItemAtIndex(0)
tableView.selectRowIndexes([selectedLayerIndex], byExtendingSelection: false)
switchingTab = false
}
}
extension ViewController: TabsControlDelegate, TabsControlDataSource {
// MARK: TabsControlDataSource
func tabsControlNumberOfTabs(_ control: TabsControl) -> Int {
return self.items.count
}
func tabsControl(_ control: TabsControl, itemAtIndex index: Int) -> AnyObject {
return self.items[index]
}
func tabsControl(_ control: TabsControl, titleForItem item: AnyObject) -> String {
return (item as! Item).title
}
// MARK: TabsControlDataSource : Optionals
func tabsControl(_ control: TabsControl, iconForItem item: AnyObject) -> NSImage? {
return (item as! Item).icon
}
// MARK: TabsControlDelegate
func tabsControl(_ control: TabsControl, canEditTitleOfItem: AnyObject) -> Bool {
return true
}
func tabsControl(_ control: TabsControl, setTitle newTitle: String, forItem item: AnyObject) {
let typedItem = item as! Item
let titles = self.items.map { $0.title }
let index = titles.index(of: typedItem.title)!
if index == control.selectedButtonIndex {
selectedCellModel.name = newTitle
}
effectModel.cellModels[index].name = newTitle
let newItem = Item(title: newTitle, icon: typedItem.icon)
let range = index..<index+1
self.items.replaceSubrange(range, with: [newItem])
}
func tabsControl(_ control: TabsControl, canSelectItem item: AnyObject) -> Bool {
return (item as! Item).selectable
}
func tabsControlDidChangeSelection(_ control: TabsControl, item: AnyObject) {
if let selectedIndex = control.selectedButtonIndex, items[selectedIndex].title != previousTitle {
switchingTab = true
if let previousIndex = getItemIndex(forTitle: previousTitle) {
updateFromBindingModel(cellIndex: previousIndex)
updateBindingModel(cellIndex: selectedIndex)
}
previousTitle = items[selectedIndex].title
switchingTab = false
}
}
func tabsControl(_ control: TabsControl, didCloseItem item: AnyObject) {
guard let selectedIndex = control.selectedButtonIndex, let item = item as? Item, items.count > 1 else { return }
if let index = getItemIndex(item: item) {
switchingTab = true
items.remove(at: index)
effectModel.cellModels.remove(at: index)
effectView?.reload(effectModels)
effectView?.needsDisplay = true
control.reloadTabs()
if selectedIndex == index {
if selectedIndex == 0 {
updateBindingModel(cellIndex: 0)
} else {
updateBindingModel(cellIndex: selectedIndex - 1)
}
}
if selectedIndex > index || selectedIndex == index {
if selectedIndex == 0 {
control.selectItemAtIndex(0)
} else {
control.selectItemAtIndex(selectedIndex - 1)
}
}
switchingTab = false
}
}
fileprivate func getItemIndex(item: Item) -> Int? {
for (index, itemModel) in items.enumerated() {
if itemModel.title == item.title {
return index
}
}
return nil
}
fileprivate func getItemIndex(forTitle title: String) -> Int? {
for (index, itemModel) in items.enumerated() {
if itemModel.title == title {
return index
}
}
return nil
}
}
class Item {
var title: String = ""
var icon: NSImage?
var selectable: Bool
init(title: String, icon: NSImage?, selectable: Bool = true) {
self.title = title
self.icon = icon
self.selectable = selectable
}
}
| mit | 7a405ccec1fed2a70db599984454f381 | 31.772152 | 151 | 0.641251 | 4.884906 | false | false | false | false |
brettg/Signal-iOS | Signal/src/views/AttachmentPointerView.swift | 1 | 4651 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
class AttachmentPointerView: UIView {
let TAG = "[AttachmentPointerView]"
let progressView = OWSProgressView()
let nameLabel = UILabel()
let statusLabel = UILabel()
let isIncoming: Bool
let filename: String
let attachmentPointer: TSAttachmentPointer
let genericFilename = NSLocalizedString("ATTACHMENT_DEFAULT_FILENAME", comment: "Generic filename for an attachment with no known name")
var progress: CGFloat = 0 {
didSet {
self.progressView.progress = progress
}
}
required init(attachmentPointer: TSAttachmentPointer, isIncoming: Bool) {
self.isIncoming = isIncoming
self.attachmentPointer = attachmentPointer
let attachmentPointerFilename = attachmentPointer.filename
if let filename = attachmentPointerFilename, !filename.isEmpty {
self.filename = filename
} else {
self.filename = genericFilename
}
super.init(frame: CGRect.zero)
createSubviews()
updateViews()
}
@available(*, unavailable)
override init(frame: CGRect) {
assertionFailure()
// This initializer should never be called, but we assign some bogus values to keep the compiler happy.
self.filename = genericFilename
self.isIncoming = false
self.attachmentPointer = TSAttachmentPointer()
super.init(frame: frame)
self.createSubviews()
self.updateViews()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
assertionFailure()
// This initializer should never be called, but we assign some bogus values to keep the compiler happy.
self.filename = genericFilename
self.isIncoming = false
self.attachmentPointer = TSAttachmentPointer()
super.init(coder: aDecoder)
self.createSubviews()
self.updateViews()
}
func createSubviews() {
self.addSubview(nameLabel)
// truncate middle to be sure we include file extension
nameLabel.lineBreakMode = .byTruncatingMiddle
nameLabel.textAlignment = .center
nameLabel.textColor = self.textColor
nameLabel.font = UIFont.ows_dynamicTypeBody()
nameLabel.autoPinWidthToSuperview()
nameLabel.autoPinEdge(toSuperviewEdge: .top)
self.addSubview(progressView)
progressView.autoPinWidthToSuperview()
progressView.autoPinEdge(.top, to: .bottom, of: nameLabel, withOffset: 6)
progressView.autoSetDimension(.height, toSize: 8)
self.addSubview(statusLabel)
statusLabel.textAlignment = .center
statusLabel.adjustsFontSizeToFitWidth = true
statusLabel.textColor = self.textColor
statusLabel.font = UIFont.ows_footnote()
statusLabel.autoPinWidthToSuperview()
statusLabel.autoPinEdge(.top, to: .bottom, of: progressView, withOffset: 4)
statusLabel.autoPinEdge(toSuperviewEdge: .bottom)
}
func emojiForContentType(_ contentType: String) -> String {
if MIMETypeUtil.isImage(contentType) {
return "📷"
} else if MIMETypeUtil.isVideo(contentType) {
return "📽"
} else if MIMETypeUtil.isAudio(contentType) {
return "📻"
} else if MIMETypeUtil.isAnimated(contentType) {
return "🎡"
} else {
// generic file
return "📁"
}
}
func updateViews() {
let emoji = self.emojiForContentType(self.attachmentPointer.contentType)
nameLabel.text = "\(emoji) \(self.filename)"
statusLabel.text = {
switch self.attachmentPointer.state {
case .enqueued:
return NSLocalizedString("ATTACHMENT_DOWNLOADING_STATUS_QUEUED", comment: "Status label when an attachment is enqueued, but hasn't yet started downloading")
case .downloading:
return NSLocalizedString("ATTACHMENT_DOWNLOADING_STATUS_IN_PROGRESS", comment: "Status label when an attachment is currently downloading")
case .failed:
return NSLocalizedString("ATTACHMENT_DOWNLOADING_STATUS_FAILED", comment: "Status label when an attachment download has failed.")
}
}()
if attachmentPointer.state == .downloading {
progressView.isHidden = false
} else {
progressView.isHidden = true
}
}
var textColor: UIColor {
return self.isIncoming ? UIColor.darkText : UIColor.white
}
}
| gpl-3.0 | c32a6ee312179f5b04c5100aa801e232 | 33.340741 | 172 | 0.649698 | 5.214848 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Scenes/Animate 3D graphic/MissionSettingsViewController.swift | 1 | 2838 | //
// Copyright 2017 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
protocol MissionSettingsViewControllerDelegate: AnyObject {
func missionSettingsViewController(_ missionSettingsViewController: MissionSettingsViewController, didSelectMissionAtIndex index: Int)
func missionSettingsViewController(_ missionSettingsViewController: MissionSettingsViewController, didChangeSpeed speed: Int)
}
class MissionSettingsViewController: UITableViewController {
@IBOutlet private weak var missionCell: UITableViewCell?
@IBOutlet private weak var speedSlider: UISlider?
@IBOutlet private weak var progressView: UIProgressView?
weak var delegate: MissionSettingsViewControllerDelegate?
var missionFileNames: [String] = []
var selectedMissionIndex: Int = 0 {
didSet {
updateMissionCell()
}
}
var animationSpeed = 50
var progress: Float = 0 {
didSet {
updateProgressViewForProgress()
}
}
private func updateProgressViewForProgress() {
progressView?.progress = progress
}
private func updateMissionCell() {
if selectedMissionIndex < missionFileNames.count {
missionCell?.detailTextLabel?.text = missionFileNames[selectedMissionIndex]
}
}
override func viewDidLoad() {
super.viewDidLoad()
updateMissionCell()
speedSlider?.value = Float(animationSpeed)
updateProgressViewForProgress()
}
// MARK: - Actions
@IBAction func speedValueChanged(_ sender: UISlider) {
animationSpeed = Int(sender.value)
delegate?.missionSettingsViewController(self, didChangeSpeed: Int(sender.value))
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView.cellForRow(at: indexPath) == missionCell {
let controller = OptionsTableViewController(labels: missionFileNames, selectedIndex: selectedMissionIndex) { (newIndex) in
self.selectedMissionIndex = newIndex
self.delegate?.missionSettingsViewController(self, didSelectMissionAtIndex: newIndex)
}
controller.title = "Mission"
show(controller, sender: self)
}
}
}
| apache-2.0 | b3705def763a8ebd17955d20d431d30e | 34.924051 | 138 | 0.695208 | 5.324578 | false | false | false | false |
tomkowz/Swifternalization | Swifternalization/Regex.swift | 1 | 3617 | //
// Regex.swift
// Swifternalization
//
// Created by Tomasz Szulc on 27/06/15.
// Copyright (c) 2015 Tomasz Szulc. All rights reserved.
//
import Foundation
/**
Class uses NSRegularExpression internally and simplifies its usability.
*/
final class Regex {
/**
Return match in a string. Optionally with index of capturing group
:param: str A string that will be matched.
:param: pattern A regex pattern.
:returns: `String` that matches pattern or nil.
*/
class func matchInString(_ str: String, pattern: String, capturingGroupIdx: Int?) -> String? {
var resultString: String?
let range = NSMakeRange(0, str.characters.distance(from: str.startIndex, to: str.endIndex))
regexp(pattern)?.enumerateMatches(in: str, options: NSRegularExpression.MatchingOptions.reportCompletion, range: range, using: { result, flags, stop in
if let result = result {
if let capturingGroupIdx = capturingGroupIdx, result.numberOfRanges > capturingGroupIdx {
resultString = self.substring(str, range: result.range(at: capturingGroupIdx))
} else {
resultString = self.substring(str, range: result.range)
}
}
})
return resultString
}
/**
Return first match in a string.
:param: str A string that will be matched.
:param: pattern A regexp pattern.
:returns: `String` that matches pattern or nil.
*/
class func firstMatchInString(_ str: String, pattern: String) -> String? {
if let result = regexp(pattern)?.firstMatch(in: str, options: .reportCompletion, range: NSMakeRange(0, str.characters.distance(from: str.startIndex, to: str.endIndex))) {
return substring(str, range: result.range)
}
return nil
}
/**
Return all matches in a string.
:param: str A string that will be matched.
:param: pattern A regexp pattern.
:returns: Array of `Strings`s. If nothing found empty array is returned.
*/
class func matchesInString(_ str: String, pattern: String) -> [String] {
var matches = [String]()
if let results = regexp(pattern)?.matches(in: str, options: .reportCompletion, range: NSMakeRange(0, str.characters.distance(from: str.startIndex, to: str.endIndex))) {
for result in results {
matches.append(substring(str, range: result.range))
}
}
return matches
}
/**
Returns new `NSRegularExpression` object.
:param: pattern A regexp pattern.
:returns: `NSRegularExpression` object or nil if it cannot be created.
*/
private class func regexp(_ pattern: String) -> NSRegularExpression? {
do {
return try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
} catch let error as NSError {
print(error)
}
return nil
}
/**
Method that substring string with passed range.
:param: str A string that is source of substraction.
:param: range A range that tells which part of `str` will be substracted.
:returns: A string contained in `range`.
*/
private class func substring(_ str: String, range: NSRange) -> String {
let startRange = str.characters.index(str.startIndex, offsetBy: range.location)
let endRange = str.characters.index(startRange, offsetBy: range.length)
return str.substring(with: startRange..<endRange)
}
}
| mit | b5bdf071a4c2741c3bc63b9bfb5cca84 | 34.811881 | 178 | 0.632015 | 4.637179 | false | false | false | false |
coderwjq/swiftweibo | SwiftWeibo/SwiftWeibo/Classes/Main/View/WelcomeViewController.swift | 1 | 1754 | //
// WelcomeViewController.swift
// SwiftWeibo
//
// Created by mzzdxt on 2016/11/3.
// Copyright © 2016年 wjq. All rights reserved.
//
import UIKit
import SDWebImage
class WelcomeViewController: UIViewController {
// MARK:- 拖线的属性
@IBOutlet weak var iconViewBottomCons: NSLayoutConstraint!
@IBOutlet weak var iconView: UIImageView!
// MARK:- 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
iconView.layer.cornerRadius = 45
iconView.layer.masksToBounds = true
// 设置头像
let profileURLString = UserAccountViewModel.sharedInstance.account?.avatar_large
// ??: 如果??前面的可选类型有值,那么将前面的可选类型进行解包并且赋值
// 如果??前面的可选类型为nil,那么直接使用??后面的值
let iconURL = URL(string: profileURLString ?? "")
iconView.sd_setImage(with: iconURL, placeholderImage: UIImage(named: "avatar_default_big"))
// 改变约束值
iconViewBottomCons.constant = UIScreen.main.bounds.size.height * 0.7
// 执行动画
// usingSpringWithDamping: 阻力系数,阻力系数越大,弹动的效果越不明显,取值0到1
// initialSpringVelocity: 初始化速度
// 枚举参数,如果不写,可用[]代替
UIView.animate(withDuration: 1.5, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 5.0, options: [], animations: {
self.iconView.layoutIfNeeded()
}) { (_) in
// 将控制器的根控制器改为从MainViewController加载
UIApplication.shared.keyWindow?.rootViewController = MainViewController()
}
}
}
| apache-2.0 | 936b3887a372e002302bc8fe9b32cca9 | 30.229167 | 137 | 0.646431 | 4.246459 | false | false | false | false |
developerY/Swift2_Playgrounds | Swift2LangRef.playground/Pages/ARC.xcplaygroundpage/Contents.swift | 1 | 14945 | //: [Previous](@previous)
//: ------------------------------------------------------------------------------------------------
//: Things to know:
//:
//: * Automatic Reference Counting allows Swift to track and manage your app's memory usage. It
//: automatically frees up memory from unused instances that are no longer in use.
//:
//: * Reference counting only applies to classes as structures and enumerations are value types.
//:
//: * Whenever a class instance is stored (to a property, constant or variable) a
//: "strong reference" is made. A strong reference ensures that the reference is not deallocated
//: for as long as the strong reference remains.
//: ------------------------------------------------------------------------------------------------
//: We can't really see ARC in actino within a Playground, but we can still follow along what
//: would normally happen.
//:
//: We'll start by creating a class to work with
class Person
{
let name: String
init (name: String)
{
self.name = name
}
}
//: We'll want to create a person and then remove our reference to it, which means we'll need to
//: use an optional Person type stored in a variable:
var person: Person? = Person(name: "Bill")
//: We now have a single strong reference to a single Person object.
//:
//: If we assign 'person' to another variable or constant, we'll increse the reference conunt by 1
//: for a total of 2:
var copyOfPerson = person
//: With a reference count of 2, we can set our original reference to nil. This will drop our
//: reference count down to 1.
person = nil
//: The copyOfPerson still exists and holds a strong reference to our instance:
copyOfPerson
//: If we clear out this reference, we will drop the reference count once more to 0, causing the
//: object to be cleaned up by ARC:
copyOfPerson = nil
//: ------------------------------------------------------------------------------------------------
//: Strong Reference Cycles between class instances
//:
//: If two classes hold a reference to each other, then they create a "Strong Reference Cycle".
//:
//: Here's an example of two classes that are capable of holding references to one another, but
//: do not do so initially (their references are optional and defaulted to nil):
class Tenant
{
let name: String
var apartment: Apartment?
init(name: String) { self.name = name }
}
class Apartment
{
let number: Int
var tenant: Tenant?
init (number: Int) { self.number = number }
}
//: We can create a tenant and an apartment which are not associated to each other. After these
//: two lines of code, each instance will have a reference count of 1.
var bill: Tenant? = Tenant(name: "Bill")
var number73: Apartment? = Apartment(number: 73)
//: Let's link them up.
//:
//: This will create a strong reference cycle because each instance will have a reference to the
//: other. The end result is that each instance will now have a reference count of 2. For example,
//: the two strong references for the Tenant instances are held by 'bill' and the 'tenant'
//: property inside the 'number73' apartment.
//:
//: Note the "!" symbols for forced unwrapping (covered in an earlier section):
bill!.apartment = number73
number73!.tenant = bill
//: If we try to clean up, the memory will not be deallocated by ARC. Let's follow along what
//: actually happens a step at a time.
//:
//: First, we set 'bill' to be nil, which drops the strong reference count for this instance of
//: Tenant down to 1. Since there is still a strong reference held to this instance, it is never
//: deallocated (and the deinit() is also never called on that instance of Person.)
bill = nil
//: Next we do the same for 'number73' dropping the strong reference count for this instance of
//: Apartment down to 1. Similarly, it is not deallocated or deinitialized.
number73 = nil
//: At this point, we have two instances that still exist in memory, but cannot be cleaned up
//: because we don't have any references to them in order to solve the problem.
//: ------------------------------------------------------------------------------------------------
//: Resolving Strong Reference Cycles between Class Instances
//:
//: Swift provides two methods to resolve strong reference cycles: weak and unowned references.
//: ------------------------------------------------------------------------------------------------
//: Weak references allow an instance to be held without actually having a strong hold on it (and
//: hence, not incrementing the reference count for the target object.)
//:
//: Use weak references when it's OK for a reference to become nil sometime during its lifetime.
//: Since the Apartment can have no tenant at some point during its lifetime, a weak reference
//: is the right way to go.
//:
//: Weak references must always be optional types (because they may be required to be nil.) When
//: an object holds a weak reference to an object, if that object is ever deallocated, Swift will
//: locate all the weak references to it and set those references to nil.
//:
//: Weak references are declared using the 'weak' keyword.
//:
//: Let's fix our Apartment class. Note that we only have to break the cycle. It's perfectly
//: fine to let the Tenant continue to hold a strong reference to our apartment. We will also
//: create a new Tenant class (we'll just give it a new name, "NamedTenant"), but only so that we
//: can change the apartment type to reference our fixed Apartment class.
class NamedTenant
{
let name: String
var apartment: FixedApartment?
init(name: String) { self.name = name }
}
class FixedApartment
{
let number: Int
weak var tenant: NamedTenant?
init (number: Int) { self.number = number }
}
//: Here is our new tenant and his new apartment.
//:
//: This will create a single strong reference to each:
var jerry: NamedTenant? = NamedTenant(name: "Jerry")
var number74: FixedApartment? = FixedApartment(number: 74)
//: Let's link them up like we did before. Note that this time we're not creating a new strong
//: reference to the NamedTenant so the reference count will remain 1. The FixedApartment
//: however, will have a reference count of 2 (because the NamedTenant will hold a strong reference
//: to it.)
jerry!.apartment = number74
number74!.tenant = jerry
//: At this point, we have one strong reference to the NamedTenant and two strong references to
//: FixedApartment.
//:
//: Let's set jerry to nil, which will drop his reference count to 0 causing it to get
//: deallocated. Once this happens, it is also deinitialized.
jerry = nil
//: With 'jerry' deallocated, the strong reference it once held to FixedApartment is also cleaned
//: up leaving only one strong reference remaining to the FixedApartment class.
//:
//: If we clear 'number74' then we'll remove the last remaining strong reference:
number74 = nil
//: ------------------------------------------------------------------------------------------------
//: Unowned References
//:
//: Unowned refernces are similar to weak references in that they do not hold a strong reference
//: to an instance. However, the key difference is that if the object the reference is deallocated
//: they will not be set to nil like weak references to. Therefore, it's important to ensure that
//: any unowned references will always have a value. If this were to happen, accessing the unowned
//: reference will trigger a runtime error. In fact, Swift guraantees that your app will crash in
//: this scenario.
//:
//: Unowned references are created using the 'unowned' keyword and they must not be optional.
//:
//: We'll showcase this with a Customer and Credit Card. This is a good example case because a
//: customer may have the credit card, or they may close the account, but once a Credit Card
//: has been created, it will always have a customer.
class Customer
{
let name: String
var card: CreditCard?
init (name: String)
{
self.name = name
}
}
class CreditCard
{
let number: Int
unowned let customer: Customer
//: Since 'customer' is not optional, it must be set in the initializer
init (number: Int, customer: Customer)
{
self.number = number
self.customer = customer
}
}
//: ------------------------------------------------------------------------------------------------
//: Unowned References and Implicitly Unwrapped Optional Properties
//:
//: We've covered two common scenarios of cyclic references, but there is a third case. Consider
//: the case of a country and its capital city. Unlike the case where a customer may have a credit
//: card, or the case where an apartment may have a tenant, a country will always have a capital
//: city and a capital city will always have a tenant.
//:
//: The solution is to use an unowned property in one class and an implicitly unwrapped optional
//: property in the other class. This allows both properties to be accessed directly (without
//: optional unwrapping) once initialization is complete, while avoiding the reference cycle.
//:
//: Let's see how this is done:
class Country
{
let name: String
let capitalCity: City!
init(name: String, capitalName: String)
{
self.name = name
self.capitalCity = City(name: capitalName, country: self)
}
}
class City
{
let name: String
unowned let country: Country
init(name: String, country: Country)
{
self.name = name
self.country = country
}
}
//: We can define a Country with a capital city
var america = Country(name: "USA", capitalName: "Washington DC")
//: Here's how and why this works.
//:
//: The relationship between Customer:CreditCard is very similar to the relationship between
//: Country:City. The two key differences are that (1) the country initializes its own city and the
//: country does not need to reference the city through the optional binding or forced unwrapping
//: because the Country defines the city with the implicitly unwrapped optional property (using the
//: exclamation mark on the type annotation (City!).
//:
//: The City uses an unowned Country property in the same way (and for the same reasons) as the
//: CreditCard uses an unowned property of a Customer.
//:
//: The Country still uses an optional (though implicitly unwrapped) for the same reason that the
//: Customer uses an optional to store a CreditCard. If we look at Country's initializer, we see
//: that it initializes a capitalCity by passing 'self' to the City initializer. Normally, an
//: initializer cannot reference its own 'self' until it has fully initialized the object. In this
//: case, the Country can access its own 'self' because once 'name' has been initialized, the object
//: is considered fully initialized. This is the case because 'capitalCity' is an optional.
//:
//: We take this just a step further by declaring 'capitalCity' to be an implicitly unwrapped
//: optinoal property so that we can avoid having to deal with unwrapping 'capitalCity' whenever we
//: want to access it.
//: ------------------------------------------------------------------------------------------------
//: Strong Reference Cycles for Closures
//:
//: We've seen how classes can reference each other creating a cyclic reference because classes are
//: reference types. However, classes aren't the only way to create a cyclic reference. These
//: problematic references can also happen with closures because they, too, are reference types.
//:
//: This happens when a closure captures an instance of a class (simply because it uses the class
//: reference within the closure) and a class maintains a reference to the closure. Note that the
//: references that a closure captures are automatically strong references.
//:
//: Let's see how this problem can manifest. We'll create a class that represents an HTML element
//: which includes a variable (asHTML) which stores a reference to a closure.
//:
//: Quick note: The asHTML variable is defined as lazy so that it can reference 'self' within the
//: closure. Try removing the 'lazy' and you'll see that you get an error trying to access 'self'.
//: This is an error because we're not allowed to access 'self' during Phase 1 initialization. By
//: making 'asHTML' lazy, we solve this problem by deferring its initialization until later.
class HTMLElement
{
let name: String
let text: String?
lazy var asHTML: () -> String =
{
if let text = self.text
{
return "<\(self.name)>\(text)</\(self.name)>"
}
else
{
return "<\(self.name) />"
}
}
init(name: String, text: String? = nil)
{
self.name = name
self.text = text
}
}
//: Let's use the HTMLElement. We'll make sure we declare it as optional so we can set it to 'nil'
//: later.
var paragraph: HTMLElement? = HTMLElement(name: "p", text: "Hello, world")
paragraph!.asHTML()
//: At this point, we've created a strong reference cycle between the HTMLElement instance and the
//: asHTML closure because the closure references the object which owns [a reference to] it.
//:
//: We can set paragraph to nil, but the HTMLElement will not get deallocated:
paragraph = nil
//: The solution here is to use a "Closure Capture List" as part of the closure's definition. This
//: essentially allows us to modify the default behavior of closures using strong references for
//: captured instances.
//:
//: Here's how we define a capture list:
//:
//: lazy var someClosure: (Int, String) -> String =
//: {
//: [unowned self] (index: Int, stringToProcess: String) -> String in
//:
//: // ... code here ...
//: }
//:
//: Some closures can used simplified syntax if their parameters are inferred while other closures
//: may not have any parameters. In both cases the method for declaring the capture list doesn't
//: change much. Simply include the capture list followed by the 'in' keyword:
//:
//: lazy var someClosure: () -> String =
//: {
//: [unowned self] in
//:
//: // ... code here ...
//: }
//:
//: Let's see how we can use this to resolve the HTMLElement problem. We'll create a new class,
//: FixedHTMLElement which is identical to the previous with the exception of the addition of the
//: line: "[unowned self] in"
class FixedHTMLElement
{
let name: String
let text: String?
lazy var asHTML: () -> String =
{
[unowned self] in
if let text = self.text
{
return "<\(self.name)>\(text)</\(self.name)>"
}
else
{
return "<\(self.name) />"
}
}
init(name: String, text: String? = nil)
{
self.name = name
self.text = text
}
}
//: Playgrounds do not allow us to test/prove this, so feel free to plug this into a compiled
//: application to see it in action.
//: [Next](@next)
| mit | 3b0004b5a39c8f83cab31892e0081977 | 38.853333 | 100 | 0.669187 | 4.455874 | false | false | false | false |
MBKwon/TestAppStore | TestAppStore/TestAppStore/AppDetailTitle.swift | 1 | 1392 | //
// AppDetailTitle.swift
// TestAppStore
//
// Created by Moonbeom KWON on 2017. 4. 17..
// Copyright © 2017년 Kyle. All rights reserved.
//
import Foundation
import UIKit
import SDWebImage
import Cosmos
class AppDetailTitle: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var starRating: CosmosView!
@IBOutlet weak var appImageView: UIImageView!
func setInfo(_ itemInfo: AppDetailModel?) {
guard let appInfoModel = itemInfo else {
return
}
if let iconUrl = appInfoModel.artworkUrl100 {
appImageView.sd_setImage(with: URL(string: iconUrl))
}
titleLabel.text = appInfoModel.appTitle
starRating.rating = appInfoModel.averageUserRatingForCurrentVersion ?? 0.0
starRating.text = "(" + "\(appInfoModel.userRatingCountForCurrentVersion ?? 0)" + ")"
starRating.alpha = 1.0
}
}
extension AppDetailTitle {
override func layoutSubviews() {
super.layoutSubviews()
appImageView.layer.masksToBounds = true
appImageView.layer.borderWidth = 1/UIScreen.main.scale
appImageView.layer.borderColor = UIColor(white: 0.7, alpha: 1.0).cgColor
appImageView.layer.cornerRadius = appImageView.frame.size.width*0.2
starRating.settings.fillMode = .precise
}
}
| mit | e4ffdde8b2dd6a20ca90a7a635885590 | 26.78 | 93 | 0.653708 | 4.4377 | false | false | false | false |
alblue/swift | test/SILGen/objc_metatypes.swift | 2 | 2529 | // RUN: %target-swift-emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership -enable-objc-interop | %FileCheck %s
import gizmo
@objc class ObjCClass {}
class A {
// CHECK-LABEL: sil hidden @$s14objc_metatypes1AC3foo{{[_0-9a-zA-Z]*}}F
// CHECK-LABEL: sil hidden [thunk] @$s14objc_metatypes1AC3fooyAA9ObjCClassCmAFmFTo
@objc dynamic func foo(_ m: ObjCClass.Type) -> ObjCClass.Type {
// CHECK: bb0([[M:%[0-9]+]] : @trivial $@objc_metatype ObjCClass.Type, [[SELF:%[0-9]+]] : @unowned $A):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $A
// CHECK: [[M_AS_THICK:%[0-9]+]] = objc_to_thick_metatype [[M]] : $@objc_metatype ObjCClass.Type to $@thick ObjCClass.Type
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE_FOO:%[0-9]+]] = function_ref @$s14objc_metatypes1AC3foo{{[_0-9a-zA-Z]*}}F
// CHECK: [[NATIVE_RESULT:%[0-9]+]] = apply [[NATIVE_FOO]]([[M_AS_THICK]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@thick ObjCClass.Type, @guaranteed A) -> @thick ObjCClass.Type
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[OBJC_RESULT:%[0-9]+]] = thick_to_objc_metatype [[NATIVE_RESULT]] : $@thick ObjCClass.Type to $@objc_metatype ObjCClass.Type
// CHECK: return [[OBJC_RESULT]] : $@objc_metatype ObjCClass.Type
// CHECK: } // end sil function '$s14objc_metatypes1AC3fooyAA9ObjCClassCmAFmFTo'
return m
}
// CHECK-LABEL: sil hidden @$s14objc_metatypes1AC3bar{{[_0-9a-zA-Z]*}}FZ
// CHECK-LABEL: sil hidden [thunk] @$s14objc_metatypes1AC3bar{{[_0-9a-zA-Z]*}}FZTo
// CHECK: bb0([[SELF:%[0-9]+]] : @trivial $@objc_metatype A.Type):
// CHECK-NEXT: [[OBJC_SELF:%[0-9]+]] = objc_to_thick_metatype [[SELF]] : $@objc_metatype A.Type to $@thick A.Type
// CHECK: [[BAR:%[0-9]+]] = function_ref @$s14objc_metatypes1AC3bar{{[_0-9a-zA-Z]*}}FZ
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[BAR]]([[OBJC_SELF]]) : $@convention(method) (@thick A.Type) -> ()
// CHECK-NEXT: return [[RESULT]] : $()
@objc dynamic class func bar() { }
@objc dynamic func takeGizmo(_ g: Gizmo.Type) { }
// CHECK-LABEL: sil hidden @$s14objc_metatypes1AC7callFoo{{[_0-9a-zA-Z]*}}F
func callFoo() {
// Make sure we peephole Type/thick_to_objc_metatype.
// CHECK-NOT: thick_to_objc_metatype
// CHECK: metatype $@objc_metatype ObjCClass.Type
foo(ObjCClass.self)
// CHECK: return
}
}
| apache-2.0 | 5777845c222d0620daadc6019c0f63b5 | 53.978261 | 191 | 0.628312 | 3.084146 | false | false | false | false |
gp09/Beefit | BeefitMsc/BeefitMsc/BeeLoginViewController.swift | 1 | 2552 | //
// BeeLoginViewController.swift
// BeefitMsc
//
// Created by Priyank on 31/07/2017.
// Copyright © 2017 priyank. All rights reserved.
//
import UIKit
import FirebaseAuth
class BeeLoginViewController: UIViewController {
@IBOutlet var signUpBtn: UIButton!
@IBOutlet var twLoginBtn: UIButton!
@IBOutlet var fbLoginBtn: UIButton!
@IBOutlet var loginBtn: UIButton!
@IBOutlet var passTxtField: UITextField!
@IBOutlet var emailTxtField: UITextField!
@IBOutlet var l: UILabel!
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.
}
@IBAction func twBtnTapped(_ sender: Any) {
}
@IBAction func fbBtnTapped(_ sender: Any) {
}
@IBAction func loginBtnTapped(_ sender: Any) {
Auth.auth().signIn(withEmail: emailTxtField.text!, password: passTxtField.text!) { (user, error) in
if((error) != nil) {
let alert = UIAlertController.init(title: "Alert", message: "Please check your email id and password", preferredStyle: .alert)
self.present(alert, animated: true, completion: nil)
}
else {
print("sign in work")
user?.getIDToken(completion: { (token, error) in
print("\(String(describing: token))")
BeeKeychainService.saveToken(token: token! as NSString)
})
if let user = user {
// The user's ID, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server,
// if you have one. Use getTokenWithCompletion:completion: instead.
let uid = user.uid
let email = user.email
let photoURL = user.photoURL
// ...
}
}
}
}
/*
// 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 | 00ee1754488eaf35f5690e3d76438e82 | 32.565789 | 142 | 0.573109 | 5.071571 | false | false | false | false |
delannoyk/SoundcloudSDK | sources/SoundcloudSDK/soundcloud/SouncloudClient.swift | 1 | 18302 | //
// SoundcloudClient.swift
// Soundcloud
//
// Created by Kevin DELANNOY on 25/04/15.
// Copyright (c) 2015 Kevin Delannoy. All rights reserved.
//
import Foundation
#if os(iOS) || os(OSX)
import KeychainAccess
#endif
// MARK: - Errors
public struct BasicError {
public let code: String
public let description: String
}
public enum SoundcloudError: Error {
case credentialsNotSet
case notFound
case forbidden
case parsing
case unknown
case network(Error)
#if os(iOS) || os(OSX)
case needsLogin
case loginError(BasicError)
#endif
}
extension SoundcloudError: RequestError {
init(networkError: Error) {
self = .network(networkError)
}
init(jsonError: Error) {
self = .parsing
}
init?(httpURLResponse: HTTPURLResponse) {
switch httpURLResponse.statusCode {
case 200, 201:
return nil
case 401:
self = .forbidden
case 404:
self = .notFound
default:
self = .unknown
}
}
}
extension SoundcloudError: Equatable { }
public func ==(lhs: SoundcloudError, rhs: SoundcloudError) -> Bool {
switch (lhs, rhs) {
case (.credentialsNotSet, .credentialsNotSet):
return true
case (.notFound, .notFound):
return true
case (.forbidden, .forbidden):
return true
case (.parsing, .parsing):
return true
case (.unknown, .unknown):
return true
case (.network(let e1), .network(let e2)):
return e1 as NSError == e2 as NSError
default:
//TODO: find a better way to express this
#if os(iOS) || os(OSX)
switch (lhs, rhs) {
case (.needsLogin, .needsLogin):
return true
default:
return false
}
#else
return false
#endif
}
}
extension PaginatedAPIResponse {
init(error: SoundcloudError) {
self.init(response: .failure(error), nextPageURL: nil) { _ in .failure(error) }
}
init(JSON: JSONObject, parse: @escaping (JSONObject) -> Result<[T], SoundcloudError>) {
self.init(response: parse(JSON["collection"]), nextPageURL: JSON["next_href"].urlValue, parse: parse)
}
}
// MARK: - Session
#if os(iOS) || os(OSX)
@objc(SoundcloudSession)
public class Session: NSObject, NSCoding, NSCopying {
//First session info
public private(set) var authorizationCode: String
//Token
public fileprivate(set) var accessToken: String?
public fileprivate(set) var accessTokenExpireDate: Date?
public fileprivate(set) var scope: String?
//Future session
public fileprivate(set) var refreshToken: String?
// MARK: Initialization
init(authorizationCode: String) {
self.authorizationCode = authorizationCode
}
// MARK: NSCoding
private static let authorizationCodeKey = "authorizationCodeKey"
private static let accessTokenKey = "accessTokenKey"
private static let accessTokenExpireDateKey = "accessTokenExpireDateKey"
private static let scopeKey = "scopeKey"
private static let refreshTokenKey = "refreshTokenKey"
required public init?(coder aDecoder: NSCoder) {
guard let authCode = aDecoder.decodeObject(forKey: Session.authorizationCodeKey) as? String else {
return nil
}
authorizationCode = authCode
accessToken = aDecoder.decodeObject(forKey: Session.accessTokenKey) as? String
accessTokenExpireDate = aDecoder.decodeObject(forKey: Session.accessTokenExpireDateKey) as? Date
scope = aDecoder.decodeObject(forKey: Session.scopeKey) as? String
refreshToken = aDecoder.decodeObject(forKey: Session.refreshTokenKey) as? String
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(authorizationCode, forKey: Session.authorizationCodeKey)
aCoder.encode(accessToken, forKey: Session.accessTokenKey)
aCoder.encode(accessTokenExpireDate, forKey: Session.accessTokenExpireDateKey)
aCoder.encode(scope, forKey: Session.scopeKey)
aCoder.encode(refreshToken, forKey: Session.refreshTokenKey)
}
// MARK: NSCopying
public func copy(with zone: NSZone?) -> Any {
let session = Session(authorizationCode: authorizationCode)
session.accessToken = accessToken
session.accessTokenExpireDate = accessTokenExpireDate
session.scope = scope
session.refreshToken = refreshToken
return session
}
}
extension Session {
// MARK: Public methods
/**
Logs a user in. This method will present an UIViewController over `displayViewController`
that will load a web view so that user is available to log in
- parameter displayViewController: An UIViewController that is in the view hierarchy
- parameter completion: The closure that will be called when the user is logged in or upon error
*/
@available(*, deprecated, message: "Login has been moved to Soundcloud. Please use `Soundcloud.login().`")
public static func login(in displayViewController: ViewController, completion: @escaping (SimpleAPIResponse<Session>) -> Void) {
SoundcloudClient.login(in: displayViewController, completion: completion)
}
/**
Refresh the token of the logged user. You should call this method when you get a 401 error on
API calls
- parameter completion: The closure that will be called when the session is refreshed or upon error
*/
public func refreshSession(completion: @escaping (SimpleAPIResponse<Session>) -> Void) {
_refreshToken { result in
if let session = result.response.result {
SoundcloudClient.session = session
}
completion(result)
}
}
/**
Logs out the current user. This is a straight-forward call.
*/
@available(*, deprecated, message: "Logout has been moved to Soundcloud. Please use `Soundcloud.destroySession()`.")
public func destroy() {
SoundcloudClient.destroySession()
}
/**
Fetch current user's profile.
**This method requires a Session.**
- parameter completion: The closure that will be called when the profile is loaded or upon error
*/
public func me(completion: @escaping (SimpleAPIResponse<User>) -> Void) {
guard let clientIdentifier = SoundcloudClient.clientIdentifier else {
completion(SimpleAPIResponse(error: .credentialsNotSet))
return
}
guard let oauthToken = accessToken else {
completion(SimpleAPIResponse(error: .needsLogin))
return
}
let url = URL(string: "https://api.soundcloud.com/me")!
let parameters = ["client_id": clientIdentifier, "oauth_token": oauthToken]
let request = Request(url: url, method: .get, parameters: parameters, parse: {
if let user = User(JSON: $0) {
return .success(user)
}
return .failure(.parsing)
}) { result in
completion(SimpleAPIResponse(result: result))
}
request.start()
}
/**
Fetch current user's profile.
**This method requires a Session.**
- parameter completion: The closure that will be called when the activities are loaded or upon error
*/
public func activities(completion: @escaping (PaginatedAPIResponse<Activity>) -> Void) {
guard let clientIdentifier = SoundcloudClient.clientIdentifier else {
completion(PaginatedAPIResponse(error: .credentialsNotSet))
return
}
guard let oauthToken = accessToken else {
completion(PaginatedAPIResponse(error: .needsLogin))
return
}
let url = URL(string: "https://api.soundcloud.com/me/activities")!
let parameters = ["client_id": clientIdentifier, "oauth_token": oauthToken, "linked_partitioning": "true"]
let parse = { (JSON: JSONObject) -> Result<[Activity], SoundcloudError> in
guard let activities = JSON.flatMap(transform: { Activity(JSON: $0) }) else {
return .failure(.parsing)
}
return .success(activities)
}
let request = Request(url: url, method: .get, parameters: parameters, parse: { JSON -> Result<PaginatedAPIResponse<Activity>, SoundcloudError> in
return .success(PaginatedAPIResponse(JSON: JSON, parse: parse))
}) { result in
completion(result.recover { PaginatedAPIResponse(error: $0) })
}
request.start()
}
// MARK: Token
func getToken(completion: @escaping (SimpleAPIResponse<Session>) -> Void) {
guard let clientId = SoundcloudClient.clientIdentifier,
let clientSecret = SoundcloudClient.clientSecret,
let redirectURI = SoundcloudClient.redirectURI else {
completion(SimpleAPIResponse(error: .credentialsNotSet))
return
}
let parameters = [
"client_id": clientId,
"client_secret": clientSecret,
"redirect_uri": redirectURI,
"grant_type": "authorization_code",
"code": authorizationCode]
token(parameters: parameters, completion: completion)
}
func _refreshToken(completion: @escaping (SimpleAPIResponse<Session>) -> Void) {
guard let clientId = SoundcloudClient.clientIdentifier,
let clientSecret = SoundcloudClient.clientSecret,
let redirectURI = SoundcloudClient.redirectURI else {
completion(SimpleAPIResponse(error: .credentialsNotSet))
return
}
guard let refreshToken = refreshToken else {
completion(SimpleAPIResponse(error: .needsLogin))
return
}
let parameters = [
"client_id": clientId,
"client_secret": clientSecret,
"redirect_uri": redirectURI,
"grant_type": "refresh_token",
"code": authorizationCode,
"refresh_token": refreshToken]
token(parameters: parameters, completion: completion)
}
private func token(parameters: HTTPParametersConvertible, completion: @escaping (SimpleAPIResponse<Session>) -> Void) {
let url = URL(string: "https://api.soundcloud.com/oauth2/token")!
let request = Request(url: url, method: .post, parameters: parameters, parse: {
if let accessToken = $0["access_token"].stringValue,
let expires = $0["expires_in"].doubleValue,
let scope = $0["scope"].stringValue {
let newSession = self.copy() as! Session
newSession.accessToken = accessToken
newSession.accessTokenExpireDate = Date(timeIntervalSinceNow: expires)
newSession.scope = scope
newSession.refreshToken = $0["refresh_token"].stringValue
return .success(newSession)
}
return .failure(.parsing)
}) { result in
completion(SimpleAPIResponse(result: result))
}
request.start()
}
}
#endif
// MARK: - SoundcloudClient
public class SoundcloudClient: NSObject {
// MARK: Properties
/// Your Soundcloud app client identifier
static var clientIdentifier: String?
/// Your Soundcloud app client secret
static var clientSecret: String?
/// Your Soundcloud redirect URI
static var redirectURI: String?
// MARK: Session Management
#if os(iOS) || os(OSX)
private static let sessionKey = "sessionKey"
private static let tokenKey = "tokenKey"
private static let keychain = Keychain(server: "https://soundcloud.com", protocolType: .https)
/// The session property is only set when a user has logged in.
public fileprivate(set) static var session: Session? = {
if let data = keychain[data: sessionKey],
let session = NSKeyedUnarchiver.unarchiveObject(with: data) as? Session {
return session
}
return nil
}() {
willSet(newSession) {
if let session = newSession {
let data = NSKeyedArchiver.archivedData(withRootObject: session)
keychain[data: sessionKey] = data
} else {
keychain[sessionKey] = nil
}
}
}
private(set) static var accessToken: String?
public static func start(clientIdentifier: String, clientSecret: String, redirectURI: String?, completion: @escaping (SimpleAPIResponse<Void>) -> Void) {
self.clientIdentifier = clientIdentifier
self.clientSecret = clientSecret
self.redirectURI = redirectURI
let url = URL(string: "https://api.soundcloud.com/oauth2/token")!
let parameters = [
"client_id": clientIdentifier,
"client_secret": clientSecret,
"grant_type": "client_credentials"
]
let request = Request(url: url, method: .post, parameters: parameters, headers: ["Content-Type": "application/x-www-form-urlencoded"]) { json in
self.accessToken = json["access_token"].stringValue
return .success(())
} completion: { result in
completion(SimpleAPIResponse(result: result))
}
request.start()
}
/**
Logs a user in. This method will present an UIViewController over `displayViewController`
that will load a web view so that user is available to log in
- parameter displayViewController: An UIViewController that is in the view hierarchy
- parameter completion: The closure that will be called when the user is logged in or upon error
*/
public static func login(in displayViewController: ViewController, completion: @escaping (SimpleAPIResponse<Session>) -> Void) {
authorize(in: displayViewController) { result in
if let session = result.response.result {
session.getToken { result in
SoundcloudClient.session = result.response.result
completion(result)
}
} else {
completion(result)
}
}
}
/**
Logs out the current user. This is a straight-forward call.
*/
public static func destroySession() {
SoundcloudClient.session = nil
}
static func authorize(in displayViewController: ViewController, completion: @escaping (SimpleAPIResponse<Session>) -> Void) {
guard let clientIdentifier = SoundcloudClient.clientIdentifier, let redirectURI = SoundcloudClient.redirectURI else {
completion(SimpleAPIResponse(error: .credentialsNotSet))
return
}
let url = URL(string: "https://soundcloud.com/connect")!
let parameters = ["client_id": clientIdentifier,
"redirect_uri": redirectURI,
"response_type": "code"]
let web = SoundcloudWebViewController()
web.autoDismissURI = redirectURI
web.url = url.appendingQueryString(parameters.queryString)
web.onDismiss = { url in
if let accessCode = url?.query?.queryDictionary["code"] {
let session = Session(authorizationCode: accessCode)
completion(SimpleAPIResponse(value: session))
} else if let code = url?.query?.queryDictionary["error"],
let description = url?.query?.queryDictionary["error_description"] {
completion(SimpleAPIResponse(error: .loginError(BasicError(code: code, description: description))))
} else {
completion(SimpleAPIResponse(error: .needsLogin))
}
}
#if os(OSX)
web.title = "Soundcloud"
web.preferredContentSize = displayViewController.view.bounds.size
displayViewController.presentAsSheet(web)
#else
web.navigationItem.title = "Soundcloud"
let nav = UINavigationController(rootViewController: web)
displayViewController.present(nav, animated: true, completion: nil)
#endif
}
#endif
// MARK: Resolve
/// A resolve response can either be a/some User(s) or a/some Track(s) or a Playlist.
public typealias ResolveResponse = (users: [User]?, tracks: [Track]?, playlist: Playlist?)
/**
Resolve allows you to lookup and access API resources when you only know the SoundCloud.com URL.
- parameter URI: The URI to lookup
- parameter completion: The closure that will be called when the result is ready or upon error
*/
public static func resolve(URI: String, completion: @escaping (SimpleAPIResponse<ResolveResponse>) -> Void) {
guard let clientIdentifier = SoundcloudClient.clientIdentifier else {
completion(SimpleAPIResponse(error: .credentialsNotSet))
return
}
let url = URL(string: "https://api.soundcloud.com/resolve")!
let parameters = ["client_id": clientIdentifier, "url": URI]
let request = Request(url: url, method: .get, parameters: parameters, parse: {
if let user = User(JSON: $0) {
return .success(ResolveResponse(users: [user], tracks: nil, playlist: nil))
}
if let playlist = Playlist(JSON: $0) {
return .success(ResolveResponse(users: nil, tracks: nil, playlist: playlist))
}
if let track = Track(JSON: $0) {
return .success(ResolveResponse(users: nil, tracks: [track], playlist: nil))
}
let users = $0.flatMap { User(JSON: $0) }
if let users = users, users.count > 0 {
return .success(ResolveResponse(users: users, tracks: nil, playlist: nil))
}
let tracks = $0.flatMap { Track(JSON: $0) }
if let tracks = tracks, tracks.count > 0 {
return .success(ResolveResponse(users: nil, tracks: tracks, playlist: nil))
}
return .failure(.parsing)
}) { result in
completion(SimpleAPIResponse(result: result))
}
request.start()
}
}
| mit | 01188221ae8ca99f42c07b19c0552ac9 | 34.537864 | 157 | 0.628183 | 4.835403 | false | false | false | false |
CoderSLZeng/EncapsulationExpressionKeyboard | EncapsulationExpressionKeyboard/EncapsulationExpressionKeyboard/ExpressionKeyboard/SLExpressionKeyboardViewController.swift | 1 | 6070 | //
// SLExpressionKeyboardViewController.swift
// EncapsulationExpressionKeyboard
//
// Created by Anthony on 16/11/30.
// Copyright © 2016年 SLZeng. All rights reserved.
// 表情键盘控制器
//
import UIKit
private let cellIdentifier = "Identifier"
class SLExpressionKeyboardViewController: UIViewController {
private var packages : [SLKeyboardPackage] = SLKeyboardPackage.loadEmotionPackage()
// MARK: - 懒加载属性
/// 表情视图控件
private lazy var collectionView : UICollectionView = {
let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: SLExpressionKeyboardLayout())
clv.dataSource = self
clv.delegate = self
clv.registerClass(SLExpressionKeyboardCell.self, forCellWithReuseIdentifier: cellIdentifier)
clv.backgroundColor = UIColor.whiteColor()
return clv
}()
/// 工具条视图控件
private lazy var toolbar : UIToolbar = {
let tb = UIToolbar()
tb.tintColor = UIColor.lightGrayColor()
var items = [UIBarButtonItem]()
var index = 0
for title in ["最近", "默认", "Emoji", "浪小花"]
{
// 1.创建标题item
let item = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SLExpressionKeyboardViewController.itemClick(_:)))
item.tag = index
index += 1
items.append(item)
// 2.创建间隙item
let spaceItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
items.append(spaceItem)
}
// 3.删除最后一个间隙item
items.removeLast()
tb.items = items
return tb
}()
// MARK: - 系统初始化函数
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
// MARK: - 设置UI界面内容
extension SLExpressionKeyboardViewController
{
private func setupUI() {
// 1.设置背景颜色
view.backgroundColor = UIColor.lightGrayColor()
// 2.添加子控件
view.addSubview(collectionView)
view.addSubview(toolbar)
// 3.取消自动布局
collectionView.translatesAutoresizingMaskIntoConstraints = false
toolbar.translatesAutoresizingMaskIntoConstraints = false
// 4.布局子控件
let dict = ["collectionView" : collectionView, "toolbar" : toolbar]
// 4.1.设置collectionView的水平布局
var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dict)
// 4.2.设置toolbar的水平布局
cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolbar]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dict)
// 4.3.设置collectionView和toolbar的垂直布局
cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-[toolbar(49)]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dict)
// 5.添加布局
view.addConstraints(cons)
}
// MARK: 处理监听事件
@objc private func itemClick(item: UIBarButtonItem)
{
let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
}
}
// MARK: - UICollectionViewDataSource
extension SLExpressionKeyboardViewController : UICollectionViewDataSource
{
// 告诉系统有多少组
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return packages.count
}
// 告诉系统每组有多少个
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return packages[section].emoticons?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// 1.取出cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! SLExpressionKeyboardCell
cell
// 2.设置数据
let package = packages[indexPath.section]
cell.emoticon = package.emoticons![indexPath.item]
// 3.返回 cell
return cell
}
}
// MARK: - UICollectionViewDelegate
extension SLExpressionKeyboardViewController : UICollectionViewDelegate
{
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
// 获取表情数据
let package = packages[indexPath.section]
let emoticon = package.emoticons![indexPath.item]
// 每使用一次就+1
emoticon.count += 1
// 判断是否是删除按钮
if !emoticon.isRemoveButton
{
// 将当前点击的表情添加到最近组中
packages[0].addFavoriteEmoticon(emoticon)
}
}
}
// MARK: - 自定义流水布局
class SLExpressionKeyboardLayout : UICollectionViewFlowLayout
{
override func prepareLayout() {
super.prepareLayout()
// 设置collectionView的属性
let width = UIScreen.mainScreen().bounds.width / 7
let heigth = collectionView!.bounds.height / 3
itemSize = CGSize(width: width, height: heigth)
minimumLineSpacing = 0
minimumInteritemSpacing = 0
scrollDirection = UICollectionViewScrollDirection.Horizontal
collectionView?.bounces = false
collectionView?.pagingEnabled = true
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.showsVerticalScrollIndicator = false
}
}
| mit | b4cfd26de1a9ba1f44e50b176761a6e9 | 31.323864 | 183 | 0.652839 | 5.248155 | false | false | false | false |
farhanpatel/firefox-ios | Client/Frontend/Browser/TabPeekViewController.swift | 1 | 8080 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
import ReadingList
import WebKit
protocol TabPeekDelegate: class {
func tabPeekDidAddBookmark(_ tab: Tab)
@discardableResult func tabPeekDidAddToReadingList(_ tab: Tab) -> ReadingListClientRecord?
func tabPeekRequestsPresentationOf(_ viewController: UIViewController)
func tabPeekDidCloseTab(_ tab: Tab)
}
class TabPeekViewController: UIViewController, WKNavigationDelegate {
fileprivate static let PreviewActionAddToBookmarks = NSLocalizedString("Add to Bookmarks", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to add current tab to Bookmarks")
fileprivate static let PreviewActionAddToReadingList = NSLocalizedString("Add to Reading List", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to add current tab to Reading List")
fileprivate static let PreviewActionSendToDevice = NSLocalizedString("Send to Device", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to send the current tab to another device")
fileprivate static let PreviewActionCopyURL = NSLocalizedString("Copy URL", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to copy the URL of the current tab to clipboard")
fileprivate static let PreviewActionCloseTab = NSLocalizedString("Close Tab", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to close the current tab")
weak var tab: Tab?
fileprivate weak var delegate: TabPeekDelegate?
fileprivate var clientPicker: UINavigationController?
fileprivate var isBookmarked: Bool = false
fileprivate var isInReadingList: Bool = false
fileprivate var hasRemoteClients: Bool = false
fileprivate var ignoreURL: Bool = false
fileprivate var screenShot: UIImageView?
fileprivate var previewAccessibilityLabel: String!
// Preview action items.
lazy var previewActions: [UIPreviewActionItem] = {
var actions = [UIPreviewActionItem]()
let urlIsTooLongToSave = self.tab?.urlIsTooLong ?? false
if !self.ignoreURL && !urlIsTooLongToSave {
if !self.isInReadingList {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionAddToReadingList, style: .default) { previewAction, viewController in
guard let tab = self.tab else { return }
_ = self.delegate?.tabPeekDidAddToReadingList(tab)
})
}
if !self.isBookmarked {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionAddToBookmarks, style: .default) { previewAction, viewController in
guard let tab = self.tab else { return }
self.delegate?.tabPeekDidAddBookmark(tab)
})
}
if self.hasRemoteClients {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionSendToDevice, style: .default) { previewAction, viewController in
guard let clientPicker = self.clientPicker else { return }
self.delegate?.tabPeekRequestsPresentationOf(clientPicker)
})
}
// only add the copy URL action if we don't already have 3 items in our list
// as we are only allowed 4 in total and we always want to display close tab
if actions.count < 3 {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionCopyURL, style: .default) { previewAction, viewController in
guard let url = self.tab?.canonicalURL else { return }
UIPasteboard.general.url = url
SimpleToast().showAlertWithText(Strings.AppMenuCopyURLConfirmMessage, bottomContainer: self.view)
})
}
}
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionCloseTab, style: .destructive) { previewAction, viewController in
guard let tab = self.tab else { return }
self.delegate?.tabPeekDidCloseTab(tab)
})
return actions
}()
init(tab: Tab, delegate: TabPeekDelegate?) {
self.tab = tab
self.delegate = delegate
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
if let webViewAccessibilityLabel = tab?.webView?.accessibilityLabel {
previewAccessibilityLabel = String(format: NSLocalizedString("Preview of %@", tableName: "3DTouchActions", comment: "Accessibility label, associated to the 3D Touch action on the current tab in the tab tray, used to display a larger preview of the tab."), webViewAccessibilityLabel)
}
// if there is no screenshot, load the URL in a web page
// otherwise just show the screenshot
setupWebView(tab?.webView)
guard let screenshot = tab?.screenshot else { return }
setupWithScreenshot(screenshot)
}
fileprivate func setupWithScreenshot(_ screenshot: UIImage) {
let imageView = UIImageView(image: screenshot)
self.view.addSubview(imageView)
imageView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
screenShot = imageView
screenShot?.accessibilityLabel = previewAccessibilityLabel
}
fileprivate func setupWebView(_ webView: WKWebView?) {
guard let webView = webView, let url = webView.url, !isIgnoredURL(url) else { return }
let clonedWebView = WKWebView(frame: webView.frame, configuration: webView.configuration)
clonedWebView.allowsLinkPreview = false
webView.accessibilityLabel = previewAccessibilityLabel
self.view.addSubview(clonedWebView)
clonedWebView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
clonedWebView.navigationDelegate = self
clonedWebView.load(URLRequest(url: url))
}
func setState(withProfile browserProfile: BrowserProfile, clientPickerDelegate: ClientPickerViewControllerDelegate) {
assert(Thread.current.isMainThread)
guard let tab = self.tab else {
return
}
guard let displayURL = tab.url?.absoluteString, displayURL.characters.count > 0 else {
return
}
let mainQueue = DispatchQueue.main
browserProfile.bookmarks.modelFactory >>== {
$0.isBookmarked(displayURL).uponQueue(mainQueue) {
self.isBookmarked = $0.successValue ?? false
}
}
browserProfile.remoteClientsAndTabs.getClientGUIDs().uponQueue(mainQueue) {
guard let clientGUIDs = $0.successValue else {
return
}
self.hasRemoteClients = !clientGUIDs.isEmpty
let clientPickerController = ClientPickerViewController()
clientPickerController.clientPickerDelegate = clientPickerDelegate
clientPickerController.profile = browserProfile
if let url = tab.url?.absoluteString {
clientPickerController.shareItem = ShareItem(url: url, title: tab.title, favicon: nil)
}
self.clientPicker = UINavigationController(rootViewController: clientPickerController)
}
let result = browserProfile.readingList?.getRecordWithURL(displayURL).successValue!
self.isInReadingList = (result?.url.characters.count ?? 0) > 0
self.ignoreURL = isIgnoredURL(displayURL)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
screenShot?.removeFromSuperview()
screenShot = nil
}
}
| mpl-2.0 | 0c3dadda69575c774bf8af8a8203b542 | 45.171429 | 294 | 0.679332 | 5.511596 | false | false | false | false |
ioscreator/ioscreator | SwiftUISimultaneousGesturesTutorial/SwiftUISimultaneousGesturesTutorial/ContentView.swift | 1 | 1162 | //
// ContentView.swift
// SwiftUISimultaneousGesturesTutorial
//
// Created by Arthur Knopper on 29/10/2020.
//
import SwiftUI
struct ContentView: View {
@State private var degrees: Double = 0
@State var scale: CGFloat = 1.0
var body: some View {
let magnificationGesture = MagnificationGesture().onChanged { (value) in
self.scale = value.magnitude
}
let rotationGesture = RotationGesture().onChanged { (value) in
self.degrees = value.degrees
}
let magnificationAndDragGesture = magnificationGesture.simultaneously(with: rotationGesture)
VStack {
Image(systemName: "star.circle.fill")
.font(.system(size: 200))
.foregroundColor(Color.red)
.gesture(magnificationAndDragGesture)
.rotationEffect(Angle(degrees: degrees))
.scaleEffect(scale)
.animation(.easeInOut)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| mit | 3dc3d6bf143a67edf36fedc966a3211d | 26.023256 | 100 | 0.578313 | 4.861925 | false | false | false | false |
Ehrippura/firefox-ios | Client/Frontend/Widgets/LoginTableViewCell.swift | 5 | 13892 | /* 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 UIKit
import SnapKit
import Storage
protocol LoginTableViewCellDelegate: class {
func didSelectOpenAndFillForCell(_ cell: LoginTableViewCell)
func shouldReturnAfterEditingDescription(_ cell: LoginTableViewCell) -> Bool
func infoItemForCell(_ cell: LoginTableViewCell) -> InfoItem?
}
private struct LoginTableViewCellUX {
static let highlightedLabelFont = UIFont.systemFont(ofSize: 12)
static let highlightedLabelTextColor = UIConstants.SystemBlueColor
static let highlightedLabelEditingTextColor = UIConstants.TableViewHeaderTextColor
static let descriptionLabelFont = UIFont.systemFont(ofSize: 16)
static let descriptionLabelTextColor = UIColor.black
static let HorizontalMargin: CGFloat = 14
static let IconImageSize: CGFloat = 34
static let indentWidth: CGFloat = 44
static let IndentAnimationDuration: TimeInterval = 0.2
static let editingDescriptionIndent: CGFloat = IconImageSize + HorizontalMargin
}
enum LoginTableViewCellStyle {
case iconAndBothLabels
case noIconAndBothLabels
case iconAndDescriptionLabel
}
class LoginTableViewCell: UITableViewCell {
fileprivate let labelContainer = UIView()
weak var delegate: LoginTableViewCellDelegate?
// In order for context menu handling, this is required
override var canBecomeFirstResponder: Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
guard let item = delegate?.infoItemForCell(self) else {
return false
}
// Menu actions for password
if item == .passwordItem {
let showRevealOption = self.descriptionLabel.isSecureTextEntry ? (action == MenuHelper.SelectorReveal) : (action == MenuHelper.SelectorHide)
return action == MenuHelper.SelectorCopy || showRevealOption
}
// Menu actions for Website
if item == .websiteItem {
return action == MenuHelper.SelectorCopy || action == MenuHelper.SelectorOpenAndFill
}
// Menu actions for Username
if item == .usernameItem {
return action == MenuHelper.SelectorCopy
}
return false
}
lazy var descriptionLabel: UITextField = {
let label = UITextField()
label.font = LoginTableViewCellUX.descriptionLabelFont
label.textColor = LoginTableViewCellUX.descriptionLabelTextColor
label.textAlignment = .left
label.backgroundColor = UIColor.white
label.isUserInteractionEnabled = false
label.autocapitalizationType = .none
label.autocorrectionType = .no
label.accessibilityElementsHidden = true
label.adjustsFontSizeToFitWidth = false
label.delegate = self
return label
}()
// Exposing this label as internal/public causes the Xcode 7.2.1 compiler optimizer to
// produce a EX_BAD_ACCESS error when dequeuing the cell. For now, this label is made private
// and the text property is exposed using a get/set property below.
fileprivate lazy var highlightedLabel: UILabel = {
let label = UILabel()
label.font = LoginTableViewCellUX.highlightedLabelFont
label.textColor = LoginTableViewCellUX.highlightedLabelTextColor
label.textAlignment = .left
label.backgroundColor = UIColor.white
label.numberOfLines = 1
return label
}()
fileprivate lazy var iconImageView: UIImageView = {
let imageView = UIImageView()
imageView.backgroundColor = UIColor.white
imageView.contentMode = .scaleAspectFit
return imageView
}()
fileprivate var showingIndent: Bool = false
fileprivate var customIndentView = UIView()
fileprivate var customCheckmarkIcon = UIImageView(image: UIImage(named: "loginUnselected"))
/// Override the default accessibility label since it won't include the description by default
/// since it's a UITextField acting as a label.
override var accessibilityLabel: String? {
get {
if descriptionLabel.isSecureTextEntry {
return highlightedLabel.text ?? ""
} else {
return "\(highlightedLabel.text ?? ""), \(descriptionLabel.text ?? "")"
}
}
set {
// Ignore sets
}
}
var style: LoginTableViewCellStyle = .iconAndBothLabels {
didSet {
if style != oldValue {
configureLayoutForStyle(style)
}
}
}
var descriptionTextSize: CGSize? {
guard let descriptionText = descriptionLabel.text else {
return nil
}
let attributes = [
NSFontAttributeName: LoginTableViewCellUX.descriptionLabelFont
]
return descriptionText.size(attributes: attributes)
}
var displayDescriptionAsPassword: Bool = false {
didSet {
descriptionLabel.isSecureTextEntry = displayDescriptionAsPassword
}
}
var editingDescription: Bool = false {
didSet {
if editingDescription != oldValue {
descriptionLabel.isUserInteractionEnabled = editingDescription
highlightedLabel.textColor = editingDescription ?
LoginTableViewCellUX.highlightedLabelEditingTextColor : LoginTableViewCellUX.highlightedLabelTextColor
// Trigger a layout configuration if we changed to editing/not editing the description.
configureLayoutForStyle(self.style)
}
}
}
var highlightedLabelTitle: String? {
get {
return highlightedLabel.text
}
set(newTitle) {
highlightedLabel.text = newTitle
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
indentationWidth = 0
selectionStyle = .none
contentView.backgroundColor = UIColor.white
labelContainer.backgroundColor = UIColor.white
labelContainer.addSubview(highlightedLabel)
labelContainer.addSubview(descriptionLabel)
contentView.addSubview(iconImageView)
contentView.addSubview(labelContainer)
customIndentView.addSubview(customCheckmarkIcon)
addSubview(customIndentView)
configureLayoutForStyle(self.style)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
delegate = nil
descriptionLabel.isSecureTextEntry = false
descriptionLabel.keyboardType = .default
descriptionLabel.returnKeyType = .default
descriptionLabel.isUserInteractionEnabled = false
}
override func layoutSubviews() {
super.layoutSubviews()
// Adjust indent frame
var indentFrame = CGRect(
origin: CGPoint.zero,
size: CGSize(width: LoginTableViewCellUX.indentWidth, height: frame.height))
if !showingIndent {
indentFrame.origin.x = -LoginTableViewCellUX.indentWidth
}
customIndentView.frame = indentFrame
customCheckmarkIcon.frame.center = CGPoint(x: indentFrame.width / 2, y: indentFrame.height / 2)
// Adjust content view frame based on indent
var contentFrame = self.contentView.frame
contentFrame.origin.x += showingIndent ? LoginTableViewCellUX.indentWidth : 0
contentView.frame = contentFrame
}
fileprivate func configureLayoutForStyle(_ style: LoginTableViewCellStyle) {
switch style {
case .iconAndBothLabels:
iconImageView.snp.remakeConstraints { make in
make.centerY.equalTo(contentView)
make.left.equalTo(contentView).offset(LoginTableViewCellUX.HorizontalMargin)
make.height.width.equalTo(LoginTableViewCellUX.IconImageSize)
}
labelContainer.snp.remakeConstraints { make in
make.centerY.equalTo(contentView)
make.right.equalTo(contentView).offset(-LoginTableViewCellUX.HorizontalMargin)
make.left.equalTo(iconImageView.snp.right).offset(LoginTableViewCellUX.HorizontalMargin)
}
highlightedLabel.snp.remakeConstraints { make in
make.left.top.equalTo(labelContainer)
make.bottom.equalTo(descriptionLabel.snp.top)
make.width.equalTo(labelContainer)
}
descriptionLabel.snp.remakeConstraints { make in
make.left.bottom.equalTo(labelContainer)
make.top.equalTo(highlightedLabel.snp.bottom)
make.width.equalTo(labelContainer)
}
case .iconAndDescriptionLabel:
iconImageView.snp.remakeConstraints { make in
make.centerY.equalTo(contentView)
make.left.equalTo(contentView).offset(LoginTableViewCellUX.HorizontalMargin)
make.height.width.equalTo(LoginTableViewCellUX.IconImageSize)
}
labelContainer.snp.remakeConstraints { make in
make.centerY.equalTo(contentView)
make.right.equalTo(contentView).offset(-LoginTableViewCellUX.HorizontalMargin)
make.left.equalTo(iconImageView.snp.right).offset(LoginTableViewCellUX.HorizontalMargin)
}
highlightedLabel.snp.remakeConstraints { make in
make.height.width.equalTo(0)
}
descriptionLabel.snp.remakeConstraints { make in
make.top.left.bottom.equalTo(labelContainer)
make.width.equalTo(labelContainer)
}
case .noIconAndBothLabels:
// Currently we only support modifying the description for this layout which is why
// we factor in the editingOffset when calculating the constraints.
let editingOffset = editingDescription ? LoginTableViewCellUX.editingDescriptionIndent : 0
iconImageView.snp.remakeConstraints { make in
make.centerY.equalTo(contentView)
make.left.equalTo(contentView).offset(LoginTableViewCellUX.HorizontalMargin)
make.height.width.equalTo(0)
}
labelContainer.snp.remakeConstraints { make in
make.centerY.equalTo(contentView)
make.right.equalTo(contentView).offset(-LoginTableViewCellUX.HorizontalMargin)
make.left.equalTo(iconImageView.snp.right).offset(editingOffset)
}
highlightedLabel.snp.remakeConstraints { make in
make.left.top.equalTo(labelContainer)
make.bottom.equalTo(descriptionLabel.snp.top)
make.width.equalTo(labelContainer)
}
descriptionLabel.snp.remakeConstraints { make in
make.left.bottom.equalTo(labelContainer)
make.top.equalTo(highlightedLabel.snp.bottom)
make.width.equalTo(labelContainer)
}
}
setNeedsUpdateConstraints()
}
override func setEditing(_ editing: Bool, animated: Bool) {
showingIndent = editing
let adjustConstraints = { [unowned self] in
// Shift over content view
var contentFrame = self.contentView.frame
contentFrame.origin.x += editing ? LoginTableViewCellUX.indentWidth : -LoginTableViewCellUX.indentWidth
self.contentView.frame = contentFrame
// Shift over custom indent view
var indentFrame = self.customIndentView.frame
indentFrame.origin.x += editing ? LoginTableViewCellUX.indentWidth : -LoginTableViewCellUX.indentWidth
self.customIndentView.frame = indentFrame
}
animated ? UIView.animate(withDuration: LoginTableViewCellUX.IndentAnimationDuration, animations: adjustConstraints) : adjustConstraints()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
customCheckmarkIcon.image = UIImage(named: selected ? "loginSelected" : "loginUnselected")
}
}
// MARK: - Menu Selectors
extension LoginTableViewCell: MenuHelperInterface {
func menuHelperReveal() {
displayDescriptionAsPassword = false
}
func menuHelperSecure() {
displayDescriptionAsPassword = true
}
func menuHelperCopy() {
// Copy description text to clipboard
UIPasteboard.general.string = descriptionLabel.text
}
func menuHelperOpenAndFill() {
delegate?.didSelectOpenAndFillForCell(self)
}
}
// MARK: - Cell Decorators
extension LoginTableViewCell {
func updateCellWithLogin(_ login: LoginData) {
descriptionLabel.text = login.hostname
highlightedLabel.text = login.username
iconImageView.image = UIImage(named: "faviconFox")
}
}
extension LoginTableViewCell: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return self.delegate?.shouldReturnAfterEditingDescription(self) ?? true
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if descriptionLabel.isSecureTextEntry {
displayDescriptionAsPassword = false
}
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
if descriptionLabel.isSecureTextEntry {
displayDescriptionAsPassword = true
}
}
}
| mpl-2.0 | 2d0208c679ab0fe14c0883a025767a09 | 34.989637 | 152 | 0.664699 | 5.567936 | false | false | false | false |
Corey2121/the-oakland-post | The Oakland Post/BiosViewController.swift | 3 | 4959 | //
// BiosViewController.swift
// The Oakland Post
//
// Content view controller for staff bios.
//
// Created by Andrew Clissold on 9/14/14.
// Copyright (c) 2014 Andrew Clissold. All rights reserved.
//
class BiosViewController: UIViewController, iCarouselDataSource, iCarouselDelegate {
@IBOutlet weak var infoToolbar: UIToolbar!
@IBOutlet weak var toolbarVerticalConstraint: NSLayoutConstraint!
@IBOutlet weak var toolbarHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descriptionTextView: UITextView!
@IBOutlet weak var carousel: iCarousel!
override func viewDidLoad() {
carousel.type = .Linear
carousel.dataSource = self
carousel.delegate = self
nameLabel.text = names[0]
descriptionTextView.attributedText = biosTexts[names[0]]
}
// MARK: iCarouselDelegate
let names = ["Oona Goodin-Smith", "Kaylee Kean", "Ali DeRees", "Jackson Gilbert", "Haley Kotwicki",
"Sean Miller", "Sélah Fischer", "Dani Cojocari", "Phillip Johnson", "Arkeem Thomas-Scott",
"Jessie DiBattista", "Megan Carson", "Jake Alsko", "Kaleigh Jerzykowski", "Andrew Wernette",
"Jasmine French", "Scott Davis", "Morgan Dean", "Nicolette Brikho", "Josh Soltman"]
var previousIndex = 0
var firstScroll = true
func carouselDidEndScrollingAnimation(carousel: iCarousel!) {
// Ignore the call to this method when the view first appears.
if firstScroll { firstScroll = false; return }
let index = carousel.currentItemIndex
if index != previousIndex {
updateContentForIndex(index, forward: index < previousIndex)
previousIndex = index
}
}
func updateContentForIndex(index: Int, forward: Bool) {
if presentingViewController == nil { return } // user went back and dismissed the Info view
let originalX = nameLabel.frame.origin.x
let containerWidth = presentingViewController!.view.frame.size.width
let padding: CGFloat = 20
let duration = 0.35
let rightPosition = containerWidth + nameLabel.frame.size.width + padding
let leftPosition = -nameLabel.frame.size.width - padding
func flyOut() {
self.nameLabel.frame.origin.x = forward ? rightPosition : leftPosition
self.descriptionTextView.alpha = 0
}
func flyIn(finished: Bool) {
let name = self.names[index]
self.nameLabel.text = self.names[index]
self.nameLabel.frame.origin.x = forward ? leftPosition : rightPosition
self.descriptionTextView.attributedText = biosTexts[name]
UIView.animateWithDuration(duration) {
self.descriptionTextView.alpha = 1
}
UIView.animateWithDuration(duration + 0.2, delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.2,
options: .CurveEaseOut,
animations: {
self.nameLabel.frame.origin.x = originalX
}, completion: nil)
}
UIView.animateWithDuration(duration - 0.1, delay: 0, options: .CurveEaseIn, animations: flyOut, completion: flyIn)
}
// MARK: iCarouselDataSource
func numberOfItemsInCarousel(carousel: iCarousel!) -> Int {
return names.count
}
func carousel(carousel: iCarousel!, viewForItemAtIndex index: Int, reusingView view: UIView!) -> UIView! {
var mutableView = view
if mutableView == nil {
mutableView = UIView(frame: CGRect(x: 0, y: 0, width: 160, height: 160))
mutableView.backgroundColor = UIColor(white: 0.25, alpha: 1)
} else {
(mutableView.subviews.first as! UIView).removeFromSuperview()
}
let imageView = UIImageView()
mutableView.addSubview(imageView)
onMain {
// Even though we're on the main queue at this point, dispatching to it will cause
// mutableView to be returned BEFORE loading the image file, reducing FPS lag.
let image = UIImage(named: self.names[index])
imageView.contentMode = .ScaleAspectFill
imageView.frame = CGRect(x: 15, y: 15, width: 130, height: 130)
imageView.clipsToBounds = true
imageView.image = image
}
return mutableView
}
// MARK: Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch (segue.identifier!) {
case biosID1, biosID2, biosID3:
let toViewController = segue.destinationViewController as! InfoViewController
toViewController.modalPresentationStyle = .CurrentContext
toViewController.transitioningDelegate = toViewController.transitionManager
default:
p("unknown segue identifier: \(segue.identifier)")
}
}
}
| bsd-3-clause | bd4a2d82f6d4f7fb12fc2a55a01188ce | 37.434109 | 122 | 0.646027 | 4.708452 | false | false | false | false |
resmio/TastyTomato | TastyTomato/Code/Types/LayerClasses/BorderLayer.swift | 1 | 3226 | //
// BorderLayer.swift
// TastyTomato
//
// Created by Jan Nash on 3/26/17.
// Copyright © 2017 resmio. All rights reserved.
//
import Foundation
// MARK: // Public
// MARK: Interface
public extension BorderLayer {
var borderEdgeInsets: UIEdgeInsets {
get { return self._borderEdgeInsets }
set { self._borderEdgeInsets = newValue }
}
}
// MARK: Class Declaration
public class BorderLayer: CAShapeLayer {
// Required Init
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self._init()
}
// Override Inits
public override init() {
super.init()
self._init()
}
public override init(layer: Any) {
super.init(layer: layer)
}
// Common Init
private func _init() {
self.lineWidth = 1
self.strokeColor = UIColor.black.cgColor
}
// Private Variables
private var __borderEdgeInsets: UIEdgeInsets = .zero
// MARK: Overrides
public override var frame: CGRect {
get { return self._frame }
set { self._frame = newValue }
}
public override func action(forKey event: String) -> CAAction? {
return nil
}
// MARK: Unavailability Overrides
@available(*, unavailable)
public override var backgroundColor: CGColor? {
get { return nil }
set { fatalError() }
}
@available(*, unavailable)
public override var borderColor: CGColor? {
get { return nil }
set { fatalError() }
}
@available(*, unavailable)
public override var fillColor: CGColor? {
get { return nil }
set { fatalError() }
}
}
// MARK: Convenience Init Unavailability Overrides
extension BorderLayer {
@available(*, unavailable)
public convenience init(path p: UIBezierPath) { fatalError() }
@available(*, unavailable)
public convenience init(rect r: CGRect) { fatalError() }
}
// MARK: // Private
// MARK: BorderInset
private extension BorderLayer {
var _borderEdgeInsets: UIEdgeInsets {
get { return self.__borderEdgeInsets }
set(newBorderEdgeInsets) {
guard newBorderEdgeInsets != self.__borderEdgeInsets else { return }
self.__borderEdgeInsets = newBorderEdgeInsets
self.path = self._createPath()
}
}
}
// MARK: Override Implementations
private extension BorderLayer {
var _frame: CGRect {
get { return super.frame }
set(newFrame) {
guard newFrame != super.frame else { return }
super.frame = newFrame
self.path = self._createPath()
}
}
}
// MARK: Create Path
private extension BorderLayer {
func _createPath() -> CGPath {
let size: CGSize = self.frame.size
let insets: UIEdgeInsets = self.borderEdgeInsets
let x: CGFloat = insets.left
let y: CGFloat = insets.top
let width: CGFloat = size.width - (x + insets.right)
let height: CGFloat = size.height - (y + insets.bottom)
let pathFrame: CGRect = CGRect(x: x, y: y, width: width, height: height)
return CGPath(rect: pathFrame, transform: nil)
}
}
| mit | ddd5f10ac6dc62a6b4c1e7fa35b9aca5 | 23.807692 | 80 | 0.604651 | 4.479167 | false | false | false | false |
csnu17/My-Swift-learning | collection-data-structures-swift/DataStructures/SwiftSetManipulator.swift | 1 | 3873 | //
// SwiftSetManipulator.swift
// DataStructures
//
// Created by Ellen Shapiro on 4/18/15.
// Copyright (c) 2015 Ray Wenderlich Tutorial Team. All rights reserved.
//
import Foundation
open class SwiftSetManipulator : SetManipulator {
fileprivate var setToManipulate = Set<String>()
fileprivate let generator = StringGenerator()
open func setHasObjects() -> Bool {
if setToManipulate.count == 0 {
return false
} else {
return true
}
}
open func setupWithObjectCount(_ objectCount: Int) -> TimeInterval {
return Profiler.runClosureForTime() {
self.setToManipulate = Set<String>(minimumCapacity: objectCount)
for _ in 0 ..< objectCount {
self.setToManipulate.insert(self.generator.standardRandomString())
}
}
}
//MARK: Add tests
fileprivate func addObjects(_ count: Int) -> TimeInterval {
let originalCount = setToManipulate.count
var objectsArray = [String]()
for _ in 0 ..< count {
//Generate the appropriate number of random strings
objectsArray.append(generator.standardRandomString())
}
//Add them all to the set, and measure how long it takes.
let timed = Profiler.runClosureForTime() {
let _ = self.setToManipulate.union(objectsArray)
}
for removeMe in objectsArray {
self.setToManipulate.remove(removeMe)
}
//Make sure we're back to where we need to be.
assert(originalCount == setToManipulate.count, "Set is not back to the original #!")
return timed
}
open func add1Object() -> TimeInterval {
return addObjects(1)
}
open func add5Objects() -> TimeInterval {
return addObjects(5)
}
open func add10Objects() -> TimeInterval {
return addObjects(10)
}
//MARK: Remove tests
fileprivate func removeObjects(_ count: Int) -> TimeInterval {
let originalCount = setToManipulate.count
var objectsArray = [String]()
for _ in 0 ..< count {
//Generate the appropriate number of random strings
objectsArray.append(generator.standardRandomString())
}
//Add them all to the set
let _ = self.setToManipulate.union(objectsArray)
//measure how long it takes to remove them.
let timed = Profiler.runClosureForTime() {
for removeMe in objectsArray {
self.setToManipulate.remove(removeMe)
}
}
//Make sure we're back to where we need to be.
assert(originalCount == setToManipulate.count, "Set is not back to the original #!")
return timed
}
open func remove1Object() -> TimeInterval {
return removeObjects(1)
}
open func remove5Objects() -> TimeInterval {
return removeObjects(5)
}
open func remove10Objects() -> TimeInterval {
return removeObjects(10)
}
//MARK: Lookup tests
fileprivate func lookupObjects(_ count: Int) -> TimeInterval {
let originalCount = setToManipulate.count
var objectsArray = [String]()
for _ in 0 ..< count {
//Generate the appropriate number of random strings
objectsArray.append(generator.standardRandomString())
}
//Add them all to the set
let _ = self.setToManipulate.union(objectsArray)
//measure how long it takes to find them
let timed = Profiler.runClosureForTime() {
for findMe in objectsArray {
let _ = self.setToManipulate.index(of: findMe)
}
}
//Remove that which was added
for removeMe in objectsArray {
self.setToManipulate.remove(removeMe)
}
//Make sure we're back to where we need to be.
assert(originalCount == setToManipulate.count, "Set is not back to the original #!")
return timed
}
open func lookup1Object() -> TimeInterval {
return lookupObjects(1)
}
open func lookup10Objects() -> TimeInterval {
return lookupObjects(10)
}
}
| mit | 9ccdf731d553cc2b4f9e986b7a0c1830 | 26.083916 | 88 | 0.659437 | 4.332215 | false | false | false | false |
gnachman/iTerm2 | SearchableComboListView/SearchableComboView/SearchableComboListViewController.swift | 2 | 7780 | //
// SearchableComboListViewController.swift
// SearchableComboListView
//
// Created by George Nachman on 1/24/20.
//
import AppKit
@objc(iTermSearchableComboListViewControllerDelegate)
protocol SearchableComboListViewControllerDelegate: NSObjectProtocol {
func searchableComboListViewController(_ listViewController: SearchableComboListViewController,
didSelectItem item: SearchableComboViewItem?)
func searchableComboListViewController(_ listViewController: SearchableComboListViewController,
maximumHeightDidChange maxHeight: CGFloat)
}
class SearchableComboListViewController: NSViewController {
@objc(delegate) @IBOutlet public weak var delegate: SearchableComboListViewControllerDelegate?
@IBOutlet public weak var tableView: SearchableComboTableView!
@IBOutlet public weak var searchField: NSSearchField!
@IBOutlet public weak var visualEffectView: NSVisualEffectView!
private var closeOnSelect = true
public var tableViewController: SearchableComboTableViewController?
var widestItemWidth: CGFloat {
return tableViewController?.widestItemWidth ?? 0
}
let groups: [SearchableComboViewGroup]
public var selectedItem: SearchableComboViewItem? {
didSet {
let _ = view
tableViewController!.selectedTag = selectedItem?.tag ?? -1
}
}
public var insets: NSEdgeInsets {
let frame = view.convert(searchField.bounds, from: searchField)
return NSEdgeInsets(top: NSMaxY(view.bounds) - NSMaxY(frame),
left: NSMinX(frame),
bottom: 0,
right: NSMaxX(view.bounds) - NSMaxX(frame))
}
var desiredHeight: CGFloat {
return (tableViewController?.desiredHeight ?? 0) + heightAboveTable + 1
}
private var heightAboveTable: CGFloat {
guard let scrollView = tableView.enclosingScrollView else {
return 0
}
return view.frame.height - scrollView.frame.maxY
}
init(groups: [SearchableComboViewGroup]) {
self.groups = groups
super.init(nibName: "SearchableComboView", bundle: Bundle(for: SearchableComboListViewController.self))
}
override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) {
preconditionFailure()
}
required init?(coder: NSCoder) {
preconditionFailure()
}
public override func awakeFromNib() {
tableViewController = SearchableComboTableViewController(tableView: tableView, groups: groups)
tableViewController?.delegate = self
visualEffectView.blendingMode = .behindWindow;
visualEffectView.material = .menu;
visualEffectView.state = .active;
}
func item(withTag tag: Int) -> SearchableComboViewItem? {
for group in groups {
for item in group.items {
if item.tag == tag {
return item
}
}
}
return nil
}
func item(withIdentifier identifier: NSUserInterfaceItemIdentifier) -> SearchableComboViewItem? {
for group in groups {
for item in group.items {
guard let itemIdentifier = item.identifier else {
continue
}
if itemIdentifier as NSString as NSUserInterfaceItemIdentifier == identifier {
return item
}
}
}
return nil
}
func item(withTitle title: String) -> SearchableComboViewItem? {
for group in groups {
for item in group.items {
if item.label == title {
return item
}
}
}
return nil
}
}
extension SearchableComboListViewController: NSTextFieldDelegate {
@objc(controlTextDidChange:)
public func controlTextDidChange(_ obj: Notification) {
let previouslySelectedItem = tableViewController?.selectedItem
tableViewController?.filter = searchField.stringValue
tableViewController?.selectOnlyItem(or: previouslySelectedItem)
delegate?.searchableComboListViewController(
self, maximumHeightDidChange: desiredHeight)
}
public override func viewWillAppear() {
let tag = tableViewController?.selectedTag
view.window?.makeFirstResponder(searchField)
tableViewController?.selectedTag = tag
}
private func makeSearchFieldFirstResponderPreservingTableViewSelectedRow() {
let selectedIndexes = tableView.selectedRowIndexes
searchField.window?.makeFirstResponder(searchField)
// The tableview removers its selection upon resigning first responder. Re-select it so that
// the serach field can manipulate the table view's selection appropriately.
tableView.selectRowIndexes(selectedIndexes, byExtendingSelection: false)
}
}
extension SearchableComboListViewController: SearchableComboTableViewControllerDelegate {
func searchableComboTableViewController(_ tableViewController: SearchableComboTableViewController,
didSelectItem item: SearchableComboViewItem?) {
selectedItem = item
delegate?.searchableComboListViewController(self, didSelectItem: item)
if closeOnSelect {
view.window?.orderOut(nil)
}
}
func searchableComboTableViewControllerGroups(_ tableViewController: SearchableComboTableViewController) -> [SearchableComboViewGroup] {
return groups
}
func searchableComboTableViewController(_ tableViewController: SearchableComboTableViewController,
didType event: NSEvent) {
// Restore keyboard focus to the search field.
guard searchField.window != nil else {
return
}
makeSearchFieldFirstResponderPreservingTableViewSelectedRow()
guard let fieldEditor = searchField.window?.fieldEditor(false, for: searchField) else {
return
}
let insertionRange = NSRange(location: fieldEditor.string.utf16.count, length: 0)
fieldEditor.selectedRange = insertionRange
fieldEditor.keyDown(with: event)
tableView.window?.makeFirstResponder(searchField)
fieldEditor.selectedRange = NSRange(location: fieldEditor.string.utf16.count, length: 0)
}
}
extension SearchableComboListViewController: SearchableComboListSearchFieldDelegate {
func searchFieldPerformKeyEquivalent(with event: NSEvent) -> Bool {
guard let window = searchField.window else {
return false
}
guard let firstResponder = window.firstResponder else {
return false
}
guard let textView = firstResponder as? NSTextView else {
return false
}
guard window.fieldEditor(false, for: nil) != nil else {
return false
}
guard searchField == textView.delegate as? NSSearchField else {
return false
}
let mask: NSEvent.ModifierFlags = [.shift, .control, .option, .command]
guard event.modifierFlags.intersection(mask) == [] else {
return super.performKeyEquivalent(with: event)
}
if event.keyCode == 125 /* down arrow */ || event.keyCode == 126 /* up arrow */ {
// TODO: Prevent reentrancy?
closeOnSelect = false
tableView.window?.makeFirstResponder(tableView)
tableView.keyDown(with: event)
closeOnSelect = true
return true
}
return super.performKeyEquivalent(with: event)
}
}
| gpl-2.0 | e0f6590f4df99cd54818151ddc12fac4 | 36.584541 | 140 | 0.654499 | 5.784387 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/GroupCallAvatarMenuItem.swift | 1 | 9640 | //
// GroupCallAvatarMenuItem.swift
// Telegram
//
// Created by Mike Renoir on 27.01.2022.
// Copyright © 2022 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import TelegramCore
import Postbox
import SwiftSignalKit
private final class PhotoOrVideoView: View, SlideViewProtocol {
private let imageView: TransformImageView
private var photoVideoView: MediaPlayerView?
private var photoVideoPlayer: MediaPlayer?
private var videoView: NSView?
required init(frame frameRect: NSRect) {
imageView = TransformImageView(frame: frameRect.size.bounds)
super.init(frame: frameRect)
addSubview(imageView)
}
func willAppear() {
}
func willDisappear() {
}
override func layout() {
super.layout()
imageView.frame = bounds
photoVideoView?.frame = imageView.frame
videoView?.frame = imageView.frame
}
deinit {
}
func setPeer(_ peer: Peer, peerPhoto: TelegramPeerPhoto?, video: NSView?, account: Account) {
self.videoView = video
if let video = video {
self.photoVideoPlayer = nil
self.photoVideoView?.removeFromSuperview()
self.photoVideoView = nil
addSubview(video)
} else if let first = peerPhoto, let video = first.image.videoRepresentations.last {
self.photoVideoView?.removeFromSuperview()
self.photoVideoView = nil
self.photoVideoView = MediaPlayerView(backgroundThread: true)
addSubview(photoVideoView!, positioned: .above, relativeTo: self.imageView)
self.photoVideoView!.isEventLess = true
self.photoVideoView!.frame = self.imageView.frame
let file = TelegramMediaFile(fileId: MediaId(namespace: 0, id: 0), partialReference: nil, resource: video.resource, previewRepresentations: first.image.representations, videoThumbnails: [], immediateThumbnailData: nil, mimeType: "video/mp4", size: video.resource.size, attributes: [])
let mediaPlayer = MediaPlayer(postbox: account.postbox, reference: MediaResourceReference.standalone(resource: file.resource), streamable: true, video: true, preferSoftwareDecoding: false, enableSound: false, fetchAutomatically: true)
mediaPlayer.actionAtEnd = .loop(nil)
self.photoVideoPlayer = mediaPlayer
if let seekTo = video.startTimestamp {
mediaPlayer.seek(timestamp: seekTo)
}
mediaPlayer.attachPlayerView(self.photoVideoView!)
mediaPlayer.play()
} else {
self.photoVideoPlayer = nil
self.photoVideoView?.removeFromSuperview()
self.photoVideoView = nil
let profileImageRepresentations:[TelegramMediaImageRepresentation]
if let peer = peer as? TelegramChannel {
profileImageRepresentations = peer.profileImageRepresentations
} else if let peer = peer as? TelegramUser {
profileImageRepresentations = peer.profileImageRepresentations
} else if let peer = peer as? TelegramGroup {
profileImageRepresentations = peer.profileImageRepresentations
} else {
profileImageRepresentations = []
}
let id = profileImageRepresentations.first?.resource.id.hashValue ?? Int(peer.id.toInt64())
let media = peerPhoto?.image ?? TelegramMediaImage(imageId: MediaId(namespace: 0, id: MediaId.Id(id)), representations: profileImageRepresentations, immediateThumbnailData: nil, reference: nil, partialReference: nil, flags: [])
if let dimension = profileImageRepresentations.last?.dimensions.size {
let arguments = TransformImageArguments(corners: ImageCorners(), imageSize: dimension, boundingSize: frame.size, intrinsicInsets: NSEdgeInsets())
self.imageView.setSignal(signal: cachedMedia(media: media, arguments: arguments, scale: self.backingScaleFactor), clearInstantly: false)
self.imageView.setSignal(chatMessagePhoto(account: account, imageReference: ImageMediaReference.standalone(media: media), peer: peer, scale: self.backingScaleFactor), clearInstantly: false, animate: true, cacheImage: { result in
cacheMedia(result, media: media, arguments: arguments, scale: System.backingScale)
})
self.imageView.set(arguments: arguments)
if let reference = PeerReference(peer) {
_ = fetchedMediaResource(mediaBox: account.postbox.mediaBox, reference: .avatar(peer: reference, resource: media.representations.last!.resource)).start()
}
} else {
self.imageView.setSignal(signal: generateEmptyRoundAvatar(self.imageView.frame.size, font: .avatar(90.0), account: account, peer: peer) |> map { TransformImageResult($0, true) })
}
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
final class GroupCallAvatarMenuItem : ContextMenuItem {
private let peer: Peer
private let context: AccountContext
init(_ peer: Peer, context: AccountContext) {
self.peer = peer
self.context = context
super.init("")
}
required init(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func rowItem(presentation: AppMenu.Presentation, interaction: AppMenuBasicItem.Interaction) -> TableRowItem {
return GroupCallAvatarMenuRowItem(.zero, presentation: presentation, interaction: interaction, peer: peer, context: context)
}
}
private final class GroupCallAvatarMenuRowItem : AppMenuBasicItem {
fileprivate let peer: Peer
fileprivate let context: AccountContext
init(_ initialSize: NSSize, presentation: AppMenu.Presentation, interaction: AppMenuBasicItem.Interaction, peer: Peer, context: AccountContext) {
self.peer = peer
self.context = context
super.init(initialSize, presentation: presentation, menuItem: nil, interaction: interaction)
}
override func viewClass() -> AnyClass {
return GroupCallAvatarMenuRowView.self
}
override var effectiveSize: NSSize {
return NSMakeSize(200, 200)
}
override var height: CGFloat {
return 200
}
}
private final class GroupCallAvatarMenuRowView : AppMenuBasicItemView {
private let slider: SliderView = SliderView(frame: .zero)
private let peerPhotosDisposable = MetaDisposable()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(slider)
slider.layer?.cornerRadius = 4
}
deinit {
peerPhotosDisposable.dispose()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layout() {
super.layout()
slider.setFrameSize(NSMakeSize(contentSize.width, contentSize.height - 4))
}
override func set(item: TableRowItem, animated: Bool = false) {
super.set(item: item, animated: animated)
guard let item = item as? GroupCallAvatarMenuRowItem else {
return
}
let peer = item.peer
let context = item.context
var photos = Array(syncPeerPhotos(peerId: peer.id).prefix(10))
let signal = peerPhotos(context: context, peerId: peer.id, force: true) |> deliverOnMainQueue
slider.frame = NSMakeRect(0, 0, frame.width - 8, frame.height - 4)
let view = PhotoOrVideoView(frame: self.slider.bounds)
view.setPeer(peer, peerPhoto: nil, video: nil, account: context.account)
self.slider.addSlide(view)
if photos.isEmpty {
peerPhotosDisposable.set(signal.start(next: { [weak self, weak view] photos in
guard let `self` = self else {
return
}
var photos = Array(photos.prefix(10))
if !photos.isEmpty {
let first = photos.removeFirst()
if !first.image.videoRepresentations.isEmpty {
photos.insert(first, at: 0)
self.slider.removeSlide(view)
}
}
for photo in photos {
let view = PhotoOrVideoView(frame: self.slider.bounds)
view.setPeer(peer, peerPhoto: photo, video: nil, account: context.account)
self.slider.addSlide(view)
}
}))
} else {
if !photos.isEmpty {
let first = photos.removeFirst()
if !first.image.videoRepresentations.isEmpty {
photos.insert(first, at: 0)
self.slider.removeSlide(view)
}
}
for photo in photos {
let view = PhotoOrVideoView(frame: self.slider.bounds)
view.setPeer(peer, peerPhoto: photo, video: nil, account: context.account)
self.slider.addSlide(view)
}
} }
}
| gpl-2.0 | d757b574237eadb6fca09ebb0f52bb62 | 37.556 | 296 | 0.610644 | 5.173913 | false | false | false | false |
austinzheng/swift-compiler-crashes | fixed/25442-llvm-smdiagnostic-smdiagnostic.swift | 7 | 2095 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a {
}
struct a
struct Q {
class A {
enum b { ()
{
struct B{
return
let l = B
struct d{ e () {
{{struct S<I:C{
{
{
class d:a{
{
if{struct B:B:d<T where S
0
struct S<e{
d
}
class A
{
}
init( ) {
" " " [ 1
enum A {
{
{}
import F
typealias B<T where B : b
}
}
}
let f = B<T where g
class a
{class a{
class x {}
}
struct S
struct S<T where g:d<e{
typealias e) {}
struct Q {
protocol c {
0
}
struct a
{
class A{
enum {
struct B<e{
}
protocol A{
func b
struct A{
{
enum A {
func d{}
{
}
{
{
}
}
}protocol e (
}
a {struct S<T , length: () -> Void{
}
func b
var _ T : b
}
var : b
{
func g: (
}
{
{
protocol c {
}
a<d
func i {}
}
}
}
func i {
struct A {
0
var : b
class B{
}}}
}
struct A {
}
struct A {
" " " [ 1
}
let closure: b(
" () -> Void in
}
}}
func g: b
struct d <e:a{
}
0
protocol c {
func a
" E
class a{
init( ) {
let a {
" E
func g: b
}
struct B{
var f=a{}
class x {
func g:B{
struct c { () -> Void{
a {
enum A {
struct A{
d<
}
}}}
protocol c {
A {
class a{
" [ 1
}
B {
}
" E
}}
struct S<Y {
struct B {
}
func g
}
class x {
}
struct S<I:e:d{
}
let l = B<T where g:t
}
class A{
d<T where g
}}protocol A{
import F
}
func g
}
}
class B<T where I:B
{class d<T where S<T where B : b
}
let l = B<e) = { e () {class B<T where g:e{
}
B : () {
}
{
struct B{
class x {
}
_ = b(
{
{
{
}
typealias B<i: b {
enum A {
}
enum b { e () {
_ = f = { )-> Void in
0
struct d <T where g:t
{
}}
func b
}protocol c {
}
func i {
}
struct B{
{
{
protocol c {
init( ) {
{
B {
protocol c { )-> Void{
}}}}
" " [ 1
}
typealias e:B<d
}
a<I:B
struct S
{
var f=a{
}
struct S
class a
}
var _ T where S<e{
}
{
" " (
if{
{
protocol c {
{
}
}
}
enum S<i: b {
{
func b
let a {
protocol e {
struct A {
{
struct a{
a{
a{struct A
typealias e{
}
class a{
{
struct d <e) = B<
}
" E
a {struct d:a
}
struct c
}
class A {
}
{{
{
protocol c {}
let a {
enum A {
protocol A{
}
a<T where g:d
}
protocol c {{
enum b {struct B
{
}
let f {
_ = { () -> {struct d <T where I
| mit | 0d59b7975f484fb4dd747091251d3001 | 7.183594 | 87 | 0.540811 | 2.097097 | false | false | false | false |
kemalenver/SwiftHackerRank | Algorithms/Strings.playground/Pages/Strings - HackerRank in a String!.xcplaygroundpage/Contents.swift | 1 | 1232 |
import Foundation
var inputs = ["10",
"knarrekcah", // NO
"hackerrank", // YES
"hackerone", // NO
"abcdefghijklmnopqrstuvwxyz", // NO
"rhackerank", // NO
"ahankerck", // NO
"hacakaeararanaka", // YES
"hhhhaaaaackkkkerrrrrrrrank", // YES
"crackerhackerknar", // NO
"hhhackkerbanker"] // NO
func readLine() -> String? {
let next = inputs.first
inputs.removeFirst()
return next
}
let hackerRank = Array("hackerrank".utf8)
func checkStringIsHackerRank(input: String.UTF8View) -> Bool {
let input = Array(input)
var i = 0
var j = 0
var result = false
while i < input.count {
if input[i]==hackerRank[j] {
j += 1
}
if j > hackerRank.count-1 {
result = true
break
}
i += 1
}
return result
}
let numberOfTests = Int(readLine()!)!
for _ in 0..<numberOfTests {
let string1 = readLine()!.utf8
if checkStringIsHackerRank(input: string1) {
print("YES")
} else {
print("NO")
}
}
| mit | 225bf82ed92d9bfa99e0ac51fabc6f37 | 17.953846 | 63 | 0.482143 | 4 | false | false | false | false |
olaf-olaf/finalProject | drumPad/FxController.swift | 1 | 3001 | //
// FxController.swift
// drumPad
//
// Created by Olaf Kroon on 11/01/17.
// Student number: 10787321
// Course: Programmeerproject
//
// FXController contains a mixer that is used to set the dry / wet ratio of effects and it
// contains button
//
// Copyright © 2017 Olaf Kroon. All rights reserved.
//
import UIKit
class FxController: UIViewController {
// MARK: - Variables.
let enabledColor = UIColor(red: (246/255.0), green: (124/255.0), blue: (113/255.0), alpha: 1.0)
// MARK: - Outlets.
@IBOutlet weak var setRing: UIButton!
@IBOutlet weak var setDelay: UIButton!
@IBOutlet weak var setDistortion: UIButton!
@IBOutlet weak var setReverb: UIButton!
@IBOutlet weak var enterFx: UIButton!
@IBOutlet weak var delaySlider: UISlider!{
didSet{
delaySlider.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_2))
}
}
@IBOutlet weak var ringSlider: UISlider!{
didSet{
ringSlider.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_2))
}
}
@IBOutlet weak var distortionSlider: UISlider!{
didSet{
distortionSlider.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_2))
}
}
@IBOutlet weak var reverbSlider: UISlider!{
didSet{
reverbSlider.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_2))
}
}
// MARK: - UIViewController lifecycle.
override func viewDidLoad() {
super.viewDidLoad()
ringSlider.value = Float(AudioController.sharedInstance.ringModulator.mix)
reverbSlider.value = Float(AudioController.sharedInstance.reverb.dryWetMix)
distortionSlider.value = Float(AudioController.sharedInstance.distortion.finalMix)
delaySlider.value = Float(AudioController.sharedInstance.delay.dryWetMix)
enterFx.layer.cornerRadius = 5
setRing.layer.cornerRadius = 5
setDelay.layer.cornerRadius = 5
setDistortion.layer.cornerRadius = 5
setReverb.layer.cornerRadius = 5
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Outlets.
@IBAction func ringPressed(_ sender: UIButton) {
setRing.backgroundColor = enabledColor
}
@IBAction func delayPressed(_ sender: UIButton) {
setDelay.backgroundColor = enabledColor
}
@IBAction func distortionPressed(_ sender: UIButton) {
setDistortion.backgroundColor = enabledColor
}
@IBAction func reverbPressed(_ sender: UIButton) {
setReverb.backgroundColor = enabledColor
}
@IBAction func setFx(_ sender: Any) {
if enterFx.isTouchInside {
enterFx.backgroundColor = enabledColor
AudioController.sharedInstance.mixFx(reverbLevel: reverbSlider.value , distortionLevel: distortionSlider.value, ringLevel: ringSlider.value, delayLevel: delaySlider.value)
}
}
}
| mit | 14d99f97c08a172d3f5ac37dc3935399 | 30.914894 | 183 | 0.665333 | 4.451039 | false | false | false | false |
LuckyChen73/CW_WEIBO_SWIFT | WeiBo/WeiBo/Classes/View(视图)/Compose(发布)/CustomKeyboard(自定义键盘)/WBCustomKeyboard.swift | 1 | 6278 | //
// WBCustomKeyboard.swift
// WeiBo
//
// Created by chenWei on 2017/4/12.
// Copyright © 2017年 陈伟. All rights reserved.
//
import UIKit
fileprivate let identifier = "emotion"
/// UICollectionViewFlowLayoutl类
fileprivate class EmotionLayout: UICollectionViewFlowLayout
{
override func prepare() {
super.prepare()
//设置layout
minimumLineSpacing = 0
minimumInteritemSpacing = 0
itemSize = CGSize(width: screenWidh, height: 150)
scrollDirection = .horizontal
}
}
class WBCustomKeyboard: UIView {
//测试数据数组
var dataSourceArr = WBEmotionTool.shared.dataSourceArr
/// 表情的collectionView
lazy var emotionView: UICollectionView = {
//创建collectionView
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: EmotionLayout())
collectionView.dataSource = self
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.delegate = self
collectionView.register(WBEmotionCell.self, forCellWithReuseIdentifier: identifier)
return collectionView
}()
/// pageControl 分页指示器
lazy var pageControl: UIPageControl = {
let pageControl = UIPageControl()
pageControl.numberOfPages = 4
pageControl.currentPage = 0
pageControl.isEnabled = false
//默认显示4页
pageControl.numberOfPages = self.dataSourceArr[0].count
pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")//默认的小图片
pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage") // 选中的图片
return pageControl
}()
/// 底部的toolBar
lazy var toolBar: WBKeyboardToolbar = {
let toolBar = WBKeyboardToolbar()
toolBar.delegate = self
return toolBar
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - 底部键盘工具条代理 WBKeyboardToolbarDelegate
extension WBCustomKeyboard: WBKeyboardToolbarDelegate {
/// 实现代理方法
func toggleKeyboard(section: Int) {
//先取到要移动到的 item 的下标路径
let indexPath = IndexPath(item: 0, section: section)
//滚动到对应路径的item
emotionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
//分页指示器跟着连动
setupPageControl(indexPath: indexPath)
}
}
// MARK: - 监听手动拖拽emotionView滚动的代理 UICollectionViewDelegate
extension WBCustomKeyboard: UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//1.拿到两个 cells
let cells = emotionView.visibleCells
//2.获取 cell在屏幕显示的区域
if cells.count > 1 {
let cell1 = cells[0]
let cell2 = cells[1]
//判断 offset与 cell 的 originX 的差值的绝对值的大小,绝对值越小,显示区域越大
let offset = scrollView.contentOffset.x
let originX1 = cell1.frame.origin.x
let originX2 = cell2.frame.origin.x
// print("offset: \(offset)")
// print("originX1:\(originX1)")
// print("originX2:\(originX2)")
// print("================================")
let origin1 = abs(offset - originX1)
let origin2 = abs(offset - originX2)
if origin1 < origin2 {
//取到 cell1所在的下标路径
let indexPath1 = emotionView.indexPath(for: cell1)
toolBar.selectedIndex = (indexPath1?.section)!
setupPageControl(indexPath: indexPath1!)
}else {
let indexPath2 = emotionView.indexPath(for: cell2)
toolBar.selectedIndex = (indexPath2?.section)!
setupPageControl(indexPath: indexPath2!)
}
}
}
}
// MARK: - UI 搭建
extension WBCustomKeyboard {
func setupUI() {
addSubview(emotionView)
addSubview(pageControl)
addSubview(toolBar)
emotionView.backgroundColor = UIColor.rgbColor(r: 243, g: 243, b: 243)
emotionView.snp.makeConstraints { (make) in
make.left.right.top.equalTo(self)
make.height.equalTo(160)
}
pageControl.snp.makeConstraints { (make) in
make.top.equalTo(emotionView.snp.bottom)
make.height.equalTo(19)
make.left.right.equalTo(self)
make.centerX.equalTo(self)
}
toolBar.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(self)
make.height.equalTo(37)
}
}
/// 创建分页指示器
func setupPageControl(indexPath: IndexPath) {
pageControl.numberOfPages = dataSourceArr[indexPath.section].count
pageControl.currentPage = indexPath.item
}
}
// MARK: - 数据源方法
extension WBCustomKeyboard: UICollectionViewDataSource {
//多少组
func numberOfSections(in collectionView: UICollectionView) -> Int {
return dataSourceArr.count //这里返回4个大组
}
//每组多少 item
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSourceArr[section].count // 返回每个大组里的小组的个数
}
//具体 item
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! WBEmotionCell
//先通过组取,再通过item取,得到一维模型数组
cell.emotions = dataSourceArr[indexPath.section][indexPath.item]
return cell
}
}
| mit | 7a94f5e2be5202046da7acf5345f2a0d | 28.741117 | 121 | 0.618877 | 4.806399 | false | false | false | false |
M2Mobi/Marky-Mark | markymark/Classes/Layout Builders/UIView/Block Builders/Block/ListViewLayoutBlockBuilder.swift | 1 | 2233 | //
// Created by Jim van Zummeren on 06/05/16.
// Copyright © 2016 M2mobi. All rights reserved.
//
import Foundation
import UIKit
class ListViewLayoutBlockBuilder: InlineAttributedStringViewLayoutBlockBuilder {
// MARK: LayoutBuilder
override func relatedMarkDownItemType() -> MarkDownItem.Type {
return UnorderedListMarkDownItem.self
}
override func build(_ markDownItem: MarkDownItem, asPartOfConverter converter: MarkDownConverter<UIView>, styling: ItemStyling) -> UIView {
let listMarkDownItem = markDownItem as! ListMarkDownItem
let listView = getListView(listMarkDownItem, styling: styling)
let spacing: UIEdgeInsets? = (styling as? ContentInsetStylingRule)?.contentInsets
return ContainerView(view: listView, spacing: spacing)
}
// MARK: Private
/**
Loops recursively through all listItems to create
vertically appended list of ListItemView's
- parameter listMarkDownItem: MarkDownItem to loop through
- parameter styling: Styling to apply to each list item
- returns: A view containing all list items of given markDownItem
*/
private func getListView(_ listMarkDownItem: ListMarkDownItem, styling: ItemStyling) -> UIView {
let listView = ListView(styling: styling)
for listItem in listMarkDownItem.listItems ?? [] {
let bulletStyling = styling as? BulletStylingRule
let listStyling = styling as? ListItemStylingRule
let attributedString = attributedStringForMarkDownItem(listItem, styling: styling)
let listItemView = ListItemView(
listMarkDownItem: listItem,
styling: bulletStyling,
attributedText: attributedString,
urlOpener: urlOpener
)
listItemView.bottomSpace = (listStyling?.bottomListItemSpacing ?? 0)
listView.addSubview(listItemView)
if let nestedListItems = listItem.listItems, nestedListItems.count > 0 {
let nestedListView = getListView(listItem, styling: styling)
listView.addSubview(nestedListView)
}
}
return listView
}
}
| mit | 85975f12951226149862a88e3e706a1e | 30.885714 | 143 | 0.672491 | 5.404358 | false | false | false | false |
zhangxigithub/GIF | GIF/ZXConverter.swift | 1 | 14084 | //
// ZXConverter.swift
// GIF
//
// Created by zhangxi on 7/1/16.
// Copyright © 2016 zhangxi.me. All rights reserved.
//
import Cocoa
import Foundation
enum Quality {
case VeryLow
case Low
case Normal
case High
case VeryHigh
func lossy() -> String{
switch self {
case VeryLow:
return ""
case Low:
return "80"
case Normal:
return "30"
case High:
return "10"
case VeryHigh:
return ""
}
}
func needCompress() -> Bool
{
return ((self != .VeryLow ) && (self != .VeryHigh))
}
}
class GIF: NSObject
{
var range : (ss:String,t:String)? = nil
var quality : Quality = .Normal
var fps:Int = 12
var palettePath : String!
var gifFileName : String!
var gifPath : String!
var comporesGifPath : String!
var fileName : String!
var path : String!{
didSet{
self.fileName = (path as NSString).lastPathComponent
self.gifFileName = String(format: "%@.gif",NSUUID().UUIDString)
self.gifPath = String(format: "%@/%@",folderPath,gifFileName)
self.comporesGifPath = String(format: "%@/c_%@",folderPath,gifFileName)
self.palettePath = String(format: "%@/p_%@",folderPath,gifFileName)
}
}
var thumb : [String]!
var duration:NSTimeInterval!
var size:CGSize!{
didSet{
wantSize = size
}
}
var wantSize:CGSize?
override var description: String
{
get{
return "=====================\npath:\(path)\nfileName:\(fileName)\ngifFileName:\(gifFileName)\nduration:\(duration)\nvideoSize:\(size)\nwantSize:\(wantSize)\nframes:\(thumb?.count)\n\n====================="
}
}
func valid() -> (valid:Bool,error:String) {
if path == nil
{
return (valid:false,error:"Can't get the file.")
}
if thumb == nil
{
return (valid:false,error:"Can't create thumbnails.")
}
if duration == nil
{
return (valid:false,error:"Can't get duration info.")
}
if wantSize == nil
{
return (valid:false,error:"Can't get video width.")
}
if size == nil
{
return (valid:false,error:"Can't get video height.")
}
return (valid:true,error:"Sucess")
}
func clean()
{
let fm = NSFileManager.defaultManager()
do{
try fm.removeItemAtPath(gifPath)
try fm.removeItemAtPath(comporesGifPath)
try fm.removeItemAtPath(palettePath)
}catch{}
}
}
/*
http://blog.csdn.net/stone_wzf/article/details/45570021
-i $1 -vf "fps=15,scale=320:-1:flags=lanczos,palettegen=stats_mode=diff" -y $palette2
-i $1 -i $palette2 -lavfi "fps=15,scale=320:-1:flags=lanczos [x]; [x][1:v] paletteuse" -gifflags +transdiff -y 3$2
//scale=320:-1:flags=lanczos
low quality:
./ffmpeg -i $1 -lavfi "fps=15" -gifflags +transdiff -y 5$2
*/
class ZXConverter: NSObject {
let ffmpeg = NSBundle.mainBundle().pathForResource("ffmpeg", ofType: "")!
let ffprobe = NSBundle.mainBundle().pathForResource("ffprobe", ofType: "")!
let gifsicle = NSBundle.mainBundle().pathForResource("gifsicle", ofType: "")!
let fm = NSFileManager.defaultManager()
var convertQueue: dispatch_queue_t? = dispatch_queue_create("me.zhnagxi.convert", nil)
override init() {
super.init()
//resetQueue()
}
var stopTask:Bool = false
func stop()
{
stopTask = true
//resetQueue()
// for task in tasks
// {
// print(task)
// task.terminate()
// }
// tasks.removeAll()
}
var tasks = [NSTask]()
func resetQueue()
{
if convertQueue != nil
{
dispatch_suspend(convertQueue!)
convertQueue = nil
convertQueue = dispatch_queue_create("me.zhnagxi.convert", nil)
}
}
func convert(gif:GIF,complete:(success:Bool,path:String?)->Void)
{
stopTask = false
dispatch_async(convertQueue!, {[unowned self] () -> Void in
print(gif.description)
gif.clean()
var result = ""
let size = gif.wantSize ?? gif.size
if gif.quality == .VeryLow
{
var arguments = [String]()
arguments += ["-i",gif.path,"-lavfi"]
if size != nil
{
arguments.append(String(format: "fps=%d,scale=%d:%d:flags=lanczos",Int(gif.fps),Int(size!.width),Int(size!.height)))
}else
{
arguments.append(String(format: "fps=%d",Int(gif.fps)))
}
if gif.range != nil
{
arguments = ["-ss",gif.range!.ss] + arguments //+ ["to",gif.range!.to]
arguments = arguments + ["-t",gif.range!.t]
}else
{
}
arguments += ["-gifflags","+transdiff","-y",gif.gifPath]
//if self.stopTask { return }
result = result + self.shell(self.ffmpeg,arguments:arguments)
//if self.stopTask { return }
}else
{
var vf = ""
var lavfi = ""
if size != nil
{
vf = String(format: "fps=%d,scale=%d:%d:flags=lanczos,palettegen=stats_mode=diff",Int(gif.fps),Int(size!.width),Int(size!.height))
lavfi = String(format: "fps=%d,scale=%d:%d:flags=lanczos [x]; [x][1:v] paletteuse=dither=floyd_steinberg",Int(gif.fps),Int(size!.width),Int(size!.height))
}else{
vf = String(format: "fps=%d,palettegen=stats_mode=diff",Int(gif.fps))
lavfi = String(format: "fps=%d [x]; [x][1:v] paletteuse=dither=floyd_steinberg",Int(gif.fps))
}
//if self.stopTask { return }
if gif.range == nil
{
result = result + self.shell(self.ffmpeg,arguments:["-i",gif.path,"-vf",vf,"-y",gif.palettePath])
if self.stopTask { return }
result = result + self.shell(self.ffmpeg,arguments:["-i",gif.path,"-i",gif.palettePath,"-lavfi",lavfi,"-gifflags","+transdiff","-y",gif.gifPath])
}else
{
result = result + self.shell(self.ffmpeg,arguments:["-ss",gif.range!.ss,"-t",gif.range!.t,"-i",gif.path,"-vf",vf,"-y",gif.palettePath])
//if self.stopTask { return }
result = result + self.shell(self.ffmpeg,arguments:["-ss",gif.range!.ss,"-t",gif.range!.t,"-i",gif.path,"-i",gif.palettePath,"-lavfi",lavfi,"-gifflags","+transdiff","-y",gif.gifPath])
}
//if self.stopTask { return }
}
print(result)
if gif.quality.needCompress()
{
self.compress(gif)
}
//if self.stopTask { return }
dispatch_async(dispatch_get_main_queue()) {
let path = gif.quality.needCompress() ? gif.comporesGifPath : gif.gifPath
if self.fm.fileExistsAtPath(path)
{
//if self.stopTask { return }
complete(success: true,path: path)
}else
{
//if self.stopTask { return }
complete(success: false,path: nil)
}
}//end main
})//end background
}
func compress(gif:GIF)
{
print("start compress")
let q = String(format:"--lossy=%@",gif.quality.lossy())
let result = shell(gifsicle,arguments:["-O3",q,"-o",gif.comporesGifPath,gif.gifPath])
print(result)
}
func loadGIF(path:String,complete:(gif:GIF,err:String)->Void)
{
stopTask = false
/*
http://stackoverflow.com/questions/7708373/get-ffmpeg-information-in-friendly-way
*/
let gif = GIF()
let fm = NSFileManager.defaultManager()
if let dir = try? fm.attributesOfItemAtPath(path)
{
let size = (dir[NSFileSize] as! NSNumber).floatValue/(1024*1024)
print(size)
if size > 100
{
complete(gif: gif, err: "GIF Works Pro can only convert file less than 100MB.")
return
}
}
dispatch_async(convertQueue!, { () -> Void in
//"-show_streams"
//"-show_format"
//let arguments = ["-v","quiet","-print_format","json","-select_streams","v:0","-show_format","-show_entries","stream=height,width,r_frame_rate",path]
let arguments = ["-v","quiet","-print_format","json","-select_streams","v:0","-show_format","-show_streams",path]
let result = self.shell(self.ffprobe,arguments:arguments)
let data = try? NSJSONSerialization.JSONObjectWithData(result.dataUsingEncoding(NSUTF8StringEncoding)!, options:.AllowFragments)
if data != nil
{
let json = JSON(data!)
print(json)
gif.path = path
gif.size = CGSizeMake(CGFloat(json["streams"][0]["width"].floatValue), CGFloat(json["streams"][0]["height"].floatValue))
gif.duration = json["format"]["duration"].doubleValue
//400 225
//print(gif)
var scale = ""
if gif.size.width/400 < gif.size.height/225
{
scale = "scale=-1:225"
}else
{
scale = "scale=400:-1"
}
let _ = try? fm.removeItemAtPath(thumbPath)
let _ = try? fm.createDirectoryAtPath(thumbPath, withIntermediateDirectories: true, attributes: nil)
var r = 36/gif.duration
r = min(r,6)
r = max(r,1)
let arguments = ["-i",path,"-r",String(format:"%.0d",Int(r)),"-vf",scale,thumbPath.stringByAppendingString("/t%5d.jpg")]
self.shell(self.ffmpeg,arguments:arguments)
var files = [String]()
do{
if let a = try? fm.contentsOfDirectoryAtPath(thumbPath)
{
for item in a
{
files.append(String(format:"%@/%@",thumbPath,item))
}
}
}
gif.thumb = files
dispatch_async(dispatch_get_main_queue()) {
complete(gif: gif, err: "")
}
}else
{
dispatch_async(dispatch_get_main_queue()) {
complete(gif: gif, err: "get video file error.")
}
}
})
}
func thumb(path:String,complete:(dir:[String]?)->Void)
{
//./ffmpeg -i 1.mp3 -vf scale=100:-1 example.%d.jpg
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { () -> Void in
let fm = NSFileManager.defaultManager()
do{
try fm.removeItemAtPath(thumbPath)
try fm.createDirectoryAtPath(thumbPath, withIntermediateDirectories: true, attributes: nil)
}catch{}
let arguments = ["-i",path,"-r","6","-vf","scale=200:-1",thumbPath.stringByAppendingString("/t%5d.jpg")]
let _ = self.shell(self.ffmpeg,arguments:arguments)
//print(result)
var files = [String]()
do{
if let a = try? fm.contentsOfDirectoryAtPath(thumbPath)
{
for item in a
{
files.append(String(format:"%@/%@",thumbPath,item))
}
}
}
if self.stopTask
{
return
}
dispatch_async(dispatch_get_main_queue()) {
complete(dir: files)
}
})
}
func shell(launchPath: String, arguments: [String]? = nil) -> String
{
if stopTask
{
return ""
}
print("shell:")
print(launchPath)
print(arguments)
print("========================")
let task = NSTask()
tasks.append(task)
task.launchPath = launchPath
if arguments == nil
{
task.arguments = [String]()
}else
{
task.arguments = arguments
}
let pipe = NSPipe()
task.standardOutput = pipe
task.standardError = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: NSUTF8StringEncoding) ?? ""
return output
}
}
/*
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { () -> Void in
dispatch_async(dispatch_get_main_queue()) {
}
})
*/
| apache-2.0 | 03e89fabc5c1ea8be588be6994eda342 | 28.836864 | 218 | 0.472627 | 4.388595 | false | false | false | false |
jpush/jchat-swift | JChat/Src/UserModule/View/JCMyInfoCell.swift | 1 | 3057 | //
// JCMyInfoCell.swift
// JChat
//
// Created by JIGUANG on 2017/3/30.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
class JCMyInfoCell: JCTableViewCell {
var icon: UIImage? {
get {
return iconView.image
}
set {
iconView.image = newValue
}
}
var title: String? {
get {
return titleLabel.text
}
set {
titleLabel.text = newValue
}
}
var detail: String? {
get {
return detailLabel.text
}
set {
detailLabel.text = newValue
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
_init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_init()
}
override func awakeFromNib() {
super.awakeFromNib()
_init()
}
private lazy var iconView: UIImageView = UIImageView()
private lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = UIFont.systemFont(ofSize: 16)
titleLabel.backgroundColor = .white
titleLabel.layer.masksToBounds = true
return titleLabel
}()
private lazy var detailLabel: UILabel = {
let detailLabel = UILabel()
detailLabel.textAlignment = .right
detailLabel.font = UIFont.systemFont(ofSize: 14)
detailLabel.textColor = UIColor(netHex: 0x999999)
detailLabel.backgroundColor = .white
detailLabel.layer.masksToBounds = true
return detailLabel
}()
private func _init() {
addSubview(iconView)
addSubview(titleLabel)
addSubview(detailLabel)
addConstraint(_JCLayoutConstraintMake(iconView, .top, .equal, contentView, .top, 13.5))
addConstraint(_JCLayoutConstraintMake(iconView, .left, .equal, contentView, .left, 15))
addConstraint(_JCLayoutConstraintMake(iconView, .width, .equal, nil, .notAnAttribute, 18))
addConstraint(_JCLayoutConstraintMake(iconView, .height, .equal, nil, .notAnAttribute, 18))
addConstraint(_JCLayoutConstraintMake(titleLabel, .centerY, .equal, contentView, .centerY))
addConstraint(_JCLayoutConstraintMake(titleLabel, .left, .equal, iconView, .right, 10))
addConstraint(_JCLayoutConstraintMake(titleLabel, .width, .equal, nil, .notAnAttribute, 100))
addConstraint(_JCLayoutConstraintMake(titleLabel, .height, .equal, nil, .notAnAttribute, 22.5))
addConstraint(_JCLayoutConstraintMake(detailLabel, .centerY, .equal, contentView, .centerY))
addConstraint(_JCLayoutConstraintMake(detailLabel, .left, .equal, titleLabel, .right))
addConstraint(_JCLayoutConstraintMake(detailLabel, .right, .equal, contentView, .right))
addConstraint(_JCLayoutConstraintMake(detailLabel, .height, .equal, contentView, .height))
}
}
| mit | f1fdf4fb959e5ec581c94c0b221979e3 | 31.489362 | 103 | 0.630976 | 4.794349 | false | false | false | false |
jordanebelanger/SwiftyBluetooth | Sources/SBError.swift | 2 | 4694 | //
// SBError.swift
//
// Copyright (c) 2016 Jordane Belanger
//
// 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 CoreBluetooth
public enum SBError: Error {
public enum SBBluetoothUnavailbleFailureReason {
case unsupported
case unauthorized
case poweredOff
case unknown
}
public enum SBOperation: String {
case connectPeripheral = "Connect peripheral"
case disconnectPeripheral = "Disconnect peripheral"
case readRSSI = "Read RSSI"
case discoverServices = "Discover services"
case discoverIncludedServices = "Discover included services"
case discoverCharacteristics = "Discover characteristics"
case discoverDescriptors = "Discover descriptors"
case readCharacteristic = "Read characteristic"
case readDescriptor = "Read descriptor"
case writeCharacteristic = "Write characteristic"
case writeDescriptor = "Write descriptor"
case updateNotificationStatus = "Update notification status"
}
case bluetoothUnavailable(reason: SBBluetoothUnavailbleFailureReason)
case scanningEndedUnexpectedly
case operationTimedOut(operation: SBOperation)
case invalidPeripheral
case peripheralFailedToConnectReasonUnknown
case peripheralServiceNotFound(missingServicesUUIDs: [CBUUID])
case peripheralCharacteristicNotFound(missingCharacteristicsUUIDs: [CBUUID])
case peripheralDescriptorsNotFound(missingDescriptorsUUIDs: [CBUUID])
case invalidDescriptorValue(descriptor: CBDescriptor)
}
extension SBError: LocalizedError {
public var errorDescription: String? {
switch self {
case .bluetoothUnavailable(let reason):
return reason.localizedDescription
case .scanningEndedUnexpectedly:
return "Your peripheral scan ended unexpectedly."
case .operationTimedOut(let operation):
return "Bluetooth operation timed out: \(operation.rawValue)"
case .invalidPeripheral:
return "Invalid Bluetooth peripheral, you must rediscover this peripheral to use it again."
case .peripheralFailedToConnectReasonUnknown:
return "Failed to connect to your peripheral for an unknown reason."
case .peripheralServiceNotFound(let missingUUIDs):
let missingUUIDsString = missingUUIDs.map { $0.uuidString }.joined(separator: ",")
return "Peripheral service(s) not found: \(missingUUIDsString)"
case .peripheralCharacteristicNotFound(let missingUUIDs):
let missingUUIDsString = missingUUIDs.map { $0.uuidString }.joined(separator: ",")
return "Peripheral charac(s) not found: \(missingUUIDsString)"
case .peripheralDescriptorsNotFound(let missingUUIDs):
let missingUUIDsString = missingUUIDs.map { $0.uuidString }.joined(separator: ",")
return "Peripheral descriptor(s) not found: \(missingUUIDsString)"
case .invalidDescriptorValue(let descriptor):
return "Failed to parse value for descriptor with uuid: \(descriptor.uuid.uuidString)"
}
}
}
extension SBError.SBBluetoothUnavailbleFailureReason {
public var localizedDescription: String {
switch self {
case .unsupported:
return "Your iOS device does not support Bluetooth."
case .unauthorized:
return "Unauthorized to use Bluetooth."
case .poweredOff:
return "Bluetooth is disabled, enable bluetooth and try again."
case .unknown:
return "Bluetooth is currently unavailable (unknown reason)."
}
}
}
| mit | 2a76d53f75e3de220168a92446e76117 | 45.019608 | 103 | 0.712399 | 5.227171 | false | false | false | false |
Sajjon/Zeus | Examples/SpotifyAPI/SpotifyAPI/ViewControllers/ArtistViewController.swift | 1 | 6219 | //
// ArtistViewController.swift
// SpotifyAPI
//
// Created by Cyon Alexander (Ext. Netlight) on 30/08/16.
// Copyright © 2016 com.cyon. All rights reserved.
//
import UIKit
private let cellIdentifier = "cellId"
private let depecheMode = "762310PdDnwsDxAQxzQkfX"
class ArtistViewController: UIViewController {
//MARK: Variables
@IBOutlet weak var tableView: UITableView!
fileprivate var artist: Artist? {
didSet {
guard artist != nil else { return }
tableView.reloadData()
}
}
//MARK: VC Lifecycle Methods
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
fetchData()
}
}
//MARK: UITableViewDataSource Methods
extension ArtistViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
guard artist != nil else { return 0 }
return 4
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rowCount = 0
if section == 0 {
rowCount = 6
} else if section == 1 {
rowCount = artist?.genres?.count ?? 0
} else if section == 2 {
rowCount = artist?.images?.count ?? 0
} else if section == 3 {
rowCount = artist?.albums?.count ?? 0
}
return rowCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
if let cell = cell as? KeyValueTableViewCell, let pair = keyValue(for: indexPath) {
cell.configure(withKey: pair.key, value: pair.value)
}
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var title: String?
if section == 0 {
title = "About"
} else if section == 1 {
title = "Genres"
} else if section == 2 {
title = "Images"
} else if section == 3 {
title = "Albums"
}
return title
}
}
//MARK: UITableViewDelegate Methods
extension ArtistViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let height = KeyValueTableViewCell.height
return height
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let album = album(for: indexPath) else { return }
let albumVC = AlbumViewController.instantiate(withAlbum: album)
navigationController?.pushViewController(albumVC, animated: true)
}
}
//MARK: Private Methods
private extension ArtistViewController {
func setupViews() {
tableView.register(UINib.init(nibName: KeyValueTableViewCell.className, bundle: nil) , forCellReuseIdentifier: cellIdentifier)
}
func fetchData() {
APIClient.sharedInstance.getArtist(byId: depecheMode, queryParams: nil) {
result in
switch result {
case .success(let data):
guard let artist = data as? Artist else { break }
self.artist = artist
self.fetchAlbums(forArtist: artist)
case .failure(let error):
print("Failed to get artist, error: \(error)")
}
}
}
func fetchAlbums(forArtist artist: Artist) {
let params = ["offset" : "0", "limit": "50"]
APIClient.sharedInstance.getAlbums(byArtist: artist.artistId, queryParams: params) {
result in
switch result {
case .success(let data):
guard let albums = data as? [Album] else { break }
self.artist?.albums = albums
self.tableView.reloadData()
case .failure(let error):
print("Failed to get albums for artist, error: \(error)")
}
}
}
func keyValue(for indexPath: IndexPath) -> KeyValuePair? {
guard let artist = artist else { return nil }
let section = indexPath.section
let row = indexPath.row
var pair: KeyValuePair?
if section == 0 {
if row == 0 {
pair = KeyValuePair("Id", artist.artistId)
} else if row == 1 {
pair = KeyValuePair("Name", artist.name)
} else if row == 2 {
pair = KeyValuePair("Type", artist.type)
} else if row == 3 {
pair = KeyValuePair("Followers", artist.followers)
} else if row == 4 {
pair = KeyValuePair("Popularity", artist.popularity)
} else if row == 5 {
pair = KeyValuePair("External url", artist.externalUrl.spotify)
}
} else if section == 1 {
guard let genres = artist.genres, row < genres.count else { return nil }
let genre = genres[row]
pair = KeyValuePair(genre, nil)
} else if section == 2 {
guard let images = artist.images, row < images.count else { return nil }
let image: Image = images[row]
pair = KeyValuePair("Image url", image.url)
} else if section == 3 {
guard let album = album(for: indexPath) else { return nil }
pair = KeyValuePair(album.name, nil)
}
return pair
}
func album(for indexPath: IndexPath) -> Album? {
guard let albums = artist?.albums, indexPath.row < albums.count else { return nil }
let album = albums[indexPath.row]
return album
}
}
struct KeyValuePair {
let key: String?
let value: String?
init(_ key: Any?, _ value: Any?) {
if let stringKey = key as? String {
self.key = stringKey
} else if let other = key {
self.key = "\(other)"
} else {
self.key = nil
}
if let stringValue = value as? String {
self.value = stringValue
} else if let other = value {
self.value = "\(other)"
} else {
self.value = nil
}
}
}
| apache-2.0 | 581ec2b19c93e268c0accd581d2f9462 | 32.074468 | 134 | 0.573496 | 4.699924 | false | false | false | false |
BENMESSAOUD/yousign | YouSign/YouSign/Env/Environement.swift | 1 | 886 | //
// Environement.swift
// YouSign
//
// Created by Mahmoud Ben Messaoud on 22/05/2017.
// Copyright © 2017 Mahmoud Ben Messaoud. All rights reserved.
//
import Foundation
@objc public enum Target: Int {
case demo = 0
case production = 1
}
enum API_URL: String{
case demoURL = "https://apidemo.yousign.fr:8181/"
case productionURL = "https://api.yousign.fr:8181/"
}
@objc public class Environement: NSObject {
var target: Target
var credentials: Credentials
private var api_Url: API_URL
public init(_ target: Target = .demo, credential: Credentials) {
self.target = target
self.credentials = credential
switch target {
case .demo:
self.api_Url = .demoURL
case .production :
self.api_Url = .productionURL
}
}
var apiURL: API_URL {
return api_Url
}
}
| apache-2.0 | cfedbfa22563e3fafb1890343cfe3e2a | 20.585366 | 68 | 0.619209 | 3.6875 | false | false | false | false |
kasei/kineo | Sources/Kineo/QuadStore/IdentityMap.swift | 1 | 15399 | //
// IdentityMap.swift
// Kineo
//
// Created by Gregory Todd Williams on 4/11/18.
// Copyright © 2018 Gregory Todd Williams. All rights reserved.
//
import Foundation
import SPARQLSyntax
public protocol IdentityMap {
associatedtype Item: Hashable
associatedtype Result: Comparable
func id(for value: Item) -> Result?
func getOrSetID(for value: Item) throws -> Result
}
public enum PackedTermType : UInt8 {
case blank = 0x01
case iri = 0x02
case commonIRI = 0x03
case language = 0x10
case datatype = 0x11
case inlinedString = 0x12
case boolean = 0x13
case date = 0x14
case dateTime = 0x15
case string = 0x16
case integer = 0x18
case int = 0x19
case decimal = 0x1A
init?(from id: UInt64) {
let typebyte = UInt8(UInt64(id) >> 56)
self.init(rawValue: typebyte)
}
var typedEmptyValue : UInt64 {
return (UInt64(self.rawValue) << 56)
}
var idRange : Range<UInt64> {
let value = rawValue
let min = (UInt64(value) << 56)
let max = (UInt64(value+1) << 56)
return min..<max
}
}
public protocol PackedIdentityMap : IdentityMap {}
public extension PackedIdentityMap where Item == Term, Result == UInt64 {
/**
Term ID type byte:
01 0x01 0000 0001 Blank
02 0x02 0000 0010 IRI
03 0x03 0000 0011 common IRIs
16 0x10 0001 0000 Language
17 0x11 0001 0001 Datatype
18 0x12 0001 0010 inlined xsd:string
19 0x13 0001 0011 xsd:boolean
20 0x14 0001 0100 xsd:date
21 0x15 0001 0101 xsd:dateTime
22 0x16 0001 0110 xsd:string
24 0x18 0001 1000 xsd:integer
25 0x19 0001 1001 xsd:int
26 0x1A 0001 1010 xsd:decimal
Prefixes:
0000 0001 blank
0000 001 iri
0001 literal
0001 01 date (with optional time)
0001 1 numeric
**/
internal static func isIRI(id: Result) -> Bool {
guard let type = PackedTermType(from: id) else { return false }
return type == .iri
}
internal static func isBlank(id: Result) -> Bool {
guard let type = PackedTermType(from: id) else { return false }
return type == .blank
}
internal static func isLanguageLiteral(id: Result) -> Bool {
guard let type = PackedTermType(from: id) else { return false }
return type == .language
}
internal static func isDatatypeLiteral(id: Result) -> Bool {
guard let type = PackedTermType(from: id) else { return false }
return type == .datatype
}
func unpack(id: Result) -> Item? {
let byte = id >> 56
let value = id & 0x00ffffffffffffff
guard let type = PackedTermType(rawValue: UInt8(byte)) else { return nil }
switch type {
case .commonIRI:
return unpack(iri: value)
case .boolean:
return unpack(boolean: value)
case .date:
return unpack(date: value)
case .dateTime:
return unpack(dateTime: value)
case .inlinedString:
return unpack(string: value)
case .integer:
return unpack(integer: value)
case .int:
return unpack(int: value)
case .decimal:
return unpack(decimal: value)
default:
return nil
}
}
func pack(value: Item) -> Result? {
switch (value.type, value.value) {
case (.iri, let v):
return pack(iri: v)
case (.datatype(.boolean), "true"), (.datatype(.boolean), "1"):
return pack(boolean: true)
case (.datatype(.boolean), "false"), (.datatype(.boolean), "0"):
return pack(boolean: false)
case (.datatype(.dateTime), _):
return pack(dateTime: value)
case (.datatype(.date), let v):
return pack(date: v)
case (.datatype(.string), let v):
return pack(string: v)
case (.datatype(.integer), let v):
return pack(integer: v)
case (.datatype("http://www.w3.org/2001/XMLSchema#int"), let v):
return pack(int: v)
case (.datatype(.decimal), let v):
return pack(decimal: v)
default:
return nil
}
}
private func pack(string: String) -> Result? {
guard string.utf8.count <= 7 else { return nil }
var id: UInt64 = PackedTermType.inlinedString.typedEmptyValue
for (i, u) in string.utf8.enumerated() {
let shift = UInt64(8 * (6 - i))
let b: UInt64 = UInt64(u) << shift
id += b
}
return id
}
private func unpack(string value: UInt64) -> Item? {
var buffer = value.bigEndian
var string: String? = nil
withUnsafePointer(to: &buffer) { (p) in
var chars = [CChar]()
p.withMemoryRebound(to: CChar.self, capacity: 8) { (charsptr) in
for i in 1...7 {
chars.append(charsptr[i])
}
}
chars.append(0)
chars.withUnsafeBufferPointer { (q) in
if let p = q.baseAddress {
string = String(utf8String: p)
}
}
}
if let string = string {
return Term(value: string, type: .datatype(.string))
}
return nil
}
private func unpack(boolean packedBooleanValue: UInt64) -> Item? {
let value = (packedBooleanValue > 0) ? "true" : "false"
return Term(value: value, type: .datatype(.boolean))
}
private func unpack(integer value: UInt64) -> Item? {
return Term(value: "\(value)", type: .datatype(.integer))
}
private func unpack(int value: UInt64) -> Item? {
return Term(value: "\(value)", type: .datatype("http://www.w3.org/2001/XMLSchema#int"))
}
private func unpack(decimal: UInt64) -> Item? {
let scale = Int((decimal & 0x00ff000000000000) >> 48)
let value = decimal & 0x00007fffffffffff
let highByte = (decimal & 0x0000ff0000000000) >> 40
let highBit = highByte & UInt64(0x80)
guard scale >= 0 else { return nil }
var combined = "\(value)"
var string = ""
while combined.count <= scale {
// pad with leading zeros so that there is at least one digit to the left of the decimal point
combined = "0\(combined)"
}
let breakpoint = combined.count - scale
for (i, c) in combined.enumerated() {
if i == breakpoint {
if i == 0 {
string += "0."
} else {
string += "."
}
}
string += String(c)
}
if highBit > 0 {
string = "-\(string)"
}
return Term(value: string, type: .datatype(.decimal))
}
private func unpack(date value: UInt64) -> Item? {
let day = value & 0x000000000000001f
let months = (value & 0x00000000001fffe0) >> 5
let month = months % 12
let year = months / 12
let date = String(format: "%04d-%02d-%02d", year, month, day)
return Term(value: date, type: .datatype(.date))
}
private func unpack(dateTime value: UInt64) -> Item? {
// ZZZZ ZZZY YYYY YYYY YYYY MMMM DDDD Dhhh hhmm mmmm ssss ssss ssss ssss
let tzSign = (value & 0x0080000000000000) >> 55
let tz = (value & 0x007e000000000000) >> 49
let year = (value & 0x0001fff000000000) >> 36
let month = (value & 0x0000000f00000000) >> 32
let day = (value & 0x00000000f8000000) >> 27
let hours = (value & 0x0000000007c00000) >> 22
let minutes = (value & 0x00000000003f0000) >> 16
let msecs = (value & 0x000000000000ffff)
let seconds = Double(msecs) / 1_000.0
var dateTime = String(format: "%04d-%02d-%02dT%02d:%02d:%02g", year, month, day, hours, minutes, seconds)
if tz == 0 {
dateTime = "\(dateTime)Z"
} else {
let offset = tz * 15
var hours = Int(offset) / 60
let minutes = Int(offset) % 60
if tzSign == 1 {
hours *= -1
}
dateTime = dateTime + String(format: "%+03d:%02d", hours, minutes)
}
return Term(value: dateTime, type: .datatype(.dateTime))
}
private func pack(decimal stringValue: String) -> Result? {
var c = stringValue.components(separatedBy: ".")
guard c.count == 2 else { return nil }
let integralValue = c[0]
var sign : UInt64 = 0
if integralValue.hasPrefix("-") {
sign = UInt64(0x80) << 40
c[0] = String(integralValue[integralValue.index(integralValue.startIndex, offsetBy: 1)...])
}
let combined = c.joined(separator: "")
guard let value = UInt64(combined) else { return nil }
let scale = UInt8(c[1].count)
guard value <= 0x00007fffffffffff else { return nil }
let id = PackedTermType.decimal.typedEmptyValue + (UInt64(scale) << 48) + (sign | value)
return id
}
private func pack(boolean booleanValue: Bool) -> Result? {
let i : UInt64 = booleanValue ? 1 : 0
let value: UInt64 = PackedTermType.boolean.typedEmptyValue
return value + i
}
private func pack(integer stringValue: String) -> Result? {
guard let i = UInt64(stringValue) else { return nil }
guard i < 0x00ffffffffffffff else { return nil }
let value: UInt64 = PackedTermType.integer.typedEmptyValue
return value + i
}
private func pack(int stringValue: String) -> Result? {
guard let i = UInt64(stringValue) else { return nil }
guard i <= 2147483647 else { return nil }
let value: UInt64 = PackedTermType.int.typedEmptyValue
return value + i
}
private func pack(date stringValue: String) -> Result? {
let values = stringValue.components(separatedBy: "-").map { Int($0) }
guard values.count == 3 else { return nil }
if let y = values[0], let m = values[1], let d = values[2] {
guard y <= 5000 else { return nil }
let months = 12 * y + m
var value = PackedTermType.date.typedEmptyValue
value += UInt64(months << 5)
value += UInt64(d)
return value
} else {
return nil
}
}
private func pack(dateTime term: Term) -> Result? {
// ZZZZ ZZZY YYYY YYYY YYYY MMMM DDDD Dhhh hhmm mmmm ssss ssss ssss ssss
guard let date = term.dateValue else {
return nil
}
guard let tz = term.timeZone else {
return nil
}
let calendar = Calendar(identifier: .gregorian)
let utc = TimeZone(secondsFromGMT: 0)!
let components = calendar.dateComponents(in: utc, from: date)
guard let _year = components.year,
let _month = components.month,
let _day = components.day,
let _hours = components.hour,
let _minutes = components.minute,
let _seconds = components.second else { return nil }
let year : UInt64 = UInt64(_year)
let month : UInt64 = UInt64(_month)
let day : UInt64 = UInt64(_day)
let hours : UInt64 = UInt64(_hours)
let minutes : UInt64 = UInt64(_minutes)
let seconds : UInt64 = UInt64(_seconds)
let msecs : UInt64 = seconds * 1_000
let offsetSeconds = tz.secondsFromGMT()
let tzSign : UInt64 = (offsetSeconds < 0) ? 1 : 0
let offsetMinutes : UInt64 = UInt64(abs(offsetSeconds) / 60)
let offset : UInt64 = offsetMinutes / 15
// guard against overflow values
guard offset >= 0 && offset < 0x7f else { return nil }
guard year >= 0 && year < 0x1fff else { return nil }
guard month >= 0 && month < 0xf else { return nil }
guard day >= 0 && day < 0x1f else { return nil }
guard hours >= 0 && hours < 0x1f else { return nil }
guard minutes >= 0 && minutes < 0x3f else { return nil }
guard seconds >= 0 && seconds < 0xffff else { return nil }
var value = PackedTermType.dateTime.typedEmptyValue
value |= (tzSign << 55)
value |= (offset << 49)
value |= (year << 36)
value |= (month << 32)
value |= (day << 27)
value |= (hours << 22)
value |= (minutes << 16)
value |= (msecs)
return value
}
private func unpack(iri value: UInt64) -> Item? {
switch value {
case 1:
return Term(value: Namespace.rdf.type, type: .iri)
case 2:
return Term(value: Namespace.rdf.List, type: .iri)
case 3:
return Term(value: Namespace.rdf.Resource, type: .iri)
case 4:
return Term(value: Namespace.rdf.first, type: .iri)
case 5:
return Term(value: Namespace.rdf.rest, type: .iri)
case 6:
return Term(value: "http://www.w3.org/2000/01/rdf-schema#comment", type: .iri)
case 7:
return Term(value: "http://www.w3.org/2000/01/rdf-schema#label", type: .iri)
case 8:
return Term(value: "http://www.w3.org/2000/01/rdf-schema#seeAlso", type: .iri)
case 9:
return Term(value: "http://www.w3.org/2000/01/rdf-schema#isDefinedBy", type: .iri)
case 256..<512:
return Term(value: "http://www.w3.org/1999/02/22-rdf-syntax-ns#_\(value-256)", type: .iri)
default:
return nil
}
}
private func pack(iri: String) -> Result? {
let mask = PackedTermType.commonIRI.typedEmptyValue
switch iri {
case Namespace.rdf.type:
return mask + 1
case Namespace.rdf.List:
return mask + 2
case Namespace.rdf.Resource:
return mask + 3
case Namespace.rdf.first:
return mask + 4
case Namespace.rdf.rest:
return mask + 5
case "http://www.w3.org/2000/01/rdf-schema#comment":
return mask + 6
case "http://www.w3.org/2000/01/rdf-schema#label":
return mask + 7
case "http://www.w3.org/2000/01/rdf-schema#seeAlso":
return mask + 8
case "http://www.w3.org/2000/01/rdf-schema#isDefinedBy":
return mask + 9
case _ where iri.hasPrefix("http://www.w3.org/1999/02/22-rdf-syntax-ns#_"):
let c = iri.components(separatedBy: "_")
guard c.count == 2 else { return nil }
guard let value = UInt64(c[1]) else { return nil }
if value >= 0 && value < 256 {
return mask + 0x100 + value
}
default:
break
}
return nil
}
}
| mit | 17b83d17420e6bb6d2cddca7de1ac48c | 34.809302 | 113 | 0.538641 | 4.00364 | false | false | false | false |
snowpunch/AppLove | App Love/UI/ViewControllers/Extensions/ReviewListVC/ReviewListVC+ActionSheets.swift | 1 | 5581 | //
// ReviewListVC+ActionSheets.swift
// App Love
//
// Created by Woodie Dovich on 2016-08-18.
// Copyright © 2016 Snowpunch. All rights reserved.
//
import UIKit
// action sheets
extension ReviewListVC {
func displaySortActionSheet(sender: UIBarButtonItem) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let ratingSortAction = UIAlertAction(title: "Sort by Rating", style: .Default) { action -> Void in
self.allReviews.sortInPlace({ $0.rating > $1.rating })
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
self.tableView.setContentOffset(CGPointZero, animated:true)
})
}
let versionSortAction = UIAlertAction(title: "Sort by Version", style: .Default) { action -> Void in
self.allReviews.sortInPlace({ $0.version > $1.version })
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
self.tableView.setContentOffset(CGPointZero, animated:true)
})
}
let territorySortAction = UIAlertAction(title: "Sort by Territory", style: .Default) { action -> Void in
self.allReviews.sortInPlace({ $0.territory < $1.territory })
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
self.tableView.setContentOffset(CGPointZero, animated:true)
})
}
let actionCancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.addAction(ratingSortAction)
alertController.addAction(versionSortAction)
alertController.addAction(territorySortAction)
alertController.addAction(actionCancel)
Theme.alertController(alertController)
if let popoverController = alertController.popoverPresentationController {
popoverController.barButtonItem = sender
}
self.presentViewController(alertController, animated: true, completion: nil)
}
func removeEmptyTerritories(button: UIBarButtonItem){
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let loadAllAction = UIAlertAction(title: "Load All Territories", style: .Default) { action -> Void in
TerritoryMgr.sharedInst.selectAllTerritories()
self.refresh("")
}
let loadDefaultAction = UIAlertAction(title: "Load Default Territories", style: .Default) { action -> Void in
let defaultTerritories = TerritoryMgr.sharedInst.getDefaultCountryCodes()
TerritoryMgr.sharedInst.setSelectedTerritories(defaultTerritories)
self.refresh("")
}
let removeEmptyAction = UIAlertAction(title: "Remove Empty Territories", style: .Destructive) { action -> Void in
let nonEmptyTeritories = ReviewLoadManager.sharedInst.getNonEmptyTerritories()
TerritoryMgr.sharedInst.setSelectedTerritories(nonEmptyTeritories)
self.refresh("")
}
let actionCancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.addAction(loadAllAction)
alertController.addAction(loadDefaultAction)
alertController.addAction(removeEmptyAction)
alertController.addAction(actionCancel)
Theme.alertController(alertController)
if let popoverController = alertController.popoverPresentationController {
popoverController.barButtonItem = button
}
self.presentViewController(alertController, animated: true, completion: nil)
}
func displayReviewOptions(model:ReviewModel, button:UIButton) {
guard let title = model.title else { return }
let alertController = UIAlertController(title:nil, message: title, preferredStyle: .ActionSheet)
let emailAction = UIAlertAction(title: "Email", style: .Default) { action -> Void in
self.displayReviewEmail(model)
}
let translateAction = UIAlertAction(title: "Translate", style: .Default) { action -> Void in
self.displayGoogleTranslationViaSafari(model)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.addAction(emailAction)
alertController.addAction(translateAction)
alertController.addAction(cancelAction)
if let popOverPresentationController : UIPopoverPresentationController = alertController.popoverPresentationController {
popOverPresentationController.sourceView = button
popOverPresentationController.sourceRect = button.bounds
popOverPresentationController.permittedArrowDirections = [.Right]
}
self.presentViewController(alertController, animated: true, completion: nil)
}
func displayGoogleTranslationViaSafari(model:ReviewModel) {
guard let title = model.title else { return }
guard let reviewText = model.comment else { return }
let rawUrlStr = "http://translate.google.ca?text="+title + "\n" + reviewText
if let urlEncoded = rawUrlStr.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()),
let url = NSURL(string: urlEncoded) {
UIApplication.sharedApplication().openURL(url)
}
}
} | mit | d3c10fa9b4d34f3c8ec22761632aa986 | 47.112069 | 135 | 0.670251 | 5.181058 | false | false | false | false |
dokun1/jordan-meme-ios | JordanHeadMeme/JordanHeadMeme/ViewController.swift | 1 | 8413 | //
// ViewController.swift
// JordanHeadMeme
//
// Created by David Okun on 12/18/15.
// Copyright © 2015 David Okun, LLC. All rights reserved.
//
import UIKit
import SVProgressHUD
import Crashlytics
import TSMessages
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, ImageEditingViewControllerDelegate, UIGestureRecognizerDelegate, TSMessageViewProtocol {
@IBOutlet weak var demoHead: UIImageView!
var demoHeadFacingRight = true
var demoHeadUnmodified = true
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let numberOfScreenAppearances = NSUserDefaults.standardUserDefaults().integerForKey("screenAppearances") + 1
NSUserDefaults.standardUserDefaults().setObject(numberOfScreenAppearances, forKey: "screenAppearances")
NSUserDefaults.standardUserDefaults().synchronize()
if numberOfScreenAppearances == 10 {
shamelesslyBegUserForAppStoreReview()
}
TSMessage.setDelegate(self)
}
func shamelesslyBegUserForAppStoreReview() {
let reviewController = UIAlertController.init(title: "App Store Review", message: "I hope you're enjoying using the app! Would you mind leaving a review on the App Store about it?", preferredStyle: .Alert)
let yesAction = UIAlertAction.init(title: "Sure", style: .Cancel) { (UIAlertAction) -> Void in
Analytics.logCustomEventWithName("App Review Alert View", customAttributes: ["Accepted":true])
UIApplication.sharedApplication().openURL(NSURL.init(string: "itms-apps://itunes.apple.com/app/id1084796562")!)
}
let noAction = UIAlertAction.init(title: "Beat it, nerd", style: .Destructive) { (UIAlertAction) -> Void in
Analytics.logCustomEventWithName("App Review Alert", customAttributes: ["Accepted":false])
}
reviewController.addAction(yesAction)
reviewController.addAction(noAction)
presentViewController(reviewController, animated: true, completion: nil)
}
// MARK: IBActions
@IBAction func takePhotoTapped() {
// TODO: Track the user action that is important for you.
Analytics.logCustomEventWithName("Photo Capture Began", customAttributes: ["Method":"Take Photo"])
let picker = UIImagePickerController.init()
picker.sourceType = .Camera
presentPicker(picker)
}
@IBAction func takeSelfieTapped() {
Analytics.logCustomEventWithName("Photo Capture Began", customAttributes: ["Method":"Take Selfie"])
let picker = UIImagePickerController.init()
picker.sourceType = .Camera
picker.cameraDevice = .Front
presentPicker(picker)
}
@IBAction func choosePhotoTapped() {
Analytics.logCustomEventWithName("Photo Capture Began", customAttributes: ["Method":"Choose Photo"])
let picker = UIImagePickerController.init()
picker.sourceType = .PhotoLibrary
presentPicker(picker)
}
func presentPicker(picker: UIImagePickerController) {
picker.allowsEditing = false
picker.delegate = self
presentViewController(picker, animated: true, completion: nil)
}
// MARK: GestureRecognizer methods
@IBAction func rotationGestureActivated(recognizer: UIRotationGestureRecognizer) {
logUserModifiedDemoHead()
demoHeadUnmodified = false
if let view = recognizer.view {
view.transform = CGAffineTransformRotate(view.transform, recognizer.rotation)
recognizer.rotation = 0
}
}
@IBAction func doubleTapGestureActivated(recognizer: UITapGestureRecognizer) {
logUserModifiedDemoHead()
demoHeadUnmodified = false
if demoHeadFacingRight == true {
demoHead.image = UIImage.init(named: "jordanHeadInverted.png")
} else {
demoHead.image = UIImage.init(named: "jordanHead.png")
}
demoHeadFacingRight = !demoHeadFacingRight
}
@IBAction func pinchGestureActivated(recognizer: UIPinchGestureRecognizer) {
logUserModifiedDemoHead()
demoHeadUnmodified = false
if let view = recognizer.view {
view.transform = CGAffineTransformScale(view.transform, recognizer.scale, recognizer.scale)
recognizer.scale = 1
}
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
@IBAction func homeButtonTapped() {
if demoHeadUnmodified == true {
showInstructions()
} else {
let hasShownInstructions = NSUserDefaults.standardUserDefaults().boolForKey("firstTimeShowingInstructions")
if hasShownInstructions == false {
showInstructions()
NSUserDefaults.standardUserDefaults().setObject(true, forKey: "firstTimeShowingInstructions")
NSUserDefaults.standardUserDefaults().synchronize()
}
self.demoHead.userInteractionEnabled = false
demoHead.image = UIImage.init(named: "jordanHead.png")
UIView.animateWithDuration(0.4, delay: 0.0, options: .CurveEaseOut, animations: { () -> Void in
self.demoHead.transform = CGAffineTransformMakeRotation(1)
self.demoHead.transform = CGAffineTransformMakeScale(1, 1)
}, completion: { (Bool) -> Void in
self.self.demoHeadUnmodified = true
self.self.demoHead.userInteractionEnabled = true
})
}
}
func logUserModifiedDemoHead() {
let userHasModifiedDemoHead = NSUserDefaults.standardUserDefaults().boolForKey("hasModifiedDemoHead")
if userHasModifiedDemoHead == false {
Analytics.logCustomEventWithName("User Tried Demo", customAttributes: nil)
NSUserDefaults.standardUserDefaults().setObject(true, forKey: "hasModifiedDemoHead")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
func showInstructions() {
Analytics.logCustomEventWithName("Instructions Shown", customAttributes: nil)
TSMessage.addCustomDesignFromFileWithName("JordanHeadMemeMessageCustomization.json")
TSMessage.showNotificationInViewController(self, title: "Play with the head!", subtitle: "Try pinch-zooming, rotating, or double tapping the head on the screen to change its appearance.", type: .Message, duration: 5.0, canBeDismissedByUser: true)
}
// MARK: UIImagePickerControllerDelegate methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
Analytics.logCustomEventWithName("Photo Capture Completed", customAttributes: ["Got Photo":info[UIImagePickerControllerOriginalImage] != nil])
picker.dismissViewControllerAnimated(true) { () -> Void in
self.performSegueWithIdentifier("editImageSegue", sender: info[UIImagePickerControllerOriginalImage] as! UIImage)
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
Analytics.logCustomEventWithName("Photo Capture Cancelled", customAttributes:nil)
picker.dismissViewControllerAnimated(true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "editImageSegue") {
let nextController:ImageEditingViewController = segue.destinationViewController as! ImageEditingViewController
nextController.uneditedImage = sender as! UIImage
nextController.delegate = self
}
}
// MARK: TSMessageDelegate Methods
func customizeMessageView(messageView: TSMessageView!) {
messageView.alpha = 1
}
// MARK: ImageEditingViewControllerDelegate methods
func controllerDidFinishWithImage(controller: ImageEditingViewController, image: UIImage) {
controller.dismissViewControllerAnimated(true) { () -> Void in
}
}
func controllerDidCancel(controller: ImageEditingViewController) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | 06919ee6d2da69fd331d64bd3436408b | 43.983957 | 254 | 0.692582 | 5.548813 | false | false | false | false |
SmallElephant/FEAlgorithm-Swift | 9-Array/9-Array/SearchSum.swift | 1 | 2713 | //
// SearchSum.swift
// 9-Array
//
// Created by FlyElephant on 17/1/3.
// Copyright © 2017年 FlyElephant. All rights reserved.
//
import Foundation
class SearchSum {
//和为S的两个数字
// 题目:输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,输出任意一对即可.
func findNumber(arr:[Int],sum:Int) -> (Int,Int)? {
if arr.count == 0 {
return nil
}
for i in 0..<arr.count {
let num:Int = arr[i]
for j in i..<arr.count {
if arr[j] == (sum - num) {
return (num,arr[j])
}
}
}
return nil
}
func findNumberWithSum(arr:[Int],sum:Int) -> (Int,Int)? {
if arr.count == 0 {
return nil
}
var low:Int = 0
var high:Int = arr.count - 1
while low < high {
let tempSum:Int = arr[low] + arr[high]
if tempSum > sum {
high = high - 1
} else if tempSum < sum {
low = low + 1
} else {
return (arr[low],arr[high])
}
}
return nil
}
// 和为S的连续正数序列
// 题目:输入一个正数S,打印出所有和为S的连续正数序列(至少有两个数)。例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以结果打印出3个连续序列1~5,4~6和7~8.
func findContinuousSequence(sum:Int) -> [[Int]]? {
if sum <= 0 {
return nil
}
var small:Int = 1
var big:Int = 2
let mid:Int = (1 + sum)/2
var allSequence:[[Int]] = []
var currentSum:Int = small + big // 至少两个数字,small最多到一半位置
while small < mid {
if currentSum == sum {// 相等保存
continuousSequence(small: small, big: big, data: &allSequence)
}
while currentSum > sum && small < mid { // 大于sum,增加small,先减后加
currentSum -= small
small += 1
if currentSum == sum {
continuousSequence(small: small, big: big, data: &allSequence)
}
}
big += 1// 小于sum,增加big
currentSum += big
}
return allSequence
}
func continuousSequence(small:Int,big:Int,data:inout [[Int]]) {
var temp:[Int] = []
for i in small...big {
temp.append(i)
}
data.append(temp)
}
}
| mit | f35f2ef8fabc73ae235571855a937d47 | 25.764045 | 98 | 0.457179 | 3.462209 | false | false | false | false |
orta/Moya | Demo/DemoTests/MoyaProviderSpec.swift | 1 | 21452 | import Quick
import Moya
import Nimble
import ReactiveCocoa
import RxSwift
class MoyaProviderSpec: QuickSpec {
override func spec() {
describe("valid endpoints") {
describe("with stubbed responses") {
describe("a provider", {
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding)))
}
it("returns stubbed data for user profile request") {
var message: String?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding)))
}
it("returns equivalent Endpoint instances for the same target") {
let target: GitHub = .Zen
let endpoint1 = provider.endpoint(target)
let endpoint2 = provider.endpoint(target)
expect(endpoint1).to(equal(endpoint2))
}
it("returns a cancellable object when a request is made") {
let target: GitHub = .UserProfile("ashfurrow")
let cancellable: Cancellable = provider.request(target) { (_, _, _, _) in }
expect(cancellable).toNot(beNil())
}
})
it("notifies at the beginning of network requests") {
var called = false
var provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, networkActivityClosure: { (change) -> () in
if change == .Began {
called = true
}
})
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in }
expect(called) == true
}
it("notifies at the end of network requests") {
var called = false
var provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, networkActivityClosure: { (change) -> () in
if change == .Ended {
called = true
}
})
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in }
expect(called) == true
}
describe("a provider with lazy data", { () -> () in
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>(endpointClosure: lazyEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding)))
}
})
it("delays execution when appropriate") {
let provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.DelayedStubbingBehaviour(2))
let startDate = NSDate()
var endDate: NSDate?
let target: GitHub = .Zen
waitUntil(timeout: 3) { done in
provider.request(target) { (data, statusCode, response, error) in
endDate = NSDate()
done()
}
return
}
expect{
return endDate?.timeIntervalSinceDate(startDate)
}.to( beGreaterThanOrEqualTo(NSTimeInterval(2)) )
}
describe("a provider with a custom endpoint resolver") { () -> () in
var provider: MoyaProvider<GitHub>!
var executed = false
let newSampleResponse = "New Sample Response"
beforeEach {
executed = false
let endpointResolution = { (endpoint: Endpoint<GitHub>) -> (NSURLRequest) in
executed = true
return endpoint.urlRequest
}
provider = MoyaProvider<GitHub>(endpointResolver: endpointResolution, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("executes the endpoint resolver") {
let target: GitHub = .Zen
provider.request(target, completion: { (data, statusCode, response, error) in })
let sampleData = target.sampleData as NSData
expect(executed).to(beTruthy())
}
}
describe("a reactive provider", { () -> () in
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns a MoyaResponse object") {
var called = false
provider.request(.Zen).subscribeNext { (object) -> Void in
if let response = object as? MoyaResponse {
called = true
}
}
expect(called).to(beTruthy())
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target).subscribeNext { (object) -> Void in
if let response = object as? MoyaResponse {
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).toNot(beNil())
}
it("returns correct data for user profile request") {
var receivedResponse: NSDictionary?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target).subscribeNext { (object) -> Void in
if let response = object as? MoyaResponse {
receivedResponse = try! NSJSONSerialization.JSONObjectWithData(response.data, options: []) as? NSDictionary
}
}
let sampleData = target.sampleData as NSData
let sampleResponse = try! NSJSONSerialization.JSONObjectWithData(sampleData, options: []) as! NSDictionary
expect(receivedResponse).toNot(beNil())
}
it("returns identical signals for inflight requests") {
let target: GitHub = .Zen
var response: MoyaResponse!
// The synchronous nature of stubbed responses makes this kind of tricky. We use the
// subscribeNext closure to get the provider into a state where the signal has been
// added to the inflightRequests dictionary. Then we ask for an identical request,
// which should return the same signal. We can't *test* those signals equivalency
// due to the use of RACSignal.defer, but we can check if the number of inflight
// requests went up or not.
let outerSignal = provider.request(target)
outerSignal.subscribeNext { (object) -> Void in
response = object as? MoyaResponse
expect(provider.inflightRequests.count).to(equal(1))
// Create a new signal and force subscription, so that the inflightRequests dictionary is accessed.
let innerSignal = provider.request(target)
innerSignal.subscribeNext { (object) -> Void in
// nop
}
expect(provider.inflightRequests.count).to(equal(1))
}
expect(provider.inflightRequests.count).to(equal(0))
}
})
describe("a RxSwift provider", { () -> () in
var provider: RxMoyaProvider<GitHub>!
beforeEach {
provider = RxMoyaProvider(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns a MoyaResponse object") {
var called = false
provider.request(.Zen).subscribeNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target).subscribeNext { (response) -> Void in
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
let sampleString = NSString(data: (target.sampleData as NSData), encoding: NSUTF8StringEncoding)
expect(message).to(equal(sampleString))
}
it("returns correct data for user profile request") {
var receivedResponse: NSDictionary?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target).subscribeNext { (response) -> Void in
receivedResponse = try! NSJSONSerialization.JSONObjectWithData(response.data, options: []) as? NSDictionary
}
let sampleData = target.sampleData as NSData
let sampleResponse: NSDictionary = try! NSJSONSerialization.JSONObjectWithData(sampleData, options: []) as! NSDictionary
expect(receivedResponse).toNot(beNil())
}
it("returns identical observables for inflight requests") {
let target: GitHub = .Zen
var response: MoyaResponse!
let parallelCount = 10
let observables = Array(0..<parallelCount).map { _ in provider.request(target) }
var completions = Array(0..<parallelCount).map { _ in false }
let queue = dispatch_queue_create("testing", DISPATCH_QUEUE_CONCURRENT)
dispatch_apply(observables.count, queue, { idx in
let i = idx
observables[i].subscribeNext { _ -> Void in
if i == 5 { // We only need to check it once.
expect(provider.inflightRequests.count).to(equal(1))
}
completions[i] = true
}
})
func allTrue(cs: [Bool]) -> Bool {
return cs.reduce(true) { (a,b) -> Bool in a && b }
}
expect(allTrue(completions)).toEventually(beTrue())
expect(provider.inflightRequests.count).to(equal(0))
}
})
describe("a subsclassed reactive provider that tracks cancellation with delayed stubs") {
struct TestCancellable: Cancellable {
static var cancelled = false
func cancel() {
TestCancellable.cancelled = true
}
}
class TestProvider<T: MoyaTarget>: ReactiveCocoaMoyaProvider<T> {
override init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEnpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil) {
super.init(endpointClosure: endpointClosure, endpointResolver: endpointResolver, stubBehavior: stubBehavior, networkActivityClosure: networkActivityClosure)
}
override func request(token: T, completion: MoyaCompletion) -> Cancellable {
return TestCancellable()
}
}
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
TestCancellable.cancelled = false
provider = TestProvider<GitHub>(stubBehavior: MoyaProvider.DelayedStubbingBehaviour(1))
}
it("cancels network request when subscription is cancelled") {
var called = false
let target: GitHub = .Zen
let disposable = provider.request(target).subscribeCompleted { () -> Void in
// Should never be executed
fail()
}
disposable.dispose()
expect(TestCancellable.cancelled).to( beTrue() )
}
}
}
describe("with stubbed errors") {
describe("a provider") { () -> () in
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var errored = false
let target: GitHub = .Zen
provider.request(target) { (object, statusCode, response, error) in
if error != nil {
errored = true
}
}
let _ = target.sampleData
expect(errored).toEventually(beTruthy())
}
it("returns stubbed data for user profile request") {
var errored = false
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (object, statusCode, response, error) in
if error != nil {
errored = true
}
}
let _ = target.sampleData
expect{errored}.toEventually(beTruthy(), timeout: 1, pollInterval: 0.1)
}
it("returns stubbed error data when present") {
var errorMessage = ""
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (object, statusCode, response, error) in
if let object = object {
errorMessage = NSString(data: object, encoding: NSUTF8StringEncoding) as! String
}
}
expect{errorMessage}.toEventually(equal("Houston, we have a problem"), timeout: 1, pollInterval: 0.1)
}
}
describe("a reactive provider", { () -> () in
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var errored = false
let target: GitHub = .Zen
provider.request(target).subscribeError { (error) -> Void in
errored = true
}
expect(errored).to(beTruthy())
}
it("returns correct data for user profile request") {
var errored = false
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target).subscribeError { (error) -> Void in
errored = true
}
expect(errored).to(beTruthy())
}
})
describe("a failing reactive provider") {
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns the HTTP status code as the error code") {
var code: Int?
provider.request(.Zen).subscribeError { (error) -> Void in
code = error.code
}
expect(code).toNot(beNil())
expect(code).to(equal(401))
}
}
}
}
}
}
| mit | 0949e94c53308e9e0a95bddc4083e0a6 | 47.865604 | 327 | 0.435997 | 7.321502 | false | false | false | false |
belatrix/iOSAllStarsRemake | AllStars/AllStars/iPhone/Classes/Profile/ProfileViewController.swift | 1 | 14692 | //
// ProfileViewController.swift
// AllStars
//
// Created by Kenyi Rodriguez Vergara on 5/05/16.
// Copyright © 2016 Belatrix SF. All rights reserved.
//
import UIKit
import CoreSpotlight
import MobileCoreServices
class ProfileViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var viewHeader : UIView!
@IBOutlet weak var viewBody : UIView!
@IBOutlet weak var imgProfile : UIImageView! {
didSet{
if isViewLoaded() {
print("DidSet imgProfile")
}
}
}
@IBOutlet weak var btnSkills : UIButton!
@IBOutlet weak var lblNameUser : UILabel!
@IBOutlet weak var lblMail : UILabel!
@IBOutlet weak var lblSkype : UILabel!
@IBOutlet weak var lblLocation : UILabel!
@IBOutlet weak var scrollContent : UIScrollView!
@IBOutlet var scoreViews : [UIView]!
@IBOutlet weak var lblMothScore : UILabel!
@IBOutlet weak var lblScore : UILabel!
@IBOutlet weak var lblLevel : UILabel!
@IBOutlet weak var clvCategories : UICollectionView!
@IBOutlet weak var viewLoading : UIView!
@IBOutlet weak var lblErrorMessage : UILabel!
@IBOutlet weak var actCategories : UIActivityIndicatorView!
@IBOutlet weak var constraintHeightContent : NSLayoutConstraint!
@IBOutlet weak var btnAction : UIButton?
@IBOutlet weak var btnBack : UIButton!
@IBOutlet weak var viewUserPhoto : UIView!
var objUser : User?
var backEnable : Bool?
var arrayCategories = NSMutableArray()
// MARK: - Initialization
override func viewDidLoad() {
super.viewDidLoad()
setViews()
if self.objUser == nil {
self.objUser = LogInBC.getCurrenteUserSession()
}
self.btnSkills.setTitle("Skills", forState: .Normal)
if (ProfileBC.validateUser(self.objUser, isEqualToUser: LogInBC.getCurrenteUserSession())) {
self.btnAction?.setTitle("Edit", forState: .Normal)
registerUserDevice()
} else {
self.btnAction?.setTitle("Recommend", forState: .Normal)
}
if backEnable != nil {
self.btnBack.hidden = false
} else {
self.btnBack.hidden = true
}
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ProfileViewController.tapProfileImage))
self.imgProfile.userInteractionEnabled = true
self.imgProfile.addGestureRecognizer(tapGesture)
}
override func viewWillAppear(animated: Bool) {
if self.objUser != nil {
self.updateUserInfo()
}
super.viewWillAppear(animated)
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
self.navigationController?.setNavigationBarHidden(true, animated: true)
if let nav = self.navigationController where nav.viewControllers.count > 1 {
self.btnBack.hidden = false
} else {
self.btnBack.hidden = true
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if let rootVC = self.navigationController?.viewControllers.first where
rootVC == self.tabBarController?.moreNavigationController.viewControllers.first {
self.navigationController?.setNavigationBarHidden(false, animated: false)
}
}
// MARK: - Style
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
// MARK: - UI
func setViews() {
self.scrollContent.addSubview(self.refreshControl)
OSPCrop.makeRoundView(self.imgProfile)
self.view.backgroundColor = UIColor.colorPrimary()
for view in self.scoreViews{
view.layer.borderWidth = 1
view.layer.borderColor = UIColor.score().CGColor
}
viewHeader.backgroundColor = UIColor.colorPrimary()
}
lazy var refreshControl : UIRefreshControl = {
let _refreshControl = UIRefreshControl()
_refreshControl.backgroundColor = .clearColor()
_refreshControl.tintColor = .whiteColor()
_refreshControl.addTarget(self, action: #selector(ProfileViewController.updateUserInfo), forControlEvents: .ValueChanged)
return _refreshControl
}()
// MARK: - IBActions
@IBAction func btnActionProfileTUI(sender: UIButton) {
if (ProfileBC.validateUser(self.objUser, isEqualToUser: LogInBC.getCurrenteUserSession())) {
self.performSegueWithIdentifier("EditProfileViewController", sender: objUser)
} else {
self.performSegueWithIdentifier("RecommendViewController", sender: objUser)
}
}
@IBAction func clickBtnBack(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
}
@IBAction func btnLogoutTUI(sender: UIButton) {
SessionUD.sharedInstance.clearSession()
let storyBoard : UIStoryboard = UIStoryboard(name: "LogIn", bundle:nil)
let logInViewController = storyBoard.instantiateViewControllerWithIdentifier("LogInViewController") as! LogInViewController
self.presentViewController(logInViewController, animated: true, completion: nil)
}
func tapProfileImage() {
var newFrame = self.viewHeader.frame
newFrame.size.height = 64.0
self.view.backgroundColor = UIColor.whiteColor()
UIView.animateWithDuration(0.5, delay: 0.0,
options: [], animations: {
self.viewUserPhoto.transform = CGAffineTransformMakeScale(3.2, 3.2)
self.viewUserPhoto.center = self.view.center
self.viewHeader.frame = newFrame
self.viewBody.alpha = 0.0
}) { (success) in
newFrame.size.height = 114.0
self.viewHeader.frame = newFrame
self.view.backgroundColor = UIColor.colorPrimary()
self.viewUserPhoto.transform = CGAffineTransformMakeScale(1.0, 1.0)
self.viewUserPhoto.center = CGPointMake(self.view.center.x, self.viewHeader.frame.maxY)
self.imgProfile.transform = CGAffineTransformMakeScale(1.0, 1.0)
self.imgProfile.center = CGPointMake(self.viewUserPhoto.frame.size.width/2, self.viewUserPhoto.frame.size.height/2)
self.viewBody.alpha = 1.0
}
self.performSelector(#selector(showUserImageViewController), withObject: nil, afterDelay: 0.5)
}
// MARK: - UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.arrayCategories.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cellIdentifier = "StarSubCategoriesCollectionViewCell"
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! StarSubCategoriesCollectionViewCell
cell.objSubCategory = self.arrayCategories[indexPath.row] as! StarSubCategoryBE
cell.updateData()
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("StarsCategoriesUserViewController", sender: self.arrayCategories[indexPath.row])
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
return CGSizeMake(UIScreen.mainScreen().bounds.size.width, 36)
}
// MARK: - WebServices
func listSubCategories() -> Void {
self.actCategories.startAnimating()
ProfileBC.listStarSubCategoriesToUser(self.objUser!) { (arrayCategories) in
self.actCategories.stopAnimating()
self.arrayCategories = arrayCategories!
self.lblErrorMessage.text = "Categories no availables"
self.viewLoading.alpha = CGFloat(!Bool(self.arrayCategories.count))
let height = Int(self.scrollContent.bounds.size.height) - 113
let newHeight = Int(self.clvCategories.frame.origin.y) + self.arrayCategories.count * 36
self.constraintHeightContent.constant = newHeight > height ? CGFloat(newHeight) : CGFloat(height)
self.clvCategories.reloadData()
}
}
// MARK: - Configuration
func updateDataUser() -> Void {
self.lblNameUser.text = "\(self.objUser!.user_first_name!) \(self.objUser!.user_last_name!)"
if let mail = self.objUser!.user_email {
self.lblMail.text = mail
}
if let skype = self.objUser!.user_skype_id {
self.lblSkype.text = "Skype: \(skype)"
}
if let location = self.objUser!.user_location_name {
self.lblLocation.text = "Location: \(location)"
}
if let monthScore = self.objUser!.user_current_month_score {
self.lblMothScore.text = "\(monthScore)"
}
if let score = self.objUser!.user_total_score {
self.lblScore.text = "\(score)"
}
if let level = self.objUser!.user_level {
self.lblLevel.text = "\(level)"
}
if let url_photo = self.objUser?.user_avatar{
if (url_photo != "") {
OSPImageDownloaded.descargarImagenEnURL(url_photo, paraImageView: self.imgProfile, conPlaceHolder: self.imgProfile.image)
} else {
self.imgProfile!.image = UIImage(named: "ic_user.png")
}
} else {
self.imgProfile!.image = UIImage(named: "ic_user.png")
}
}
func updateUserInfo() -> Void {
self.updateDataUser()
ProfileBC.getInfoToUser(self.objUser!) { (user) in
self.refreshControl.endRefreshing()
if user != nil {
self.objUser = user!
self.updateDataUser()
}
}
self.listSubCategories()
}
func registerUserDevice() -> Void {
let userDev = UserDevice()
userDev.user_id = self.objUser!.user_pk!
userDev.user_ios_id = SessionUD.sharedInstance.getUserPushToken()
LogInBC.registerUserDevice(userDev) { (userDevice) in
if userDevice != nil {
print(userDevice!.user_ios_id!)
}
}
}
func registerUserForSpotlight() {
guard let user = self.objUser
else { return }
// It's recommended that you use reverse DNS notation for the required activity type property.
let activity = NSUserActivity(activityType: "com.belatrix.belatrixconnect")
activity.userInfo = ["userId" : user.user_pk!] as [NSObject : AnyObject]
// Set properties that describe the activity and that can be used in search.
activity.keywords = NSSet(objects: (user.user_first_name)!, (user.user_last_name)!, (user.user_email)!) as! Set<String>
let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeData as String)
attributeSet.title = (user.user_first_name)! + " " + (user.user_last_name)!
attributeSet.contentDescription = "Belatrix connect contact"
attributeSet.thumbnailData = UIImageJPEGRepresentation(self.imgProfile.image!, 0.9)
if let email = user.user_email {
attributeSet.emailAddresses = [email]
}
activity.contentAttributeSet = attributeSet;
// Add the item to the private on-device index.
activity.eligibleForSearch = true;
self.userActivity = activity;
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "StarsCategoriesUserViewController" {
let controller = segue.destinationViewController as! StarsCategoriesUserViewController
controller.objStarSubCategory = sender as! StarSubCategoryBE
controller.objUser = self.objUser!
} else if segue.identifier == "RecommendViewController" {
let controller = segue.destinationViewController as! RecommendViewController
controller.objUser = self.objUser
} else if segue.identifier == "EditProfileViewController" {
let controller = segue.destinationViewController as! EditProfileViewController
controller.objUser = self.objUser
controller.isNewUser = false
} else if segue.identifier == "UserSkillsViewController" {
let controller = segue.destinationViewController as! UserSkillsViewController
controller.objUser = self.objUser
}
}
func showUserImageViewController() {
let storyboard = self.storyboard
let userImageVC = storyboard?.instantiateViewControllerWithIdentifier("UserProfileImageViewController") as! UserProfileImageViewController
userImageVC.userImage = self.imgProfile.image
userImageVC.modalPresentationStyle = .PageSheet
self.presentViewController(userImageVC, animated: false, completion: nil)
}
} | mit | 1cae73aac8d16c90b384d12641e4c693 | 37.161039 | 168 | 0.607787 | 5.433062 | false | false | false | false |
pauljohanneskraft/Algorithms-and-Data-structures | AlgorithmsDataStructures/Classes/Graphs/GraphColoring.swift | 1 | 1594 | //
// Graph_Coloring.swift
// Algorithms&DataStructures
//
// Created by Paul Kraft on 07.04.17.
// Copyright © 2017 pauljohanneskraft. All rights reserved.
//
/*
extension Graph {
var complete: Bool {
let vertexCount = vertices.count
for v in vertices {
guard self[v].count == vertexCount else { return false }
}
return true
}
var chromaticNonAdjacentVertices: (Int, Int)? {
let vertices = self.vertices
var firstPair: (Int, Int)? = nil
func getNeighborHoodCount(of pair: (Int, Int)) -> Int {
let startNeighbors = Set(self[pair.0].map { $0.end })
let endNeighbors = Set(self[pair.1].map { $0.end })
return startNeighbors.intersection(endNeighbors).count
}
for start in vertices {
for end in vertices {
guard self[start, end] == nil else { continue }
guard let fp = firstPair else { firstPair = (start, end); continue }
guard getNeighborHoodCount(of: (start, end)) >= getNeighborHoodCount(of: fp) else { continue }
}
}
}
var chromaticNumber: Int? {
var g = self
while true {
guard !g.complete else { return g.vertices.count }
}
return 0
}
}
*/
| mit | 688041f1bdbd5dfb3ea6e1380a1d9a5a | 21.757143 | 110 | 0.466416 | 4.87156 | false | false | false | false |
jungtong/LernaFramework | Pod/Classes/LernaString.swift | 2 | 10152 | //
// LernaString.swift
// Pods
//
// Created by jungtong on 2016. 1. 5..
//
//
// MARK:- Drag this file into the file navigator of your Xcode project. Make sure you select add to target -
// Because of Xcode errors it's not possible to integrate this project with Cocoapods or as Embedded Framework. Read more at Dev Forum
import Foundation
enum LernaStringError: ErrorType {
case cropError
}
public class LernaString {
func substringWithIntRange(string: String, range: Range<Int>) -> String {
return string.substringWithRange(string.startIndex.advancedBy(range.startIndex)...string.startIndex.advancedBy(range.endIndex-1))
}
// 문자열 바꿔준기
func cleanUp(inout string: String) {
string = string.stringByReplacingOccurrencesOfString("\t", withString: "")
string = string.stringByReplacingOccurrencesOfString("\n", withString: "")
string = string.stringByReplacingOccurrencesOfString(" ", withString: " ")
string = string.stringByReplacingOccurrencesOfString("&", withString: "&")
string = string.stringByReplacingOccurrencesOfString(""", withString: "\"")
string = string.stringByReplacingOccurrencesOfString("<", withString: "<")
string = string.stringByReplacingOccurrencesOfString(">", withString: ">")
string = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
// 모든 subString을 찾아서 배열을 반환.
func rangeOfAllSubstrings(string: String, str: String) -> [Range<String.Index>]! {
return string.rangeOfAllSubstrings(str)
}
}
extension String {
func substringWithIntRange(range: Range<Int>) -> String {
return self.substringWithRange(self.startIndex.advancedBy(range.startIndex)...self.startIndex.advancedBy(range.endIndex-1))
}
// 문자열 바꿔준기
mutating func cleanUp() {
self = self.stringByReplacingOccurrencesOfString("\t", withString: "")
self = self.stringByReplacingOccurrencesOfString("\n", withString: "")
self = self.stringByReplacingOccurrencesOfString(" ", withString: " ")
self = self.stringByReplacingOccurrencesOfString("&", withString: "&")
self = self.stringByReplacingOccurrencesOfString(""", withString: "\"")
self = self.stringByReplacingOccurrencesOfString("<", withString: "<")
self = self.stringByReplacingOccurrencesOfString(">", withString: ">")
self = self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
// 모든 subString을 찾아서 배열을 반환.
func rangeOfAllSubstrings(str: String) -> [Range<String.Index>]! {
var result = [Range<String.Index>]()
var indexFirst: String.Index = self.startIndex
var rangeFind: Range<String.Index>? = nil
while true {
rangeFind = self.rangeOfString(str, range: Range(start: indexFirst, end: self.endIndex))
if rangeFind != nil {
result.append(rangeFind!)
indexFirst = rangeFind!.endIndex
}
else {
break
}
}
return result
}
// first 와 second 사이의 range 를 모두 검색.
func rangeOfAllBetweenSubstrings(first first: String, second: String, firstInclude: Bool, secondInclude: Bool, first2: String? = nil) -> [Range<String.Index>]! {
var result = [Range<String.Index>]()
var indexFirst: String.Index = self.startIndex
var firstFind: Range<String.Index>? = nil
var secondFind: Range<String.Index>? = nil
while true {
var isOnlySecond = false
firstFind = self.rangeOfString(first, range: Range(start: indexFirst, end: self.endIndex))
if firstFind == nil && first2 != nil {
firstFind = self.rangeOfString(first2!, range: Range(start: indexFirst, end: self.endIndex))
isOnlySecond = true
}
if firstFind != nil { // 첫번째 문자열 찾음
if !isOnlySecond && first2 != nil { // 첫번째 문자열의 2번째 옵션 검색
if let tempFind = self.rangeOfString(first2!, range: Range(start: indexFirst, end: self.endIndex)) {
if firstFind?.startIndex > tempFind.startIndex {
firstFind = tempFind
}
}
}
secondFind = self.rangeOfString(second, range: Range(start: firstFind!.endIndex, end: self.endIndex))
if secondFind != nil { // 두번째 문자열 찾음
var firstIndex: String.Index
var secondIndex: String.Index
if firstInclude {
firstIndex = firstFind!.startIndex
}
else {
firstIndex = firstFind!.endIndex
}
if secondInclude {
secondIndex = secondFind!.endIndex
}
else {
secondIndex = secondFind!.startIndex
}
result.append(firstIndex..<secondIndex)
}
else {
break
}
indexFirst = secondFind!.endIndex
}
else {
break
}
}
return result
}
// 제일 마지막 fromString과 제일 처음 toString 사이의 문자열로 잘라낸다.
mutating func cropString(fromString fromString: String, toString: String, isFirstFromString: Bool = false) throws {
if isFirstFromString {
// 제일 마지막에 있는 FromString 의 range 를 찾는다.
guard let lastFromStringRange = self.rangeOfString(fromString) else {
throw LernaStringError.cropError
}
guard let firstToStringRange = self.rangeOfString(toString) else {
throw LernaStringError.cropError
}
guard lastFromStringRange.last < firstToStringRange.first else {
throw LernaStringError.cropError
}
self = self.substringWithRange(lastFromStringRange.first!...firstToStringRange.last!)
return
}
// 제일 마지막에 있는 FromString 의 range 를 찾는다.
guard let lastFromStringRange = self.rangeOfAllSubstrings(fromString).last else {
throw LernaStringError.cropError
}
guard let firstToStringRange = self.rangeOfString(toString) else {
throw LernaStringError.cropError
}
guard lastFromStringRange.last < firstToStringRange.first else {
throw LernaStringError.cropError
}
self = self.substringWithRange(lastFromStringRange.first!...firstToStringRange.last!)
}
// 두 문자열 사이의 문자열울 return(첫번쨰 검색 된 것만) , 찾기로 한 문자열을 포함할지 선택.
func subStringBetweenStrings(first first: String, second: String, firstInclude: Bool, secondInclude: Bool) -> String? {
for range in self.rangeOfAllBetweenSubstrings(first: first, second: second, firstInclude: firstInclude, secondInclude: secondInclude) {
let result = self.substringWithRange(range)
return result
}
return nil
}
// 맨 뒤에서부터 str 사이의 문자열을 return.
func subStringReverseFindToEnd(str: String) -> String? {
if let findIndex = self.rangeOfString(str, options: NSStringCompareOptions.BackwardsSearch)?.last {
return self.substringWithRange(findIndex.advancedBy(1)..<self.endIndex)
}
else {
return nil
}
}
// 맨 뒤에 있는 first 와 second 사이의 문자열을 return.
func subStringBetweenStringsReverse(first first: String, second: String) -> String? {
if let secondIndex = self.rangeOfString(second, options: NSStringCompareOptions.BackwardsSearch)?.first {
if let firstIndex = self.rangeOfString(first, options: NSStringCompareOptions.BackwardsSearch, range: Range(start: self.startIndex, end: secondIndex))?.last {
return self.substringWithRange(firstIndex.advancedBy(1)..<secondIndex)
}
else {
return nil
}
}
else {
return nil
}
}
// 첫번째 second를 찾고, 그 바로 앞의 first를 찾아서 그 사이의 문자열을 return
func subStringBetweenSecondToFirst(first first: String, second: String) -> String? {
if let secondIndex = self.rangeOfString(second)?.first {
if let firstIndex = self.rangeOfString(first, options: NSStringCompareOptions.BackwardsSearch, range: Range(start: self.startIndex, end: secondIndex))?.last {
return self.substringWithRange(firstIndex.advancedBy(1)..<secondIndex)
}
else {
return nil
}
}
else {
return nil
}
}
// first와 second 사이의 문자열을 지운다.
mutating func removeSubStringBetweenStrings(first first: String, second: String) {
while(true) {
if let firstFind = self.rangeOfString(first)?.first {
if let secondFind = self.rangeOfString(second, range:Range(start: firstFind, end: self.endIndex))?.endIndex {
self.removeRange(Range(start:firstFind, end:secondFind))
}
else {
return
}
}
else {
return
}
}
}
} | mit | 8f5bc069a3c80e651e27a47a539e62c4 | 39.352697 | 170 | 0.581859 | 4.697585 | false | false | false | false |
qiuncheng/CuteAttribute | Example/ViewController.swift | 1 | 2183 | //
// ViewController.swift
// Example
//
// Created by vsccw on 2017/8/13.
// Copyright © 2017年 https://vsccw.com. All rights reserved.
//
import UIKit
import CuteAttribute
class ViewController: UIViewController {
let text = """
hello world,
17600636630
2018-04-21 18:03:48
https://blog.vsccw.com
"""
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var testLabel: TapableLabel!
override func viewDidLoad() {
super.viewDidLoad()
let dateFont = UIFont(name: "Menlo", size: 24) ?? UIFont.systemFont(ofSize: 24)
textView.cute.attributedText = text.cute
.from(0)
.to(10)
.blue
.font(UIFont.systemFont(ofSize: 40))
.matchAllPhoneNumber()
.rgbColor(0x880011)
.underline(.single)
.underlineColor(.gray)
.matchAllURL()
.red
.singleUnderline
.underlineColor(.blue)
.matchAllDate()
.green
.doubleUnderline
.underlineColor(.orange)
.font(dateFont)
let cuteAttr = "请点击该链接:https://vsccw.com,17600636630😆😆😆😆😆😆"
.cute
.matchAllURL()
.color(.red)
.underline(NSUnderlineStyle.single)
.matchAll()
.lineSpacing(30)
.tap(.link)
.highlight(.default)
.tap(.phoneNumber)
.highlight(.default)
testLabel.cute.attributedText = cuteAttr
testLabel.delegate = self
}
private func showAlertController(_ message: String?) {
let alertController = UIAlertController(title: "你点击了", message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "我知道啦", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
}
extension ViewController: TapableLabelDelegate {
func tapableLabel(_ label: TapableLabel, didTap range: NSRange, text: String?) {
showAlertController(text)
}
}
| mit | 8315866a0ac2aff1c487d06a769c68a8 | 27.783784 | 104 | 0.573709 | 4.391753 | false | false | false | false |
FuckBoilerplate/RxCache | Sources/Core/internal/cache/RetrieveRecord.swift | 1 | 3255 | // RetrievedRecord.swift
// RxCache
//
// Copyright (c) 2016 Victor Albertos https://github.com/VictorAlbertos
//
// 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.
class RetrieveRecord : Action {
let memory : Memory
fileprivate let evictRecord : EvictRecord
fileprivate let hasRecordExpired : HasRecordExpired
fileprivate let persistence : Persistence
init(memory : Memory, evictRecord : EvictRecord, hasRecordExpired : HasRecordExpired, persistence : Persistence) {
self.memory = memory
self.evictRecord = evictRecord
self.hasRecordExpired = hasRecordExpired
self.persistence = persistence
}
func retrieve<T>(_ providerKey: String, dynamicKey : DynamicKey?, dynamicKeyGroup : DynamicKeyGroup?, useExpiredDataIfLoaderNotAvailable: Bool, lifeCache: LifeCache?) -> Record<T>? {
let composedKey = composeKey(providerKey, dynamicKey: dynamicKey, dynamicKeyGroup: dynamicKeyGroup);
var record : Record<T>
if let recordMemory : Record<T> = memory.getIfPresent(composedKey) {
record = recordMemory
record.source = Source.Memory
} else if let recordPersistence: Record<T> = persistence.retrieveRecord(composedKey) {
record = recordPersistence
record.source = Source.Persistence
memory.put(composedKey, record: record)
} else {
return nil
}
let lifeTimeInSeconds = lifeCache != nil ? lifeCache!.getLifeTimeInSeconds() : 0
record.lifeTimeInSeconds = lifeTimeInSeconds
if hasRecordExpired.hasRecordExpired(record: record) {
if let dynamicKeyGroup = dynamicKeyGroup {
evictRecord.evictRecordMatchingDynamicKeyGroup(providerKey, dynamicKey: dynamicKey, dynamicKeyGroup: dynamicKeyGroup)
} else if let dynamicKey = dynamicKey {
evictRecord.evictRecordsMatchingDynamicKey(providerKey, dynamicKey: dynamicKey)
} else {
evictRecord.evictRecordsMatchingProviderKey(providerKey)
}
return useExpiredDataIfLoaderNotAvailable ? record : nil
}
return record
}
}
| mit | 70a13dc3d06d6e05ff7e7e6d1c2061ad | 44.84507 | 186 | 0.699232 | 4.786765 | false | false | false | false |
Yalantis/ColorMatchTabs | ColorMatchTabs/Classes/Views/CircleMenu.swift | 1 | 7238 | //
// ColorMatchTabs.swift
// ColorMatchTabs
//
// Created by Sergey Butenko on 9/6/16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import UIKit
@objc public protocol CircleMenuDelegate: class {
@objc
optional func circleMenuWillDisplayItems(_ circleMenu: CircleMenu)
@objc
optional func circleMenuWillHideItems(_ circleMenu: CircleMenu)
@objc
optional func circleMenu(_ circleMenu: CircleMenu, didSelectItemAt index: Int)
}
public protocol CircleMenuDataSource: class {
func numberOfItems(inMenu circleMenu: CircleMenu) -> Int
func circleMenu(_ circleMenu: CircleMenu, tintColorAt index: Int) -> UIColor
}
/// A menu with items spreaded by a circle around the button.
open class CircleMenu: UIControl {
/// Delegate.
open weak var delegate: CircleMenuDelegate?
/// Delegate.
open weak var dataSource: CircleMenuDataSource?
/// Animation delay.
open var animationDelay: TimeInterval = 0
/// Animation duration.
open var animationDuration: TimeInterval = 0.5
// Radius of spreading the elements.
@IBInspectable open var itemsSpacing: CGFloat = 130
/// Item dimension.
@IBInspectable open var itemDimension: CGFloat = 50
/// Image for a button to open/close menu.
@IBInspectable open var image: UIImage? {
didSet {
imageView.image = image
}
}
fileprivate var visible = false
fileprivate var buttons: [UIButton] = []
fileprivate var imageView: UIImageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override open var frame: CGRect {
didSet {
imageView.frame = bounds
}
}
override open var bounds: CGRect {
didSet {
imageView.frame = bounds
}
}
override open func didMoveToSuperview() {
super.didMoveToSuperview()
buttons.filter{ $0.superview == nil }.forEach{ superview?.addSubview($0) }
}
}
public extension CircleMenu {
func reloadData() {
guard let dataSource = dataSource else {
return
}
removeOldButtons()
for index in 0..<dataSource.numberOfItems(inMenu: self) {
let button = UIButton(frame: CGRect.zero)
button.addTarget(self, action: #selector(selectItem(_:)), for: .touchUpInside)
button.tag = index
button.layoutIfNeeded()
button.backgroundColor = dataSource.circleMenu(self, tintColorAt: index)
button.layer.cornerRadius = itemDimension / 2
button.layer.masksToBounds = true
superview?.addSubview(button)
buttons.append(button)
}
}
/**
- parameter index: Index of item
- returns: CGPoint with center of item at index
*/
func centerOfItem(atIndex index: Int) -> CGPoint {
let count = dataSource?.numberOfItems(inMenu: self) ?? 0
assert(index >= 0)
assert(index < count)
let deltaAngle = CGFloat(Double.pi / Double(Double(count)))
let angle = deltaAngle * CGFloat(Double(index) + 0.5) - CGFloat(Double.pi)
let x = itemsSpacing * cos(angle) + bounds.size.width / 2
let y = itemsSpacing * sin(angle) + bounds.size.height / 2
let point = CGPoint(x: x, y: y)
let convertedPoint = convert(point, to: superview)
return convertedPoint
}
func selectItem(atIndex: Int) {
let count = dataSource?.numberOfItems(inMenu: self) ?? 0
guard atIndex < count else {
return
}
if visible {
delegate?.circleMenu?(self, didSelectItemAt: atIndex)
hideItems()
}
}
@objc
func triggerMenu(_ sender: AnyObject? = nil) {
assert(superview != nil, "You must add the menu to superview before perfoming any actions with it")
visible = !visible
if visible {
showItems()
} else {
hideItems()
}
setCloseButtonHidden(!visible)
}
@objc
func selectItem(_ sender: UIButton) {
hideItems()
delegate?.circleMenu?(self, didSelectItemAt: sender.tag)
}
}
// setup
private extension CircleMenu {
func commonInit() {
addSubview(imageView)
addTarget(self, action: #selector(triggerMenu), for: .touchUpInside)
}
func removeOldButtons() {
self.buttons.forEach {
$0.removeFromSuperview()
}
buttons = []
}
}
// animations
extension CircleMenu {
var sourceFrame: CGRect {
let origin = CGPoint(x: center.x - itemDimension / 2, y: center.y - itemDimension / 2)
let size = CGSize(width: itemDimension, height: itemDimension)
return CGRect(origin: origin, size: size)
}
func showItems() {
guard let superview = superview else {
fatalError("You must add the menu to superview before perfoming any actions with it")
}
visible = true
delegate?.circleMenuWillDisplayItems?(self)
for (index, button) in buttons.enumerated() {
button.frame = sourceFrame
performAnimated({
button.isHidden = false
button.frame = self.targetFrameForItem(at: index)
})
}
superview.bringSubviewToFront(self)
}
func hideItems() {
assert(superview != nil, "You must add the menu to superview before perfoming any actions with it")
delegate?.circleMenuWillHideItems?(self)
setCloseButtonHidden(true)
performAnimated({
for button in self.buttons {
button.frame = self.sourceFrame
button.isHidden = true
}
})
visible = false
}
func setCloseButtonHidden(_ hidden: Bool) {
performAnimated({
self.transform = hidden ? CGAffineTransform.identity : CGAffineTransform(rotationAngle: CGFloat(Double.pi) * 0.75)
})
}
func performAnimated(_ block: @escaping () -> Void, completion: ((Bool) -> Void)? = nil) {
UIView.animate(
withDuration: animationDuration,
delay: animationDelay,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 3,
options: [],
animations: block,
completion: completion
)
}
func targetFrameForItem(at index: Int) -> CGRect {
let centerPoint = centerOfItem(atIndex: index)
let itemOrigin = CGPoint(x: centerPoint.x - itemDimension / 2, y: centerPoint.y - itemDimension / 2)
let itemSize = CGSize(width: itemDimension, height: itemDimension)
let targetFrame = CGRect(origin: itemOrigin, size: itemSize)
return targetFrame
}
}
| mit | 4b96c1912e4f6aab7443b18143cb6c7d | 27.269531 | 126 | 0.586984 | 4.933197 | false | false | false | false |
davidvuong/ddfa-app | ios/Pods/GooglePlacePicker/Example/GooglePlacePickerDemos/ShadowView.swift | 13 | 2932 | /*
* Copyright 2016 Google Inc. All rights reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import UIKit
/// A simple UIView subclass which renders a configurable drop-shadow. The view itself is
/// transparent and only shows the drop-shadow. The drop-shadow draws the same size as the frame of
/// the view, and can take an optional corner radius into account when calculating the effect.
class ShadowView: UIView {
/// The blur radius of the drop-shadow, defaults to 0.
var shadowRadius = CGFloat() { didSet { update() } }
/// The opacity of the drop-shadow, defaults to 0.
var shadowOpacity = Float() { didSet { update() } }
/// The x,y offset of the drop-shadow from being cast straight down.
var shadowOffset = CGSize.zero { didSet { update() } }
/// The color of the drop-shadow, defaults to black.
var shadowColor = UIColor.black { didSet { update() } }
/// Whether to display the shadow, defaults to false.
var enableShadow = false { didSet { update() } }
/// The corner radius to take into account when casting the shadow, defaults to 0.
var cornerRadius = CGFloat() { didSet { update() } }
override var frame: CGRect {
didSet(oldFrame) {
// Check to see if the size of the frame has changed, if it has then we need to recalculate
// the shadow.
if oldFrame.size != frame.size {
update()
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
private func setup() {
// Configure the view
backgroundColor = UIColor.clear
isOpaque = false
isHidden = true
// Enable rasterization on the layer, this will improve the performance of shadow rendering.
layer.shouldRasterize = true
}
private func update() {
isHidden = !enableShadow
if enableShadow {
// Configure the layer properties.
layer.shadowRadius = shadowRadius
layer.shadowOffset = shadowOffset
layer.shadowOpacity = shadowOpacity
layer.shadowColor = shadowColor.cgColor
// Set a shadow path as an optimization, this significantly improves shadow performance.
layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
} else {
// Disable the shadow.
layer.shadowRadius = 0
layer.shadowOpacity = 0
}
}
}
| mit | ee0009bee2ba775209de9f9b35e38cf1 | 34.325301 | 99 | 0.691678 | 4.449165 | false | false | false | false |
sora0077/DribbbleKit | DribbbleKit/Sources/Users/Likes/ListUserLikes.swift | 1 | 2201 | //
// ListUserLikes.swift
// DribbbleKit
//
// Created by 林 達也 on 2017/04/28.
// Copyright © 2017年 jp.sora0077. All rights reserved.
//
import Foundation
import APIKit
import Alter
// MARK: - ListUserLikes
public struct ListUserLikes<Like: LikeData, Shot: ShotData, User: UserData, Team: TeamData>: PaginatorRequest {
public typealias Element = (like: Like, shot: Shot, user: User, team: Team?)
public let path: String
public let parameters: Any?
public init(id: User.Identifier, page: Int? = nil, perPage: Int? = configuration?.perPage) {
path = "/users/\(id.value)/likes"
parameters = [
"page": page,
"per_page": perPage].cleaned
}
public init(path: String, parameters: [String : Any]) throws {
self.path = path
self.parameters = parameters
}
public func responseElements(from objects: [Any], meta: Meta) throws -> [Element] {
return try objects.map {
try (decode($0),
decode($0, rootKeyPath: "shot"),
decode($0, rootKeyPath: ["shot", "user"]),
decode($0, rootKeyPath: ["shot", "team"], optional: true))
}
}
}
// MARK: - ListAuthenticatedUserLikes
public struct ListAuthenticatedUserLikes<Like: LikeData, Shot: ShotData, User: UserData, Team: TeamData>: PaginatorRequest {
public typealias Element = (like: Like, shot: Shot, user: User, team: Team?)
public let path: String
public let parameters: Any?
public init(page: Int? = nil, perPage: Int? = configuration?.perPage) {
path = "/user/likes"
parameters = [
"page": page,
"per_page": perPage].cleaned
}
public init(path: String, parameters: [String : Any]) throws {
self.path = path
self.parameters = parameters
}
public func responseElements(from objects: [Any], meta: Meta) throws -> [Element] {
return try objects.map {
try (decode($0),
decode($0, rootKeyPath: "shot"),
decode($0, rootKeyPath: ["shot", "user"]),
decode($0, rootKeyPath: ["shot", "team"], optional: true))
}
}
}
| mit | 0672c5c1a35756a9ce77788c625e71b1 | 30.768116 | 124 | 0.593522 | 4.051756 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Tree/110_Balanced Binary Tree.swift | 1 | 1388 | // 110_Balanced Binary Tree
// https://leetcode.com/problems/balanced-binary-tree/
//
// Created by Honghao Zhang on 9/18/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given a binary tree, determine if it is height-balanced.
//
//For this problem, a height-balanced binary tree is defined as:
//
//a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
//
//Example 1:
//
//Given the following tree [3,9,20,null,null,15,7]:
//
// 3
// / \
// 9 20
// / \
// 15 7
//Return true.
//
//Example 2:
//
//Given the following tree [1,2,2,3,3,null,null,4,4]:
//
// 1
// / \
// 2 2
// / \
// 3 3
// / \
// 4 4
//Return false.
//
import Foundation
class Num110 {
/// Check with max depth but also return if the branch is balanced.
func isBalanced(_ root: TreeNode?) -> Bool {
return isBalancedHelper(root).0
}
/// returns if the tree is balanced and it's depth
private func isBalancedHelper(_ root: TreeNode?) -> (Bool, Int) {
if root == nil {
return (true, 0)
}
let (leftIsBalanced, leftDepth) = isBalancedHelper(root?.left)
let (rightIsBalanced, rightDepth) = isBalancedHelper(root?.right)
let isBalanced = leftIsBalanced && rightIsBalanced && abs(leftDepth - rightDepth) <= 1
return (isBalanced, max(leftDepth, rightDepth) + 1)
}
}
| mit | 88123418a4a4074df26b61f17be1ad79 | 23.333333 | 97 | 0.633021 | 3.248244 | false | false | false | false |
ovenbits/Alexandria | Sources/UIViewController+Extensions.swift | 1 | 2661 | //
// UIViewController+Extensions.swift
//
// Created by Jonathan Landon on 4/15/15.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Oven Bits, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
extension UIViewController {
/// Retrieve the view controller currently on-screen
///
/// Based off code here: http://stackoverflow.com/questions/24825123/get-the-current-view-controller-from-the-app-delegate
public static var current: UIViewController? {
if let controller = UIApplication.shared.keyWindow?.rootViewController {
return findCurrent(controller)
}
return nil
}
private static func findCurrent(_ controller: UIViewController) -> UIViewController {
if let controller = controller.presentedViewController {
return findCurrent(controller)
}
else if let controller = controller as? UISplitViewController, let lastViewController = controller.viewControllers.first, controller.viewControllers.count > 0 {
return findCurrent(lastViewController)
}
else if let controller = controller as? UINavigationController, let topViewController = controller.topViewController, controller.viewControllers.count > 0 {
return findCurrent(topViewController)
}
else if let controller = controller as? UITabBarController, let selectedViewController = controller.selectedViewController, (controller.viewControllers?.count ?? 0) > 0 {
return findCurrent(selectedViewController)
}
else {
return controller
}
}
}
| mit | 2a6e8585cd8a77abadcd2311e835bfbd | 44.101695 | 178 | 0.721157 | 5.068571 | false | false | false | false |
cpageler93/ConsulSwift | Sources/ConsulSwift/ConsulAgentService.swift | 1 | 1797 | //
// ConsulAgentService.swift
// ConsulSwift
//
// Created by Christoph Pageler on 14.06.17.
//
import Foundation
import Quack
public extension Consul {
public class AgentServiceOutput: Quack.Model {
public var id: String
public var service: String
public var tags: [String]
public var address: String
public var port: Int
public required init?(json: JSON) {
guard let id = json["ID"].string,
let service = json["Service"].string,
let address = json["Address"].string,
let port = json["Port"].int
else {
return nil
}
self.id = id
self.service = service
var tags: [String] = []
if let jsonTags = json["Tags"].array {
for jsonTag in jsonTags {
if let jsonTagString = jsonTag.string {
tags.append(jsonTagString)
}
}
}
self.tags = tags
self.address = address
self.port = port
}
}
public class AgentServiceInput {
public var id: String?
public var name: String
public var tags: [String]
public var address: String?
public var port: Int?
public init(name: String,
id: String? = nil,
tags: [String] = [],
address: String? = nil,
port: Int? = nil) {
self.name = name
self.id = id
self.tags = tags
self.address = address
self.port = port
}
}
}
| mit | 4749f8440a6c99bbd39b43ab4bdb31b0 | 24.309859 | 59 | 0.452977 | 4.950413 | false | false | false | false |
wuzhenli/MyDailyTestDemo | swiftTest/swifter-tips+swift+3.0/Swifter.playground/Pages/currying.xcplaygroundpage/Contents.swift | 2 | 1366 |
import Foundation
func addOne(num: Int) -> Int {
return num + 1
}
func addTo(_ adder: Int) -> (Int) -> Int {
return {
num in
return num + adder
}
}
let addTwo = addTo(2) // addToFour: Int -> Int
let result = addTwo(6) // result = 8
func greaterThan(_ comparer: Int) -> (Int) -> Bool {
return { $0 > comparer }
}
let greaterThan10 = greaterThan(10);
greaterThan10(13) // => true
greaterThan10(9) // => false
protocol TargetAction {
func performAction()
}
struct TargetActionWrapper<T: AnyObject>: TargetAction {
weak var target: T?
let action: (T) -> () -> ()
func performAction() -> () {
if let t = target {
action(t)()
}
}
}
enum ControlEvent {
case TouchUpInside
case ValueChanged
// ...
}
class Control {
var actions = [ControlEvent: TargetAction]()
func setTarget<T: AnyObject>(target: T,
action: @escaping (T) -> () -> (), controlEvent: ControlEvent) {
actions[controlEvent] = TargetActionWrapper(
target: target, action: action)
}
func removeTargetForControlEvent(controlEvent: ControlEvent) {
actions[controlEvent] = nil
}
func performActionForControlEvent(controlEvent: ControlEvent) {
actions[controlEvent]?.performAction()
}
}
| apache-2.0 | fc7eb9cf9ffc46a4bc18ab55eda8ee1e | 19.69697 | 72 | 0.582723 | 4.08982 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.