repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
Esri/tips-and-tricks-ios | DevSummit2015_TipsAndTricksDemos/Tips-And-Tricks/CustomCallout/CustomCalloutVC.swift | 1 | 10088 | // Copyright 2015 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 Foundation
import UIKit
import ArcGIS
class CustomCalloutVC: UIViewController, AGSMapViewTouchDelegate, AGSCalloutDelegate, AGSLayerCalloutDelegate, AGSPopupsContainerDelegate {
@IBOutlet weak var mapView: AGSMapView!
@IBOutlet weak var toggleControl: UISegmentedControl!
var graphicsLayer: AGSGraphicsLayer!
var graphic: AGSGraphic!
var calloutMapView: AGSMapView!
var popupsContainerVC: AGSPopupsContainerViewController!
override func viewDidLoad() {
super.viewDidLoad()
// set touch delegate
self.mapView.touchDelegate = self
// add base layer to map
let streetMapUrl = NSURL(string: "http://services.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer")
let tiledLayer = AGSTiledMapServiceLayer(URL: streetMapUrl);
self.mapView.addMapLayer(tiledLayer, withName:"Tiled Layer")
// zoom to envelope
let envelope = AGSEnvelope.envelopeWithXmin(-12973339.119440766, ymin:4004738.947715673, xmax:-12972574.749157893, ymax:4006095.704967771, spatialReference: AGSSpatialReference.webMercatorSpatialReference()) as AGSEnvelope
self.mapView.zoomToEnvelope(envelope, animated: true)
// map view callout is selected by default
self.toggleCustomCallout(self.toggleControl)
// add observer to visibleAreaEnvelope
self.mapView.addObserver(self, forKeyPath: "visibleAreaEnvelope", options: NSKeyValueObservingOptions.New, context: nil)
}
// MARK: Toggle Action
@IBAction func toggleCustomCallout(sender: UISegmentedControl) {
//
// if
if (self.toggleControl.selectedSegmentIndex == 0) {
//
// remove graphics layer
self.mapView.removeMapLayer(self.graphicsLayer)
// hide callout
self.mapView.callout.hidden = true
//
// init callout map view
self.calloutMapView = AGSMapView(frame: CGRectMake(0, 0, 180, 140))
// add base layer to callout map view
let imageryMapUrl = NSURL(string: "http://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer")
let imageryLayer = AGSTiledMapServiceLayer(URL: imageryMapUrl);
self.calloutMapView.addMapLayer(imageryLayer, withName:"Tiled Layer")
// add graphics layer to map
self.graphicsLayer = AGSGraphicsLayer.graphicsLayer() as AGSGraphicsLayer
self.calloutMapView.addMapLayer(self.graphicsLayer, withName:"Graphics Layer")
// zoom to geometry
if self.mapView.visibleAreaEnvelope != nil {
self.zoomToVisibleEnvelopeForCalloutMapView()
}
}
else if (self.toggleControl.selectedSegmentIndex == 1) {
//
// add graphics layer to map
self.graphicsLayer = AGSGraphicsLayer.graphicsLayer() as AGSGraphicsLayer
self.graphicsLayer.calloutDelegate = self
self.mapView.addMapLayer(self.graphicsLayer, withName:"Graphics Layer")
// add graphics to map
self.addRandomPoints(15, envelope: self.mapView.visibleAreaEnvelope)
}
}
// MARK: Helper Methods
func addRandomPoints(numPoints: Int, envelope: AGSEnvelope) {
var graphics = [AGSGraphic]()
for index in 1...numPoints {
// get random point
let pt = self.randomPointInEnvelope(envelope)
// create a graphic to display on the map
let pms = AGSPictureMarkerSymbol(imageNamed: "green_pin")
pms.leaderPoint = CGPointMake(0, 14)
let g = AGSGraphic(geometry: pt, symbol: pms, attributes: nil)
// set attributes
g.setValue(String(index), forKey: "ID")
g.setValue("Test Name", forKey: "Name")
g.setValue("Test Title", forKey: "Title")
g.setValue("Test Value", forKey: "Value")
// add graphic to graphics array
graphics.append(g)
}
// add graphics to layer
self.graphicsLayer.addGraphics(graphics)
}
func randomPointInEnvelope(envelope : AGSEnvelope) -> AGSPoint {
var xDomain: UInt32 = (UInt32)(envelope.xmax - envelope.xmin)
var dx: Double = 0
if (xDomain != 0) {
let x: UInt32 = arc4random() % xDomain
dx = envelope.xmin + Double(x)
}
var yDomain: UInt32 = (UInt32)(envelope.ymax - envelope.ymin)
var dy: Double = 0
if (yDomain != 0) {
let y: UInt32 = arc4random() % xDomain
dy = envelope.ymin + Double(y)
}
return AGSPoint(x: dx, y: dy, spatialReference: envelope.spatialReference)
}
func zoomToVisibleEnvelopeForCalloutMapView() {
let mutableEnvelope = self.mapView.visibleAreaEnvelope.mutableCopy() as AGSMutableEnvelope
mutableEnvelope.expandByFactor(0.15)
self.calloutMapView.zoomToGeometry(mutableEnvelope, withPadding: 0, animated: true)
}
// MARK: MapView Touch Delegate
func mapView(mapView: AGSMapView!, shouldProcessClickAtPoint screen: CGPoint, mapPoint mappoint: AGSPoint!) -> Bool {
// only process tap if we are showing popup callout view
if (self.toggleControl.selectedSegmentIndex == 1) {
return true
}
return false
}
func mapView(mapView: AGSMapView!, didTapAndHoldAtPoint screen: CGPoint, mapPoint mappoint: AGSPoint!, features: [NSObject : AnyObject]!) {
//
// process only for map view callout
if (self.toggleControl.selectedSegmentIndex == 0) {
//
// set custom view of callout and show it
self.mapView.callout.color = UIColor.brownColor()
self.mapView.callout.leaderPositionFlags = .Top | .Bottom
self.mapView.callout.customView = self.calloutMapView
self.mapView.callout.showCalloutAt(mappoint, screenOffset: CGPointMake(0, 0), animated: true)
// pan callout map view
self.calloutMapView.centerAtPoint(mappoint, animated: true)
// add graphic to callout map view
if self.graphicsLayer.graphics.count == 0 {
let symbol = AGSSimpleMarkerSymbol(color: UIColor(red: 255, green: 0, blue: 0, alpha: 0.5))
self.graphic = AGSGraphic(geometry: mappoint, symbol:symbol as AGSSymbol, attributes: nil)
self.graphicsLayer.addGraphic(self.graphic)
}
else {
self.graphic.geometry = mappoint;
}
}
}
func mapView(mapView: AGSMapView!, didMoveTapAndHoldAtPoint screen: CGPoint, mapPoint mappoint: AGSPoint!, features: [NSObject : AnyObject]!) {
//
// process only for map view callout
if (self.toggleControl.selectedSegmentIndex == 0) {
//
// move callout
self.mapView.callout.moveCalloutTo(mappoint, screenOffset: CGPointMake(0, 0), animated: true)
// update geometry of graphic
self.graphic.geometry = mappoint;
// pan callout map view
self.calloutMapView.centerAtPoint(mappoint, animated: true)
}
}
func mapView(mapView: AGSMapView!, didEndTapAndHoldAtPoint screen: CGPoint, mapPoint mappoint: AGSPoint!, features: [NSObject : AnyObject]!) {
//
// process only for map view callout
if (self.toggleControl.selectedSegmentIndex == 0) {
//
// remove all graphics from graphics layer
self.graphicsLayer.removeAllGraphics()
}
}
// MARK: Callout Delegate
func callout(callout: AGSCallout!, willShowForFeature feature: AGSFeature!, layer: AGSLayer!, mapPoint: AGSPoint!) -> Bool {
//
// show popup view controller in callout
let popupInfo = AGSPopupInfo(forGraphic: AGSGraphic(feature: feature))
self.popupsContainerVC = AGSPopupsContainerViewController(popupInfo: popupInfo, graphic: AGSGraphic(feature: feature), usingNavigationControllerStack: false)
self.popupsContainerVC.delegate = self
self.popupsContainerVC.doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: nil, action: nil)
self.popupsContainerVC.actionButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Trash, target: nil, action: nil)
self.popupsContainerVC.view.frame = CGRectMake(0,0,150,180)
callout.leaderPositionFlags = .Right | .Left
callout.customView = self.popupsContainerVC.view
return true
}
// MARK: Poups Container Delegate
func popupsContainerDidFinishViewingPopups(popupsContainer: AGSPopupsContainer!) {
self.mapView.callout.hidden = true
}
// MARK: Observe
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
// get the object
let mapView: AGSMapView = object as AGSMapView
// zoom in the callout map view
self.zoomToVisibleEnvelopeForCalloutMapView()
}
}
| apache-2.0 |
roecrew/AudioKit | AudioKit/Common/Operations/Generators/Noise/whiteNoise.swift | 2 | 537 | //
// whiteNoise.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
extension AKOperation {
/// White noise generator
///
/// - parameter amplitude: Amplitude. (Value between 0-1). (Default: 1.0, Minimum: 0.0, Maximum: 10.0)
///
public static func whiteNoise(
amplitude amplitude: AKParameter = 1.0
) -> AKOperation {
return AKOperation(module: "noise", inputs: amplitude)
}
}
| mit |
nickynick/Tails | TailsTests/TailsTests.swift | 1 | 888 | //
// TailsTests.swift
// TailsTests
//
// Created by Nick Tymchenko on 01/07/14.
// Copyright (c) 2014 Nick Tymchenko. All rights reserved.
//
import XCTest
class TailsTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
IAskWind/IAWExtensionTool | Pods/SwiftMessages/SwiftMessages/PhysicsAnimation.swift | 4 | 5005 | //
// PhysicsAnimation.swift
// SwiftMessages
//
// Created by Timothy Moose on 6/14/17.
// Copyright © 2017 SwiftKick Mobile. All rights reserved.
//
import UIKit
public class PhysicsAnimation: NSObject, Animator {
public enum Placement {
case top
case center
case bottom
}
public var placement: Placement = .center
public var panHandler = PhysicsPanHandler()
public weak var delegate: AnimationDelegate?
weak var messageView: UIView?
weak var containerView: UIView?
var context: AnimationContext?
public override init() {}
init(delegate: AnimationDelegate) {
self.delegate = delegate
}
public func show(context: AnimationContext, completion: @escaping AnimationCompletion) {
NotificationCenter.default.addObserver(self, selector: #selector(adjustMargins), name: UIDevice.orientationDidChangeNotification, object: nil)
install(context: context)
showAnimation(context: context, completion: completion)
}
public func hide(context: AnimationContext, completion: @escaping AnimationCompletion) {
NotificationCenter.default.removeObserver(self)
if panHandler.isOffScreen {
context.messageView.alpha = 0
panHandler.state?.stop()
}
let view = context.messageView
self.context = context
CATransaction.begin()
CATransaction.setCompletionBlock {
view.alpha = 1
view.transform = CGAffineTransform.identity
completion(true)
}
UIView.animate(withDuration: hideDuration!, delay: 0, options: [.beginFromCurrentState, .curveEaseIn, .allowUserInteraction], animations: {
view.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
}, completion: nil)
UIView.animate(withDuration: hideDuration!, delay: 0, options: [.beginFromCurrentState, .curveEaseIn, .allowUserInteraction], animations: {
view.alpha = 0
}, completion: nil)
CATransaction.commit()
}
public var showDuration: TimeInterval? { return 0.5 }
public var hideDuration: TimeInterval? { return 0.15 }
func install(context: AnimationContext) {
let view = context.messageView
let container = context.containerView
messageView = view
containerView = container
self.context = context
view.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(view)
switch placement {
case .center:
view.centerYAnchor.constraint(equalTo: container.centerYAnchor).with(priority: UILayoutPriority(200)).isActive = true
case .top:
view.topAnchor.constraint(equalTo: container.topAnchor).with(priority: UILayoutPriority(200)).isActive = true
case .bottom:
view.bottomAnchor.constraint(equalTo: container.bottomAnchor).with(priority: UILayoutPriority(200)).isActive = true
}
NSLayoutConstraint(item: view, attribute: .leading, relatedBy: .equal, toItem: container, attribute: .leading, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: container, attribute: .trailing, multiplier: 1, constant: 0).isActive = true
// Important to layout now in order to get the right safe area insets
container.layoutIfNeeded()
adjustMargins()
container.layoutIfNeeded()
installInteractive(context: context)
}
@objc public func adjustMargins() {
guard let adjustable = messageView as? MarginAdjustable & UIView,
let context = context else { return }
adjustable.preservesSuperviewLayoutMargins = false
if #available(iOS 11, *) {
adjustable.insetsLayoutMarginsFromSafeArea = false
}
adjustable.layoutMargins = adjustable.defaultMarginAdjustment(context: context)
}
func showAnimation(context: AnimationContext, completion: @escaping AnimationCompletion) {
let view = context.messageView
view.alpha = 0.25
view.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
CATransaction.begin()
CATransaction.setCompletionBlock {
completion(true)
}
UIView.animate(withDuration: showDuration!, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: [.beginFromCurrentState, .curveLinear, .allowUserInteraction], animations: {
view.transform = CGAffineTransform.identity
}, completion: nil)
UIView.animate(withDuration: 0.3 * showDuration!, delay: 0, options: [.beginFromCurrentState, .curveLinear, .allowUserInteraction], animations: {
view.alpha = 1
}, completion: nil)
CATransaction.commit()
}
func installInteractive(context: AnimationContext) {
guard context.interactiveHide else { return }
panHandler.configure(context: context, animator: self)
}
}
| mit |
AmitaiB/MyPhotoViewer | Pods/Cache/Source/Shared/Storage/SyncStorage.swift | 1 | 1307 | import Foundation
/// Manipulate storage in a "all sync" manner.
/// Block the current queue until the operation completes.
public class SyncStorage {
fileprivate let internalStorage: StorageAware
fileprivate let serialQueue: DispatchQueue
init(storage: StorageAware, serialQueue: DispatchQueue) {
self.internalStorage = storage
self.serialQueue = serialQueue
}
}
extension SyncStorage: StorageAware {
public func entry<T: Codable>(ofType type: T.Type, forKey key: String) throws -> Entry<T> {
var entry: Entry<T>!
try serialQueue.sync {
entry = try internalStorage.entry(ofType: type, forKey: key)
}
return entry
}
public func removeObject(forKey key: String) throws {
try serialQueue.sync {
try self.internalStorage.removeObject(forKey: key)
}
}
public func setObject<T: Codable>(_ object: T, forKey key: String,
expiry: Expiry? = nil) throws {
try serialQueue.sync {
try internalStorage.setObject(object, forKey: key, expiry: expiry)
}
}
public func removeAll() throws {
try serialQueue.sync {
try internalStorage.removeAll()
}
}
public func removeExpiredObjects() throws {
try serialQueue.sync {
try internalStorage.removeExpiredObjects()
}
}
}
| mit |
FuckBoilerplate/RxCache | watchOS/Pods/RxSwift/RxSwift/Observables/Implementations/Producer.swift | 6 | 3195 | //
// Producer.swift
// Rx
//
// Created by Krunoslav Zaher on 2/20/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class Producer<Element> : Observable<Element> {
override init() {
super.init()
}
override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element {
if !CurrentThreadScheduler.isScheduleRequired {
// The returned disposable needs to release all references once it was disposed.
let disposer = SinkDisposer()
let sinkAndSubscription = run(observer, cancel: disposer)
disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription)
return disposer
}
else {
return CurrentThreadScheduler.instance.schedule(()) { _ in
let disposer = SinkDisposer()
let sinkAndSubscription = self.run(observer, cancel: disposer)
disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription)
return disposer
}
}
}
func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
abstractMethod()
}
}
fileprivate class SinkDisposer: Cancelable {
fileprivate enum DisposeState: UInt32 {
case disposed = 1
case sinkAndSubscriptionSet = 2
}
// Jeej, swift API consistency rules
fileprivate enum DisposeStateInt32: Int32 {
case disposed = 1
case sinkAndSubscriptionSet = 2
}
private var _state: UInt32 = 0
private var _sink: Disposable? = nil
private var _subscription: Disposable? = nil
var isDisposed: Bool {
return (_state & DisposeState.disposed.rawValue) != 0
}
func setSinkAndSubscription(sink: Disposable, subscription: Disposable) {
_sink = sink
_subscription = subscription
let previousState = OSAtomicOr32OrigBarrier(DisposeState.sinkAndSubscriptionSet.rawValue, &_state)
if (previousState & DisposeStateInt32.sinkAndSubscriptionSet.rawValue) != 0 {
rxFatalError("Sink and subscription were already set")
}
if (previousState & DisposeStateInt32.disposed.rawValue) != 0 {
sink.dispose()
subscription.dispose()
_sink = nil
_subscription = nil
}
}
func dispose() {
let previousState = OSAtomicOr32OrigBarrier(DisposeState.disposed.rawValue, &_state)
if (previousState & DisposeStateInt32.disposed.rawValue) != 0 {
return
}
if (previousState & DisposeStateInt32.sinkAndSubscriptionSet.rawValue) != 0 {
guard let sink = _sink else {
rxFatalError("Sink not set")
}
guard let subscription = _subscription else {
rxFatalError("Subscription not set")
}
sink.dispose()
subscription.dispose()
_sink = nil
_subscription = nil
}
}
}
| mit |
Acidburn0zzz/firefox-ios | XCUITests/PocketTests.swift | 1 | 1894 | /* 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 XCTest
class PocketTest: BaseTestCase {
// Disabled due to #7855
/*func testPocketEnabledByDefault() {
navigator.goto(NewTabScreen)
waitForExistence(app.staticTexts["pocketTitle"])
XCTAssertEqual(app.staticTexts["pocketTitle"].label, "Trending on Pocket")
// There should be two stories on iPhone and three on iPad
let numPocketStories = app.collectionViews.containing(.cell, identifier:"TopSitesCell").children(matching: .cell).count-1
if iPad() {
XCTAssertEqual(numPocketStories, 9)
} else {
XCTAssertEqual(numPocketStories, 3)
}
// Disable Pocket
navigator.performAction(Action.TogglePocketInNewTab)
navigator.goto(NewTabScreen)
waitForNoExistence(app.staticTexts["pocketTitle"])
// Enable it again
navigator.performAction(Action.TogglePocketInNewTab)
navigator.goto(NewTabScreen)
waitForExistence(app.staticTexts["pocketTitle"])
// Tap on the first Pocket element
app.collectionViews.containing(.cell, identifier:"TopSitesCell").children(matching: .cell).element(boundBy: 1).tap()
waitUntilPageLoad()
// The url textField is not empty
XCTAssertNotEqual(app.textFields["url"].value as! String, "", "The url textField is empty")
}*/
func testTapOnMore() {
waitForExistence(app.buttons["More"], timeout: 5)
app.buttons["More"].tap()
waitUntilPageLoad()
navigator.nowAt(BrowserTab)
waitForExistence(app.textFields["url"], timeout: 15)
waitForValueContains(app.textFields["url"], value: "getpocket.com/explore")
}
}
| mpl-2.0 |
davepatterson/SwiftValidator | SwiftValidator/Rules/HexColorRule.swift | 2 | 400 | //
// HexColorRule.swift
// Validator
//
// Created by Bhargav Gurlanka on 2/4/16.
// Copyright © 2016 jpotts18. All rights reserved.
//
import Foundation
public class HexColorRule: RegexRule {
static let regex = "^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$"
public init(message: String = "Invalid regular expression") {
super.init(regex: HexColorRule.regex, message: message)
}
} | mit |
Alex-ZHOU/XYQSwift | XYQSwiftTests/Learn-from-Imooc/Play-with-Swift-2/04-Control-Flow/04-3-switch-advanced.playground/Contents.swift | 1 | 1047 | //
// 4-4 Swift 2.0逻辑控制之switch的高级用法
// 04-3-switch-advanced.playground
//
// Created by AlexZHOU on 21/05/2017.
// Copyright © 2016年 AlexZHOU. All rights reserved.
//
import UIKit
var str = "04-3-switch-advanced"
print(str)
let point = (1,1)
switch point{
case (0,0):
print("It's origin!")
case (_,0):
print("It on the x-axis.")
case (0,_):
print("It on the y-axis.")
default:
print("It's just an ordinary point.")
}
switch point{
case (0,0):
print("It's origin!")
case (_,0):
print("It on the x-axis.")
case (0,_):
print("It on the y-axis.")
case (-2...2,-2...2):
print("It's near the origin.")
default:
print("It's just an ordinary point.")
}
// Value binding
switch point{
case (0,0):
print("It's origin!")
case (let x,0):
print("It on the x-axis.")
print("The x value is \(x)")
case (0,let y):
print("It on the y-axis.")
print("The y value is \(y)")
case (let x,let y):
print("It's just an ordinary point.")
print("The point is ( \(x) , \(y) )")
} | apache-2.0 |
erremauro/Password-Update | Password Update/KeychainController.swift | 1 | 3240 | //
// KeychainController.swift
// Password Update
//
// Created by Roberto Mauro on 4/24/17.
// Copyright © 2017 roberto mauro. All rights reserved.
//
import Foundation
import Security
struct AccountType {
static let generic = kSecClassGenericPassword
static let internet = kSecClassInternetPassword
}
class KeychainController {
private let accountTypes = [AccountType.generic, AccountType.internet]
func add(account:String, password: String, for accountType: CFString) -> Bool {
let keychainQuery: NSDictionary = [
kSecClass: accountType,
kSecAttrLabel: account,
kSecAttrAccount: account,
kSecValueData: password.data(using: String.Encoding.utf8)!
]
var dataStatusRef: AnyObject?
let status = SecItemAdd(keychainQuery, &dataStatusRef)
return status == errSecSuccess
}
func delete(account: String) -> Bool {
var success = true
for accountType in accountTypes {
if exists(account, for: accountType) {
let deleted = delete(account, for: accountType)
if !deleted { success = false }
}
}
return success
}
func delete(_ account: String, for accountType: CFString) -> Bool {
let keychainQuery: NSDictionary = [
kSecClass: accountType,
kSecAttrAccount: account,
kSecMatchLimit: kSecMatchLimitAll
]
let status = SecItemDelete(keychainQuery)
return status == errSecSuccess
}
func changePassword(account: String, password: String) -> Bool {
var success = true
for accountType in accountTypes {
if exists(account, for: accountType) {
let updated = update(account, with: password, for: accountType)
if !updated && success {
success = false
}
}
}
return success
}
func exists(_ account: String) -> Bool {
var success = false
for accountType in accountTypes {
let hasAccount = exists(account, for: accountType)
if hasAccount && !success {
success = true
}
}
return success
}
func exists(_ account: String, for accountType: CFString) -> Bool {
let keychainQuery: NSDictionary = [
kSecClass: accountType,
kSecAttrAccount: account,
kSecMatchLimit : kSecMatchLimitOne
]
var dataTypeRef: AnyObject?
let status = SecItemCopyMatching(keychainQuery, &dataTypeRef)
return status == errSecSuccess
}
func update(_ account: String, with password: String, for accountType: CFString) -> Bool {
let keychainQueryGeneric: NSDictionary = [
kSecClass: accountType,
kSecAttrAccount: account,
kSecMatchLimit : kSecMatchLimitAll
]
let updateDict: NSDictionary = [
kSecValueData: password.data(using: String.Encoding.utf8)!
]
let status = SecItemUpdate(keychainQueryGeneric, updateDict)
return status == errSecSuccess
}
}
| mit |
pocketworks/FloatLabelFields | FloatLabelExample/FloatLabelExample/ViewController.swift | 1 | 982 | //
// ViewController.swift
// FloatLabelExample
//
// Created by Fahim Farook on 28/11/14.
// Copyright (c) 2014 RookSoft Ltd. All rights reserved.
//
// Updated for Swift 2.0 by Myles Ringle on 15/10/15.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var vwAddress:FloatLabelTextView!
@IBOutlet var vwHolder:UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Set font for placeholder of a FloatLabelTextView
if let fnt = UIFont(name:"HelveticaNeue", size:12) {
vwAddress.titleFont = fnt
}
// Set up a FloatLabelTextField via code
let fld = FloatLabelTextField(frame:vwHolder.bounds)
fld.placeholder = "Comments"
// Set font for place holder (only displays in title mode)
if let fnt = UIFont(name:"HelveticaNeue", size:12) {
fld.titleFont = fnt
}
vwHolder.addSubview(fld)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Loader/LoadingCircleView.swift | 1 | 1552 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public class LoadingCircleView: UIView {
// MARK: - Properties
/// The width of the stroke line
private let strokeWidth: CGFloat
override public var layer: CAShapeLayer {
super.layer as! CAShapeLayer
}
override public class var layerClass: AnyClass {
CAShapeLayer.self
}
// MARK: - Setup
init(
diameter: CGFloat,
strokeColor: UIColor,
strokeBackgroundColor: UIColor,
fillColor: UIColor,
strokeWidth: CGFloat = 8
) {
self.strokeWidth = strokeWidth
super.init(frame: CGRect(origin: .zero, size: CGSize(edge: diameter)))
configure(layer, strokeColor: strokeColor, fillColor: fillColor)
let strokeBackgroundLayer = CAShapeLayer()
configure(strokeBackgroundLayer, strokeColor: strokeBackgroundColor, fillColor: fillColor)
layer.addSublayer(strokeBackgroundLayer)
isAccessibilityElement = false
}
private func configure(_ layer: CAShapeLayer, strokeColor: UIColor, fillColor: UIColor) {
layer.strokeColor = strokeColor.cgColor
layer.lineWidth = strokeWidth
layer.lineCap = .round
layer.fillColor = fillColor.cgColor
layer.path = UIBezierPath(ovalIn: bounds.insetBy(dx: strokeWidth / 2, dy: strokeWidth / 2)).cgPath
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| lgpl-3.0 |
EasyIOS/EasyCoreData | Pod/Classes/EasyORM.swift | 1 | 12736 | //
// NSManagedObject+EZExtend.swift
// medical
//
// Created by zhuchao on 15/5/30.
// Copyright (c) 2015年 zhuchao. All rights reserved.
//
import Foundation
import CoreData
public class EasyORM {
public static var generateRelationships = false
public static func setUpEntities(entities: [String:NSManagedObject.Type]) {
nameToEntities = entities
}
private static var nameToEntities: [String:NSManagedObject.Type] = [String:NSManagedObject.Type]()
}
public extension NSManagedObject{
private func defaultContext() -> NSManagedObjectContext{
return self.managedObjectContext ?? self.dynamicType.defaultContext()
}
public static func defaultContext() -> NSManagedObjectContext{
return NSManagedObjectContext.defaultContext
}
private static var query:NSFetchRequest{
return self.defaultContext().createFetchRequest(self.entityName())
}
public static func condition(condition: AnyObject?) -> NSFetchRequest{
return self.query.condition(condition)
}
public static func orderBy(key:String,_ order:String = "ASC") -> NSFetchRequest{
return self.query.orderBy(key, order)
}
/**
* Set the "limit" value of the query.
*
* @param int value
* @return self
* @static
*/
public static func limit(value:Int) -> NSFetchRequest{
return self.query.limit(value)
}
/**
* Alias to set the "limit" value of the query.
*
* @param int value
* @return NSFetchRequest
*/
public static func take(value:Int) -> NSFetchRequest{
return self.query.take(value)
}
/**
* Set the limit and offset for a given page.
*
* @param int page
* @param int perPage
* @return NSFetchRequest
*/
public static func forPage(page:Int,_ perPage:Int) -> NSFetchRequest{
return self.query.forPage(page,perPage)
}
public static func all() -> [NSManagedObject] {
return self.query.get()
}
public static func count() -> Int {
return self.query.count()
}
public static func updateOrCreate(unique:[String:AnyObject],data:[String:AnyObject]) -> NSManagedObject{
if let object = self.find(unique) {
object.update(data)
return object
}else{
return self.create(data)
}
}
public static func findOrCreate(properties: [String:AnyObject]) -> NSManagedObject {
let transformed = self.transformProperties(properties)
let existing = self.find(properties)
return existing ?? self.create(transformed)
}
public static func find(condition: AnyObject) -> NSManagedObject? {
return self.query.condition(condition).first()
}
public func update(properties: [String:AnyObject]) {
if (properties.count == 0) {
return
}
let context = self.defaultContext()
let transformed = self.dynamicType.transformProperties(properties)
//Finish
for (key, value) in transformed {
self.willChangeValueForKey(key)
self.setSafeValue(value, forKey: key)
self.didChangeValueForKey(key)
}
}
public func save() -> Bool {
return self.defaultContext().save()
}
public func delete() -> NSManagedObject {
let context = self.defaultContext()
context.deleteObject(self)
return self
}
public static func deleteAll() -> NSManagedObjectContext{
for o in self.all() {
o.delete()
}
return self.defaultContext()
}
public static func create() -> NSManagedObject {
let o = NSEntityDescription.insertNewObjectForEntityForName(self.entityName(), inManagedObjectContext: self.defaultContext()) as! NSManagedObject
if let idprop = self.autoIncrementingId() {
o.setPrimitiveValue(NSNumber(integer: self.nextId()), forKey: idprop)
}
return o
}
public static func create(properties: [String:AnyObject]) -> NSManagedObject {
let newEntity: NSManagedObject = self.create()
newEntity.update(properties)
if let idprop = self.autoIncrementingId() {
if newEntity.primitiveValueForKey(idprop) == nil {
newEntity.setPrimitiveValue(NSNumber(integer: self.nextId()), forKey: idprop)
}
}
return newEntity
}
public static func autoIncrements() -> Bool {
return self.autoIncrementingId() != nil
}
public static func nextId() -> Int {
let key = "SwiftRecord-" + self.entityName() + "-ID"
if let idprop = self.autoIncrementingId() {
let id = NSUserDefaults.standardUserDefaults().integerForKey(key)
NSUserDefaults.standardUserDefaults().setInteger(id + 1, forKey: key)
return id
}
return 0
}
public class func autoIncrementingId() -> String? {
return nil
}
//Private
private static func transformProperties(properties: [String:AnyObject]) -> [String:AnyObject]{
let entity = NSEntityDescription.entityForName(self.entityName(), inManagedObjectContext: self.defaultContext())!
let attrs = entity.attributesByName
let rels = entity.relationshipsByName
var transformed = [String:AnyObject]()
for (key, value) in properties {
let localKey = self.keyForRemoteKey(key)
if attrs[localKey] != nil {
transformed[localKey] = value
} else if let rel = rels[localKey] as? NSRelationshipDescription {
if EasyORM.generateRelationships {
if rel.toMany {
if let array = value as? [[String:AnyObject]] {
transformed[localKey] = self.generateSet(rel, array: array)
} else {
#if DEBUG
println("Invalid value for relationship generation in \(NSStringFromClass(self)).\(localKey)")
println(value)
#endif
}
} else if let dict = value as? [String:AnyObject] {
transformed[localKey] = self.generateObject(rel, dict: dict)
} else {
#if DEBUG
println("Invalid value for relationship generation in \(NSStringFromClass(self)).\(localKey)")
println(value)
#endif
}
}
}
}
return transformed
}
private func setSafeValue(value: AnyObject?, forKey key: String) {
if (value == nil) {
self.setNilValueForKey(key)
return
}
let val: AnyObject = value!
if let attr = self.entity.attributesByName[key] as? NSAttributeDescription {
let attrType = attr.attributeType
if attrType == NSAttributeType.StringAttributeType && value is NSNumber {
self.setPrimitiveValue((val as! NSNumber).stringValue, forKey: key)
} else if let s = val as? String {
if self.isIntegerAttributeType(attrType) {
self.setPrimitiveValue(NSNumber(integer: val.integerValue), forKey: key)
return
} else if attrType == NSAttributeType.BooleanAttributeType {
self.setPrimitiveValue(NSNumber(bool: val.boolValue), forKey: key)
return
} else if (attrType == NSAttributeType.FloatAttributeType) {
self.setPrimitiveValue(NSNumber(floatLiteral: val.doubleValue), forKey: key)
return
} else if (attrType == NSAttributeType.DateAttributeType) {
self.setPrimitiveValue(self.dynamicType.dateFormatter.dateFromString(s), forKey: key)
return
}
}
}
self.setPrimitiveValue(value, forKey: key)
}
private func isIntegerAttributeType(attrType: NSAttributeType) -> Bool {
return attrType == NSAttributeType.Integer16AttributeType || attrType == NSAttributeType.Integer32AttributeType || attrType == NSAttributeType.Integer64AttributeType
}
private static var dateFormatter: NSDateFormatter {
if _dateFormatter == nil {
_dateFormatter = NSDateFormatter()
_dateFormatter!.dateFormat = "yyyy-MM-dd HH:mm:ss z"
}
return _dateFormatter!
}
private static var _dateFormatter: NSDateFormatter?
public class func mappings() -> [String:String] {
return [String:String]()
}
public static func keyForRemoteKey(remote: String) -> String {
if let s = cachedMappings[remote] {
return s
}
let entity = NSEntityDescription.entityForName(self.entityName(), inManagedObjectContext: self.defaultContext())!
let properties = entity.propertiesByName
if properties[entity.propertiesByName] != nil {
_cachedMappings![remote] = remote
return remote
}
let camelCased = remote.camelCase
if properties[camelCased] != nil {
_cachedMappings![remote] = camelCased
return camelCased
}
_cachedMappings![remote] = remote
return remote
}
private static var cachedMappings: [String:String] {
if let m = _cachedMappings {
return m
} else {
var m = [String:String]()
for (key, value) in mappings() {
m[value] = key
}
_cachedMappings = m
return m
}
}
private static var _cachedMappings: [String:String]?
private static func generateSet(rel: NSRelationshipDescription, array: [[String:AnyObject]]) -> NSSet {
var cls: NSManagedObject.Type?
if EasyORM.nameToEntities.count > 0 {
cls = EasyORM.nameToEntities[rel.destinationEntity!.managedObjectClassName]
}
if cls == nil {
cls = (NSClassFromString(rel.destinationEntity!.managedObjectClassName) as! NSManagedObject.Type)
} else {
println("Got class name from entity setup")
}
var set = NSMutableSet()
for d in array {
set.addObject(cls!.findOrCreate(d))
}
return set
}
private static func generateObject(rel: NSRelationshipDescription, dict: [String:AnyObject]) -> NSManagedObject {
var entity = rel.destinationEntity!
var cls: NSManagedObject.Type = NSClassFromString(entity.managedObjectClassName) as! NSManagedObject.Type
return cls.findOrCreate(dict)
}
public static func primaryKey() -> String {
NSException(name: "Primary key undefined in " + NSStringFromClass(self), reason: "Override primaryKey if you want to support automatic creation, otherwise disable this feature", userInfo: nil).raise()
return ""
}
private static func entityName() -> String {
var name = NSStringFromClass(self)
if name.rangeOfString(".") != nil {
let comp = split(name) {$0 == "."}
if comp.count > 1 {
name = comp.last!
}
}
if name.rangeOfString("_") != nil {
var comp = split(name) {$0 == "_"}
var last: String = ""
var remove = -1
for (i,s) in enumerate(comp.reverse()) {
if last == s {
remove = i
}
last = s
}
if remove > -1 {
comp.removeAtIndex(remove)
name = "_".join(comp)
}
}
return name
}
}
public extension String {
var camelCase: String {
let spaced = self.stringByReplacingOccurrencesOfString("_", withString: " ", options: nil, range:Range<String.Index>(start: self.startIndex, end: self.endIndex))
let capitalized = spaced.capitalizedString
let spaceless = capitalized.stringByReplacingOccurrencesOfString(" ", withString: "", options:nil, range:Range<String.Index>(start:self.startIndex, end:self.endIndex))
return spaceless.stringByReplacingCharactersInRange(Range<String.Index>(start:spaceless.startIndex, end:spaceless.startIndex.successor()), withString: "\(spaceless[spaceless.startIndex])".lowercaseString)
}
}
| mit |
kylef/Stencil | Sources/_SwiftSupport.swift | 1 | 185 | import Foundation
#if !swift(>=4.2)
extension ArraySlice where Element: Equatable {
func firstIndex(of element: Element) -> Int? {
return index(of: element)
}
}
#endif
| bsd-2-clause |
Ethenyl/JAMFKit | JamfKit/Sources/Models/DirectoryBinding.swift | 1 | 3988 | //
// Copyright © 2017-present JamfKit. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
/// Represents a logical binding between a computer and an active directory user.
@objc(JMFKDirectoryBinding)
public final class DirectoryBinding: BaseObject, Endpoint {
// MARK: - Constants
public static let Endpoint = "directorybindings"
static let PriorityKey = "priority"
static let DomainKey = "domain"
static let UsernameKey = "username"
static let PasswordKey = "password"
static let ComputerOrganisationalUnitKey = "computer_ou"
static let TypeKey = "type"
// MARK: - Properties
@objc
public var priority: UInt = 0
@objc
public var domain = ""
@objc
public var username = ""
@objc
public var password = ""
@objc
public var computerOrganisationalUnit = ""
@objc
public var type = ""
// MARK: - Initialization
public required init?(json: [String: Any], node: String = "") {
priority = json[DirectoryBinding.PriorityKey] as? UInt ?? 0
domain = json[DirectoryBinding.DomainKey] as? String ?? ""
username = json[DirectoryBinding.UsernameKey] as? String ?? ""
password = json[DirectoryBinding.PasswordKey] as? String ?? ""
computerOrganisationalUnit = json[DirectoryBinding.ComputerOrganisationalUnitKey] as? String ?? ""
type = json[DirectoryBinding.TypeKey] as? String ?? ""
super.init(json: json)
}
public override init?(identifier: UInt, name: String) {
super.init(identifier: identifier, name: name)
}
// MARK: - Functions
public override func toJSON() -> [String: Any] {
var json = super.toJSON()
json[DirectoryBinding.PriorityKey] = priority
json[DirectoryBinding.DomainKey] = domain
json[DirectoryBinding.UsernameKey] = username
json[DirectoryBinding.PasswordKey] = password
json[DirectoryBinding.ComputerOrganisationalUnitKey] = computerOrganisationalUnit
json[DirectoryBinding.TypeKey] = type
return json
}
}
// MARK: - Creatable
extension DirectoryBinding: Creatable {
public func createRequest() -> URLRequest? {
return getCreateRequest()
}
}
// MARK: - Readable
extension DirectoryBinding: Readable {
public static func readAllRequest() -> URLRequest? {
return getReadAllRequest()
}
public static func readRequest(identifier: String) -> URLRequest? {
return getReadRequest(identifier: identifier)
}
public func readRequest() -> URLRequest? {
return getReadRequest()
}
/// Returns a GET **URLRequest** based on the supplied name.
public static func readRequest(name: String) -> URLRequest? {
return getReadRequest(name: name)
}
/// Returns a GET **URLRequest** based on the email.
public func readRequestWithName() -> URLRequest? {
return getReadRequestWithName()
}
}
// MARK: - Updatable
extension DirectoryBinding: Updatable {
public func updateRequest() -> URLRequest? {
return getUpdateRequest()
}
/// Returns a PUT **URLRequest** based on the name.
public func updateRequestWithName() -> URLRequest? {
return getUpdateRequestWithName()
}
}
// MARK: - Deletable
extension DirectoryBinding: Deletable {
public static func deleteRequest(identifier: String) -> URLRequest? {
return getDeleteRequest(identifier: identifier)
}
public func deleteRequest() -> URLRequest? {
return getDeleteRequest()
}
/// Returns a DELETE **URLRequest** based on the supplied name.
public static func deleteRequest(name: String) -> URLRequest? {
return getDeleteRequest(name: name)
}
/// Returns a DELETE **URLRequest** based on the name.
public func deleteRequestWithName() -> URLRequest? {
return getDeleteRequestWithName()
}
}
| mit |
Jnosh/swift | test/Runtime/crash_without_backtrace.swift | 4 | 517 | // RUN: rm -rf %t
// RUN: mkdir %t
// RUN: %target-build-swift %s -o %t/out
// RUN: not --crash %t/out 2>&1 | %FileCheck %s
// UNSUPPORTED: OS=watchos
// UNSUPPORTED: OS=ios
// UNSUPPORTED: OS=tvos
// REQUIRES: swift_stdlib_no_asserts
// REQUIRES: executable_test
// This file just causes a crash in the runtime to check whether or not a stack
// trace is produced from the runtime.
// CHECK-NOT: Current stack trace:
import Swift
func foo() -> Int {
return UnsafePointer<Int>(bitPattern: 0)!.pointee
}
foo()
| apache-2.0 |
kysonyangs/ysbilibili | ysbilibili/Classes/Player/NormalPlayer/ViewModel/ZHNnormalPlayerViewModel.swift | 1 | 3315 | //
// ZHNnormalPlayerViewModel.swift
// zhnbilibili
//
// Created by zhn on 16/12/14.
// Copyright © 2016年 zhn. All rights reserved.
//
import UIKit
import SwiftyJSON
import Alamofire
import HandyJSON
/// 获取视频播放url成功的通知
let kgetPlayUrlSuccessNotification = Notification.Name("kgetPlayUrlSuccessNotification")
class ZHNnormalPlayerViewModel {
/// 视频播放的url
var playerUrl: String?
/// 弹幕的数据数组
var danmuModelArray: [danmuModel]?
/// 视频的相关数据
var detailModel: YSPlayDetailModel?
func requestData(aid: Int,finishCallBack:@escaping ()->(),failueCallBack:@escaping ()->()) {
let urlStr = "http://app.bilibili.com/x/view?actionKey=appkey&aid=\(aid)&appkey=27eb53fc9058f8c3&build=3380"
print(urlStr)
YSNetworkTool.shared.requestData(.get, URLString: urlStr, finished: { (result) in
let resultJson = JSON(result)
// 1. 获取视频的相关数据
self.detailModel = JSONDeserializer<YSPlayDetailModel>.deserializeFrom(dict: resultJson["data"].dictionaryObject as NSDictionary?)
// 2. 获取播放的url和弹幕
let dict = resultJson["data"]["pages"].array?.first?.dictionaryObject
guard let cid = dict?["cid"] as? Int else {return}
guard let page = dict?["page"] as? Int else {return}
let group = DispatchGroup()
// <1.获取视频播放的url
group.enter()
VideoURL.getWithAid(aid, cid: cid, page: page, completionBlock: { (url) in
guard let urlStr = url?.absoluteString else {return}
self.playerUrl = urlStr
NotificationCenter.default.post(name: kgetPlayUrlSuccessNotification, object: nil)
group.leave()
})
// <2.获取弹幕数据
self.requestDanmuStatus(cid: cid, group: group)
group.notify(queue: DispatchQueue.main, execute: {
finishCallBack()
})
}) { (error) in
failueCallBack()
}
}
func requestDanmuStatus(cid: Int,group: DispatchGroup) {
group.enter()
self.danmuModelArray?.removeAll()
let URLString = "http://comment.bilibili.com/\(cid).xml"
Alamofire.request(URLString, method: .get, parameters: nil).responseData { (response) in
guard let result = try? XMLReader.dictionary(forXMLData: response.data) else {return}
self.danmuModelArray = danmuModel.modelArray(dict: result)
group.leave()
}
}
func requestPagePlayUrl(page: Int,cid: Int,finishAction:@escaping (()->Void)) {
let group = DispatchGroup()
group.enter()
VideoURL.getWithAid((detailModel?.aid)!, cid: cid, page: page, completionBlock: { (url) in
guard let urlStr = url?.absoluteString else {return}
self.playerUrl = urlStr
NotificationCenter.default.post(name: kgetPlayUrlSuccessNotification, object: nil)
group.leave()
})
requestDanmuStatus(cid: cid, group: group)
group.notify(queue: DispatchQueue.main) {
finishAction()
}
}
}
| mit |
googlearchive/science-journal-ios | ScienceJournal/Sensors/MotionSensor.swift | 1 | 1271 | /*
* 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 CoreMotion
import Foundation
/// A sensor that uses a motion manager to collect data from the device.
class MotionSensor: Sensor {
/// The motion manager for the motion manager sensor.
///
/// Important: An app should create only a single instance of the CMMotionManager class. Multiple
/// instances of this class can affect the rate at which data is received from the accelerometer
/// and gyroscope.
static let motionManager = CMMotionManager()
/// The interval at which to have the motion sensor update its data. 0.01 is suggested when using
/// the "pull" method of accessing data.
let updateInterval = 0.01
}
| apache-2.0 |
linkedin/LayoutKit | Sources/ObjCSupport/LOKLayout.swift | 1 | 6222 | // Copyright 2018 LinkedIn Corp.
// 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.
import CoreGraphics
/**
A protocol for types that layout view frames.
### Basic layouts
Many UIs can be expressed by composing the basic layouts that LayoutKit provides:
- `LOKLabelLayout`
- `LOKInsetLayout`
- `LOKSizeLayout`
- `LOKStackLayout`
If your UI can not be expressed by composing these basic layouts,
then you can create a custom layout. Custom layouts are recommended but not required to conform
to the `ConfigurableLayout` protocol due to the type safety and default implementation that it adds.
### Layout algorithm
Layout is performed in two steps:
1. `measurement(within:)`
2. `arrangement(within:measurement:)`.
### Threading
Layouts MUST be thread-safe.
*/
@objc public protocol LOKLayout {
/**
Measures the minimum size of the layout and its sublayouts.
It MAY be run on a background thread.
- parameter maxSize: The maximum size available to the layout.
- returns: The minimum size required by the layout and its sublayouts given a maximum size.
The size of the layout MUST NOT exceed `maxSize`.
*/
@objc func measurement(within maxSize: CGSize) -> LOKLayoutMeasurement
/**
Returns the arrangement of frames for the layout inside a given rect.
The frames SHOULD NOT overflow rect, otherwise they may overlap with adjacent layouts.
The layout MAY choose to not use the entire rect (and instead align itself in some way inside of the rect),
but the caller SHOULD NOT reallocate unused space to other layouts because this could break the layout's desired alignment and padding.
Space allocation SHOULD happen during the measure pass.
MAY be run on a background thread.
- parameter rect: The rectangle that the layout must position itself in.
- parameter measurement: A measurement which has size less than or equal to `rect.size` and greater than or equal to `measurement.maxSize`.
- returns: A complete set of frames for the layout.
*/
@objc func arrangement(within rect: CGRect, measurement: LOKLayoutMeasurement) -> LOKLayoutArrangement
/**
Indicates whether a View object needs to be created for this layout.
Layouts that just position their sublayouts can return `false` here.
*/
@objc var needsView: Bool { get }
/**
Returns a new `UIView` for the layout.
It is not called on a layout if the layout is using a recycled view.
MUST be run on the main thread.
*/
@objc func makeView() -> View
/**
Configures the given view.
MUST be run on the main thread.
*/
@objc func configureView(_ view: View)
/**
The flexibility of the layout.
If a layout has a single sublayout, it SHOULD inherit the flexiblity of its sublayout.
If a layout has no sublayouts (e.g. `LOKLabelLayout`), it SHOULD allow its flexibility to be configured.
All layouts SHOULD provide a default flexiblity.
TODO: figure out how to assert if inflexible layouts are compressed.
*/
@objc var flexibility: LOKFlexibility { get }
/**
An identifier for the view that is produced by this layout.
If this layout is applied to an existing view hierarchy, and if there is a view with an identical viewReuseId,
then that view will be reused for the new layout. If there is more than one view with the same viewReuseId, then an arbitrary one will be reused.
*/
@objc var viewReuseId: String? { get }
}
extension LOKLayout {
var unwrapped: Layout {
/*
Need to check to see if `self` is one of the LayoutKit provided layouts.
If so, we want to cast it as `LOKBaseLayout` and return the wrapped layout
object directly.
If `self` is not one of the LayoutKit provided layouts, we want to wrap it
so that the methods of the class are called. We do this to make sure that if
someone were to subclass one of the LayoutKit provided layouts, we would want
to call their overriden methods instead of just the underlying layout object directly.
Certain platforms don't have certain layouts, so we make a different array for each platform
with only the layouts that it supports.
*/
let allLayoutClasses: [AnyClass]
#if os(OSX)
allLayoutClasses = [
LOKInsetLayout.self,
LOKOverlayLayout.self,
LOKSizeLayout.self,
LOKStackLayout.self
]
#elseif os(tvOS)
allLayoutClasses = [
LOKInsetLayout.self,
LOKOverlayLayout.self,
LOKTextViewLayout.self,
LOKButtonLayout.self,
LOKSizeLayout.self,
LOKStackLayout.self
]
#else
allLayoutClasses = [
LOKInsetLayout.self,
LOKOverlayLayout.self,
LOKTextViewLayout.self,
LOKButtonLayout.self,
LOKLabelLayout.self,
LOKSizeLayout.self,
LOKStackLayout.self
]
#endif
if let object = self as? NSObject {
if allLayoutClasses.contains(where: { object.isMember(of: $0) }) {
// Executes if `self` is one of the LayoutKit provided classes; not if it's a subclass
guard let layout = (self as? LOKBaseLayout)?.layout else {
assertionFailure("LayoutKit provided layout does not inherit from LOKBaseLayout")
return ReverseWrappedLayout(layout: self)
}
return layout
}
}
return (self as? WrappedLayout)?.layout ?? ReverseWrappedLayout(layout: self)
}
}
| apache-2.0 |
ivlasov/EvoShare | EvoShareSwift/QRCodeController.swift | 2 | 2888 | //
// QRCodeController.swift
// EvoShareSwift
//
// Created by Ilya Vlasov on 12/24/14.
// Copyright (c) 2014 mtu. All rights reserved.
//
import Foundation
import UIKit
class QRCodeController : UIViewController, ConnectionManagerDelegate {
@IBOutlet weak var qrimage: UIImageView!
@IBOutlet weak var activityIndicator: UIImageView!
var promoGuid : String?
var checkID : Int = 0
var summ : Double = 0
var currency : String?
@IBAction func cancelTapped(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
}
override func viewDidAppear(animated: Bool) {
self.rotateLayerInfinity(self.activityIndicator.layer)
}
override func viewDidDisappear(animated: Bool) {
self.activityIndicator.layer.removeAllAnimations()
}
override func viewDidLoad() {
let imgURLString = "http://service.evo-share.com/image.ashx?i=qr&t=\(EVOUidSingleton.sharedInstance.userID())|\(promoGuid)"
let awesomeURL = imgURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL(string: awesomeURL!)
var err: NSError?
var imageData: NSData = NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingMapped, error: &err)!
var relatedPromoImage = UIImage(data:imageData)
qrimage.image = relatedPromoImage
}
override func didReceiveMemoryWarning() {
//
}
func rotateLayerInfinity(layer:CALayer) {
var rotation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotation.fromValue = NSNumber(float: 0)
rotation.toValue = NSNumber(floatLiteral: 2*M_PI)
rotation.duration = 1.1
rotation.repeatCount = HUGE
layer.removeAllAnimations()
layer.addAnimation(rotation, forKey: "Spin")
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "offerSegue" {
var confirmControlelr = segue.destinationViewController as! OfferController
ConnectionManager.sharedInstance.delegate = confirmControlelr
var price : String = String(format: "%.2f", summ)
confirmControlelr.summ = price
confirmControlelr.curr = currency
confirmControlelr.checkID = checkID
}
}
}
extension QRCodeController : ConnectionManagerDelegate {
func connectionManagerDidRecieveObject(responseObject: AnyObject) {
activityIndicator.layer.removeAllAnimations()
let responseDict = responseObject as! Dictionary<String,AnyObject>
summ = responseDict["SUM"] as! Double
currency = responseDict["CUR"] as? String
checkID = responseDict["CID"] as! Int
performSegueWithIdentifier("offerSegue", sender: self)
}
} | unlicense |
dekatotoro/SlideMenuControllerSwift | SlideMenuControllerSwift/SwiftViewController.swift | 5 | 442 | //
// SwiftViewController.swift
// SlideMenuControllerSwift
//
// Created by Yuji Hato on 1/19/15.
// Copyright (c) 2015 Yuji Hato. All rights reserved.
//
import UIKit
class SwiftViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.setNavigationBarItem()
}
}
| mit |
ytbryan/swiftknife | project/project/AppDelegate.swift | 1 | 7581 | //
// AppDelegate.swift
// project
//
// Created by Bryan Lim on 10/22/14.
// Copyright (c) 2014 TADA. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as UINavigationController
navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
let masterNavigationController = splitViewController.viewControllers[0] as UINavigationController
let controller = masterNavigationController.topViewController as MasterViewController
controller.managedObjectContext = self.managedObjectContext
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
}
return false
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.tada.project" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("project", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("project.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit |
a2/Simon | SimonKit/Color.swift | 1 | 394 | public enum Color: Int {
case Red
case Green
case Yellow
case Blue
}
extension Color: CustomStringConvertible {
public var description: String {
switch self {
case .Red:
return "Red"
case .Green:
return "Green"
case .Yellow:
return "Yellow"
case .Blue:
return "Blue"
}
}
}
| mit |
el-hoshino/NotAutoLayout | Sources/NotAutoLayout/LayoutMaker/MakerBasics/LayoutPropertyCanStoreRightType.swift | 1 | 2394 | //
// LayoutPropertyCanStoreRightType.swift
// NotAutoLayout
//
// Created by 史翔新 on 2017/11/12.
// Copyright © 2017年 史翔新. All rights reserved.
//
import UIKit
public protocol LayoutPropertyCanStoreRightType: LayoutMakerPropertyType {
associatedtype WillSetRightProperty: LayoutMakerPropertyType
func storeRight(_ right: LayoutElement.Horizontal) -> WillSetRightProperty
}
private extension LayoutMaker where Property: LayoutPropertyCanStoreRightType {
func storeRight(_ right: LayoutElement.Horizontal) -> LayoutMaker<Property.WillSetRightProperty> {
let newProperty = self.didSetProperty.storeRight(right)
let newMaker = self.changintProperty(to: newProperty)
return newMaker
}
}
extension LayoutMaker where Property: LayoutPropertyCanStoreRightType {
public func setRight(to right: Float) -> LayoutMaker<Property.WillSetRightProperty> {
let right = LayoutElement.Horizontal.constant(right)
let maker = self.storeRight(right)
return maker
}
public func setRight(by right: @escaping (_ property: ViewLayoutGuides) -> Float) -> LayoutMaker<Property.WillSetRightProperty> {
let right = LayoutElement.Horizontal.byParent(right)
let maker = self.storeRight(right)
return maker
}
public func pinRight(to referenceView: UIView?, with right: @escaping (ViewPinGuides.Horizontal) -> Float) -> LayoutMaker<Property.WillSetRightProperty> {
return self.pinRight(by: { [weak referenceView] in referenceView }, with: right)
}
public func pinRight(by referenceView: @escaping () -> UIView?, with right: @escaping (ViewPinGuides.Horizontal) -> Float) -> LayoutMaker<Property.WillSetRightProperty> {
let right = LayoutElement.Horizontal.byReference(referenceGetter: referenceView, right)
let maker = self.storeRight(right)
return maker
}
}
public protocol LayoutPropertyCanStoreRightToEvaluateFrameType: LayoutPropertyCanStoreRightType {
func evaluateFrame(right: LayoutElement.Horizontal, parameters: IndividualFrameCalculationParameters) -> Rect
}
extension LayoutPropertyCanStoreRightToEvaluateFrameType {
public func storeRight(_ right: LayoutElement.Horizontal) -> IndividualProperty.Layout {
let layout = IndividualProperty.Layout(frame: { (parameters) -> Rect in
return self.evaluateFrame(right: right, parameters: parameters)
})
return layout
}
}
| apache-2.0 |
stripe/stripe-ios | StripeCardScan/StripeCardScan/Source/CardScan/UI/ScanConfiguration.swift | 1 | 209 | import Foundation
enum ScanPerformance: Int {
case fast
case accurate
}
class ScanConfiguration: NSObject {
var runOnOldDevices = false
var setPreviouslyDeniedDevicesAsIncompatible = false
}
| mit |
dbruzzone/wishing-tree | iOS/Type/Type/ViewController.swift | 1 | 510 | //
// ViewController.swift
// Type
//
// Created by Davide Bruzzone on 11/29/15.
// Copyright © 2015 Bitwise Samurai. 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.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 |
fgengine/quickly | Quickly/Compositions/Standart/QListFieldComposition.swift | 1 | 5760 | //
// Quickly
//
open class QListFieldComposable : QComposable {
public typealias ShouldClosure = (_ composable: QListFieldComposable) -> Bool
public typealias Closure = (_ composable: QListFieldComposable) -> Void
public var fieldStyle: QListFieldStyleSheet
public var selectedRow: QListFieldPickerRow?
public var height: CGFloat
public var isValid: Bool{
get { return self.selectedRow != nil }
}
public var isEditing: Bool
public var shouldBeginEditing: ShouldClosure?
public var beginEditing: Closure?
public var select: Closure?
public var shouldEndEditing: ShouldClosure?
public var endEditing: Closure?
public init(
edgeInsets: UIEdgeInsets = UIEdgeInsets.zero,
fieldStyle: QListFieldStyleSheet,
height: CGFloat = 44,
selectedRow: QListFieldPickerRow? = nil,
shouldBeginEditing: ShouldClosure? = nil,
beginEditing: Closure? = nil,
select: Closure? = nil,
shouldEndEditing: ShouldClosure? = nil,
endEditing: Closure? = nil
) {
self.fieldStyle = fieldStyle
self.selectedRow = selectedRow
self.height = height
self.isEditing = false
self.shouldBeginEditing = shouldBeginEditing
self.beginEditing = beginEditing
self.select = select
self.shouldEndEditing = shouldEndEditing
self.endEditing = endEditing
super.init(edgeInsets: edgeInsets)
}
}
open class QListFieldComposition< Composable: QListFieldComposable > : QComposition< Composable >, IQEditableComposition {
public lazy private(set) var fieldView: QListField = {
let view = QListField(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
view.onShouldBeginEditing = { [weak self] _ in return self?._shouldBeginEditing() ?? true }
view.onBeginEditing = { [weak self] _ in self?._beginEditing() }
view.onSelect = { [weak self] listField, composable in self?._select(composable) }
view.onShouldEndEditing = { [weak self] _ in return self?._shouldEndEditing() ?? true }
view.onEndEditing = { [weak self] _ in self?._endEditing() }
self.contentView.addSubview(view)
return view
}()
private var _edgeInsets: UIEdgeInsets?
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.contentView.removeConstraints(self._constraints) }
didSet { self.contentView.addConstraints(self._constraints) }
}
open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize {
return CGSize(
width: spec.containerSize.width,
height: composable.edgeInsets.top + composable.height + composable.edgeInsets.bottom
)
}
deinit {
if let observer = self.owner as? IQListFieldObserver {
self.fieldView.remove(observer: observer)
}
}
open override func setup(owner: AnyObject) {
super.setup(owner: owner)
if let observer = owner as? IQListFieldObserver {
self.fieldView.add(observer: observer, priority: 0)
}
}
open override func preLayout(composable: Composable, spec: IQContainerSpec) {
if self._edgeInsets != composable.edgeInsets {
self._edgeInsets = composable.edgeInsets
self._constraints = [
self.fieldView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.fieldView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left),
self.fieldView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right),
self.fieldView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom)
]
}
}
open override func apply(composable: Composable, spec: IQContainerSpec) {
self.fieldView.apply(composable.fieldStyle)
}
open override func postLayout(composable: Composable, spec: IQContainerSpec) {
self.fieldView.selectedRow = composable.selectedRow
}
// MARK: IQCompositionEditable
open func beginEditing() {
self.fieldView.beginEditing()
}
open func endEditing() {
self.fieldView.endEditing(false)
}
// MARK: Private
private func _shouldBeginEditing() -> Bool {
guard let composable = self.composable else { return true }
if let closure = composable.shouldBeginEditing {
return closure(composable)
}
return true
}
private func _beginEditing() {
guard let composable = self.composable else { return }
composable.selectedRow = self.fieldView.selectedRow
composable.isEditing = self.fieldView.isEditing
if let closure = composable.beginEditing {
closure(composable)
}
}
private func _select(_ pickerRow: QListFieldPickerRow) {
guard let composable = self.composable else { return }
composable.selectedRow = pickerRow
if let closure = composable.select {
closure(composable)
}
}
private func _shouldEndEditing() -> Bool {
guard let composable = self.composable else { return true }
if let closure = composable.shouldEndEditing {
return closure(composable)
}
return true
}
private func _endEditing() {
guard let composable = self.composable else { return }
composable.isEditing = self.fieldView.isEditing
if let closure = composable.endEditing {
closure(composable)
}
}
}
| mit |
remirobert/Dotzu | Framework/Dotzu/Dotzu/InformationsTableViewController.swift | 2 | 1576 | //
// InformationsTableViewController.swift
// exampleWindow
//
// Created by Remi Robert on 18/01/2017.
// Copyright © 2017 Remi Robert. All rights reserved.
//
import UIKit
class InformationsTableViewController: UITableViewController {
@IBOutlet weak var labelVersionNumber: UILabel!
@IBOutlet weak var labelBuildNumber: UILabel!
@IBOutlet weak var labelBundleName: UILabel!
@IBOutlet weak var labelScreenResolution: UILabel!
@IBOutlet weak var labelScreenSize: UILabel!
@IBOutlet weak var labelDeviceModel: UILabel!
@IBOutlet weak var labelCrashCount: UILabel!
var device: Device = Device()
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let store = StoreManager<LogCrash>(store: .crash)
let count = store.logs().count
labelCrashCount.text = "\(count)"
labelCrashCount.textColor = count > 0 ? UIColor.red : UIColor.white
}
override func viewDidLoad() {
super.viewDidLoad()
labelCrashCount.frame.size = CGSize(width: 30, height: 20)
labelVersionNumber.text = ApplicationInformation.versionNumber
labelBuildNumber.text = ApplicationInformation.buildNumber
labelBundleName.text = ApplicationInformation.bundleName
labelScreenResolution.text = self.device.screenResolution
labelScreenSize.text = "\(self.device.screenSize)"
labelDeviceModel.text = "\(self.device.deviceModel)"
}
}
| mit |
meteochu/HanekeSwift | Haneke/UIImageView+Haneke.swift | 1 | 5624 | //
// UIImageView+Haneke.swift
// Haneke
//
// Created by Hermes Pique on 9/17/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
public extension UIImageView {
public var hnk_format : Format<UIImage> {
let viewSize = self.bounds.size
assert(viewSize.width > 0 && viewSize.height > 0, "[\(Mirror(reflecting: self).description) \(#function)]: UImageView size is zero. Set its frame, call sizeToFit or force layout first.")
let scaleMode = self.hnk_scaleMode
return HanekeGlobals.UIKit.formatWithSize(size: viewSize, scaleMode: scaleMode)
}
public func hnk_setImageFromURL(URL: URL, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) {
let fetcher = NetworkFetcher<UIImage>(url: URL)
self.hnk_setImageFromFetcher(fetcher: fetcher, placeholder: placeholder, format: format, failure: fail, success: succeed)
}
public func hnk_setImage( image: @autoclosure @escaping () -> UIImage, key: String, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, success succeed : ((UIImage) -> ())? = nil) {
let fetcher = SimpleFetcher<UIImage>(key: key, value: image)
self.hnk_setImageFromFetcher(fetcher: fetcher, placeholder: placeholder, format: format, success: succeed)
}
public func hnk_setImageFromFile(path: String, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) {
let fetcher = DiskFetcher<UIImage>(path: path)
self.hnk_setImageFromFetcher(fetcher: fetcher, placeholder: placeholder, format: format, failure: fail, success: succeed)
}
public func hnk_setImageFromFetcher(fetcher : Fetcher<UIImage>,
placeholder : UIImage? = nil,
format : Format<UIImage>? = nil,
failure fail : ((NSError?) -> ())? = nil,
success succeed : ((UIImage) -> ())? = nil) {
self.hnk_cancelSetImage()
self.hnk_fetcher = fetcher
let didSetImage = self.hnk_fetchImageForFetcher(fetcher: fetcher, format: format, failure: fail, success: succeed)
if didSetImage { return }
if let placeholder = placeholder {
self.image = placeholder
}
}
public func hnk_cancelSetImage() {
if let fetcher = self.hnk_fetcher {
fetcher.cancelFetch()
self.hnk_fetcher = nil
}
}
// MARK: Internal
// See: http://stackoverflow.com/questions/25907421/associating-swift-things-with-nsobject-instances
var hnk_fetcher : Fetcher<UIImage>! {
get {
let wrapper = objc_getAssociatedObject(self, &HanekeGlobals.UIKit.SetImageFetcherKey) as? ObjectWrapper
let fetcher = wrapper?.object as? Fetcher<UIImage>
return fetcher
}
set (fetcher) {
var wrapper : ObjectWrapper?
if let fetcher = fetcher {
wrapper = ObjectWrapper(value: fetcher)
}
objc_setAssociatedObject(self, &HanekeGlobals.UIKit.SetImageFetcherKey, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public var hnk_scaleMode : ImageResizer.ScaleMode {
switch (self.contentMode) {
case .scaleToFill:
return .Fill
case .scaleAspectFit:
return .AspectFit
case .scaleAspectFill:
return .AspectFill
case .redraw, .center, .top, .bottom, .left, .right, .topLeft, .topRight, .bottomLeft, .bottomRight:
return .None
}
}
func hnk_fetchImageForFetcher(fetcher : Fetcher<UIImage>, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())?, success succeed : ((UIImage) -> ())?) -> Bool {
let cache = Shared.imageCache
let format = format ?? self.hnk_format
if cache.formats[format.name] == nil {
cache.addFormat(format: format)
}
var animated = false
let fetch = cache.fetch(fetcher: fetcher, formatName: format.name, failure: {[weak self] error in
if let strongSelf = self {
if strongSelf.hnk_shouldCancelForKey(key: fetcher.key) { return }
strongSelf.hnk_fetcher = nil
fail?(error)
}
}) { [weak self] image in
if let strongSelf = self {
if strongSelf.hnk_shouldCancelForKey(key: fetcher.key) { return }
strongSelf.hnk_setImage(image: image, animated: animated, success: succeed)
}
}
animated = true
return fetch.hasSucceeded
}
func hnk_setImage(image : UIImage, animated : Bool, success succeed : ((UIImage) -> ())?) {
self.hnk_fetcher = nil
if let succeed = succeed {
succeed(image)
} else if animated {
UIView.transition(with: self, duration: HanekeGlobals.UIKit.SetImageAnimationDuration, options: .transitionCrossDissolve, animations: {
self.image = image
}, completion: nil)
} else {
self.image = image
}
}
func hnk_shouldCancelForKey(key:String) -> Bool {
if self.hnk_fetcher?.key == key { return false }
Log.debug(message: "Cancelled set image for \((key as NSString).lastPathComponent)")
return true
}
}
| apache-2.0 |
austinzheng/swift-compiler-crashes | crashes-duplicates/15716-swift-sourcemanager-getmessage.swift | 11 | 264 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var b {
deinit {
protocol A {
struct A {
func compose( ) {
for in x = {
if true {
class
case ,
| mit |
jaksatomovic/Snapgram | Snapgram/signUpVC.swift | 1 | 9105 | //
// signUpVC.swift
// Snapgram
//
// Created by Jaksa Tomovic on 28/11/16.
// Copyright © 2016 Jaksa Tomovic. All rights reserved.
//
import UIKit
import Parse
class signUpVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// profile image
@IBOutlet weak var avaImg: UIImageView!
// textfields
@IBOutlet weak var usernameTxt: UITextField!
@IBOutlet weak var passwordTxt: UITextField!
@IBOutlet weak var repeatPassword: UITextField!
@IBOutlet weak var emailTxt: UITextField!
@IBOutlet weak var fullnameTxt: UITextField!
@IBOutlet weak var bioTxt: UITextField!
@IBOutlet weak var webTxt: UITextField!
// buttons
@IBOutlet weak var signUpBtn: UIButton!
@IBOutlet weak var cancelBtn: UIButton!
// scrollView
@IBOutlet weak var scrollView: UIScrollView!
// reset default size
var scrollViewHeight : CGFloat = 0
// keyboard frame size
var keyboard = CGRect()
// default func
override func viewDidLoad() {
super.viewDidLoad()
// scrollview frame size
scrollView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
scrollView.contentSize.height = self.view.frame.height
scrollViewHeight = scrollView.frame.size.height
// check notifications if keyboard is shown or not
NotificationCenter.default.addObserver(self, selector: #selector(signUpVC.showKeyboard(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(signUpVC.hideKeybard(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
// declare hide kyboard tap
let hideTap = UITapGestureRecognizer(target: self, action: #selector(signUpVC.hideKeyboardTap(_:)))
hideTap.numberOfTapsRequired = 1
self.view.isUserInteractionEnabled = true
self.view.addGestureRecognizer(hideTap)
// round ava
avaImg.layer.cornerRadius = avaImg.frame.size.width / 2
avaImg.clipsToBounds = true
// declare select image tap
let avaTap = UITapGestureRecognizer(target: self, action: #selector(signUpVC.loadImg(_:)))
avaTap.numberOfTapsRequired = 1
avaImg.isUserInteractionEnabled = true
avaImg.addGestureRecognizer(avaTap)
// alignment
avaImg.frame = CGRect(x: self.view.frame.size.width / 2 - 40, y: 40, width: 80, height: 80)
usernameTxt.frame = CGRect(x: 10, y: avaImg.frame.origin.y + 90, width: self.view.frame.size.width - 20, height: 30)
passwordTxt.frame = CGRect(x: 10, y: usernameTxt.frame.origin.y + 40, width: self.view.frame.size.width - 20, height: 30)
repeatPassword.frame = CGRect(x: 10, y: passwordTxt.frame.origin.y + 40, width: self.view.frame.size.width - 20, height: 30)
emailTxt.frame = CGRect(x: 10, y: repeatPassword.frame.origin.y + 60, width: self.view.frame.size.width - 20, height: 30)
fullnameTxt.frame = CGRect(x: 10, y: emailTxt.frame.origin.y + 40, width: self.view.frame.size.width - 20, height: 30)
bioTxt.frame = CGRect(x: 10, y: fullnameTxt.frame.origin.y + 40, width: self.view.frame.size.width - 20, height: 30)
webTxt.frame = CGRect(x: 10, y: bioTxt.frame.origin.y + 40, width: self.view.frame.size.width - 20, height: 30)
signUpBtn.frame = CGRect(x: 20, y: webTxt.frame.origin.y + 50, width: self.view.frame.size.width / 4, height: 30)
signUpBtn.layer.cornerRadius = signUpBtn.frame.size.width / 20
cancelBtn.frame = CGRect(x: self.view.frame.size.width - self.view.frame.size.width / 4 - 20, y: signUpBtn.frame.origin.y, width: self.view.frame.size.width / 4, height: 30)
cancelBtn.layer.cornerRadius = cancelBtn.frame.size.width / 20
// background
let bg = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
bg.image = UIImage(named: "bg.jpg")
bg.layer.zPosition = -1
self.view.addSubview(bg)
}
// call picker to select image
func loadImg(_ recognizer:UITapGestureRecognizer) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}
// connect selected image to our ImageView
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
avaImg.image = info[UIImagePickerControllerEditedImage] as? UIImage
self.dismiss(animated: true, completion: nil)
}
// hide keyboard if tapped
func hideKeyboardTap(_ recoginizer:UITapGestureRecognizer) {
self.view.endEditing(true)
}
// show keyboard
func showKeyboard(_ notification:Notification) {
// define keyboard size
keyboard = (((notification as NSNotification).userInfo?[UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue)!
// move up UI
UIView.animate(withDuration: 0.4, animations: { () -> Void in
self.scrollView.frame.size.height = self.scrollViewHeight - self.keyboard.height
})
}
// hide keyboard func
func hideKeybard(_ notification:Notification) {
// move down UI
UIView.animate(withDuration: 0.4, animations: { () -> Void in
self.scrollView.frame.size.height = self.view.frame.height
})
}
// clicked sign up
@IBAction func signUpBtn_click(_ sender: AnyObject) {
print("sign up pressed")
// dismiss keyboard
self.view.endEditing(true)
// if fields are empty
if (usernameTxt.text!.isEmpty || passwordTxt.text!.isEmpty || repeatPassword.text!.isEmpty || emailTxt.text!.isEmpty || fullnameTxt.text!.isEmpty || bioTxt.text!.isEmpty || webTxt.text!.isEmpty) {
// alert message
let alert = UIAlertController(title: "PLEASE", message: "fill all fields", preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
return
}
// if different passwords
if passwordTxt.text != repeatPassword.text {
// alert message
let alert = UIAlertController(title: "PASSWORDS", message: "do not match", preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
return
}
// send data to server to related collumns
let user = PFUser()
user.username = usernameTxt.text?.lowercased()
user.email = emailTxt.text?.lowercased()
user.password = passwordTxt.text
user["fullname"] = fullnameTxt.text?.lowercased()
user["bio"] = bioTxt.text
user["web"] = webTxt.text?.lowercased()
// in Edit Profile it's gonna be assigned
user["tel"] = ""
user["gender"] = ""
// convert our image for sending to server
let avaData = UIImageJPEGRepresentation(avaImg.image!, 0.5)
let avaFile = PFFile(name: "ava.jpg", data: avaData!)
user["ava"] = avaFile
// save data in server
user.signUpInBackground { (success, error) -> Void in
if success {
print("registered")
// remember looged user
UserDefaults.standard.set(user.username, forKey: "username")
UserDefaults.standard.synchronize()
// call login func from AppDelegate.swift class
let appDelegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.login()
} else {
// show alert message
let alert = UIAlertController(title: "Error", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
}
}
// clicked cancel
@IBAction func cancelBtn_click(_ sender: AnyObject) {
// hide keyboard when pressed cancel
self.view.endEditing(true)
self.dismiss(animated: true, completion: nil)
}
}
| mit |
newtonstudio/cordova-plugin-device | imgly-sdk-ios-master/imglyKit/Backend/Processing/Response Filters/IMGLYEightiesFilter.swift | 1 | 570 | //
// IMGLYEightiesFilter.swift
// imglyKit
//
// Created by Carsten Przyluczky on 24/02/15.
// Copyright (c) 2015 9elements GmbH. All rights reserved.
//
import Foundation
public class IMGLYEightiesFilter: IMGLYResponseFilter {
init() {
super.init(responseName: "Eighties")
self.imgly_displayName = "80s"
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override var filterType:IMGLYFilterType {
get {
return IMGLYFilterType.Eighties
}
}
} | apache-2.0 |
cburrows/swift-protobuf | Tests/SwiftProtobufTests/unittest_import_lite.pb.swift | 2 | 6031 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: google/protobuf/unittest_import_lite.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
//
// This is like unittest_import.proto but with optimize_for = LITE_RUNTIME.
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _3: SwiftProtobuf.ProtobufAPIVersion_3 {}
typealias Version = _3
}
enum ProtobufUnittestImport_ImportEnumLite: SwiftProtobuf.Enum {
typealias RawValue = Int
case importLiteFoo // = 7
case importLiteBar // = 8
case importLiteBaz // = 9
init() {
self = .importLiteFoo
}
init?(rawValue: Int) {
switch rawValue {
case 7: self = .importLiteFoo
case 8: self = .importLiteBar
case 9: self = .importLiteBaz
default: return nil
}
}
var rawValue: Int {
switch self {
case .importLiteFoo: return 7
case .importLiteBar: return 8
case .importLiteBaz: return 9
}
}
}
struct ProtobufUnittestImport_ImportMessageLite {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var d: Int32 {
get {return _d ?? 0}
set {_d = newValue}
}
/// Returns true if `d` has been explicitly set.
var hasD: Bool {return self._d != nil}
/// Clears the value of `d`. Subsequent reads from it will return its default value.
mutating func clearD() {self._d = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _d: Int32? = nil
}
#if swift(>=5.5) && canImport(_Concurrency)
extension ProtobufUnittestImport_ImportMessageLite: @unchecked Sendable {}
#endif // swift(>=5.5) && canImport(_Concurrency)
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "protobuf_unittest_import"
extension ProtobufUnittestImport_ImportEnumLite: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
7: .same(proto: "IMPORT_LITE_FOO"),
8: .same(proto: "IMPORT_LITE_BAR"),
9: .same(proto: "IMPORT_LITE_BAZ"),
]
}
extension ProtobufUnittestImport_ImportMessageLite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".ImportMessageLite"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "d"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularInt32Field(value: &self._d) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
try { if let v = self._d {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)
} }()
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittestImport_ImportMessageLite, rhs: ProtobufUnittestImport_ImportMessageLite) -> Bool {
if lhs._d != rhs._d {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| apache-2.0 |
wbaumann/SmartReceiptsiOS | SmartReceiptsTests/Modules Tests/TripDistancesModuleTest.swift | 2 | 1357 | //
// TripDistancesModuleTest.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 05/06/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
@testable import Cuckoo
@testable import SmartReceipts
import XCTest
import Viperit
class TripDistancesModuleTest: XCTestCase {
var presenter: MockTripDistancesPresenter!
var interactor: MockTripDistancesInteractor!
var hasDistance = true
override func setUp() {
super.setUp()
var module = AppModules.tripDistances.build()
module.injectMock(presenter: MockTripDistancesPresenter().withEnabledSuperclassSpy())
module.injectMock(interactor: MockTripDistancesInteractor().withEnabledSuperclassSpy())
presenter = module.presenter as? MockTripDistancesPresenter
interactor = module.interactor as? MockTripDistancesInteractor
configureStubs()
}
func configureStubs() {
stub(interactor) { mock in
mock.delete(distance: Distance()).then({ distance in
self.hasDistance = false
})
}
}
override func tearDown() {
super.tearDown()
hasDistance = true
}
func testPresenterToInteractor() {
presenter.delete(distance: Distance())
XCTAssertFalse(hasDistance)
}
}
| agpl-3.0 |
ktmswzw/jwtSwiftDemoClient | Temp/TableViewController.swift | 1 | 6199 | //
// TableViewController.swift
// Temp
//
// Created by vincent on 4/2/16.
// Copyright © 2016 xecoder. All rights reserved.
//
import UIKit
import CryptoSwift
import Alamofire
import SwiftyJSON
import AlamofireObjectMapper
class TableViewController: UITableViewController {
let userDefaults = NSUserDefaults.standardUserDefaults()
var books = [Book]()
override func viewDidLoad() {
books.removeAll()
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = self.editButtonItem()
// let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
// self.navigationItem.rightBarButtonItem = addButton
sleep(1)//吐司延时
//refreshData()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
books.removeAll()
super.viewWillAppear(true)
self.refreshData()
}
func insertNewObject(sender: AnyObject) {
getBook()
}
func refreshData()
{
if refreshControl != nil {
refreshControl!.beginRefreshing()
}
refresh(refreshControl!)
}
func getBook()
{
// let random = arc4random_uniform(100)
// let stateMe = random > 50 ? "123123" : "2222222"
// let book = Book(inId: "\(random)", inContent: stateMe, inTitle: "\(random)"+"123", inDate: NSDate() )
// books.append(book)
//
let jwt = JWTTools()
let newDict = Dictionary<String,String>()
let headers = jwt.getHeader(jwt.token, myDictionary: newDict)
Alamofire.request(.GET, "http://192.168.137.1:80/book/all", headers: headers)
.responseArray { (response: Response<[Book], NSError>) in
let bookList = response.result.value
if let list = bookList {
for book in list {
self.books.append(book)
}
self.tableView.reloadData()
}
}
}
@IBAction func refresh(sender: UIRefreshControl) {
books.removeAll()
getBook()
refreshControl!.endRefreshing()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return books.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("BookInfo", forIndexPath: indexPath) as! BookTableViewCell
// Configure the cell...
let bookCell = books[indexPath.row] as Book
cell.title.text = bookCell.title
cell.id.text = bookCell.id
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
cell.content.text = dateFormatter.stringFromDate(bookCell.publicDate)
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
let bookCell = books[indexPath.row] as Book
books.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
let jwt = JWTTools()
let newDict: [String: String] = [:]//["id": bookCell.id]
let headers = jwt.getHeader(jwt.token, myDictionary: newDict)
Alamofire.request(.DELETE, "http://192.168.137.1:80/book/pathDelete/\(bookCell.id)",headers:headers)
.responseJSON { response in
}
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showBook" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = books[indexPath.row] as Book
(segue.destinationViewController as! BookViewController).detailItem = object
}
}
}
}
| apache-2.0 |
maximkhatskevich/MKHSequence | Sources/OperationFlow/Defaults.swift | 2 | 395 | //
// Defaults.swift
// MKHOperationFlow
//
// Created by Maxim Khatskevich on 11/12/16.
// Copyright © 2016 Maxim Khatskevich. All rights reserved.
//
import Foundation
//===
public
extension OFL
{
public
enum Defaults
{
public
static
var targetQueue = OperationQueue()
public
static
var maxRetries: UInt = 3
}
}
| mit |
dvlproad/CJFoundation | UITestDemo/Finished-3/HalfTunes/HalfTunesFakeTests/HalfTunesFakeTests.swift | 2 | 3508 | /**
* Copyright (c) 2016 Razeware 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 XCTest
@testable import HalfTunes
class HalfTunesFakeTests: XCTestCase {
var controllerUnderTest: SearchViewController!
override func setUp() {
super.setUp()
controllerUnderTest = UIStoryboard(name: "Main",
bundle: nil).instantiateInitialViewController() as! SearchViewController!
let testBundle = Bundle(for: type(of: self))
let path = testBundle.path(forResource: "abbaData", ofType: "json")
let data = try? Data(contentsOf: URL(fileURLWithPath: path!), options: .alwaysMapped)
let url = URL(string: "https://itunes.apple.com/search?media=music&entity=song&term=abba")
let urlResponse = HTTPURLResponse(url: url!, statusCode: 200, httpVersion: nil, headerFields: nil)
let sessionMock = URLSessionMock(data: data, response: urlResponse, error: nil)
controllerUnderTest.defaultSession = sessionMock
}
override func tearDown() {
controllerUnderTest = nil
super.tearDown()
}
// Fake URLSession with DHURLSession protocol and stubs
func test_UpdateSearchResults_ParsesData() {
// given
let promise = expectation(description: "Status code: 200")
// when
XCTAssertEqual(controllerUnderTest?.searchResults.count, 0, "searchResults should be empty before the data task runs")
let url = URL(string: "https://itunes.apple.com/search?media=music&entity=song&term=abba")
let dataTask = controllerUnderTest?.defaultSession.dataTask(with: url!) {
data, response, error in
// if HTTP request is successful, call updateSearchResults(_:) which parses the response data into Tracks
if let error = error {
print(error.localizedDescription)
} else if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
promise.fulfill()
self.controllerUnderTest?.updateSearchResults(data)
}
}
}
dataTask?.resume()
waitForExpectations(timeout: 5, handler: nil)
// then
XCTAssertEqual(controllerUnderTest?.searchResults.count, 3, "Didn't parse 3 items from fake response")
}
// Performance
func test_StartDownload_Performance() {
let track = Track(name: "Waterloo", artist: "ABBA", previewUrl: "http://a821.phobos.apple.com/us/r30/Music/d7/ba/ce/mzm.vsyjlsff.aac.p.m4a")
measure {
self.controllerUnderTest?.startDownload(track)
}
}
}
| mit |
tardieu/swift | validation-test/compiler_crashers_fixed/26126-std-function-func-swift-type-subst.swift | 65 | 445 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol c{class B{}class B<T{struct S<a>:S<a>
| apache-2.0 |
quickthyme/PUTcat | PUTcat/Application/Data/TransactionResponse/PCTransactionResponseRepository.swift | 1 | 725 |
import Foundation
protocol PCTransactionResponseRepositoryDataStoreProvider {
static func getDataStore() -> PCTransactionResponseDataStore.Type
}
class PCTransactionResponseRepository {
static var dataStoreProvider : PCTransactionResponseRepositoryDataStoreProvider.Type = PCTransactionResponseDataStoreProvider.self
fileprivate static var dataStore : PCTransactionResponseDataStore.Type { return self.dataStoreProvider.getDataStore() }
}
extension PCTransactionResponseRepository {
class func fetch(transaction: PCTransaction, variables: PCList<PCVariable>) -> Composed.Action<Any, PCTransactionResponse> {
return self.dataStore.fetch(transaction: transaction, variables: variables)
}
}
| apache-2.0 |
brentdax/swift | stdlib/public/SDK/Foundation/NSURL.swift | 25 | 892 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
extension NSURL : _CustomPlaygroundQuickLookable {
@available(*, deprecated, message: "NSURL.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: PlaygroundQuickLook {
guard let str = absoluteString else { return .text("Unknown URL") }
return .url(str)
}
}
| apache-2.0 |
nghiaphunguyen/NKit | NKit/ViewController.swift | 1 | 569 | //
// ViewController.swift
// NKit
//
// Created by Nghia Nguyen on 8/25/16.
// Copyright © 2016 Nghia Nguyen. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// let locationManager = NKLocationManager.init()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
xuech/OMS-WH | OMS-WH/Classes/DeliveryGoods/Controller/SendByOtherViewController.swift | 1 | 13516 | //
// SendByOtherViewController.swift
// OMS-WH
//
// Created by ___Gwy on 2017/8/21.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
import SVProgressHUD
//判断发货类型
public enum SendBehaviour : Int{
case byZSFH = 0
case byKDFH
case byDBFH
case byHKFH
case byZTFH
}
class SendByOtherViewController: UIViewController {
var modeBehaviour: SendBehaviour!
fileprivate var viewModel = DeliveryGoodsViewModel()
var orderModel:OrderListModel?
var outboundModel:DGOutBoundListModel?
//快递发货所需
var defaultModel:[String:AnyObject]?{
didSet{
table.reloadData()
}
}
//快递发货所需
var expressArr = [[String:AnyObject]]()
var expressCode:String?
//航空发货所需
var airCompanyArr = [[String:AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
setUp()
switch modeBehaviour {
case .byZSFH:
title = "直送发货"
requstDefaultInfo()
case .byKDFH:
title = "快递发货"
requstExpress()
case .byDBFH:
title = "大巴发货"
case .byHKFH:
title = "航空发货"
requstAirCompany()
case .byZTFH:
title = "自提发货"
default:
return
}
}
fileprivate func setUp(){
view.addSubview(table)
view.addSubview(submitBtn)
submitBtn.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(self.view)
make.height.equalTo(44)
}
}
//MARK:确定按钮
fileprivate lazy var submitBtn: UIButton = {
let submitBtn = UIButton(imageName: "", fontSize: 15, color: UIColor.white, title: "提交", bgColor: kAppearanceColor)
submitBtn.addTarget(self, action: #selector(submit), for: .touchUpInside)
return submitBtn
}()
//列表
fileprivate lazy var table:UITableView = {
let table = UITableView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight-44), style: .plain)
table.separatorStyle = .none
table.dataSource = self
table.delegate = self
table.register(PicAndTFTableViewCell.self)
return table
}()
//直送发货-请求默认信息
fileprivate func requstDefaultInfo(){
viewModel.requstdefaultDirectDeliveryInfo(orderModel!.sONo, "oms-api-v3/order/operation/defaultDirectDeliveryInfo") { (data, error) in
self.defaultModel = data
}
}
//快递发货-请求快递方式
fileprivate func requstExpress(){
viewModel.requstDict(["dictTypeCode":"RFNOTP","dictSubClass1":"Express"]) { (data, error) in
self.expressArr = data
}
}
//航空发货-请求航空公司
fileprivate func requstAirCompany(){
viewModel.requstDict(["dictTypeCode":"RFNOTP","dictSubClass1":"AIR"]) { (data, error) in
self.airCompanyArr = data
}
}
fileprivate func operationSuccess(){
if let vc = self.navigationController?.viewControllers[1] as? DeliveryGoodsViewController,let sONo = orderModel?.sONo {
SVProgressHUD.showSuccess("订单\(sONo)发货成功")
_ = self.navigationController?.popToViewController(vc, animated: true)
}
}
@objc func submit(){
let cellOne = table.cellForRow(at: IndexPath(row: 0, section: 0)) as! PicAndTFTableViewCell
let cellTwo = table.cellForRow(at: IndexPath(row: 1, section: 0)) as! PicAndTFTableViewCell
let cellThree = table.cellForRow(at: IndexPath(row: 2, section: 0)) as! PicAndTFTableViewCell
var param = [String:Any]()
switch modeBehaviour! {
case .byZSFH:
guard cellOne.textTF.text != "" else { return SVProgressHUD.showError("请输入送货人姓名") }
guard cellTwo.textTF.text != "" else { return SVProgressHUD.showError("请输入送货人手机") }
var modelData = [String:String]()
modelData["deliverymanRemark"] = cellThree.textTF.text
param["deliveryman"] = cellOne.textTF.text
param["deliverymanPhone"] = cellTwo.textTF.text
param["sONo"] = orderModel?.sONo
param["wONo"] = outboundModel?.wONo
param["modelData"] = modelData
viewModel.submit(param, "oms-api-v3/order/operation/deliveryByDirect") { (data, error) in
self.operationSuccess()
}
case .byKDFH:
guard cellOne.textTF.text != "" else { return SVProgressHUD.showError("请选择快递公司") }
guard cellTwo.textTF.text != "" else { return SVProgressHUD.showError("请输入快递单号") }
param["expressCompanyName"] = expressCode
param["expressNumber"] = cellTwo.textTF.text
param["sendRemark"] = cellThree.textTF.text
param["sONo"] = orderModel?.sONo
param["wONo"] = outboundModel?.wONo
viewModel.submit(param, "oms-api-v3/order/operation/deliveryByExpress", { (data, error) in
self.operationSuccess()
})
case .byDBFH:
let cellFour = table.cellForRow(at: IndexPath(row: 3, section: 0)) as! PicAndTFTableViewCell
guard cellOne.textTF.text != "" else { return SVProgressHUD.showError("请输入车牌号") }
guard cellTwo.textTF.text != "" else { return SVProgressHUD.showError("请输入司机电话") }
param["busNumber"] = cellOne.textTF.text
param["busDriverMobileNumber"] = cellTwo.textTF.text
param["busDriverName"] = cellThree.textTF.text
param["carrierTransRemark"] = cellFour.textTF.text
param["sONo"] = orderModel?.sONo
param["wONo"] = outboundModel?.wONo
viewModel.submit(param, "oms-api-v3/order/operation/deliveryByBus", { (data, error) in
self.operationSuccess()
})
case.byHKFH:
let cellFour = table.cellForRow(at: IndexPath(row: 3, section: 0)) as! PicAndTFTableViewCell
let cellFive = table.cellForRow(at: IndexPath(row: 4, section: 0)) as! PicAndTFTableViewCell
guard cellOne.textTF.text != "" else { return SVProgressHUD.showError("请选择航空公司") }
guard cellTwo.textTF.text != "" else { return SVProgressHUD.showError("请输入航班号") }
guard cellThree.textTF.text != "" else { return SVProgressHUD.showError("请输入送货人") }
guard cellFour.textTF.text != "" else { return SVProgressHUD.showError("请输入送货人手机") }
param["airlineCompany"] = cellOne.textTF.text
param["carrierTransPerson"] = cellThree.textTF.text
param["carrierTransPersonMobile"] = cellFour.textTF.text
param["carrierTransRemark"] = cellFive.textTF.text
param["flightNumber"] = cellTwo.textTF.text
param["sONo"] = orderModel?.sONo
param["wONo"] = outboundModel?.wONo
viewModel.submit(param, "oms-api-v3/order/operation/deliveryByAir", { (data, error) in
self.operationSuccess()
})
case .byZTFH:
guard cellOne.textTF.text != "" else { return SVProgressHUD.showError("请输入提货人") }
guard cellTwo.textTF.text != "" else { return SVProgressHUD.showError("请输入提货人手机") }
param["pickUpPerson"] = cellOne.textTF.text
param["pickUpPersonMobile"] = cellTwo.textTF.text
param["carrierTransRemark"] = cellThree.textTF.text
param["sONo"] = orderModel?.sONo
param["wONo"] = outboundModel?.wONo
viewModel.submit(param, "oms-api-v3/order/operation/deliveryByPickUp", { (data, error) in
self.operationSuccess()
})
}
}
}
extension SendByOtherViewController:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PicAndTFTableViewCell") as! PicAndTFTableViewCell
switch modeBehaviour! {
case .byZSFH:
if indexPath.row == 0{
cell.textTF.placeholder = "送货人"
cell.textTF.text = defaultModel?["deliveryman"] as? String
cell.needImage.isHidden = false
}else if indexPath.row == 1{
cell.textTF.placeholder = "送货人手机"
cell.textTF.text = defaultModel?["deliverymanPhone"] as? String
cell.needImage.isHidden = false
}else{
cell.textTF.placeholder = "送货备注"
}
case .byKDFH:
if indexPath.row == 0{
cell.textTF.placeholder = "快递公司"
cell.textTF.isUserInteractionEnabled = false
cell.needImage.isHidden = false
}else if indexPath.row == 1{
cell.textTF.placeholder = "快递单号"
cell.needImage.isHidden = false
}else{
cell.textTF.placeholder = "送货备注"
cell.textTF.text = "运费已付"
}
case .byDBFH:
if indexPath.row == 0{
cell.textTF.placeholder = "车牌号"
cell.needImage.isHidden = false
}else if indexPath.row == 1{
cell.textTF.placeholder = "司机电话"
cell.needImage.isHidden = false
}else if indexPath.row == 2{
cell.textTF.placeholder = "司机"
cell.needImage.isHidden = false
}else{
cell.textTF.placeholder = "送货备注"
cell.textTF.text = "运费已付"
}
case .byHKFH:
if indexPath.row == 0{
cell.textTF.placeholder = "航空公司"
cell.textTF.isUserInteractionEnabled = false
cell.needImage.isHidden = false
}else if indexPath.row == 1{
cell.textTF.placeholder = "航班号"
cell.needImage.isHidden = false
}else if indexPath.row == 2{
cell.textTF.placeholder = "送货人"
cell.needImage.isHidden = false
}else if indexPath.row == 3{
cell.textTF.placeholder = "送货人手机"
cell.needImage.isHidden = false
}else{
cell.textTF.placeholder = "送货人备注"
cell.textTF.text = "运费已付"
}
case .byZTFH:
if indexPath.row == 0{
cell.textTF.placeholder = "提货人"
cell.needImage.isHidden = false
}else if indexPath.row == 1{
cell.textTF.placeholder = "提货人手机"
cell.needImage.isHidden = false
cell.textTF.keyboardType = .phonePad
}else{
cell.textTF.placeholder = "提货备注(对提货的特殊提醒,如张三 身份证xxx)"
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch modeBehaviour! {
case .byKDFH:
if indexPath.row == 0{
let chooseVC = PickViewController(frame: self.view.bounds, dataSource: self.expressArr, title: "请选择快递公司", modeBehaviour: ChooseBehaviour.chooseDictValue)
chooseVC.GetCode = {(indexpath:Int) in
let cell = self.table.cellForRow(at: IndexPath(row: indexPath.row, section: 0)) as! PicAndTFTableViewCell
cell.textTF.text = self.expressArr[indexpath]["dictValueName"] as? String
self.expressCode = self.expressArr[indexpath]["dictValueCode"] as? String
}
self.view.addSubview(chooseVC.view)
self.addChildViewController(chooseVC)
}
case .byHKFH:
if indexPath.row == 0{
let chooseVC = PickViewController(frame: self.view.bounds, dataSource: self.airCompanyArr, title: "请选择航空公司", modeBehaviour: ChooseBehaviour.chooseDictValue)
chooseVC.GetCode = {(indexpath:Int) in
let cell = self.table.cellForRow(at: IndexPath(row: indexPath.row, section: 0)) as! PicAndTFTableViewCell
cell.textTF.text = self.airCompanyArr[indexpath]["dictValueName"] as? String
}
self.view.addSubview(chooseVC.view)
self.addChildViewController(chooseVC)
}
default:
return
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch modeBehaviour! {
case .byDBFH:
return 4
case .byHKFH:
return 5
default:
return 3
}
}
}
| mit |
herobin22/TopOmnibus | TopOmnibus/TopOmnibus/TopNews/Model/OYNewsTopicModel.swift | 1 | 306 | //
// OYNewsTopicModel.swift
// TopOmnibus
//
// Created by Gold on 2016/11/7.
// Copyright © 2016年 herob. All rights reserved.
//
import UIKit
class OYNewsTopicModel: NSObject {
var topic: String?
var process: CGFloat = 0
init(topic: String) {
self.topic = topic
}
}
| mit |
hooman/swift | stdlib/public/core/Random.swift | 9 | 6870 | //===--- Random.swift -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
/// A type that provides uniformly distributed random data.
///
/// When you call methods that use random data, such as creating new random
/// values or shuffling a collection, you can pass a `RandomNumberGenerator`
/// type to be used as the source for randomness. When you don't pass a
/// generator, the default `SystemRandomNumberGenerator` type is used.
///
/// When providing new APIs that use randomness, provide a version that accepts
/// a generator conforming to the `RandomNumberGenerator` protocol as well as a
/// version that uses the default system generator. For example, this `Weekday`
/// enumeration provides static methods that return a random day of the week:
///
/// enum Weekday: CaseIterable {
/// case sunday, monday, tuesday, wednesday, thursday, friday, saturday
///
/// static func random<G: RandomNumberGenerator>(using generator: inout G) -> Weekday {
/// return Weekday.allCases.randomElement(using: &generator)!
/// }
///
/// static func random() -> Weekday {
/// var g = SystemRandomNumberGenerator()
/// return Weekday.random(using: &g)
/// }
/// }
///
/// Conforming to the RandomNumberGenerator Protocol
/// ================================================
///
/// A custom `RandomNumberGenerator` type can have different characteristics
/// than the default `SystemRandomNumberGenerator` type. For example, a
/// seedable generator can be used to generate a repeatable sequence of random
/// values for testing purposes.
///
/// To make a custom type conform to the `RandomNumberGenerator` protocol,
/// implement the required `next()` method. Each call to `next()` must produce
/// a uniform and independent random value.
///
/// Types that conform to `RandomNumberGenerator` should specifically document
/// the thread safety and quality of the generator.
public protocol RandomNumberGenerator {
/// Returns a value from a uniform, independent distribution of binary data.
///
/// Use this method when you need random binary data to generate another
/// value. If you need an integer value within a specific range, use the
/// static `random(in:using:)` method on that integer type instead of this
/// method.
///
/// - Returns: An unsigned 64-bit random value.
mutating func next() -> UInt64
}
extension RandomNumberGenerator {
// An unavailable default implementation of next() prevents types that do
// not implement the RandomNumberGenerator interface from conforming to the
// protocol; without this, the default next() method returning a generic
// unsigned integer will be used, recursing infinitely and probably blowing
// the stack.
@available(*, unavailable)
@_alwaysEmitIntoClient
public mutating func next() -> UInt64 { fatalError() }
/// Returns a value from a uniform, independent distribution of binary data.
///
/// Use this method when you need random binary data to generate another
/// value. If you need an integer value within a specific range, use the
/// static `random(in:using:)` method on that integer type instead of this
/// method.
///
/// - Returns: A random value of `T`. Bits are randomly distributed so that
/// every value of `T` is equally likely to be returned.
@inlinable
public mutating func next<T: FixedWidthInteger & UnsignedInteger>() -> T {
return T._random(using: &self)
}
/// Returns a random value that is less than the given upper bound.
///
/// Use this method when you need random binary data to generate another
/// value. If you need an integer value within a specific range, use the
/// static `random(in:using:)` method on that integer type instead of this
/// method.
///
/// - Parameter upperBound: The upper bound for the randomly generated value.
/// Must be non-zero.
/// - Returns: A random value of `T` in the range `0..<upperBound`. Every
/// value in the range `0..<upperBound` is equally likely to be returned.
@inlinable
public mutating func next<T: FixedWidthInteger & UnsignedInteger>(
upperBound: T
) -> T {
_precondition(upperBound != 0, "upperBound cannot be zero.")
// We use Lemire's "nearly divisionless" method for generating random
// integers in an interval. For a detailed explanation, see:
// https://arxiv.org/abs/1805.10941
var random: T = next()
var m = random.multipliedFullWidth(by: upperBound)
if m.low < upperBound {
let t = (0 &- upperBound) % upperBound
while m.low < t {
random = next()
m = random.multipliedFullWidth(by: upperBound)
}
}
return m.high
}
}
/// The system's default source of random data.
///
/// When you generate random values, shuffle a collection, or perform another
/// operation that depends on random data, this type is the generator used by
/// default. For example, the two method calls in this example are equivalent:
///
/// let x = Int.random(in: 1...100)
/// var g = SystemRandomNumberGenerator()
/// let y = Int.random(in: 1...100, using: &g)
///
/// `SystemRandomNumberGenerator` is automatically seeded, is safe to use in
/// multiple threads, and uses a cryptographically secure algorithm whenever
/// possible.
///
/// Platform Implementation of `SystemRandomNumberGenerator`
/// ========================================================
///
/// While the system generator is automatically seeded and thread-safe on every
/// platform, the cryptographic quality of the stream of random data produced by
/// the generator may vary. For more detail, see the documentation for the APIs
/// used by each platform.
///
/// - Apple platforms use `arc4random_buf(3)`.
/// - Linux platforms use `getrandom(2)` when available; otherwise, they read
/// from `/dev/urandom`.
/// - Windows uses `BCryptGenRandom`.
@frozen
public struct SystemRandomNumberGenerator: RandomNumberGenerator, Sendable {
/// Creates a new instance of the system's default random number generator.
@inlinable
public init() { }
/// Returns a value from a uniform, independent distribution of binary data.
///
/// - Returns: An unsigned 64-bit random value.
@inlinable
public mutating func next() -> UInt64 {
var random: UInt64 = 0
swift_stdlib_random(&random, MemoryLayout<UInt64>.size)
return random
}
}
| apache-2.0 |
kumabook/MusicFav | MusicFav/TutorialView.swift | 1 | 7990 | //
// TutorialView.swift
// MusicFav
//
// Created by Hiroki Kumamoto on 4/19/15.
// Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//
import EAIntroView
protocol TutorialViewDelegate: EAIntroDelegate {
func tutorialLoginButtonTapped()
}
class TutorialView: EAIntroView {
class func tutorialView(_ frame: CGRect, delegate: TutorialViewDelegate?) -> TutorialView {
let menuPage = capturePage(frame, title: String.tutorialString("menu_page_title"),
desc: String.tutorialString("menu_page_desc"),
bgColor: UIColor.theme,
imageName: "menu_cap")
let streamPage = capturePage(frame, title: String.tutorialString("stream_page_title"),
desc: String.tutorialString("stream_page_desc"),
bgColor: UIColor.theme,
imageName: "stream_cap")
let playlistPage = capturePage(frame, title: String.tutorialString("playlist_page_title"),
desc: String.tutorialString("playlist_page_desc"),
bgColor: UIColor.theme,
imageName: "playlist_cap")
let playerPage = capturePage(frame, title: String.tutorialString("player_page_title"),
desc: String.tutorialString("player_page_desc"),
bgColor: UIColor.theme,
imageName: "player_cap")
let pages: [EAIntroPage] = [firstPage(frame),
streamPage,
playlistPage,
playerPage,
menuPage,
lastPage(frame, delegate: delegate)]
let tutorialView = TutorialView(frame: frame, andPages: pages)
tutorialView?.delegate = delegate
return tutorialView!
}
class func firstPage(_ frame: CGRect) -> EAIntroPage {
let height = frame.height
let width = frame.width
let page = EAIntroPage()
page.title = String.tutorialString("first_page_title")
page.titlePositionY = frame.height * 0.55
let imageView = UIImageView(image: UIImage(named: "note"))
imageView.contentMode = UIViewContentMode.scaleAspectFit
imageView.frame = CGRect(x: 0, y: 0, width: width * 0.3, height: height * 0.3)
page.titleIconView = imageView
page.desc = String.tutorialString("first_page_desc")
page.descPositionY = frame.height * 0.4
page.bgColor = UIColor.theme
let deviceType = DeviceType.from(UIDevice.current)
switch deviceType {
case .iPhone4OrLess:
page.descFont = UIFont.systemFont(ofSize: 14)
page.titleFont = UIFont.boldSystemFont(ofSize: 20)
case .iPhone5:
page.descFont = UIFont.systemFont(ofSize: 16)
page.titleFont = UIFont.boldSystemFont(ofSize: 24)
case .iPhone6:
page.descFont = UIFont.systemFont(ofSize: 18)
page.titleFont = UIFont.boldSystemFont(ofSize: 26)
case .iPhone6Plus:
page.descFont = UIFont.systemFont(ofSize: 20)
page.titleFont = UIFont.boldSystemFont(ofSize: 28)
case .iPad:
page.descFont = UIFont.systemFont(ofSize: 30)
page.titleFont = UIFont.boldSystemFont(ofSize: 36)
case .unknown:
page.descFont = UIFont.systemFont(ofSize: 16)
page.titleFont = UIFont.boldSystemFont(ofSize: 24)
}
return page
}
class func capturePage(_ frame: CGRect, title: String, desc: String, bgColor: UIColor, imageName: String) -> EAIntroPage {
let height = frame.height
let width = frame.width
let deviceType = DeviceType.from(UIDevice.current)
let descLabel = UILabel(frame: CGRect(x: width*0.1, y: height*0.58,
width: width*0.8, height: height*0.2))
descLabel.textColor = UIColor.white
descLabel.textAlignment = NSTextAlignment.left
descLabel.numberOfLines = 6
descLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
descLabel.text = desc
let page = EAIntroPage()
page.title = title
page.titlePositionY = frame.height * 0.5
page.bgColor = bgColor
let imageView = UIImageView(image: UIImage(named: imageName))
imageView.contentMode = UIViewContentMode.scaleAspectFit
imageView.frame = CGRect(x: 0, y: 0, width: width * 0.8, height: height * 0.4)
page.titleIconView = imageView
page.subviews = [descLabel]
switch deviceType {
case .iPhone4OrLess:
descLabel.font = UIFont.systemFont(ofSize: 12)
page.titleFont = UIFont.boldSystemFont(ofSize: 16)
case .iPhone5:
descLabel.font = UIFont.systemFont(ofSize: 14)
page.titleFont = UIFont.boldSystemFont(ofSize: 20)
case .iPhone6:
descLabel.font = UIFont.systemFont(ofSize: 16)
page.titleFont = UIFont.boldSystemFont(ofSize: 24)
case .iPhone6Plus:
descLabel.font = UIFont.systemFont(ofSize: 18)
page.titleFont = UIFont.boldSystemFont(ofSize: 26)
case .iPad:
descLabel.font = UIFont.systemFont(ofSize: 26)
page.titleFont = UIFont.boldSystemFont(ofSize: 36)
case .unknown:
descLabel.font = UIFont.systemFont(ofSize: 18)
page.titleFont = UIFont.boldSystemFont(ofSize: 26)
}
return page
}
class func lastPage(_ frame: CGRect, delegate: TutorialViewDelegate?) -> EAIntroPage {
let height = frame.height
let width = frame.width
let deviceType = DeviceType.from(UIDevice.current)
let page = EAIntroPage()
page.title = String.tutorialString("last_page_title")
page.titleFont = UIFont.boldSystemFont(ofSize: 32)
page.titlePositionY = height * 0.5
let imageView = UIImageView(image: UIImage(named: "note"))
imageView.contentMode = UIViewContentMode.scaleAspectFit
imageView.frame = CGRect(x: 0, y: 0, width: width * 0.4, height: height * 0.4)
page.titleIconView = imageView
page.desc = String.tutorialString("last_page_desc")
page.descFont = UIFont.systemFont(ofSize: 20)
page.descPositionY = height * 0.4
page.bgColor = UIColor.theme
switch deviceType {
case .iPhone4OrLess:
page.descFont = UIFont.systemFont(ofSize: 16)
page.titleFont = UIFont.boldSystemFont(ofSize: 24)
case .iPhone5:
page.descFont = UIFont.systemFont(ofSize: 18)
page.titleFont = UIFont.boldSystemFont(ofSize: 26)
case .iPhone6:
page.descFont = UIFont.systemFont(ofSize: 22)
page.titleFont = UIFont.boldSystemFont(ofSize: 28)
case .iPhone6Plus:
page.descFont = UIFont.systemFont(ofSize: 24)
page.titleFont = UIFont.boldSystemFont(ofSize: 30)
case .iPad:
page.descFont = UIFont.systemFont(ofSize: 30)
page.titleFont = UIFont.boldSystemFont(ofSize: 36)
case .unknown:
page.descFont = UIFont.systemFont(ofSize: 18)
page.titleFont = UIFont.boldSystemFont(ofSize: 26)
}
return page
}
}
| mit |
narner/AudioKit | Examples/iOS/MIDIUtility/MIDIUtility/MIDISenderVC.swift | 1 | 4980 | //
// MIDISenderVC.swift
// MIDIUtility
//
// Created by Jeff Cooper on 9/11/17.
// Copyright © 2017 AudioKit. All rights reserved.
//
import Foundation
import AudioKit
import UIKit
class MIDISenderVC: UIViewController {
let midiOut = AKMIDI()
@IBOutlet var noteNumField: UITextField!
@IBOutlet var noteVelField: UITextField!
@IBOutlet var noteChanField: UITextField!
@IBOutlet var ccField: UITextField!
@IBOutlet var ccValField: UITextField!
@IBOutlet var ccChanField: UITextField!
@IBOutlet var sysexField: UITextView!
var noteToSend: Int? {
return Int(noteNumField.text!)
}
var velocityToSend: Int? {
return Int(noteVelField.text!)
}
var noteChanToSend: Int {
if noteChanField.text == nil || Int(noteChanField.text!) == nil {
return 1
}
return Int(noteChanField.text!)! - 1
}
var ccToSend: Int? {
return Int(ccField.text!)
}
var ccValToSend: Int? {
return Int(ccValField.text!)
}
var ccChanToSend: Int {
if ccChanField.text == nil || Int(ccChanField.text!) == nil {
return 1
}
return Int(ccChanField.text!)! - 1
}
var sysexToSend: [Int]? {
var data = [Int]()
if sysexField.text == nil {
return nil
}
let splitField = sysexField.text!.components(separatedBy: " ")
for entry in splitField {
let intVal = Int(entry)
if intVal != nil && intVal! <= 247 && intVal! > -1 {
data.append(intVal!)
}
}
return data
}
override func viewDidLoad() {
midiOut.openOutput()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
@IBAction func sendNotePressed(_ sender: UIButton) {
if noteToSend != nil && velocityToSend != nil {
print("sending note: \(noteToSend!) - \(velocityToSend!)")
let event = AKMIDIEvent(noteOn: MIDINoteNumber(noteToSend!), velocity: MIDIVelocity(velocityToSend!), channel: MIDIChannel(noteChanToSend))
midiOut.sendEvent(event)
} else {
print("error w note fields")
}
}
@IBAction func sendCCPressed(_ sender: UIButton) {
if ccToSend != nil && ccValToSend != nil {
print("sending cc: \(ccToSend!) - \(ccValToSend!)")
let event = AKMIDIEvent(controllerChange: MIDIByte(ccToSend!), value: MIDIByte(ccValToSend!), channel: MIDIChannel(ccChanToSend))
midiOut.sendEvent(event)
} else {
print("error w cc fields")
}
}
@IBAction func sendSysexPressed(_ sender: UIButton) {
if sysexToSend != nil {
var midiBytes = [MIDIByte]()
for byte in sysexToSend! {
midiBytes.append(MIDIByte(byte))
}
if midiBytes[0] != 240 || midiBytes.last != 247 || midiBytes.count < 2 {
print("bad sysex data - must start with 240 and end with 247")
print("parsed sysex: \(sysexToSend!)")
return
}
print("sending sysex \(sysexToSend!)")
let event = AKMIDIEvent(data: midiBytes)
midiOut.sendEvent(event)
} else {
print("error w sysex field")
}
}
@IBAction func receiveMIDIButtonPressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
class MIDIChannelField: UITextField, UITextFieldDelegate {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
}
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
var startString = ""
if (textField.text != nil) {
startString += textField.text!
}
startString += string
let limitNumber = Int(startString)
if limitNumber == nil || limitNumber! > 16 || limitNumber! == 0 {
return false
} else {
return true
}
}
}
class MIDINumberField: UITextField, UITextFieldDelegate {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
}
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
var startString = ""
if (textField.text != nil) {
startString += textField.text!
}
startString += string
let limitNumber = Int(startString)
if limitNumber == nil || limitNumber! > 127 {
return false
} else {
return true
}
}
}
| mit |
jemmons/Medea | Sources/Medea/AnyJSON.swift | 1 | 1501 | import Foundation
public enum AnyJSON {
case null, bool(Bool), number(NSNumber), string(String), array(JSONArray), object(JSONObject)
public init(_ value: Any) throws {
switch value {
case is NSNull:
self = .null
case let b as Bool:
self = .bool(b)
case let n as NSNumber:
self = .number(n)
case let s as String:
self = .string(s)
case let a as JSONArray:
self = .array(a)
case let d as JSONObject:
self = .object(d)
default:
throw JSONError.invalidType
}
}
}
public extension AnyJSON {
func objectValue() throws -> JSONObject {
guard case .object(let d) = self else {
throw JSONError.unexpectedType
}
return d
}
func arrayValue() throws -> JSONArray {
guard case .array(let a) = self else {
throw JSONError.unexpectedType
}
return a
}
func stringValue() throws -> String {
guard case .string(let s) = self else {
throw JSONError.unexpectedType
}
return s
}
func boolValue() throws -> Bool {
guard case .bool(let b) = self else {
throw JSONError.unexpectedType
}
return b
}
func numberValue() throws -> NSNumber {
guard case .number(let n) = self else {
throw JSONError.unexpectedType
}
return n
}
var isNull: Bool {
switch self {
case .null:
return true
default:
return false
}
}
var isNotNull: Bool {
return !isNull
}
}
| mit |
tinrobots/Mechanica | Tests/StandardLibraryTests/OptionalUtilsTests.swift | 1 | 2788 | import XCTest
@testable import Mechanica
extension OptionalUtilsTests {
static var allTests = [
("testHasValue", testHasValue),
("testOr", testOr),
("testOrWithAutoclosure", testOrWithAutoclosure),
("testOrWithClosure", testOrWithClosure),
("testOrThrowException", testOrThrowException),
("testCollectionIsNilOrEmpty", testCollectionIsNilOrEmpty),
("testStringIsNilOrEmpty", testStringIsNilOrEmpty),
("isNilOrBlank", testIsNilOrBlank),
]
}
final class OptionalUtilsTests: XCTestCase {
func testHasValue() {
var value: Any?
XCTAssert(!value.hasValue)
value = "tinrobots"
XCTAssert(value.hasValue)
}
func testOr() {
let value1: String? = "hello"
XCTAssertEqual(value1.or("world"), "hello")
let value2: String? = nil
XCTAssertEqual(value2.or("world"), "world")
}
func testOrWithAutoclosure() {
func runMe() -> String {
return "world"
}
let value1: String? = "hello"
XCTAssertEqual(value1.or(else: runMe()), "hello")
let value2: String? = nil
XCTAssertEqual(value2.or(else: runMe()), "world")
}
func testOrWithClosure() {
let value1: String? = "hello"
XCTAssertEqual(value1.or(else: { return "world" }), "hello")
let value2: String? = nil
XCTAssertEqual(value2.or(else: { return "world" }), "world")
}
func testOrThrowException() {
enum DemoError: Error { case test }
let value1: String? = "hello"
XCTAssertNoThrow(try value1.or(throw: DemoError.test))
let value2: String? = nil
XCTAssertThrowsError(try value2.or(throw: DemoError.test))
}
func testCollectionIsNilOrEmpty() {
do {
let collection: [Int]? = [1, 2, 3]
XCTAssertFalse(collection.isNilOrEmpty)
}
do {
let collection: [Int]? = nil
XCTAssertTrue(collection.isNilOrEmpty)
}
do {
let collection: [Int]? = []
XCTAssertTrue(collection.isNilOrEmpty)
}
}
func testStringIsNilOrEmpty() {
do {
let text: String? = "mechanica"
XCTAssertFalse(text.isNilOrEmpty)
}
do {
let text: String? = " "
XCTAssertFalse(text.isNilOrEmpty)
}
do {
let text: String? = ""
XCTAssertTrue(text.isNilOrEmpty)
}
do {
let text: String? = nil
XCTAssertTrue(text.isNilOrEmpty)
}
}
func testIsNilOrBlank() {
do {
let text: String? = "mechanica"
XCTAssertFalse(text.isNilOrBlank)
}
do {
let text: String? = " "
XCTAssertTrue(text.isNilOrBlank)
}
do {
let text: String? = " "
XCTAssertTrue(text.isNilOrBlank)
}
do {
let text: String? = ""
XCTAssertTrue(text.isNilOrBlank)
}
do {
let text: String? = nil
XCTAssertTrue(text.isNilOrBlank)
}
}
}
| mit |
h-n-y/UICollectionView-TheCompleteGuide | chapter-2/2-selection-view/chapter2-5/CollectionViewCell.swift | 1 | 1712 | //
// CollectionViewCell.swift
// chapter2-5
//
// Created by Hans Yelek on 4/25/16.
// Copyright © 2016 Hans Yelek. All rights reserved.
//
import UIKit
class CollectionViewCell: UICollectionViewCell {
private let imageView = UIImageView()
var image: UIImage? = nil {
didSet {
imageView.image = image
}
}
override var highlighted: Bool {
didSet {
if highlighted {
imageView.alpha = 0.8
} else {
imageView.alpha = 1.0
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
imageView.frame = CGRectInset(self.bounds, 10, 10)
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
self.contentView.addSubview(imageView)
let selectedBackgroundView = UIView(frame: CGRectZero)
selectedBackgroundView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.8)
self.selectedBackgroundView = selectedBackgroundView
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
imageView.frame = CGRectInset(self.bounds, 10, 10)
self.contentView.addSubview(imageView)
let selectedBackgroundView = UIView(frame: CGRectZero)
selectedBackgroundView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.8)
self.selectedBackgroundView = selectedBackgroundView
}
override func prepareForReuse() {
super.prepareForReuse()
self.backgroundColor = UIColor.whiteColor()
self.image = nil
}
}
| mit |
watson-developer-cloud/ios-sdk | Sources/AssistantV1/Models/Mention.swift | 1 | 1619 | /**
* (C) Copyright IBM Corp. 2019, 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
A mention of a contextual entity.
*/
public struct Mention: Codable, Equatable {
/**
The name of the entity.
*/
public var entity: String
/**
An array of zero-based character offsets that indicate where the entity mentions begin and end in the input text.
*/
public var location: [Int]
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case entity = "entity"
case location = "location"
}
/**
Initialize a `Mention` with member variables.
- parameter entity: The name of the entity.
- parameter location: An array of zero-based character offsets that indicate where the entity mentions begin and
end in the input text.
- returns: An initialized `Mention`.
*/
public init(
entity: String,
location: [Int]
)
{
self.entity = entity
self.location = location
}
}
| apache-2.0 |
flodolo/firefox-ios | ThirdParty/Deferred/DeferredTests/DeferredTests.swift | 13 | 6919 | //
// DeferredTests.swift
// DeferredTests
//
// Created by John Gallagher on 7/19/14.
// Copyright (c) 2014 Big Nerd Ranch. All rights reserved.
//
import XCTest
#if os(iOS)
import Deferred
#else
import DeferredMac
#endif
func dispatch_main_after(interval: NSTimeInterval, block: () -> ()) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(NSTimeInterval(NSEC_PER_SEC)*interval)),
dispatch_get_main_queue(), block)
}
class DeferredTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testPeek() {
let d1 = Deferred<Int>()
let d2 = Deferred(value: 1)
XCTAssertNil(d1.peek())
XCTAssertEqual(d2.value, 1)
}
func testValueOnFilled() {
let filled = Deferred(value: 2)
XCTAssertEqual(filled.value, 2)
}
func testValueBlocksWhileUnfilled() {
let unfilled = Deferred<Int>()
var expect = expectationWithDescription("value blocks while unfilled")
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
_ = unfilled.value
XCTFail("value did not block")
}
dispatch_main_after(0.1) {
expect.fulfill()
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func testValueUnblocksWhenUnfilledIsFilled() {
let d = Deferred<Int>()
let expect = expectationWithDescription("value blocks until filled")
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
XCTAssertEqual(d.value, 3)
expect.fulfill()
}
dispatch_main_after(0.1) {
d.fill(3)
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func testFill() {
let d = Deferred<Int>()
d.fill(1)
XCTAssertEqual(d.value, 1)
}
func testFillIfUnfilled() {
let d = Deferred(value: 1)
XCTAssertEqual(d.value, 1)
d.fillIfUnfilled(2)
XCTAssertEqual(d.value, 1)
}
func testIsFilled() {
let d = Deferred<Int>()
XCTAssertFalse(d.isFilled)
d.fill(1)
XCTAssertTrue(d.isFilled)
}
func testUponWithFilled() {
let d = Deferred(value: 1)
for i in 0 ..< 10 {
let expect = expectationWithDescription("upon blocks called with correct value")
d.upon { value in
XCTAssertEqual(value, 1)
expect.fulfill()
}
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func testUponNotCalledWhileUnfilled() {
let d = Deferred<Int>()
d.upon { _ in
XCTFail("unexpected upon block call")
}
let expect = expectationWithDescription("upon blocks not called while deferred is unfilled")
dispatch_main_after(0.1) {
expect.fulfill()
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func testUponCalledWhenFilled() {
let d = Deferred<Int>()
for i in 0 ..< 10 {
let expect = expectationWithDescription("upon blocks not called while deferred is unfilled")
d.upon { value in
XCTAssertEqual(value, 1)
XCTAssertEqual(d.value, value)
expect.fulfill()
}
}
dispatch_main_after(0.1) {
d.fill(1)
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func testConcurrentUpon() {
let d = Deferred<Int>()
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
// upon with an unfilled deferred appends to an internal array (protected by a write lock)
// spin up a bunch of these in parallel...
for i in 0 ..< 32 {
let expectUponCalled = expectationWithDescription("upon block \(i)")
dispatch_async(queue) {
d.upon { _ in expectUponCalled.fulfill() }
}
}
// ...then fill it (also in parallel)
dispatch_async(queue) { d.fill(1) }
// ... and make sure all our upon blocks were called (i.e., the write lock protected access)
waitForExpectationsWithTimeout(1, handler: nil)
}
func testBoth() {
let d1 = Deferred<Int>()
let d2 = Deferred<String>()
let both = d1.both(d2)
XCTAssertFalse(both.isFilled)
d1.fill(1)
XCTAssertFalse(both.isFilled)
d2.fill("foo")
let expectation = expectationWithDescription("paired deferred should be filled")
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
while (!both.isFilled) { /* spin */ }
XCTAssertEqual(both.value.0, 1)
XCTAssertEqual(both.value.1, "foo")
expectation.fulfill()
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func testAll() {
var d = [Deferred<Int>]()
for i in 0 ..< 10 {
d.append(Deferred())
}
let w = all(d)
let outerExpectation = expectationWithDescription("all results filled in")
let innerExpectation = expectationWithDescription("paired deferred should be filled")
// skip first
for i in 1 ..< d.count {
d[i].fill(i)
}
dispatch_main_after(0.1) {
XCTAssertFalse(w.isFilled) // unfilled because d[0] is still unfilled
d[0].fill(0)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
while (!w.isFilled) { /* spin */ }
XCTAssertTrue(w.value == [Int](0 ..< d.count))
innerExpectation.fulfill()
}
outerExpectation.fulfill()
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func testAny() {
var d = [Deferred<Int>]()
for i in 0 ..< 10 {
d.append(Deferred())
}
let w = any(d)
d[3].fill(3)
let expectation = expectationWithDescription("any is filled")
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
while !w.isFilled { /* spin */ }
XCTAssertTrue(w.value === d[3])
XCTAssertEqual(w.value.value, 3)
d[4].fill(4)
dispatch_main_after(0.1) {
XCTAssertTrue(w.value === d[3])
XCTAssertEqual(w.value.value, 3)
expectation.fulfill()
}
}
waitForExpectationsWithTimeout(1, handler: nil)
}
}
| mpl-2.0 |
sharath-cliqz/browser-ios | Client/Cliqz/Frontend/Browser/Dashboard/Tab Redesign/PortraitFlowLayout.swift | 2 | 3085 | //
// PortraitFlowLayout.swift
// TabsRedesign
//
// Created by Tim Palade on 3/29/17.
// Copyright © 2017 Tim Palade. All rights reserved.
//
import UIKit
class TabSwitcherLayoutAttributes: UICollectionViewLayoutAttributes {
var displayTransform: CATransform3D = CATransform3DIdentity
override func copy(with zone: NSZone? = nil) -> Any {
let _copy = super.copy(with: zone) as! TabSwitcherLayoutAttributes
_copy.displayTransform = displayTransform
return _copy
}
override func isEqual(_ object: Any?) -> Bool {
guard let attr = object as? TabSwitcherLayoutAttributes else { return false }
return super.isEqual(object) && CATransform3DEqualToTransform(displayTransform, attr.displayTransform)
}
}
class PortraitFlowLayout: UICollectionViewFlowLayout {
var currentCount: Int = 0
var currentTransform: CATransform3D = CATransform3DIdentity
override init() {
super.init()
self.minimumInteritemSpacing = UIScreen.main.bounds.size.width
self.minimumLineSpacing = 0.0
self.scrollDirection = .vertical
self.sectionInset = UIEdgeInsetsMake(16, 0, 0, 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override class var layoutAttributesClass: AnyClass {
return TabSwitcherLayoutAttributes.self
}
override func prepare() {
if let count = self.collectionView?.numberOfItems(inSection: 0) {
if count != currentCount {
currentTransform = computeTransform(count: count)
currentCount = count
}
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attrs = super.layoutAttributesForElements(in: rect) else {return nil}
return attrs.map({ attr in
return pimpedAttribute(attr)
})
}
func pimpedAttribute(_ attribute: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
if let attr = attribute.copy() as? TabSwitcherLayoutAttributes {
//attr.zIndex = attr.indexPath.item
attr.displayTransform = currentTransform
return attr
}
return attribute
}
func computeTransform(count:Int) -> CATransform3D {
var t: CATransform3D = CATransform3DIdentity
t.m34 = -1.0 / (CGFloat(1000))
t = CATransform3DRotate(t, -CGFloat(Knobs.tiltAngle(count: count)), 1, 0, 0)
//calculate how much down t will take the layer and then compensate for that.
//this view must have the dimensions of the view this attr is going to be applied to.
let view = UIView(frame: CGRect(x: 0, y: 0, width: Knobs.cellWidth(), height: Knobs.cellHeight()))
view.layer.transform = t
t = CATransform3DTranslate(t, 0, -view.layer.frame.origin.y, 0)
return t
}
}
| mpl-2.0 |
OverSwift/VisualReader | MangaReader/Classes/Presentation/Scenes/MultyLevelTableController.swift | 1 | 2728 | //
// MultyLevelTableController.swift
// MangaReader
//
// Created by Sergiy Loza on 09.02.17.
// Copyright © 2017 Serhii Loza. All rights reserved.
//
import UIKit
class MultyLevelTableController: UITableViewController {
let dataIdentifiers = ["HeaderCell", "ReadNotesCell","ReadNotesCell", "LocationCell", "ReadNotesCell","ReadNotesCell", "RescheduleCell"]
let shadowView = UIView(frame: CGRect.zero)
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
tableView.contentInset.bottom += 28
var nib = UINib(nibName: "HeaderCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "HeaderCell")
nib = UINib(nibName: "ReadNotesCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "ReadNotesCell")
nib = UINib(nibName: "RescheduleCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "RescheduleCell")
nib = UINib(nibName: "LocationCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "LocationCell")
shadowView.backgroundColor = UIColor.white
self.view.addSubview(shadowView)
self.view.sendSubview(toBack: shadowView)
let layer = shadowView.layer
layer.masksToBounds = false
layer.shadowRadius = 5
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor
layer.shadowOpacity = 1.0
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.reloadData()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let newFrame = CGRect(x: 10, y: 10, width: self.tableView.contentSize.width - 20, height: self.tableView.contentSize.height - 10)
shadowView.frame = newFrame
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if !segue.destination.isViewLoaded {
segue.destination.loadViewIfNeeded()
segue.destination.view.setNeedsLayout()
segue.destination.view.layoutIfNeeded()
print("Child bounds \(segue.destination.view.bounds)")
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataIdentifiers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: dataIdentifiers[indexPath.row], for: indexPath)
return cell
}
}
| bsd-3-clause |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/What's New/Views/AnnouncementCell.swift | 1 | 4278 |
class AnnouncementCell: AnnouncementTableViewCell {
// MARK: - View elements
private lazy var headingLabel: UILabel = {
return makeLabel(font: Appearance.headingFont)
}()
private lazy var subHeadingLabel: UILabel = {
return makeLabel(font: Appearance.subHeadingFont, color: .textSubtle)
}()
private lazy var descriptionStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [headingLabel, subHeadingLabel])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
return stackView
}()
private lazy var announcementImageView: UIImageView = {
return UIImageView()
}()
private lazy var mainStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [announcementImageView, descriptionStackView])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.alignment = .center
stackView.setCustomSpacing(Appearance.imageTextSpacing, after: announcementImageView)
return stackView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(mainStackView)
contentView.pinSubviewToSafeArea(mainStackView, insets: Appearance.mainStackViewInsets)
NSLayoutConstraint.activate([
announcementImageView.heightAnchor.constraint(equalToConstant: Appearance.announcementImageSize),
announcementImageView.widthAnchor.constraint(equalToConstant: Appearance.announcementImageSize)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Configures the labels and image views using the data from a `WordPressKit.Feature` object.
/// - Parameter feature: The `feature` containing the information to fill the cell with.
func configure(feature: WordPressKit.Feature) {
if let iconBase64Components = feature.iconBase64,
!iconBase64Components.isEmpty,
let base64Image = iconBase64Components.components(separatedBy: ";base64,")[safe: 1],
let imageData = Data(base64Encoded: base64Image, options: .ignoreUnknownCharacters),
let icon = UIImage(data: imageData) {
announcementImageView.image = icon
}
else if let url = URL(string: feature.iconUrl) {
announcementImageView.af_setImage(withURL: url)
}
headingLabel.text = feature.title
subHeadingLabel.text = feature.subtitle
}
/// Configures the labels and image views using the data passed as parameters.
/// - Parameters:
/// - title: The title string to use for the heading.
/// - description: The description string to use for the sub heading.
/// - image: The image to use for the image view.
func configure(title: String, description: String, image: UIImage?) {
headingLabel.text = title
subHeadingLabel.text = description
announcementImageView.image = image
announcementImageView.isHidden = image == nil
}
}
// MARK: Helpers
private extension AnnouncementCell {
func makeLabel(font: UIFont, color: UIColor? = nil) -> UILabel {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.font = font
if let color = color {
label.textColor = color
}
return label
}
}
// MARK: - Appearance
private extension AnnouncementCell {
enum Appearance {
// heading
static let headingFont = UIFont(descriptor: UIFontDescriptor.preferredFontDescriptor(withTextStyle: .headline), size: 17)
// sub-heading
static let subHeadingFont = UIFont(descriptor: UIFontDescriptor.preferredFontDescriptor(withTextStyle: .subheadline), size: 15)
// announcement image
static let announcementImageSize: CGFloat = 48
// main stack view
static let imageTextSpacing: CGFloat = 16
static let mainStackViewInsets = UIEdgeInsets(top: 0, left: 0, bottom: 24, right: 0)
}
}
| gpl-2.0 |
frootloops/swift | test/stdlib/UIKit.swift | 2 | 9030 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift -swift-version 3 %s -o %t/a.out3 && %target-run %t/a.out3
// RUN: %target-build-swift -swift-version 4 %s -o %t/a.out4 && %target-run %t/a.out4
// REQUIRES: executable_test
// UNSUPPORTED: OS=macosx
// REQUIRES: objc_interop
import UIKit
import StdlibUnittest
import StdlibUnittestFoundationExtras
#if swift(>=4)
let UIKitTests = TestSuite("UIKit_Swift4")
#else
let UIKitTests = TestSuite("UIKit_Swift3")
#endif
#if !os(watchOS) && !os(tvOS)
private func printDevice(_ o: UIDeviceOrientation) -> String {
var s = "\(o.isPortrait) \(UIDeviceOrientationIsPortrait(o)), "
s += "\(o.isLandscape) \(UIDeviceOrientationIsLandscape(o)), "
s += "\(o.isFlat), \(o.isValidInterfaceOrientation) "
s += "\(UIDeviceOrientationIsValidInterfaceOrientation(o))"
return s
}
private func printInterface(_ o: UIInterfaceOrientation) -> String {
return "\(o.isPortrait) \(UIInterfaceOrientationIsPortrait(o)), " +
"\(o.isLandscape) \(UIInterfaceOrientationIsLandscape(o))"
}
UIKitTests.test("UIDeviceOrientation") {
expectEqual("false false, false false, false, false false",
printDevice(.unknown))
expectEqual("true true, false false, false, true true",
printDevice(.portrait))
expectEqual("true true, false false, false, true true",
printDevice(.portraitUpsideDown))
expectEqual("false false, true true, false, true true",
printDevice(.landscapeLeft))
expectEqual("false false, true true, false, true true",
printDevice(.landscapeRight))
expectEqual("false false, false false, true, false false",
printDevice(.faceUp))
expectEqual("false false, false false, true, false false",
printDevice(.faceDown))
}
UIKitTests.test("UIInterfaceOrientation") {
expectEqual("false false, false false",
printInterface(.unknown))
expectEqual("true true, false false",
printInterface(.portrait))
expectEqual("true true, false false",
printInterface(.portraitUpsideDown))
expectEqual("false false, true true",
printInterface(.landscapeLeft))
expectEqual("false false, true true",
printInterface(.landscapeRight))
}
#endif
UIKitTests.test("UIEdgeInsets") {
let insets = [
UIEdgeInsets(top: 1.0, left: 2.0, bottom: 3.0, right: 4.0),
UIEdgeInsets(top: 1.0, left: 2.0, bottom: 3.1, right: 4.0),
UIEdgeInsets.zero
]
checkEquatable(insets, oracle: { $0 == $1 })
}
UIKitTests.test("UIOffset") {
let offsets = [
UIOffset(horizontal: 1.0, vertical: 2.0),
UIOffset(horizontal: 1.0, vertical: 3.0),
UIOffset.zero
]
checkEquatable(offsets, oracle: { $0 == $1 })
}
UIKitTests.test("UIFont.Weight") {
guard #available(iOS 8.2, *) else { return }
#if swift(>=4) // Swift 4
let regularFontWeight: UIFont.Weight = .regular
expectTrue(regularFontWeight == .regular)
expectTrue(regularFontWeight > .light)
expectTrue(regularFontWeight < .heavy)
expectTrue(regularFontWeight + 0.1 == 0.1 + regularFontWeight)
#else // Swift 3
let regularFontWeight: UIFontWeight = UIFontWeightRegular
expectTrue(regularFontWeight == UIFontWeightRegular)
expectTrue(regularFontWeight > UIFontWeightLight)
expectTrue(regularFontWeight < UIFontWeightHeavy)
expectTrue(regularFontWeight + 0.1 == 0.1 + UIFontWeightRegular)
#endif
}
#if !os(watchOS)
UIKitTests.test("UILayoutPriority") {
#if swift(>=4) // Swift 4
let lowLayoutPriority: UILayoutPriority = .defaultLow
let highLayoutPriority: UILayoutPriority = .defaultHigh
expectTrue(lowLayoutPriority < highLayoutPriority)
expectTrue(lowLayoutPriority + 2.0 == UILayoutPriority(lowLayoutPriority.rawValue + 2.0))
expectTrue(2.0 + lowLayoutPriority == UILayoutPriority(lowLayoutPriority.rawValue + 2.0))
expectTrue(lowLayoutPriority - 2.0 == UILayoutPriority(lowLayoutPriority.rawValue - 2.0))
expectTrue(highLayoutPriority - lowLayoutPriority == highLayoutPriority.rawValue - lowLayoutPriority.rawValue)
expectTrue(lowLayoutPriority + (highLayoutPriority - lowLayoutPriority) == highLayoutPriority)
var mutablePriority = lowLayoutPriority
mutablePriority -= 1.0
mutablePriority += 2.0
expectTrue(mutablePriority == lowLayoutPriority + 1.0)
let priorotyRange = lowLayoutPriority...highLayoutPriority
expectTrue(priorotyRange.contains(.defaultLow))
expectFalse(priorotyRange.contains(.required))
#else // Swift 3
let lowLayoutPriority: UILayoutPriority = UILayoutPriorityDefaultLow
let highLayoutPriority: UILayoutPriority = UILayoutPriorityDefaultHigh
expectTrue(lowLayoutPriority < highLayoutPriority)
expectTrue(2.0 + lowLayoutPriority == lowLayoutPriority + 2.0)
expectTrue(lowLayoutPriority + (highLayoutPriority - lowLayoutPriority) == highLayoutPriority)
var mutablePriority = lowLayoutPriority
mutablePriority -= 1.0
mutablePriority += 2.0
expectTrue(mutablePriority == lowLayoutPriority + 1.0)
#endif
}
#endif
#if !os(watchOS)
class TestChildView : UIView, CustomPlaygroundQuickLookable {
convenience init() {
self.init(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
}
var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text("child")
}
}
UIKitTests.test("CustomPlaygroundQuickLookable") {
switch PlaygroundQuickLook(reflecting: TestChildView()) {
case .text("child"): break
default: expectUnreachable(
"TestChildView custom quicklookable should have been invoked")
}
}
#endif
UIKitTests.test("NSValue bridging") {
expectBridgeToNSValue(UIEdgeInsets(top: 17, left: 38, bottom: 6, right: 79),
nsValueInitializer: { NSValue(uiEdgeInsets: $0) },
nsValueGetter: { $0.uiEdgeInsetsValue },
equal: (==))
expectBridgeToNSValue(UIOffset(horizontal: 17, vertical: 38),
nsValueInitializer: { NSValue(uiOffset: $0) },
nsValueGetter: { $0.uiOffsetValue },
equal: (==))
}
#if os(iOS) || os(tvOS)
UIKitTests.test("UIContentSizeCategory comparison") {
if #available(iOS 11.0, tvOS 11.0, *) {
expectTrue(UIContentSizeCategory.large < UIContentSizeCategory.extraLarge)
expectTrue(UIContentSizeCategory.large <= UIContentSizeCategory.extraLarge)
expectFalse(UIContentSizeCategory.large >= UIContentSizeCategory.extraLarge)
expectFalse(UIContentSizeCategory.large > UIContentSizeCategory.extraLarge)
expectFalse(UIContentSizeCategory.large == UIContentSizeCategory.extraLarge)
expectTrue(UIContentSizeCategory.extraLarge > UIContentSizeCategory.large)
expectTrue(UIContentSizeCategory.extraLarge >= UIContentSizeCategory.large)
expectFalse(UIContentSizeCategory.extraLarge < UIContentSizeCategory.large)
expectFalse(UIContentSizeCategory.extraLarge <= UIContentSizeCategory.large)
expectFalse(UIContentSizeCategory.extraLarge == UIContentSizeCategory.large)
expectTrue(UIContentSizeCategory.large == UIContentSizeCategory.large)
expectTrue(UIContentSizeCategory.large >= UIContentSizeCategory.large)
expectTrue(UIContentSizeCategory.large <= UIContentSizeCategory.large)
expectFalse(UIContentSizeCategory.large > UIContentSizeCategory.large)
expectFalse(UIContentSizeCategory.large < UIContentSizeCategory.large)
expectTrue(UIContentSizeCategory.accessibilityExtraExtraExtraLarge.isAccessibilityCategory)
expectFalse(UIContentSizeCategory.extraSmall.isAccessibilityCategory)
}
}
#endif
#if os(iOS) || os(watchOS) || os(tvOS)
UIKitTests.test("UIFontMetrics scaling") {
if #available(iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
let metrics = UIFontTextStyle.headline.metrics
expectTrue(metrics != nil)
}
}
#endif
#if os(iOS) || os(tvOS)
UIKitTests.test("UIFocusEnvironment") {
if #available(iOS 11.0, tvOS 11.0, *) {
let item1 = UIView()
let item2 = UIView()
_ = item1.contains(item2)
_ = item1.isFocused
}
}
#endif
#if os(iOS)
UIKitTests.test("NSItemProviderReadingWriting support") {
if #available(iOS 11.0, *) {
func f<T : UIDragDropSession>(session: T) {
_ = session.canLoadObjects(ofClass: String.self)
_ = session.canLoadObjects(ofClass: URL.self)
}
func g<T : UIDropSession>(session: T) {
_ = session.loadObjects(ofClass: String.self) { _ in ()}
_ = session.loadObjects(ofClass: URL.self) { _ in () }
}
let pc0 = UIPasteConfiguration(forAccepting: String.self)
let pc1 = UIPasteConfiguration(forAccepting: URL.self)
pc0.addTypeIdentifiers(forAccepting: URL.self)
pc1.addTypeIdentifiers(forAccepting: String.self)
var pb = UIPasteboard.general
pb.setObjects(["Hello"])
pb.setObjects([URL(string: "https://www.apple.com")!])
pb.setObjects(["Hello"], localOnly: true, expirationDate: nil)
pb.setObjects([URL(string: "https://www.apple.com")!], localOnly: true, expirationDate: nil)
}
}
#endif
runAllTests()
| apache-2.0 |
AlbertMontserrat/AMGLanguageManager | Example/Tests/Tests23.swift | 1 | 9110 | import UIKit
import AMGLanguageManager
class Tests23
{
func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample68() {
// This is an example of a functional test case.
}
func testExample67() {
// This is an example of a functional test case.
}
func testExample66() {
// This is an example of a functional test case.
}
func testExample65() {
// This is an example of a functional test case.
}
func testExample64() {
// This is an example of a functional test case.
}
func testExample63() {
// This is an example of a functional test case.
}
func testExample62() {
// This is an example of a functional test case.
}
func testExample61() {
// This is an example of a functional test case.
}
func testExample60() {
// This is an example of a functional test case.
}
func testExample59() {
// This is an example of a functional test case.
}
func testExample58() {
// This is an example of a functional test case.
}
func testExample57() {
// This is an example of a functional test case.
}
func testExample56() {
// This is an example of a functional test case.
}
func testExample55() {
// This is an example of a functional test case.
}
func testExample54() {
// This is an example of a functional test case.
}
func testExample53() {
// This is an example of a functional test case.
}
func testExample52() {
// This is an example of a functional test case.
}
func testExample51() {
// This is an example of a functional test case.
}
func testExample50() {
// This is an example of a functional test case.
}
func testExample49() {
// This is an example of a functional test case.
}
func testExample48() {
// This is an example of a functional test case.
}
func testExample47() {
// This is an example of a functional test case.
}
func testExample46() {
// This is an example of a functional test case.
}
func testExample45() {
// This is an example of a functional test case.
}
func testExample44() {
// This is an example of a functional test case.
}
func testExample43() {
// This is an example of a functional test case.
}
func testExample42() {
// This is an example of a functional test case.
}
func testExample41() {
// This is an example of a functional test case.
}
func testExample40() {
// This is an example of a functional test case.
}
func testExample39() {
// This is an example of a functional test case.
}
func testExample38() {
// This is an example of a functional test case.
}
func testExample37() {
// This is an example of a functional test case.
}
func testExample36() {
// This is an example of a functional test case.
}
func testExample35() {
// This is an example of a functional test case.
}
func testExample34() {
// This is an example of a functional test case.
}
func testExample33() {
// This is an example of a functional test case.
}
func testExample32() {
// This is an example of a functional test case.
}
func testExample31() {
// This is an example of a functional test case.
}
func testExample30() {
// This is an example of a functional test case.
}
func testExample29() {
// This is an example of a functional test case.
}
func testExample28() {
// This is an example of a functional test case.
}
func testExample27() {
// This is an example of a functional test case.
}
func testExample26() {
// This is an example of a functional test case.
}
func testExample25() {
// This is an example of a functional test case.
}
func testExample24() {
// This is an example of a functional test case.
}
func testExample23() {
// This is an example of a functional test case.
}
func testExample22() {
// This is an example of a functional test case.
}
func testExample21() {
// This is an example of a functional test case.
}
func testExample20() {
// This is an example of a functional test case.
}
func testExample19() {
// This is an example of a functional test case.
}
func testExample18() {
// This is an example of a functional test case.
}
func testExample17() {
// This is an example of a functional test case.
}
func testExample16() {
// This is an example of a functional test case.
}
func testExample15() {
// This is an example of a functional test case.
}
func testExample14() {
// This is an example of a functional test case.
}
func testExample13() {
// This is an example of a functional test case.
}
func testExample12() {
// This is an example of a functional test case.
}
func testExample11() {
// This is an example of a functional test case.
}
func testExample10() {
// This is an example of a functional test case.
}
func testExample9() {
// This is an example of a functional test case.
}
func testExample8() {
// This is an example of a functional test case.
}
func testExample7() {
// This is an example of a functional test case.
}
func testExample6() {
// This is an example of a functional test case.
}
func testExample5() {
// This is an example of a functional test case.
}
func testExample4() {
// This is an example of a functional test case.
}
func testExample3() {
// This is an example of a functional test case.
}
func testExample2() {
// This is an example of a functional test case.
}
func testExample1() {
// This is an example of a functional test case.
}
func testPerformanceExample() {
// This is an example of a performance test case.
}
}
| mit |
inoity/nariko | Nariko/Classes/BubbleTapGestureRecognizer.swift | 1 | 412 | //
// BubbleTapGestureRecognizer.swift
// Nariko
//
// Created by Zsolt Papp on 13/06/16.
// Copyright © 2016 Nariko. All rights reserved.
//
import UIKit
import UIKit.UIGestureRecognizerSubclass
open class BubbleTapGestureRecognizer: UITapGestureRecognizer {
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
NarikoTool.sharedInstance.removeBubble()
}
}
| mit |
SmallPlanetSwift/PlanetSwift | Tools/template/swift/global_base.swift | 1 | 4930 | <%
FULL_NAME_CAPS = "_"..string.upper(this.namespace).."_"
FULL_NAME_CAMEL = capitalizedString(this.namespace)
%>//
// Autogenerated by gaxb at <%= os.date("%I:%M:%S %p on %x") %>
//
// swiftlint:disable superfluous_disable_command
// swiftlint:disable cyclomatic_complexity
// swiftlint:disable identifier_name
// swiftlint:disable force_cast
// swiftlint:disable type_body_length
// swiftlint:disable function_body_length
// swiftlint:disable line_length
// swiftlint:disable file_length
import Foundation
import AEXML
<% if (this.namespace ~= "PlanetUI") then %>import PlanetSwift
<% end %>
//private let xmlCache = NSCache<NSString, AnyObject>()
open class <%= FULL_NAME_CAMEL %> {
open class func readFromFile(_ filePath: String, prepare: Bool = true) -> GaxbElement? {
do {
let xmlString = try String(contentsOfFile: filePath, encoding: .utf8)
return <%= FULL_NAME_CAMEL %>.readFromString(xmlString, prepare: prepare)
} catch {
return nil
}
}
open class func readFromString(_ string: String, prepare: Bool = true) -> GaxbElement? {
/*
if let cachedElement = xmlCache.object(forKey: string as NSString) as? GaxbElement {
let copiedCache = cachedElement.copy()
if prepare {
copiedCache.visit() { $0.gaxbPrepare() }
}
return copiedCache
}*/
if let xmlData = <%= FULL_NAME_CAMEL %>.processExpressions(string).data(using: .utf8, allowLossyConversion: false) {
do {
var options = AEXMLOptions()
options.parserSettings.shouldProcessNamespaces = true
let xmlDoc = try AEXMLDocument(xml: xmlData, options: options)
if let parsedElement = <%= FULL_NAME_CAMEL %>.parseElement(xmlDoc.root) {
//let copiedElement = parsedElement.copy()
//xmlCache.setObject(copiedElement, forKey: string as NSString)
if prepare {
parsedElement.visit { $0.gaxbPrepare() }
}
return parsedElement
}
} catch {
return nil
}
}
return nil
}
open class func namespaceForElement(_ element: AEXMLElement) -> String {
if let namespaceURI = element.namespaceURI {
return NSString(string: namespaceURI).lastPathComponent
}
return "<%= FULL_NAME_CAMEL %>"
}
open class func parseElement(_ element: AEXMLElement) -> GaxbElement? {
guard let entity = GaxbFactory.element(namespaceForElement(element), name: element.name) else { return nil }
if let styleId = element.attributes["styleId"],
let styleElement = Object.styleForId(styleId) {
_ = styleElement.imprintAttributes(entity)
}
// Note: the ordering of the attributes are not gauranteed, so check if externalClass exists first
// and set it if it does, so the external class can have access to all of the attributes
for (attribute, value) in element.attributes where attribute == "externalClass" {
entity.setAttribute(value, key: attribute)
break
}
for (attribute, value) in element.attributes where attribute != "externalClass" {
entity.setAttribute(value, key: attribute)
}
for child in element.children {
if let subEntity = PlanetUI.parseElement(child) {
entity.setElement(subEntity, key: child.name)
}
}
return entity
}
<%
-- simpleType definitions, such as enums
for k,v in pairs(schema.simpleTypes) do
-- only include defintions from this schema's namespace
if (isEnumForItem(v)) then
if (schema.namespace == v.namespace) then
gaxb_print("\tpublic enum "..v.name..": String {\n");
local appinfo = gaxb_xpath(v.xml, "./XMLSchema:annotation/XMLSchema:appinfo");
local enums = gaxb_xpath(v.xml, "./XMLSchema:restriction/XMLSchema:enumeration");
if(appinfo ~= nil) then
appinfo = appinfo[1].content;
end
if(appinfo == "ENUM" or appinfo == "NAMED_ENUM") then
for k,v in pairs(enums) do
gaxb_print("\t\tcase "..v.attributes.value.."\n")
end
end
-- if(appinfo == "ENUM_MASK") then
-- local i = 1
-- gaxb_print("\topen enum\n{\n")
-- for k,v in pairs(enums) do
-- gaxb_print("\t\t"..v.attributes.value.." = "..i..",\n")
-- i = i * 2;
-- end
-- gaxb_print("\t};\n")
-- end
gaxb_print("\t}\n\n");
end
end
end
%>}
@objc(<%= FULL_NAME_CAMEL %>GaxbFactory) public class <%= FULL_NAME_CAMEL %>GaxbFactory: GaxbFactory {
public override func classWithName(_ name: String) -> GaxbElement? {
switch name {<%
for k,v in pairs(schema.elements) do
-- if not in the schema namespace, skip
if (schema.namespace == v.namespace) then
v.name = cleanedName(v.name);%>
case "<%= v.name %>":
return <%= v.name %>()<%
end
end %>
default:
return nil
}
}
}
public extension GaxbElement {<%
for k,v in pairs(schema.elements) do
-- if not in the schema namespace, skip
if (schema.namespace == v.namespace) then
v.name = cleanedName(v.name);%>
var as<%= v.name %>: <%= v.name %>? { return self as? <%= v.name %> }<%
end
end %>
}
| mit |
xwu/swift | test/SILGen/c_function_pointers.swift | 15 | 4413 | // RUN: %target-swift-emit-silgen -verify %s | %FileCheck %s
if true {
var x = 0 // expected-warning {{variable 'x' was never mutated; consider changing to 'let' constant}}
func local() -> Int { return 0 }
func localWithContext() -> Int { return x }
func transitiveWithoutContext() -> Int { return local() }
// Can't convert a closure with context to a C function pointer
let _: @convention(c) () -> Int = { x } // expected-error{{cannot be formed from a closure that captures context}}
let _: @convention(c) () -> Int = { [x] in x } // expected-error{{cannot be formed from a closure that captures context}}
let _: @convention(c) () -> Int = localWithContext // expected-error{{cannot be formed from a local function that captures context}}
let _: @convention(c) () -> Int = local
let _: @convention(c) () -> Int = transitiveWithoutContext
}
class C {
static func staticMethod() -> Int { return 0 }
class func classMethod() -> Int { return 0 }
}
class Generic<X : C> {
func f<Y : C>(_ y: Y) {
let _: @convention(c) () -> Int = { return 0 }
let _: @convention(c) () -> Int = { return X.staticMethod() } // expected-error{{cannot be formed from a closure that captures generic parameters}}
let _: @convention(c) () -> Int = { return Y.staticMethod() } // expected-error{{cannot be formed from a closure that captures generic parameters}}
}
}
func values(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(c) (Int) -> Int {
return arg
}
// CHECK-LABEL: sil hidden [ossa] @$s19c_function_pointers6valuesyS2iXCS2iXCF
// CHECK: bb0(%0 : $@convention(c) (Int) -> Int):
// CHECK: return %0 : $@convention(c) (Int) -> Int
@discardableResult
func calls(_ arg: @convention(c) (Int) -> Int, _ x: Int) -> Int {
return arg(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s19c_function_pointers5callsyS3iXC_SitF
// CHECK: bb0(%0 : $@convention(c) @noescape (Int) -> Int, %1 : $Int):
// CHECK: [[RESULT:%.*]] = apply %0(%1)
// CHECK: return [[RESULT]]
@discardableResult
func calls_no_args(_ arg: @convention(c) () -> Int) -> Int {
return arg()
}
func global(_ x: Int) -> Int { return x }
func no_args() -> Int { return 42 }
// CHECK-LABEL: sil hidden [ossa] @$s19c_function_pointers0B19_to_swift_functionsyySiF
func pointers_to_swift_functions(_ x: Int) {
// CHECK: bb0([[X:%.*]] : $Int):
func local(_ y: Int) -> Int { return y }
// CHECK: [[GLOBAL_C:%.*]] = function_ref @$s19c_function_pointers6globalyS2iFTo
// CHECK: [[CVT:%.*]] = convert_function [[GLOBAL_C]]
// CHECK: apply {{.*}}([[CVT]], [[X]])
calls(global, x)
// CHECK: [[LOCAL_C:%.*]] = function_ref @$s19c_function_pointers0B19_to_swift_functionsyySiF5localL_yS2iFTo
// CHECK: [[CVT:%.*]] = convert_function [[LOCAL_C]]
// CHECK: apply {{.*}}([[CVT]], [[X]])
calls(local, x)
// CHECK: [[CLOSURE_C:%.*]] = function_ref @$s19c_function_pointers0B19_to_swift_functionsyySiFS2iXEfU_To
// CHECK: [[CVT:%.*]] = convert_function [[CLOSURE_C]]
// CHECK: apply {{.*}}([[CVT]], [[X]])
calls({ $0 + 1 }, x)
calls_no_args(no_args)
// CHECK: [[NO_ARGS_C:%.*]] = function_ref @$s19c_function_pointers7no_argsSiyFTo
// CHECK: [[CVT:%.*]] = convert_function [[NO_ARGS_C]]
// CHECK: apply {{.*}}([[CVT]])
}
func unsupported(_ a: Any) -> Int { return 0 }
func pointers_to_bad_swift_functions(_ x: Int) {
calls(unsupported, x) // expected-error{{C function pointer signature '(Any) -> Int' is not compatible with expected type '@convention(c) (Int) -> Int'}}
}
// CHECK-LABEL: sil private [ossa] @$s19c_function_pointers22StructWithInitializersV3fn1yyXCvpfiyycfU_ : $@convention(thin) () -> () {
// CHECK-LABEL: sil private [thunk] [ossa] @$s19c_function_pointers22StructWithInitializersV3fn1yyXCvpfiyycfU_To : $@convention(c) () -> () {
struct StructWithInitializers {
let fn1: @convention(c) () -> () = {}
init(a: ()) {}
init(b: ()) {}
}
func pointers_to_nested_local_functions_in_generics<T>(x: T) -> Int{
func foo(y: Int) -> Int { return y }
return calls(foo, 0)
}
func capture_list_no_captures(x: Int) {
calls({ [x] in $0 }, 0) // expected-warning {{capture 'x' was never used}}
}
class Selfless {
func capture_dynamic_self() {
calls_no_args { _ = Self.self; return 0 }
// expected-error@-1 {{a C function pointer cannot be formed from a closure that captures dynamic Self type}}
}
}
| apache-2.0 |
kstaring/swift | test/Constraints/same_types.swift | 3 | 5212 | // RUN: %target-parse-verify-swift
protocol Fooable {
associatedtype Foo
var foo: Foo { get }
}
protocol Barrable {
associatedtype Bar: Fooable
var bar: Bar { get }
}
struct X {}
struct Y: Fooable {
typealias Foo = X
var foo: X { return X() }
}
struct Z: Barrable {
typealias Bar = Y
var bar: Y { return Y() }
}
protocol TestSameTypeRequirement {
func foo<F1: Fooable>(_ f: F1) where F1.Foo == X
}
struct SatisfySameTypeRequirement : TestSameTypeRequirement {
func foo<F2: Fooable>(_ f: F2) where F2.Foo == X {}
}
func test1<T: Fooable>(_ fooable: T) -> X where T.Foo == X {
return fooable.foo
}
struct NestedConstraint<T> {
func tFoo<U: Fooable>(_ fooable: U) -> T where U.Foo == T {
return fooable.foo
}
}
func test2<T: Fooable, U: Fooable>(_ t: T, u: U) -> (X, X)
where T.Foo == X, U.Foo == T.Foo {
return (t.foo, u.foo)
}
func test2a<T: Fooable, U: Fooable>(_ t: T, u: U) -> (X, X)
where T.Foo == X, T.Foo == U.Foo {
return (t.foo, u.foo)
}
func test3<T: Fooable, U: Fooable>(_ t: T, u: U) -> (X, X)
where T.Foo == X, U.Foo == X, T.Foo == U.Foo {
return (t.foo, u.foo)
}
func fail1<
T: Fooable, U: Fooable
>(_ t: T, u: U) -> (X, Y)
where T.Foo == X, U.Foo == Y, T.Foo == U.Foo { // expected-error{{generic parameter 'Foo' cannot be equal to both 'X' and 'Y'}}
return (t.foo, u.foo)
}
func fail2<
T: Fooable, U: Fooable
>(_ t: T, u: U) -> (X, Y)
where T.Foo == U.Foo, T.Foo == X, U.Foo == Y { // expected-error{{generic parameter 'Foo' cannot be equal to both 'X' and 'Y'}}
return (t.foo, u.foo) // expected-error{{cannot convert return expression of type 'X' to return type 'Y'}}
}
func test4<T: Barrable>(_ t: T) -> Y where T.Bar == Y {
return t.bar
}
func fail3<T: Barrable>(_ t: T) -> X
where T.Bar == X { // expected-error{{'X' does not conform to required protocol 'Fooable'}}
return t.bar // expected-error{{cannot convert return expression of type 'T.Bar' to return type 'X'}}
}
func test5<T: Barrable>(_ t: T) -> X where T.Bar.Foo == X {
return t.bar.foo
}
func test6<T: Barrable>(_ t: T) -> (Y, X) where T.Bar == Y {
return (t.bar, t.bar.foo)
}
func test7<T: Barrable>(_ t: T) -> (Y, X) where T.Bar == Y, T.Bar.Foo == X {
return (t.bar, t.bar.foo)
}
func fail4<T: Barrable>(_ t: T) -> (Y, Z)
where
T.Bar == Y,
T.Bar.Foo == Z { // expected-error{{generic parameter 'Foo' cannot be equal to both 'Y.Foo' (aka 'X') and 'Z'}}
return (t.bar, t.bar.foo) // expected-error{{cannot convert return expression of type 'X' to return type 'Z'}}
}
// TODO: repeat diagnostic
func fail5<T: Barrable>(_ t: T) -> (Y, Z)
where
T.Bar.Foo == Z,
T.Bar == Y { // expected-error 2{{generic parameter 'Foo' cannot be equal to both 'Z' and 'Y.Foo'}}
return (t.bar, t.bar.foo) // expected-error{{cannot convert return expression of type 'X' to return type 'Z'}}
}
func test8<T: Fooable>(_ t: T) where T.Foo == X, T.Foo == Y {} // expected-error{{generic parameter 'Foo' cannot be equal to both 'X' and 'Y'}}
func testAssocTypeEquivalence<T: Fooable>(_ fooable: T) -> X.Type
where T.Foo == X {
return T.Foo.self
}
func fail6<T>(_ t: T) -> Int where T == Int { // expected-error{{same-type requirement makes generic parameter 'T' non-generic}}
return t
}
func test8<T: Barrable, U: Barrable>(_ t: T, u: U) -> (Y, Y, X, X)
where T.Bar == Y, U.Bar.Foo == X, T.Bar == U.Bar {
return (t.bar, u.bar, t.bar.foo, u.bar.foo)
}
func test8a<T: Barrable, U: Barrable>(_ t: T, u: U) -> (Y, Y, X, X)
where
T.Bar == Y, U.Bar.Foo == X, U.Bar == T.Bar {
return (t.bar, u.bar, t.bar.foo, u.bar.foo)
}
// rdar://problem/19137463
func rdar19137463<T>(_ t: T) where T.a == T {} // expected-error{{'a' is not a member type of 'T'}}
rdar19137463(1)
struct Brunch<U : Fooable> where U.Foo == X {}
struct BadFooable : Fooable {
typealias Foo = DoesNotExist // expected-error{{use of undeclared type 'DoesNotExist'}}
var foo: Foo { while true {} }
}
func bogusInOutError(d: inout Brunch<BadFooable>) {}
// Some interesting invalid cases that used to crash
protocol P {
associatedtype A
associatedtype B
}
struct Q : P {
typealias A = Int
typealias B = Int
}
struct S1<T : P> {
func foo<X, Y>(x: X, y: Y) where X == T.A, Y == T.B {
print(X.self)
print(Y.self)
print(x)
print(y)
}
}
S1<Q>().foo(x: 1, y: 2)
struct S2<T : P> where T.A == T.B {
// expected-error@+1 {{same-type requirement makes generic parameters 'X' and 'Y' equivalent}}
func foo<X, Y>(x: X, y: Y) where X == T.A, Y == T.B {
print(X.self)
print(Y.self)
print(x)
print(y)
}
}
S2<Q>().foo(x: 1, y: 2)
struct S3<T : P> {
// expected-error@+1 {{same-type requirement makes generic parameters 'X' and 'Y' equivalent}}
func foo<X, Y>(x: X, y: Y) where X == T.A, Y == T.A {}
}
S3<Q>().foo(x: 1, y: 2)
// Secondaries can be equated OK, even if we're imposing
// new conformances onto an outer secondary
protocol PPP {}
protocol PP {
associatedtype A : PPP
}
struct SSS : PPP {}
struct SS : PP { typealias A = SSS }
struct QQ : P {
typealias A = SSS
typealias B = Int
}
struct S4<T : P> {
func foo<X : PP>(x: X) where X.A == T.A {
print(x)
print(X.self)
}
}
S4<QQ>().foo(x: SS())
| apache-2.0 |
lieven/fietsknelpunten-ios | FietsknelpuntenAPI/Jurisdiction.swift | 1 | 385 | //
// Jurisdiction.swift
// Fietsknelpunten
//
// Created by Lieven Dekeyser on 25/11/16.
// Copyright © 2016 Fietsknelpunten. All rights reserved.
//
import Foundation
public struct Jurisdiction
{
public let identifier: String
public let name: String
public let countryCode: String
public let postalCodes: [String]
public let info: String?
public let types: [String]?
}
| mit |
luckytianyiyan/TySimulator | TySimulator/DirectoryWatcher.swift | 1 | 4802 | //
// DirectoryWatcher.swift
// TySimulator
//
// Created by ty0x2333 on 2017/7/20.
// Copyright © 2017年 ty0x2333. All rights reserved.
//
import Foundation
/// https://developer.apple.com/library/content/samplecode/DocInteraction/Listings/ReadMe_txt.html
class DirectoryWatcher {
var dirFD: Int32 = -1
var kq: Int32 = -1
var dirKQRef: CFFileDescriptor?
private var didChange: (() -> Void)?
deinit {
invalidate()
}
class func watchFolder(path: String, didChange:(() -> Void)?) -> DirectoryWatcher? {
let result: DirectoryWatcher = DirectoryWatcher()
result.didChange = didChange
if result.startMonitoring(directory: path as NSString) {
return result
}
return nil
}
func invalidate() {
if dirKQRef != nil {
CFFileDescriptorInvalidate(dirKQRef)
dirKQRef = nil
// We don't need to close the kq, CFFileDescriptorInvalidate closed it instead.
// Change the value so no one thinks it's still live.
kq = -1
}
if dirFD != -1 {
close(dirFD)
dirFD = -1
}
}
// MARK: Private
func kqueueFired() {
assert(kq >= 0)
var event: kevent = kevent()
var timeout: timespec = timespec(tv_sec: 0, tv_nsec: 0)
let eventCount = kevent(kq, nil, 0, &event, 1, &timeout)
assert((eventCount >= 0) && (eventCount < 2))
didChange?()
CFFileDescriptorEnableCallBacks(dirKQRef, kCFFileDescriptorReadCallBack)
}
func startMonitoring(directory: NSString) -> Bool {
// Double initializing is not going to work...
if dirKQRef == nil && dirFD == -1 && kq == -1 {
// Open the directory we're going to watch
dirFD = open(directory.fileSystemRepresentation, O_EVTONLY)
if dirFD >= 0 {
// Create a kqueue for our event messages...
kq = kqueue()
if kq >= 0 {
var eventToAdd: kevent = kevent()
eventToAdd.ident = UInt(dirFD)
eventToAdd.filter = Int16(EVFILT_VNODE)
eventToAdd.flags = UInt16(EV_ADD | EV_CLEAR)
eventToAdd.fflags = UInt32(NOTE_WRITE)
eventToAdd.data = 0
eventToAdd.udata = nil
let errNum = kevent(kq, &eventToAdd, 1, nil, 0, nil)
if errNum == 0 {
var context = CFFileDescriptorContext(version: 0, info: UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()), retain: nil, release: nil, copyDescription: nil)
let callback: CFFileDescriptorCallBack = { (kqRef: CFFileDescriptor?, callBackTypes: CFOptionFlags, info: UnsafeMutableRawPointer?) in
guard let info = info else {
return
}
let obj: DirectoryWatcher = Unmanaged<DirectoryWatcher>.fromOpaque(info).takeUnretainedValue()
assert(callBackTypes == kCFFileDescriptorReadCallBack)
obj.kqueueFired()
}
// Passing true in the third argument so CFFileDescriptorInvalidate will close kq.
dirKQRef = CFFileDescriptorCreate(nil, kq, true, callback, &context)
if dirKQRef != nil {
if let rls = CFFileDescriptorCreateRunLoopSource(nil, dirKQRef, 0) {
CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, CFRunLoopMode.defaultMode)
CFFileDescriptorEnableCallBacks(dirKQRef, kCFFileDescriptorReadCallBack)
// If everything worked, return early and bypass shutting things down
return true
}
// Couldn't create a runloop source, invalidate and release the CFFileDescriptorRef
CFFileDescriptorInvalidate(dirKQRef)
dirKQRef = nil
}
}
// kq is active, but something failed, close the handle...
close(kq)
kq = -1
}
// file handle is open, but something failed, close the handle...
close(dirFD)
dirFD = -1
}
}
return false
}
}
| mit |
noppoMan/aws-sdk-swift | Sources/Soto/Services/Athena/Athena_Paginator.swift | 1 | 22854 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension Athena {
/// Streams the results of a single query execution specified by QueryExecutionId from the Athena query results location in Amazon S3. For more information, see Query Results in the Amazon Athena User Guide. This request does not execute the query but returns results. Use StartQueryExecution to run a query. To stream query results successfully, the IAM principal with permission to call GetQueryResults also must have permissions to the Amazon S3 GetObject action for the Athena query results location. IAM principals with permission to the Amazon S3 GetObject action for the query results location are able to retrieve query results from Amazon S3 even if permission to the GetQueryResults action is denied. To restrict user or role access, ensure that Amazon S3 permissions to the Athena query location are denied.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func getQueryResultsPaginator<Result>(
_ input: GetQueryResultsInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, GetQueryResultsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: getQueryResults,
tokenKey: \GetQueryResultsOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func getQueryResultsPaginator(
_ input: GetQueryResultsInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (GetQueryResultsOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: getQueryResults,
tokenKey: \GetQueryResultsOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the data catalogs in the current AWS account.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listDataCatalogsPaginator<Result>(
_ input: ListDataCatalogsInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListDataCatalogsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listDataCatalogs,
tokenKey: \ListDataCatalogsOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listDataCatalogsPaginator(
_ input: ListDataCatalogsInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListDataCatalogsOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listDataCatalogs,
tokenKey: \ListDataCatalogsOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the databases in the specified data catalog.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listDatabasesPaginator<Result>(
_ input: ListDatabasesInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListDatabasesOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listDatabases,
tokenKey: \ListDatabasesOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listDatabasesPaginator(
_ input: ListDatabasesInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListDatabasesOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listDatabases,
tokenKey: \ListDatabasesOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provides a list of available query IDs only for queries saved in the specified workgroup. Requires that you have access to the specified workgroup. If a workgroup is not specified, lists the saved queries for the primary workgroup. For code samples using the AWS SDK for Java, see Examples and Code Samples in the Amazon Athena User Guide.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listNamedQueriesPaginator<Result>(
_ input: ListNamedQueriesInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListNamedQueriesOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listNamedQueries,
tokenKey: \ListNamedQueriesOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listNamedQueriesPaginator(
_ input: ListNamedQueriesInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListNamedQueriesOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listNamedQueries,
tokenKey: \ListNamedQueriesOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provides a list of available query execution IDs for the queries in the specified workgroup. If a workgroup is not specified, returns a list of query execution IDs for the primary workgroup. Requires you to have access to the workgroup in which the queries ran. For code samples using the AWS SDK for Java, see Examples and Code Samples in the Amazon Athena User Guide.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listQueryExecutionsPaginator<Result>(
_ input: ListQueryExecutionsInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListQueryExecutionsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listQueryExecutions,
tokenKey: \ListQueryExecutionsOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listQueryExecutionsPaginator(
_ input: ListQueryExecutionsInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListQueryExecutionsOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listQueryExecutions,
tokenKey: \ListQueryExecutionsOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the metadata for the tables in the specified data catalog database.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listTableMetadataPaginator<Result>(
_ input: ListTableMetadataInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListTableMetadataOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listTableMetadata,
tokenKey: \ListTableMetadataOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listTableMetadataPaginator(
_ input: ListTableMetadataInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListTableMetadataOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listTableMetadata,
tokenKey: \ListTableMetadataOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the tags associated with an Athena workgroup or data catalog resource.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listTagsForResourcePaginator<Result>(
_ input: ListTagsForResourceInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListTagsForResourceOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listTagsForResource,
tokenKey: \ListTagsForResourceOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listTagsForResourcePaginator(
_ input: ListTagsForResourceInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListTagsForResourceOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listTagsForResource,
tokenKey: \ListTagsForResourceOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists available workgroups for the account.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listWorkGroupsPaginator<Result>(
_ input: ListWorkGroupsInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListWorkGroupsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listWorkGroups,
tokenKey: \ListWorkGroupsOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listWorkGroupsPaginator(
_ input: ListWorkGroupsInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListWorkGroupsOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listWorkGroups,
tokenKey: \ListWorkGroupsOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension Athena.GetQueryResultsInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Athena.GetQueryResultsInput {
return .init(
maxResults: self.maxResults,
nextToken: token,
queryExecutionId: self.queryExecutionId
)
}
}
extension Athena.ListDataCatalogsInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Athena.ListDataCatalogsInput {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension Athena.ListDatabasesInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Athena.ListDatabasesInput {
return .init(
catalogName: self.catalogName,
maxResults: self.maxResults,
nextToken: token
)
}
}
extension Athena.ListNamedQueriesInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Athena.ListNamedQueriesInput {
return .init(
maxResults: self.maxResults,
nextToken: token,
workGroup: self.workGroup
)
}
}
extension Athena.ListQueryExecutionsInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Athena.ListQueryExecutionsInput {
return .init(
maxResults: self.maxResults,
nextToken: token,
workGroup: self.workGroup
)
}
}
extension Athena.ListTableMetadataInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Athena.ListTableMetadataInput {
return .init(
catalogName: self.catalogName,
databaseName: self.databaseName,
expression: self.expression,
maxResults: self.maxResults,
nextToken: token
)
}
}
extension Athena.ListTagsForResourceInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Athena.ListTagsForResourceInput {
return .init(
maxResults: self.maxResults,
nextToken: token,
resourceARN: self.resourceARN
)
}
}
extension Athena.ListWorkGroupsInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Athena.ListWorkGroupsInput {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
| apache-2.0 |
VeinGuo/VGPlayer | VGPlayerExample/VGPlayerExample/DefaultPlayerView/VGMediaViewController.swift | 1 | 3404 | //
// VGMediaViewController.swift
// Example
//
// Created by Vein on 2017/5/29.
// Copyright © 2017年 Vein. All rights reserved.
//
import UIKit
import VGPlayer
import SnapKit
class VGMediaViewController: UIViewController {
var player = VGPlayer()
var url1 : URL?
override func viewDidLoad() {
super.viewDidLoad()
self.url1 = URL(fileURLWithPath: Bundle.main.path(forResource: "2", ofType: "mp4")!)
let url = URL(string: "http://lxdqncdn.miaopai.com/stream/6IqHc-OnSMBIt-LQjPJjmA__.mp4?ssig=a81b90fdeca58e8ea15c892a49bce53f&time_stamp=1508166491488")!
self.player.replaceVideo(url)
view.addSubview(self.player.displayView)
self.player.play()
self.player.backgroundMode = .proceed
self.player.delegate = self
self.player.displayView.delegate = self
self.player.displayView.titleLabel.text = "China NO.1"
self.player.displayView.snp.makeConstraints { [weak self] (make) in
guard let strongSelf = self else { return }
make.top.equalTo(strongSelf.view.snp.top)
make.left.equalTo(strongSelf.view.snp.left)
make.right.equalTo(strongSelf.view.snp.right)
make.height.equalTo(strongSelf.view.snp.width).multipliedBy(3.0/4.0) // you can 9.0/16.0
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: true)
UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: false)
self.player.play()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: true)
UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.default, animated: false)
UIApplication.shared.setStatusBarHidden(false, with: .none)
self.player.pause()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func changeMedia(_ sender: Any) {
player.replaceVideo(url1!)
player.play()
}
}
extension VGMediaViewController: VGPlayerDelegate {
func vgPlayer(_ player: VGPlayer, playerFailed error: VGPlayerError) {
print(error)
}
func vgPlayer(_ player: VGPlayer, stateDidChange state: VGPlayerState) {
print("player State ",state)
}
func vgPlayer(_ player: VGPlayer, bufferStateDidChange state: VGPlayerBufferstate) {
print("buffer State", state)
}
}
extension VGMediaViewController: VGPlayerViewDelegate {
func vgPlayerView(_ playerView: VGPlayerView, willFullscreen fullscreen: Bool) {
}
func vgPlayerView(didTappedClose playerView: VGPlayerView) {
if playerView.isFullScreen {
playerView.exitFullscreen()
} else {
self.navigationController?.popViewController(animated: true)
}
}
func vgPlayerView(didDisplayControl playerView: VGPlayerView) {
UIApplication.shared.setStatusBarHidden(!playerView.isDisplayControl, with: .fade)
}
}
| mit |
gu704823/huobanyun | huobanyun/Spring/SpringLabel.swift | 18 | 2732 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To (meng@designcode.io)
//
// 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
open class SpringLabel: UILabel, Springable {
@IBInspectable public var autostart: Bool = false
@IBInspectable public var autohide: Bool = false
@IBInspectable public var animation: String = ""
@IBInspectable public var force: CGFloat = 1
@IBInspectable public var delay: CGFloat = 0
@IBInspectable public var duration: CGFloat = 0.7
@IBInspectable public var damping: CGFloat = 0.7
@IBInspectable public var velocity: CGFloat = 0.7
@IBInspectable public var repeatCount: Float = 1
@IBInspectable public var x: CGFloat = 0
@IBInspectable public var y: CGFloat = 0
@IBInspectable public var scaleX: CGFloat = 1
@IBInspectable public var scaleY: CGFloat = 1
@IBInspectable public var rotate: CGFloat = 0
@IBInspectable public var curve: String = ""
public var opacity: CGFloat = 1
public var animateFrom: Bool = false
lazy private var spring : Spring = Spring(self)
override open func awakeFromNib() {
super.awakeFromNib()
self.spring.customAwakeFromNib()
}
open override func layoutSubviews() {
super.layoutSubviews()
spring.customLayoutSubviews()
}
public func animate() {
self.spring.animate()
}
public func animateNext(completion: @escaping () -> ()) {
self.spring.animateNext(completion: completion)
}
public func animateTo() {
self.spring.animateTo()
}
public func animateToNext(completion: @escaping () -> ()) {
self.spring.animateToNext(completion: completion)
}
}
| mit |
gewill/Feeyue | Feeyue/Helpers/ViewControllerHelper.swift | 1 | 403 | //
// ViewControllerHelper.swift
// Feeyue
//
// Created by Will on 11/05/2017.
// Copyright © 2017 Will. All rights reserved.
//
import Foundation
func gw_present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
UIApplication.shared.keyWindow?.rootViewController?.present(viewControllerToPresent, animated: flag, completion: completion)
}
| mit |
qiuncheng/study-for-swift | YLQRCode/Demo/ViewController.swift | 1 | 2300 | //
// ViewController.swift
// YLQRCode
//
// Created by yolo on 2017/1/1.
// Copyright © 2017年 Qiuncheng. All rights reserved.
//
import UIKit
import YLQRCodeHelper
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
textField.text = "http://weixin.qq.com/r/QkB8ZE7EuxPErQoH9xVQ"
imageView.isUserInteractionEnabled = true
let long = UILongPressGestureRecognizer(target: self, action: #selector(detecteQRCode(gesture:)))
imageView.addGestureRecognizer(long)
generateQRCodeButtonClicked(nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func detecteQRCode(gesture: UILongPressGestureRecognizer) {
guard gesture.state == .ended else { return }
func detect() {
guard let image = imageView.image else { return }
// YLDetectQRCode.scanQRCodeFromPhotoLibrary(image: image) { (result) in
// guard let _result = result else { return }
// YLQRScanCommon.playSound()
// print(_result)
// }
}
let alertController = UIAlertController(title: "", message: "", preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "识别二维码", style: .default, handler: { (action) in
detect()
}))
alertController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
present(alertController, animated: true, completion: nil)
}
@IBAction func generateQRCodeButtonClicked(_ sender: Any?) {
view.endEditing(true)
guard let text = textField.text else {
return
}
// YLGenerateQRCode.beginGenerate(text: text) {
// guard let image = $0 else { return }
// DispatchQueue.main.async { [weak self] in
// self?.imageView.image = image
// }
// }
}
}
| mit |
cwwise/CWWeChat | CWWeChat/Expand/Tool/CWChatConst.swift | 2 | 1761 | //
// CWChatConst.swift
// CWWeChat
//
// Created by chenwei on 16/6/22.
// Copyright © 2016年 chenwei. All rights reserved.
//
import Foundation
import UIKit
import CocoaLumberjack
let kScreenSize = UIScreen.main.bounds.size
let kScreenWidth = UIScreen.main.bounds.size.width
let kScreenHeight = UIScreen.main.bounds.size.height
let kScreenScale = UIScreen.main.scale
let kNavigationBarHeight:CGFloat = 64
// stolen from Kingfisher: https://github.com/onevcat/Kingfisher/blob/master/Sources/ThreadHelper.swift
extension DispatchQueue {
// This method will dispatch the `block` to self.
// If `self` is the main queue, and current thread is main thread, the block
// will be invoked immediately instead of being dispatched.
func safeAsync(_ block: @escaping ()->()) {
if self === DispatchQueue.main && Thread.isMainThread {
block()
} else {
async { block() }
}
}
}
typealias Task = (_ cancel : Bool) -> Void
@discardableResult func DispatchQueueDelay(_ time: TimeInterval, task: @escaping ()->()) -> Task? {
func dispatch_later(block: @escaping ()->()) {
let t = DispatchTime.now() + time
DispatchQueue.main.asyncAfter(deadline: t, execute: block)
}
var closure: (()->Void)? = task
var result: Task?
let delayedClosure: Task = {
cancel in
if let internalClosure = closure {
if (cancel == false) {
DispatchQueue.main.async(execute: internalClosure)
}
}
closure = nil
result = nil
}
result = delayedClosure
dispatch_later {
if let delayedClosure = result {
delayedClosure(false)
}
}
return result
}
| mit |
steelwheels/KiwiScript | KiwiLibrary/Source/Data/KLEnum.swift | 1 | 950 | /**
* @file KLEnum.swift
* @brief Extend CNEnum class
* @par Copyright
* Copyright (C) 2021 Steel Wheels Project
*/
import CoconutData
import KiwiEngine
import JavaScriptCore
import Foundation
public extension CNEnum
{
static func isEnum(scriptValue val: JSValue) -> Bool {
if let dict = val.toDictionary() as? Dictionary<String, Any> {
if let _ = dict["type"] as? NSString,
let _ = dict["value"] as? NSNumber {
return true
} else {
return false
}
} else {
return false
}
}
static func fromJSValue(scriptValue val: JSValue) -> CNEnum? {
if let dict = val.toDictionary() as? Dictionary<String, Any> {
if let typestr = dict["type"] as? String,
let membstr = dict["member"] as? String {
return CNEnum.fromValue(typeName: typestr, memberName: membstr)
}
}
return nil
}
func toJSValue(context ctxt: KEContext) -> JSValue {
return JSValue(int32: Int32(self.value), in: ctxt)
}
}
| lgpl-2.1 |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/2131-swift-parser-parsedeclclass.swift | 12 | 583 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class b<T.h : a {
var b {
}
class func f<T -> Any) -> {
self.b {
struct A = b<T.init() {
struct S : T] {
}
class A : h>? = g<c> S {
f<j {
{
}
}
}
struct S : SequenceType where T {
}
class func d: C = { class C<Q<T? {
}
}
f = D> Any) -> A {
}
enum e: b() -> t, length: Any) -> String {
var b<T : a {
class a {
}
}
}
}
switch x in x }
}
}
protocol P {
func a<b: a {
(i<
| apache-2.0 |
zbw209/- | StudyNotes/StudyNotes/知识点/控件封装/tableViewCell插入优化/OptimizeTableViewCellAnimateVC.swift | 1 | 1582 | //
// OptimizeTableViewCellAnimateVC.swift
// StudyNotes
//
// Created by zhoubiwen on 2018/11/6.
// Copyright © 2018年 zhou. All rights reserved.
//
import UIKit
class OptimizeTableViewCellAnimateVC: UIViewController {
var tableView : UITableView?
var arr : Array<String>?
override func viewDidLoad() {
super.viewDidLoad()
// setupTableView()
arr?.append("123")
arr?.append("123")
arr?.append("123")
arr?.append("123")
arr?.append("123")
}
}
extension OptimizeTableViewCellAnimateVC {
func setupTableView() {
self.tableView = UITableView()
self.tableView!.delegate = self
self.tableView!.dataSource = self
self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
self.tableView?.frame = CGRect(origin: CGPoint.zero, size: self.view.bounds.size)
self.view.addSubview(self.tableView!)
}
func insertEvent() {
}
}
extension OptimizeTableViewCellAnimateVC : UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
cell.textLabel?.text = "indexPath = \(indexPath)"
return cell
}
}
| mit |
rgbycch/rgbycch_swift_api | Pod/Classes/Team.swift | 1 | 1320 | // The MIT License (MIT)
// Copyright (c) 2015 rgbycch
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
/// Represents a Team
public class Team {
public var identifier:Int32 = 0
public var title:String = ""
public var club:Club?
public var players:[Player] = []
} | mit |
riana/NickelSwift | NickelSwift/NickelWebViewController.swift | 1 | 8054 | //
// PolymerWebView.swift
// PolymerIos
//
// Created by Riana Ralambomanana on 17/12/2015.
// Copyright © 2016 Riana.io. All rights reserved.
//
import Foundation
import WebKit
struct TransferData {
var timeStamp:Int = 0
var operation:String = "NOOP"
var callback:Bool = false
var data:[NSObject:AnyObject]?
}
public typealias BridgedMethod = (String, [NSObject:AnyObject]) -> [NSObject:AnyObject]?
public protocol NickelFeature {
func setupFeature(nickelViewController:NickelWebViewController)
}
public class NickelWebViewController: UIViewController, WKScriptMessageHandler, WKNavigationDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
var myWebView:WKWebView?;
var timer:NSTimer?
var elapsedTime:Int = 0
let imagePicker = UIImagePickerController()
var bridgedMethods = [String: BridgedMethod]()
var features = [NickelFeature]()
public override func viewDidLoad() {
super.viewDidLoad()
let theConfiguration = WKWebViewConfiguration()
theConfiguration.userContentController.addScriptMessageHandler(self, name: "native")
theConfiguration.allowsInlineMediaPlayback = true
myWebView = WKWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height), configuration: theConfiguration)
myWebView?.scrollView.bounces = false
myWebView?.navigationDelegate = self
self.view.addSubview(myWebView!)
}
public func setMainPage(name:String){
let localUrl = NSBundle.mainBundle().URLForResource(name, withExtension: "html");
// let requestObj = NSURLRequest(URL: localUrl!);
// myWebView!.loadRequest(requestObj);
myWebView!.loadFileURL(localUrl!, allowingReadAccessToURL: localUrl!)
}
public func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
let stringData = message.body as! String;
let receivedData = stringData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(receivedData, options: .AllowFragments) as! [NSObject: AnyObject]
var transferData = TransferData()
if let timeStamp = jsonData["timestamp"] as? Int {
transferData.timeStamp = timeStamp
}
if let operation = jsonData["operation"] as? String {
transferData.operation = operation
}
if let callback = jsonData["callback"] as? Bool {
transferData.callback = callback
}
if let data = jsonData["data"] as? [NSObject:AnyObject]{
transferData.data = data
}
// print("\(transferData)")
if let bridgedMethod = bridgedMethods[transferData.operation] {
if let result = bridgedMethod(transferData.operation, transferData.data!) {
if(transferData.callback){
sendtoView("\(transferData.operation)-\(transferData.timeStamp)", data:result);
}
}
}else {
print("Bridged operation not found : \(transferData.operation)")
}
}catch{
print("error serializing JSON: \(error)")
}
}
public func sendtoView(operation:String, data:AnyObject){
let jsonProperties:AnyObject = ["operation": operation, "data": data]
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(jsonProperties,options:NSJSONWritingOptions())
let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
let callbackString = "window.NickelBridge.handleMessage"
let jsFunction = "(\(callbackString)(\(jsonString)))";
// print(jsFunction)
myWebView!.evaluateJavaScript(jsFunction) { (JSReturnValue:AnyObject?, error:NSError?)-> Void in
if let errorDescription = error?.description{
print("returned value: \(errorDescription)")
}
}
} catch let error {
print("error converting to json: \(error)")
}
}
public func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
// JS function Initialized
sendtoView("Initialized", data:["status" : "ok"])
doRegisterFeatures()
registerBridgedFunction("pickImage", bridgedMethod: self.pickImage)
registerBridgedFunction("startTimer", bridgedMethod: self.startTimer)
registerBridgedFunction("stopTimer", bridgedMethod: self.stopTimer)
features.append(StorageFeature())
features.append(LocalNotificationFeature())
features.append(AwakeFeature())
features.append(TTSFeature())
features.append(AudioFeature())
features.append(JSONFeature())
features.append(i18nFeature())
for feature in features {
feature.setupFeature(self)
}
}
public func registerBridgedFunction(operationId:String, bridgedMethod:BridgedMethod){
bridgedMethods[operationId] = bridgedMethod
}
public func doRegisterFeatures() {
}
/**
* Select image feature
**/
func pickImage(operation:String, content:[NSObject:AnyObject]) -> [NSObject:AnyObject]?{
imagePicker.delegate = self
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
return [NSObject:AnyObject]()
}
public func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
let imageResized = resizeImage(pickedImage, newWidth: 100)
let imageData = UIImagePNGRepresentation(imageResized)
let base64String = imageData!.base64EncodedStringWithOptions(.EncodingEndLineWithLineFeed)
let imagesString = "data:image/png;base64,\(base64String)"
sendtoView("imagePicked", data:["image" :imagesString ])
}
dismissViewControllerAnimated(true, completion: nil)
}
func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
let scale = newWidth / image.size.width
let newHeight = image.size.height * scale
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/**
* END Select image feature
**/
/**
* Native Timer feature
**/
func startTimer(operation:String, content:[NSObject:AnyObject]) -> [NSObject:AnyObject]?{
self.elapsedTime = 0
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("timerTick"), userInfo: nil, repeats: true)
return [NSObject:AnyObject]()
}
func stopTimer(operation:String, content:[NSObject:AnyObject]) -> [NSObject:AnyObject]?{
timer?.invalidate()
sendtoView("timerComplete", data:["elapsedTime" : self.elapsedTime]);
return [NSObject:AnyObject]()
}
func timerTick(){
self.elapsedTime++;
sendtoView("timeStep", data:["elapsedTime" : self.elapsedTime]);
}
/**
* END Native Timer feature
**/
}
| mit |
ArtSabintsev/Swift-3-CocoaHeads-DC-Talk | Demo/0069-0088-ModernizedSyntax.playground/Contents.swift | 1 | 525 | import Foundation
/**
SE-0069
*/
// Old
let oldUrl = NSURL(string: "http://www.washingtonpost.com")
//url?.URLByAppendingPathComponent("posttv")
// New
let newUrl = URL(string: "http://www.washingtonpost.com")
try newUrl?.appendingPathComponent("posttv")
/**
SE-0088
*/
// Old
//let oldQueue = dispatch_queue_create("label", DISPATCH_QUEUE_SERIAL)
//dispatch_async(oldQueue) {
// // Do Something
//}
// New
let newQueue = DispatchQueue(label: "com.washingtonpost.asyncQueue")
newQueue.async {
// Do Stuff
}
| mit |
codytwinton/SwiftyVIPER | Example/SwiftyVIPERExample/Modules/RootRouter.swift | 1 | 626 | //
// RootRouter.swift
// Project: SwiftyVIPER
//
// Module: Root
//
// By Cody Winton 11/5/16
// codeRed 2016
//
// MARK: Imports
import Foundation
import SwiftyVIPER
import UIKit
// MARK: Protocols
protocol RootPresenterRouterProtocol: PresenterRouterProtocol {
func detailsSelected()
}
// MARK: -
final class RootRouter: RouterProtocol, RootPresenterRouterProtocol {
// MARK: - Variables
weak var viewController: UIViewController?
// MARK: - Router Protocol
// MARK: Root Presenter to Router Protocol
func detailsSelected() {
DetailModule().present(from: viewController, style: .coverVertical)
}
}
| mit |
vector-im/vector-ios | Riot/Modules/Room/ParticipantsInviteModal/ContactsPicker/ContactsPickerViewModelProtocol.swift | 1 | 1642 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
protocol ContactsPickerViewModelCoordinatorDelegate: AnyObject {
func contactsPickerViewModelDidStartLoading(_ viewModel: ContactsPickerViewModelProtocol)
func contactsPickerViewModelDidEndLoading(_ viewModel: ContactsPickerViewModelProtocol)
func contactsPickerViewModelDidStartInvite(_ viewModel: ContactsPickerViewModelProtocol)
func contactsPickerViewModelDidEndInvite(_ viewModel: ContactsPickerViewModelProtocol)
func contactsPickerViewModel(_ viewModel: ContactsPickerViewModelProtocol, inviteFailedWithError error: Error?)
func contactsPickerViewModel(_ viewModel: ContactsPickerViewModelProtocol, display message: String, title: String, actions: [UIAlertAction])
}
protocol ContactsPickerViewModelProtocol {
var coordinatorDelegate: ContactsPickerViewModelCoordinatorDelegate? { get set }
var areParticipantsLoaded: Bool { get }
func loadParticipants()
@discardableResult func prepare(contactsViewController: RoomInviteViewController, currentSearchText: String?) -> Bool
}
| apache-2.0 |
sanjubhatt2010/CarCollection | CarCollection/CarCollection/CarTableHeader.swift | 1 | 353 | //
// CarTableHeader.swift
// CarCollection
//
// Created by Appinventiv on 16/02/17.
// Copyright © 2017 Appinventiv. All rights reserved.
//
import UIKit
class CarTableHeader: UITableViewHeaderFooterView {
//MARK : IBOutlets
@IBOutlet weak var sectionHideAndShowButton: UIButton!
@IBOutlet weak var CarTitleLabel: UILabel!
}
| mit |
gerryisaac/iPhone-CTA-Bus-Tracker-App | Bus Tracker/DirectionsViewController.swift | 1 | 9814 | //
// DirectionsViewController.swift
// Bus Tracker
//
// Created by Gerard Isaac on 10/30/14.
// Copyright (c) 2014 Gerard Isaac. All rights reserved.
//
import UIKit
class DirectionsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let cellIdentifier = "cellIdentifier"
var patternID:NSString? = NSString()
var routeNumber:NSString = NSString()
var directionsTable:UITableView = UITableView(frame: CGRectMake(0, 64, screenDimensions.screenWidth, screenDimensions.screenHeight - 64))
//Directions Table Data Variables
var directions: NSArray = []
var directionsData: NSMutableArray = []
var directionsCount: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//println("Get Directions")
self.view.backgroundColor = UIColor.blueColor()
//Create Background Image
let bgImage = UIImage(named:"bg-DirectionsI5.png")
var bgImageView = UIImageView(frame: CGRectMake(0, 0, screenDimensions.screenWidth, screenDimensions.screenHeight))
bgImageView.image = bgImage
self.view.addSubview(bgImageView)
retrieveDirections()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func retrieveDirections() {
//Create Spinner
var spinner:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
spinner.frame = CGRectMake(screenDimensions.screenWidth/2 - 25, screenDimensions.screenHeight/2 - 25, 50, 50);
spinner.transform = CGAffineTransformMakeScale(1.5, 1.5);
//spinner.backgroundColor = [UIColor blackColor];
self.view.addSubview(spinner);
spinner.startAnimating()
//Load Bus Tracker Data
let feedURL:NSString = "http://www.ctabustracker.com/bustime/api/v1/getpatterns?key=\(yourCTAkey.keyValue)&rt=\(routeNumber)"
//println("Directions URL is \(feedURL)")
let manager = AFHTTPRequestOperationManager()
manager.responseSerializer = AFHTTPResponseSerializer()
let contentType:NSSet = NSSet(object: "text/xml")
manager.responseSerializer.acceptableContentTypes = contentType
manager.GET(feedURL,
parameters: nil,
success: {
(operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
//println("Success")
var responseData:NSData = responseObject as NSData
//var responseString = NSString(data: responseData, encoding:NSASCIIStringEncoding)
//println(responseString)
var rxml:RXMLElement = RXMLElement.elementFromXMLData(responseData) as RXMLElement
//self.directions = rxml.children("dir")
self.directions = rxml.children("ptr")
self.directionsData.addObjectsFromArray(self.directions)
self.directionsCount = self.directions.count
if self.directionsCount == 0 {
//println("No Data")
var noDataLabel:UILabel = UILabel(frame: CGRectMake( 0, 200, screenDimensions.screenWidth, 75))
noDataLabel.font = UIFont(name:"Gotham-Bold", size:30.0)
noDataLabel.textColor = self.uicolorFromHex(0xfffee8)
noDataLabel.textAlignment = NSTextAlignment.Center
noDataLabel.numberOfLines = 0
noDataLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
noDataLabel.text = "No Data Available"
self.view.addSubview(noDataLabel)
} else {
var i:Int? = 0
for direction in self.directions {
i = i! + 1
}
//println(i!)
//Create Direction Entries
self.directionsTable.backgroundColor = UIColor.clearColor()
self.directionsTable.dataSource = self
self.directionsTable.delegate = self
self.directionsTable.separatorInset = UIEdgeInsetsZero
self.directionsTable.layoutMargins = UIEdgeInsetsZero
self.directionsTable.bounces = true
// Register the UITableViewCell class with the tableView
self.directionsTable.registerClass(DirectionsCell.self, forCellReuseIdentifier: self.cellIdentifier)
//self.patternTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
//Add the Table View
self.view.addSubview(self.directionsTable)
}
spinner.stopAnimating()
},
failure: {
(operation: AFHTTPRequestOperation!, error: NSError!) in
var alertView = UIAlertView(title: "Error Retrieving Data", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK")
alertView.show()
println(error)
})
}
//Table View Configuration
// Table Delegates and Data Source
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, shouldIndentWhileEditing indexPath: NSIndexPath) -> Bool {
return false
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return self.directionsCount
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var appElement:RXMLElement = directionsData.objectAtIndex(indexPath.row) as RXMLElement
var direction:NSString? = appElement.child("rtdir").text
self.patternID = appElement.child("pid").text
var subPoints: NSArray = []
subPoints = appElement.children("pt")
var subPointsData: NSMutableArray = []
subPointsData.addObjectsFromArray(subPoints)
var lastElement:RXMLElement = subPointsData.lastObject as RXMLElement
var lastStopName:NSString? = lastElement.child("stpnm").text
//println(lastElement)
var cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier) as DirectionsCell
if direction == nil {
cell.accessoryType = UITableViewCellAccessoryType.None
cell.cellDirectionLabel.text = "No Stops Available"
} else {
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.cellDirectionLabel.text = direction
cell.cellDestinationLabel.text = lastStopName?.uppercaseString
cell.cellpIDLabel.text = self.patternID
}
cell.tintColor = UIColor.whiteColor()
return cell
}
//Remove Table Insets and Margins
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.respondsToSelector("setSeparatorInset:") {
cell.separatorInset.left = CGFloat(0.0)
}
if tableView.respondsToSelector("setLayoutMargins:") {
tableView.layoutMargins = UIEdgeInsetsZero
}
if cell.respondsToSelector("setLayoutMargins:") {
cell.layoutMargins.left = CGFloat(0.0)
}
}
func tableView(tableView:UITableView, heightForRowAtIndexPath indexPath:NSIndexPath)->CGFloat {
tableView.separatorColor = UIColor.whiteColor()
return 100
}
func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
// UITableViewDelegate methods
//Double check didSelectRowAtIndexPath VS didDeselectRowAtIndexPath
func tableView(tableView:UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var cellDirection: NSString?
if let thisCell:DirectionsCell = tableView.cellForRowAtIndexPath(indexPath) as? DirectionsCell {
self.patternID = thisCell.cellpIDLabel.text
cellDirection = thisCell.cellDirectionLabel.text
}
var displayPatterns:patternDisplayViewController = patternDisplayViewController()
displayPatterns.pID = self.patternID!
displayPatterns.patternRequestNumber = self.routeNumber
displayPatterns.title = NSString(string:"\(self.patternID!) \(cellDirection!)")
self.navigationController?.pushViewController(displayPatterns, animated: true)
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
tableView.deselectRowAtIndexPath(indexPath, animated: false)
}
//Hex Color Values Function
func uicolorFromHex(rgbValue:UInt32)->UIColor{
let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
let blue = CGFloat(rgbValue & 0xFF)/256.0
return UIColor(red:red, green:green, blue:blue, alpha:1.0)
}
}
| mit |
jackywpy/AudioKit | Templates/File Templates/AudioKit/Swift AudioKit Instrument.xctemplate/___FILEBASENAME___.swift | 16 | 1143 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
//___COPYRIGHT___
//
class ___FILEBASENAME___: AKInstrument {
// Instrument Properties
var pan = AKInstrumentProperty(value: 0.0, minimum: 0.0, maximum: 1.0)
// Auxilliary Outputs (if any)
var auxilliaryOutput = AKAudio()
override init() {
super.init()
// Instrument Properties
// Note Properties
let note = ___FILEBASENAME___Note()
// Instrument Definition
let oscillator = AKFMOscillator();
oscillator.baseFrequency = note.frequency;
oscillator.amplitude = note.amplitude;
let panner = AKPanner(audioSource: oscillator, pan: pan)
auxilliaryOutput = AKAudio.globalParameter()
assignOutput(auxilliaryOutput, to:panner)
}
}
class ___FILEBASENAME___Note: AKNote {
// Note Properties
var frequency = AKNoteProperty(minimum: 440, maximum: 880)
var amplitude = AKNoteProperty(minimum: 0, maximum: 1)
override init() {
super.init()
addProperty(frequency)
addProperty(amplitude)
}
}
| mit |
lyragosa/tipcalc | TipCalc/ViewController.swift | 1 | 2262 | //
// ViewController.swift
// TipCalc
//
// Created by Lyragosa on 15/10/19.
// Copyright © 2015年 Lyragosa. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var totalTextField : UITextField!
@IBOutlet var taxPctSlider : UISlider!
@IBOutlet var taxPctLabel : UILabel!
@IBOutlet var resultsTextView : UITextView!
let tipCalc = TipCalculatorModel(total:200,taxPct:0.06)
@IBAction func calculateTapped(sender : AnyObject) {
saveData();
let possibleTips = tipCalc.returnPossibleTips()
var results = ""
var keys = Array(possibleTips.keys)
keys.sortInPlace();
for tipPct in keys {
let tipValue = possibleTips[tipPct]!
let predoValue = String(format:"%.2f",tipValue)
results += "\(tipPct)%: \(predoValue)\n"
}
/*
//old:
for (tipPct, tipValue) in possibleTips {
let predoValue = String(format:"%.2f",tipValue)
results += "\(tipPct)%: \(predoValue)\n"
}*/
resultsTextView.text = results
}
func test123(a:Int,b:Int) -> Int {
return Int(a+b)
}
@IBAction func taxPercentageChanged(sender : AnyObject) {
saveData();
tipCalc.taxPct = Double(taxPctSlider.value)
refreshUI()
}
@IBAction func viewTapped(sender : AnyObject) {
totalTextField.resignFirstResponder();
}
@IBAction func baseTotalInputed(sender : AnyObject) {
saveData();
}
func saveData() {
tipCalc.total = Double( (totalTextField.text! as NSString).doubleValue )
}
func refreshUI() {
totalTextField.text = String(tipCalc.total)
taxPctSlider.value = Float(tipCalc.taxPct)
taxPctLabel.text = "Tax (\(Int(taxPctSlider.value * 100.0))%)"
resultsTextView.text = "";
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
refreshUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
wnagrodzki/DragGestureRecognizer | DragGestureRecognizer/DragGestureRecognizer.swift | 1 | 3273 | //
// DragGestureRecognizer.swift
// DragGestureRecognizer
//
// Created by Wojciech Nagrodzki on 01/09/16.
// Copyright © 2016 Wojciech Nagrodzki. All rights reserved.
//
import UIKit
import UIKit.UIGestureRecognizerSubclass
/// `DragGestureRecognizer` is a subclass of `UILongPressGestureRecognizer` that allows for tracking translation similarly to `UIPanGestureRecognizer`.
class DragGestureRecognizer: UILongPressGestureRecognizer {
private var initialTouchLocationInScreenFixedCoordinateSpace: CGPoint?
private var initialTouchLocationsInViews = [UIView: CGPoint]()
/// The total translation of the drag gesture in the coordinate system of the specified view.
/// - parameters:
/// - view: The view in whose coordinate system the translation of the drag gesture should be computed. Pass `nil` to indicate window.
func translation(in view: UIView?) -> CGPoint {
// not attached to a view or outside window
guard let window = self.view?.window else { return CGPoint() }
// gesture not in progress
guard let initialTouchLocationInScreenFixedCoordinateSpace = initialTouchLocationInScreenFixedCoordinateSpace else { return CGPoint() }
let initialLocation: CGPoint
let currentLocation: CGPoint
if let view = view {
initialLocation = initialTouchLocationsInViews[view] ?? window.screen.fixedCoordinateSpace.convert(initialTouchLocationInScreenFixedCoordinateSpace, to: view)
currentLocation = location(in: view)
}
else {
initialLocation = initialTouchLocationInScreenFixedCoordinateSpace
currentLocation = location(in: nil)
}
return CGPoint(x: currentLocation.x - initialLocation.x, y: currentLocation.y - initialLocation.y)
}
/// Sets the translation value in the coordinate system of the specified view.
/// - parameters:
/// - translation: A point that identifies the new translation value.
/// - view: A view in whose coordinate system the translation is to occur. Pass `nil` to indicate window.
func setTranslation(_ translation: CGPoint, in view: UIView?) {
// not attached to a view or outside window
guard let window = self.view?.window else { return }
// gesture not in progress
guard let _ = initialTouchLocationInScreenFixedCoordinateSpace else { return }
let inView = view ?? window
let currentLocation = location(in: inView)
let initialLocation = CGPoint(x: currentLocation.x - translation.x, y: currentLocation.y - translation.y)
initialTouchLocationsInViews[inView] = initialLocation
}
override var state: UIGestureRecognizer.State {
didSet {
switch state {
case .began:
initialTouchLocationInScreenFixedCoordinateSpace = location(in: nil)
case .ended, .cancelled, .failed:
initialTouchLocationInScreenFixedCoordinateSpace = nil
initialTouchLocationsInViews = [:]
case .possible, .changed:
break
}
}
}
}
| mit |
shajrawi/swift | test/Interpreter/fractal.swift | 1 | 9677 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -emit-library -o %t/%target-library-name(complex) -emit-module %S/complex.swift -module-link-name complex
// RUN: %target-jit-run %s -I %t -L %t | %FileCheck %s
// RUN: grep -v import %s > %t/main.swift
// RUN: %target-jit-run %t/main.swift %S/complex.swift | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: swift_interpreter
// JIT runs in swift-version 4
// UNSUPPORTED: swift_test_mode_optimize_none_with_implicit_dynamic
import complex
func printDensity(_ d: Int) {
if (d > 40) {
print(" ", terminator: "")
} else if d > 6 {
print(".", terminator: "")
} else if d > 4 {
print("+", terminator: "")
} else if d > 2 {
print("*", terminator: "")
} else {
print("#", terminator: "")
}
}
extension Double {
func abs() -> Double {
if (self >= 0.0) { return self }
return self * -1.0
}
}
func getMandelbrotIterations(_ c: Complex, maxIterations: Int) -> Int {
var n = 0
var z = Complex()
while (n < maxIterations && z.magnitude() < 4.0) {
z = z*z + c
n += 1
}
return n
}
func fractal (_ densityFunc:(_ c: Complex, _ maxIterations: Int) -> Int,
xMin:Double, xMax:Double,
yMin:Double, yMax:Double,
rows:Int, cols:Int,
maxIterations:Int) {
// Set the spacing for the points in the Mandelbrot set.
var dX = (xMax - xMin) / Double(rows)
var dY = (yMax - yMin) / Double(cols)
// Iterate over the points an determine if they are in the
// Mandelbrot set.
for row in stride(from: xMin, to: xMax, by: dX) {
for col in stride(from: yMin, to: yMax, by: dY) {
var c = Complex(real: col, imag: row)
printDensity(densityFunc(c, maxIterations))
}
print("\n", terminator: "")
}
}
fractal(getMandelbrotIterations,
xMin: -1.35, xMax: 1.4, yMin: -2.0, yMax: 1.05, rows: 40, cols: 80,
maxIterations: 200)
// CHECK: ################################################################################
// CHECK: ##############################********************##############################
// CHECK: ########################********************************########################
// CHECK: ####################***************************+++**********####################
// CHECK: #################****************************++...+++**********#################
// CHECK: ##############*****************************++++......+************##############
// CHECK: ############******************************++++.......+++************############
// CHECK: ##########******************************+++++.... ...++++************##########
// CHECK: ########******************************+++++.... ..++++++**********#########
// CHECK: #######****************************+++++....... .....++++++**********#######
// CHECK: ######*************************+++++....... . .. ............++*********######
// CHECK: #####*********************+++++++++... .. . ... ..++*********#####
// CHECK: ####******************++++++++++++..... ..++**********####
// CHECK: ###***************++++++++++++++... . ...+++**********###
// CHECK: ##**************+++................. ....+***********##
// CHECK: ##***********+++++................. .++***********##
// CHECK: #**********++++++..... ..... ..++***********##
// CHECK: #*********++++++...... . ..++************#
// CHECK: #*******+++++....... ..+++************#
// CHECK: #++++............ ...+++************#
// CHECK: #++++............ ...+++************#
// CHECK: #******+++++........ ..+++************#
// CHECK: #********++++++..... . ..++************#
// CHECK: #**********++++++..... .... .++************#
// CHECK: #************+++++................. ..++***********##
// CHECK: ##*************++++................. . ..+***********##
// CHECK: ###***************+.+++++++++++..... ....++**********###
// CHECK: ###******************+++++++++++++..... ...+++*********####
// CHECK: ####*********************++++++++++.... .. ..++*********#####
// CHECK: #####*************************+++++........ . . . .......+*********######
// CHECK: #######***************************+++.......... .....+++++++*********#######
// CHECK: ########*****************************++++++.... ...++++++**********########
// CHECK: ##########*****************************+++++..... ....++++***********##########
// CHECK: ###########******************************+++++........+++***********############
// CHECK: #############******************************++++.. ...++***********##############
// CHECK: ################****************************+++...+++***********################
// CHECK: ###################***************************+.+++**********###################
// CHECK: #######################**********************************#######################
// CHECK: ############################************************############################
// CHECK: ################################################################################
func getBurningShipIterations(_ c: Complex, maxIterations: Int) -> Int {
var n = 0
var z = Complex()
while (n < maxIterations && z.magnitude() < 4.0) {
var zTmp = Complex(real: z.real.abs(), imag: z.imag.abs())
z = zTmp*zTmp + c
n += 1
}
return n
}
print("\n== BURNING SHIP ==\n\n", terminator: "")
fractal(getBurningShipIterations,
xMin: -2.0, xMax: 1.2, yMin: -2.1, yMax: 1.2, rows: 40, cols: 80,
maxIterations: 200)
// CHECK: ################################################################################
// CHECK: ################################################################################
// CHECK: ################################################################################
// CHECK: #####################################################################*****######
// CHECK: ################################################################*******+...+*###
// CHECK: #############################################################**********+...****#
// CHECK: ###########################################################************. .+****#
// CHECK: #########################################################***********++....+.****
// CHECK: ######################################################************+++......++***
// CHECK: ##############################*******************###************..... .....+++++
// CHECK: ########################*******+++*******************+ .+++++ . . ........+*
// CHECK: ####################**********+.. .+++*******+.+++**+. .....+.+**
// CHECK: #################**********++++...+...++ .. . . .+ ...+++++.***
// CHECK: ##############***********++..... . ... . ...++++++****#
// CHECK: ############*************....... . . ...+++********#
// CHECK: ##########***************. .. ...+++*********#
// CHECK: #########***************++. .. . . ...+++*********##
// CHECK: #######*****************. ... ...+++**********##
// CHECK: ######*****************+. ...+++**********###
// CHECK: #####****************+++ . .....++***********###
// CHECK: #####**********++..... . ....+++***********###
// CHECK: ####*********+++.. . ....+++***********####
// CHECK: ####********++++. ....+++***********####
// CHECK: ###*******++++. ...++++***********####
// CHECK: ###**++*+..+... ...+++************####
// CHECK: ### ...+++************####
// CHECK: ###*********+++++++++......... ...... ..++************####
// CHECK: ####****************++++++.................... .++***********#####
// CHECK: #####********************++++++++++++++++........ .+***********#####
// CHECK: ########****************************+++++++++....... ++***********#####
// CHECK: ###########*******************************++++++...... ..++**********######
// CHECK: ###############*******************************+++++.........++++*********#######
// CHECK: ####################****************************++++++++++++++**********########
// CHECK: ##########################*************************+++++++++***********#########
// CHECK: ################################**************************************##########
// CHECK: ####################################********************************############
// CHECK: ########################################***************************#############
// CHECK: ###########################################**********************###############
// CHECK: #############################################*****************##################
// CHECK: ################################################***********#####################
| apache-2.0 |
dbgrandi/EulerKit | euler/Problems/Problem5.swift | 1 | 298 | //
// 2520 is the smallest number that can be divided by each of
// the numbers from 1 to 10 without any remainder.
//
// What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
//
final class Problem5: EulerProblem {
final override func run() {
}
}
| mit |
contentful-labs/markdown-example-ios | Code/MDEmbedlyViewController.swift | 1 | 1153 | //
// MDEmbedlyViewController.swift
// Markdown
//
// Created by Boris Bügling on 24/12/15.
// Copyright © 2015 Contentful GmbH. All rights reserved.
//
import UIKit
class MDEmbedlyViewController: MDWebViewController {
let embedlyCode = "<script>(function(w, d){var id='embedly-platform', n = 'script';if (!d.getElementById(id)){ w.embedly = w.embedly || function() {(w.embedly.q = w.embedly.q || []).push(arguments);}; var e = d.createElement(n); e.id = id; e.async=1; e.src = ('https:' === document.location.protocol ? 'https' : 'http') + '://cdn.embedly.com/widgets/platform.js'; var s = d.getElementsByTagName(n)[0]; s.parentNode.insertBefore(e, s); } })(window, document); </script>"
convenience init() {
self.init(nibName: nil, bundle: nil)
self.entryId = "3qhObH1ZPyG6uCkqwyiiCG"
self.tabBarItem = UITabBarItem(title: "Embedly", image: UIImage(named: "webView"), tag: 0)
}
override func convertMarkdownToHTML(_ markdown: String) throws -> String {
let html = try super.convertMarkdownToHTML(markdown)
return "<html><head>\(embedlyCode)</head><body>\(html)</body></html>"
}
}
| mit |
soapyigu/LeetCode_Swift | Array/SmallestRange.swift | 1 | 1572 | /**
* Question Link: https://leetcode.com/problems/smallest-range/
* Primary idea: Merge K lists + Minimum Window Substring
* Time Complexity: O(nm), Space Complexity: O(nm)
*
*/
class SmallestRange {
func smallestRange(_ nums: [[Int]]) -> [Int] {
let mergedNums = merge(nums)
var left = 0, diff = Int.max, res = [Int]()
var numsIndexFreq = Dictionary((0..<nums.count).map { ($0, 0) }, uniquingKeysWith: +), count = 0
for (right, numIndex) in mergedNums.enumerated() {
if numsIndexFreq[numIndex.1]! == 0 {
count += 1
}
numsIndexFreq[numIndex.1]! += 1
while count == nums.count {
if diff > mergedNums[right].0 - mergedNums[left].0 {
diff = mergedNums[right].0 - mergedNums[left].0
res = [mergedNums[left], mergedNums[right]].map { $0.0 }
}
if numsIndexFreq[mergedNums[left].1]! == 1 {
count -= 1
}
numsIndexFreq[mergedNums[left].1]! -= 1
left += 1
}
}
return res
}
fileprivate func merge(_ nums: [[Int]]) -> [(Int, Int)] {
var res = [(Int, Int)]()
for (numsIndex, nums) in nums.enumerated() {
for num in nums {
res.append((num, numsIndex))
}
}
return res.sorted { return $0.0 < $1.0 }
}
} | mit |
rock-n-code/Kashmir | Kashmir/Shared/Common/Errors/URLResponseError.swift | 1 | 2273 | //
// URLResponseError.swift
// Kashmir
//
// Created by Javier Cicchelli on 29/06/16.
// Copyright © 2016 Rock & Code. All rights reserved.
//
/**
Representation for the error codes defined on the **StatusCode** enumeration of *URLResponse*.
* **unauthorizedAccess**: Similar to *forbiddenAccess*, but specifically for use when authentication is required and has failed or has not yet been provided.
* **forbiddenAccess**: The request was a valid request, but the server is refusing to respond to it. The user might be logged in but does not have the necessary permissions for the resource.
* **resourceNotFound**: The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.
* **methodNotAllowed**: A request method is not supported for the requested resource; for example, a GET request on a form which requires data to be presented via POST, or a PUT request on a read-only resource.
* **unprocessableEntity**: The request was well-formed but was unable to be followed due to semantic errors.
* **internalServerError**: A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
*/
public enum URLResponseError: Error {
/// Similar to *forbiddenAccess*, but specifically for use when authentication is required and has failed or has not yet been provided.
case unauthorizedAccess
/// The request was a valid request, but the server is refusing to respond to it. The user might be logged in but does not have the necessary permissions for the resource.
case forbiddenAccess
/// The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.
case resourceNotFound
/// A request method is not supported for the requested resource; for example, a GET request on a form which requires data to be presented via POST, or a PUT request on a read-only resource.
case methodNotAllowed
/// The request was well-formed but was unable to be followed due to semantic errors.
case unprocessableEntity
/// A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
case internalServerError
}
| mit |
davidkobilnyk/BNRGuideSolutionsInSwift | 06-ViewControllers/HypnoNerd/HypnoNerd/AppDelegate.swift | 1 | 3207 | //
// AppDelegate.swift
// HypnoNerd
//
// Created by David Kobilnyk on 7/7/14.
// Copyright (c) 2014 David Kobilnyk. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
// Override point for customization after application launch.
// In iOS8, you have to get permission from the user for notifications before they're allowed.
// Without it, alerts won't work, and you'll get a console warning about
// "haven't received permission from the user to display alerts"
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert |
UIUserNotificationType.Badge, categories: nil
))
let hvc = BNRHypnosisViewController()
// Look in the appBundle for the file BNRReminderViewController.xib
let rvc = BNRReminderViewController()
let tabBarController = UITabBarController()
tabBarController.viewControllers = [hvc, rvc]
self.window!.rootViewController = tabBarController
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
saeta/penguin | Sources/PenguinStructures/SourceInitializableCollection.swift | 1 | 1312 | //******************************************************************************
// Copyright 2020 Penguin Authors
//
// 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
//
// https://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.
//
/// A collection that can be initialized to contain exactly the elements of a source collection.
public protocol SourceInitializableCollection: Collection {
/// Creates an instance containing exactly the elements of `source`.
///
/// Requires: Instances can hold `source.count` elements.
init<Source: Collection>(_ source: Source) where Source.Element == Element
// Note: we don't have a generalization to `Sequence` because we couldn't
// find an implementation optimizes nearly as well, and in practice
// `Sequence`'s that are not `Collection`s are extremely rare.
}
extension Array: SourceInitializableCollection {}
| apache-2.0 |
huangboju/Eyepetizer | Eyepetizer/Eyepetizer/Protocols/MenuPresenter.swift | 1 | 597 | //
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
protocol MenuPresenter: class {
var menuButton: MenuButton? { get set }
func menuBtnDidClick()
}
extension MenuPresenter where Self: UIViewController {
func setupMenuButton(type: MenuButtonType = .None) {
menuButton = MenuButton(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 40, height: 40)), type: type)
menuButton?.addTarget(self, action: Selector("menuBtnDidClick"), forControlEvents: .TouchUpInside)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: menuButton!)
}
}
| mit |
benkraus/Operations | Operations/UIUserNotifications+Operations.swift | 1 | 2662 | /*
The MIT License (MIT)
Original work Copyright (c) 2015 pluralsight
Modified work Copyright 2016 Ben Kraus
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.
*/
#if os(iOS)
import UIKit
extension UIUserNotificationSettings {
/// Check to see if one Settings object is a superset of another Settings object.
func contains(settings: UIUserNotificationSettings) -> Bool {
// our types must contain all of the other types
if !types.contains(settings.types) {
return false
}
let otherCategories = settings.categories ?? []
let myCategories = categories ?? []
return myCategories.isSupersetOf(otherCategories)
}
/**
Merge two Settings objects together. `UIUserNotificationCategories` with
the same identifier are considered equal.
*/
func settingsByMerging(settings: UIUserNotificationSettings) -> UIUserNotificationSettings {
let mergedTypes = types.union(settings.types)
let myCategories = categories ?? []
var existingCategoriesByIdentifier = Dictionary(sequence: myCategories) { $0.identifier }
let newCategories = settings.categories ?? []
let newCategoriesByIdentifier = Dictionary(sequence: newCategories) { $0.identifier }
for (newIdentifier, newCategory) in newCategoriesByIdentifier {
existingCategoriesByIdentifier[newIdentifier] = newCategory
}
let mergedCategories = Set(existingCategoriesByIdentifier.values)
return UIUserNotificationSettings(forTypes: mergedTypes, categories: mergedCategories)
}
}
#endif
| mit |
zhihuilong/ZHTabBarController | ZHTabBarController/Classes/ZHAddTabBar.swift | 1 | 1563 | //
// ZHAddTabBar.swift
// ZHTabBarController
//
// Created by Sunny on 15/10/4.
// Copyright © 2015年 sunny. All rights reserved.
//
import UIKit
public final class ZHAddTabBar: ZHTabBar {
fileprivate let centerBtn = UIImageView()
var btnClickBlock:(() -> Void)?
func didTap() {
if let tap = btnClickBlock {
tap()
} else {
print("!!!You must assign to btnClickBlock")
}
}
override func adjustItemFrame() {
let width = frame.height
centerBtn.isUserInteractionEnabled = true
centerBtn.frame = CGRect(origin: CGPoint(x: (SCREEN_WIDTH-width)/2, y: 0), size: CGSize(width: width, height: width))
centerBtn.backgroundColor = UIColor.clear
centerBtn.contentMode = UIViewContentMode.scaleAspectFit
centerBtn.image = UIImage(named: "centerBtn")
centerBtn.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ZHAddTabBar.didTap)))
addSubview(centerBtn)
let count = subviews.count - 1
let itemWidth = frame.size.width / CGFloat(count+1)
let itemHeight = frame.size.height
for i in 0..<count {
let item = subviews[i] as! ZHBarItem
item.tag = i
if i < 2 {
item.frame = CGRect(x: CGFloat(i) * itemWidth, y: 0, width: itemWidth, height: itemHeight)
} else {
item.frame = CGRect(x: CGFloat(i+1) * itemWidth, y: 0, width: itemWidth, height: itemHeight)
}
}
}
}
| mit |
wuhduhren/Mr-Ride-iOS | Pods/SideMenu/Pod/Classes/SideMenuTransition.swift | 1 | 22749 | //
// SideMenuTransition.swift
// Pods
//
// Created by Jon Kent on 1/14/16.
//
//
import UIKit
internal class SideMenuTransition: UIPercentDrivenInteractiveTransition, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
private var presenting = false
private var interactive = false
private static weak var originalSuperview: UIView?
internal static let singleton = SideMenuTransition()
internal static var presentDirection: UIRectEdge = .Left;
internal static weak var tapView: UIView!
internal static weak var statusBarView: UIView?
// prevent instantiation
private override init() {}
private class var viewControllerForPresentedMenu: UIViewController? {
get {
return SideMenuManager.menuLeftNavigationController?.presentingViewController != nil ? SideMenuManager.menuLeftNavigationController?.presentingViewController : SideMenuManager.menuRightNavigationController?.presentingViewController
}
}
private class var visibleViewController: UIViewController? {
get {
return getVisibleViewControllerFromViewController(UIApplication.sharedApplication().keyWindow?.rootViewController)
}
}
private class func getVisibleViewControllerFromViewController(viewController: UIViewController?) -> UIViewController? {
if let navigationController = viewController as? UINavigationController {
return getVisibleViewControllerFromViewController(navigationController.visibleViewController)
} else if let tabBarController = viewController as? UITabBarController {
return getVisibleViewControllerFromViewController(tabBarController.selectedViewController)
} else if let presentedViewController = viewController?.presentedViewController {
return getVisibleViewControllerFromViewController(presentedViewController)
}
return viewController
}
class func handlePresentMenuPan(pan: UIPanGestureRecognizer) {
// how much distance have we panned in reference to the parent view?
if let view = viewControllerForPresentedMenu != nil ? viewControllerForPresentedMenu?.view : pan.view {
let transform = view.transform
view.transform = CGAffineTransformIdentity
let translation = pan.translationInView(pan.view!)
view.transform = transform
// do some math to translate this to a percentage based value
if !singleton.interactive {
if translation.x == 0 {
return // not sure which way the user is swiping yet, so do nothing
}
if let edge = pan as? UIScreenEdgePanGestureRecognizer {
SideMenuTransition.presentDirection = edge.edges == .Left ? .Left : .Right
} else {
SideMenuTransition.presentDirection = translation.x > 0 ? .Left : .Right
}
if let menuViewController: UINavigationController = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController : SideMenuManager.menuRightNavigationController {
singleton.interactive = true
if let visibleViewController = visibleViewController {
visibleViewController.presentViewController(menuViewController, animated: true, completion: nil)
}
}
}
let direction:CGFloat = SideMenuTransition.presentDirection == .Left ? 1 : -1
let distance = translation.x / SideMenuManager.menuWidth
// now lets deal with different states that the gesture recognizer sends
switch (pan.state) {
case .Began, .Changed:
if pan is UIScreenEdgePanGestureRecognizer {
singleton.updateInteractiveTransition(min(distance * direction, 1))
} else if distance > 0 && SideMenuTransition.presentDirection == .Right && SideMenuManager.menuLeftNavigationController != nil {
SideMenuTransition.presentDirection = .Left
singleton.cancelInteractiveTransition()
viewControllerForPresentedMenu?.presentViewController(SideMenuManager.menuLeftNavigationController!, animated: true, completion: nil)
} else if distance < 0 && SideMenuTransition.presentDirection == .Left && SideMenuManager.menuRightNavigationController != nil {
SideMenuTransition.presentDirection = .Right
singleton.cancelInteractiveTransition()
viewControllerForPresentedMenu?.presentViewController(SideMenuManager.menuRightNavigationController!, animated: true, completion: nil)
} else {
singleton.updateInteractiveTransition(min(distance * direction, 1))
}
default:
singleton.interactive = false
view.transform = CGAffineTransformIdentity
let velocity = pan.velocityInView(pan.view!).x * direction
view.transform = transform
if velocity >= 100 || velocity >= -50 && abs(distance) >= 0.5 {
singleton.finishInteractiveTransition()
} else {
singleton.cancelInteractiveTransition()
}
}
}
}
class func handleHideMenuPan(pan: UIPanGestureRecognizer) {
let translation = pan.translationInView(pan.view!)
let direction:CGFloat = SideMenuTransition.presentDirection == .Left ? -1 : 1
let distance = translation.x / SideMenuManager.menuWidth * direction
switch (pan.state) {
case .Began:
singleton.interactive = true
viewControllerForPresentedMenu?.dismissViewControllerAnimated(true, completion: nil)
case .Changed:
singleton.updateInteractiveTransition(max(min(distance, 1), 0))
default:
singleton.interactive = false
let velocity = pan.velocityInView(pan.view!).x * direction
if velocity >= 100 || velocity >= -50 && distance >= 0.5 {
singleton.finishInteractiveTransition()
}
else {
singleton.cancelInteractiveTransition()
}
}
}
class func handleHideMenuTap(tap: UITapGestureRecognizer) {
viewControllerForPresentedMenu?.dismissViewControllerAnimated(true, completion: nil)
}
internal class func hideMenuStart() {
NSNotificationCenter.defaultCenter().removeObserver(SideMenuTransition.singleton)
let mainViewController = SideMenuTransition.viewControllerForPresentedMenu!
let menuView = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController!.view : SideMenuManager.menuRightNavigationController!.view
menuView.transform = CGAffineTransformIdentity
mainViewController.view.transform = CGAffineTransformIdentity
mainViewController.view.alpha = 1
SideMenuTransition.tapView.frame = CGRectMake(0, 0, mainViewController.view.frame.width, mainViewController.view.frame.height)
menuView.frame.origin.y = 0
menuView.frame.size.width = SideMenuManager.menuWidth
menuView.frame.size.height = mainViewController.view.frame.height
SideMenuTransition.statusBarView?.frame = UIApplication.sharedApplication().statusBarFrame
SideMenuTransition.statusBarView?.alpha = 0
switch SideMenuManager.menuPresentMode {
case .ViewSlideOut:
menuView.alpha = 1 - SideMenuManager.menuAnimationFadeStrength
menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? 0 : mainViewController.view.frame.width - SideMenuManager.menuWidth
mainViewController.view.frame.origin.x = 0
menuView.transform = CGAffineTransformMakeScale(SideMenuManager.menuAnimationTransformScaleFactor, SideMenuManager.menuAnimationTransformScaleFactor)
case .ViewSlideInOut:
menuView.alpha = 1
menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? -menuView.frame.width : mainViewController.view.frame.width
mainViewController.view.frame.origin.x = 0
case .MenuSlideIn:
menuView.alpha = 1
menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? -menuView.frame.width : mainViewController.view.frame.width
case .MenuDissolveIn:
menuView.alpha = 0
menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? 0 : mainViewController.view.frame.width - SideMenuManager.menuWidth
mainViewController.view.frame.origin.x = 0
}
}
internal class func hideMenuComplete() {
let mainViewController = SideMenuTransition.viewControllerForPresentedMenu!
let menuView = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController!.view : SideMenuManager.menuRightNavigationController!.view
SideMenuTransition.tapView.removeFromSuperview()
SideMenuTransition.statusBarView?.removeFromSuperview()
mainViewController.view.motionEffects.removeAll()
mainViewController.view.layer.shadowOpacity = 0
menuView.layer.shadowOpacity = 0
if let topNavigationController = mainViewController as? UINavigationController {
topNavigationController.interactivePopGestureRecognizer!.enabled = true
}
originalSuperview?.addSubview(mainViewController.view)
}
internal class func presentMenuStart(forSize size: CGSize = UIScreen.mainScreen().bounds.size) {
let mainViewController = SideMenuTransition.viewControllerForPresentedMenu!
if let menuView = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController?.view : SideMenuManager.menuRightNavigationController?.view {
menuView.transform = CGAffineTransformIdentity
mainViewController.view.transform = CGAffineTransformIdentity
menuView.frame.size.width = SideMenuManager.menuWidth
menuView.frame.size.height = size.height
menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? 0 : size.width - SideMenuManager.menuWidth
SideMenuTransition.statusBarView?.frame = UIApplication.sharedApplication().statusBarFrame
SideMenuTransition.statusBarView?.alpha = 1
switch SideMenuManager.menuPresentMode {
case .ViewSlideOut:
menuView.alpha = 1
let direction:CGFloat = SideMenuTransition.presentDirection == .Left ? 1 : -1
mainViewController.view.frame.origin.x = direction * (menuView.frame.width)
mainViewController.view.layer.shadowColor = SideMenuManager.menuShadowColor.CGColor
mainViewController.view.layer.shadowRadius = SideMenuManager.menuShadowRadius
mainViewController.view.layer.shadowOpacity = SideMenuManager.menuShadowOpacity
mainViewController.view.layer.shadowOffset = CGSizeMake(0, 0)
case .ViewSlideInOut:
menuView.alpha = 1
menuView.layer.shadowColor = SideMenuManager.menuShadowColor.CGColor
menuView.layer.shadowRadius = SideMenuManager.menuShadowRadius
menuView.layer.shadowOpacity = SideMenuManager.menuShadowOpacity
menuView.layer.shadowOffset = CGSizeMake(0, 0)
let direction:CGFloat = SideMenuTransition.presentDirection == .Left ? 1 : -1
mainViewController.view.frame.origin.x = direction * (menuView.frame.width)
mainViewController.view.transform = CGAffineTransformMakeScale(SideMenuManager.menuAnimationTransformScaleFactor, SideMenuManager.menuAnimationTransformScaleFactor)
mainViewController.view.alpha = 1 - SideMenuManager.menuAnimationFadeStrength
case .MenuSlideIn, .MenuDissolveIn:
menuView.alpha = 1
menuView.layer.shadowColor = SideMenuManager.menuShadowColor.CGColor
menuView.layer.shadowRadius = SideMenuManager.menuShadowRadius
menuView.layer.shadowOpacity = SideMenuManager.menuShadowOpacity
menuView.layer.shadowOffset = CGSizeMake(0, 0)
mainViewController.view.frame = CGRectMake(0, 0, size.width, size.height)
mainViewController.view.transform = CGAffineTransformMakeScale(SideMenuManager.menuAnimationTransformScaleFactor, SideMenuManager.menuAnimationTransformScaleFactor)
mainViewController.view.alpha = 1 - SideMenuManager.menuAnimationFadeStrength
}
}
}
internal class func presentMenuComplete() {
NSNotificationCenter.defaultCenter().addObserver(SideMenuTransition.singleton, selector:#selector(SideMenuTransition.applicationDidEnterBackgroundNotification), name: UIApplicationDidEnterBackgroundNotification, object: nil)
let mainViewController = SideMenuTransition.viewControllerForPresentedMenu!
switch SideMenuManager.menuPresentMode {
case .MenuSlideIn, .MenuDissolveIn:
if SideMenuManager.menuParallaxStrength != 0 {
let horizontal = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis)
horizontal.minimumRelativeValue = -SideMenuManager.menuParallaxStrength
horizontal.maximumRelativeValue = SideMenuManager.menuParallaxStrength
let vertical = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis)
vertical.minimumRelativeValue = -SideMenuManager.menuParallaxStrength
vertical.maximumRelativeValue = SideMenuManager.menuParallaxStrength
let group = UIMotionEffectGroup()
group.motionEffects = [horizontal, vertical]
mainViewController.view.addMotionEffect(group)
}
case .ViewSlideOut, .ViewSlideInOut: break;
}
if let topNavigationController = mainViewController as? UINavigationController {
topNavigationController.interactivePopGestureRecognizer!.enabled = false
}
}
// MARK: UIViewControllerAnimatedTransitioning protocol methods
// animate a change from one viewcontroller to another
internal func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let statusBarStyle = SideMenuTransition.visibleViewController?.preferredStatusBarStyle()
// get reference to our fromView, toView and the container view that we should perform the transition in
let container = transitionContext.containerView()!
if let menuBackgroundColor = SideMenuManager.menuAnimationBackgroundColor {
container.backgroundColor = menuBackgroundColor
}
// create a tuple of our screens
let screens : (from:UIViewController, to:UIViewController) = (transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!, transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!)
// assign references to our menu view controller and the 'bottom' view controller from the tuple
// remember that our menuViewController will alternate between the from and to view controller depending if we're presenting or dismissing
let menuViewController = (!presenting ? screens.from : screens.to)
let topViewController = !presenting ? screens.to : screens.from
let menuView = menuViewController.view
let topView = topViewController.view
// prepare menu items to slide in
if presenting {
let tapView = UIView()
tapView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
let exitPanGesture = UIPanGestureRecognizer()
exitPanGesture.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handleHideMenuPan(_:)))
let exitTapGesture = UITapGestureRecognizer()
exitTapGesture.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handleHideMenuTap(_:)))
tapView.addGestureRecognizer(exitPanGesture)
tapView.addGestureRecognizer(exitTapGesture)
SideMenuTransition.tapView = tapView
SideMenuTransition.originalSuperview = topView.superview
// add the both views to our view controller
switch SideMenuManager.menuPresentMode {
case .ViewSlideOut:
container.addSubview(menuView)
container.addSubview(topView)
topView.addSubview(tapView)
case .MenuSlideIn, .MenuDissolveIn, .ViewSlideInOut:
container.addSubview(topView)
container.addSubview(tapView)
container.addSubview(menuView)
}
if SideMenuManager.menuFadeStatusBar {
let blackBar = UIView()
if let menuShrinkBackgroundColor = SideMenuManager.menuAnimationBackgroundColor {
blackBar.backgroundColor = menuShrinkBackgroundColor
} else {
blackBar.backgroundColor = UIColor.blackColor()
}
blackBar.userInteractionEnabled = false
container.addSubview(blackBar)
SideMenuTransition.statusBarView = blackBar
}
SideMenuTransition.hideMenuStart() // offstage for interactive
}
// perform the animation!
let duration = transitionDuration(transitionContext)
let options: UIViewAnimationOptions = interactive ? .CurveLinear : .CurveEaseInOut
UIView.animateWithDuration(duration, delay: 0, options: options, animations: { () -> Void in
if self.presenting {
SideMenuTransition.presentMenuStart() // onstage items: slide in
}
else {
SideMenuTransition.hideMenuStart()
}
}) { (finished) -> Void in
if SideMenuTransition.visibleViewController?.preferredStatusBarStyle() != statusBarStyle {
print("Warning: do not change the status bar style while using custom transitions or you risk transitions not properly completing and locking up the UI. See http://www.openradar.me/21961293")
}
// tell our transitionContext object that we've finished animating
if transitionContext.transitionWasCancelled() {
if self.presenting {
SideMenuTransition.hideMenuComplete()
} else {
SideMenuTransition.presentMenuComplete()
}
transitionContext.completeTransition(false)
} else {
if self.presenting {
SideMenuTransition.presentMenuComplete()
transitionContext.completeTransition(true)
switch SideMenuManager.menuPresentMode {
case .ViewSlideOut:
container.addSubview(topView)
case .MenuSlideIn, .MenuDissolveIn, .ViewSlideInOut:
container.insertSubview(topView, atIndex: 0)
}
if let statusBarView = SideMenuTransition.statusBarView {
container.bringSubviewToFront(statusBarView)
}
} else {
SideMenuTransition.hideMenuComplete()
transitionContext.completeTransition(true)
menuView.removeFromSuperview()
}
}
}
}
// return how many seconds the transiton animation will take
internal func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return presenting ? SideMenuManager.menuAnimationPresentDuration : SideMenuManager.menuAnimationDismissDuration
}
// MARK: UIViewControllerTransitioningDelegate protocol methods
// return the animataor when presenting a viewcontroller
// rememeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol
internal func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = true
SideMenuTransition.presentDirection = presented == SideMenuManager.menuLeftNavigationController ? .Left : .Right
return self
}
// return the animator used when dismissing from a viewcontroller
internal func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
presenting = false
return self
}
internal func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
// if our interactive flag is true, return the transition manager object
// otherwise return nil
return interactive ? SideMenuTransition.singleton : nil
}
internal func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactive ? SideMenuTransition.singleton : nil
}
internal func applicationDidEnterBackgroundNotification() {
if let menuViewController: UINavigationController = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController : SideMenuManager.menuRightNavigationController {
SideMenuTransition.hideMenuStart()
SideMenuTransition.hideMenuComplete()
menuViewController.dismissViewControllerAnimated(false, completion: nil)
}
}
}
| mit |
guipanizzon/ioscreator | WatchKitLabelTutorial/WatchKitLabelTutorial/ViewController.swift | 41 | 502 | //
// ViewController.swift
// WatchKitLabelTutorial
//
// Created by Arthur Knopper on 19/11/14.
// Copyright (c) 2014 Arthur Knopper. 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.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
GeekerHua/GHSwiftTest | 02-闭包基础/02-闭包Tests/_2___Tests.swift | 1 | 970 | //
// _2___Tests.swift
// 02-闭包Tests
//
// Created by GeekerHua on 15/12/25.
// Copyright © 2015年 GeekerHua. All rights reserved.
//
import XCTest
@testable import _2___
class _2___Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| mit |
IBM-MIL/IBM-Ready-App-for-Retail | iOS/ReadyAppRetail/ReadyAppRetail/Controllers/LoginViewController.swift | 1 | 20880 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
import Security
class LoginViewController: SummitUIViewController, UITextFieldDelegate, UIAlertViewDelegate {
@IBOutlet weak var loginBoxView: UIView!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var summitLogoImageView: UIImageView!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var signUpButton: UIButton!
@IBOutlet weak var appNameLabel: UILabel!
@IBOutlet weak var logoHolderTopSpace: NSLayoutConstraint!
@IBOutlet weak var loginBoxViewBottomSpace: NSLayoutConstraint!
var logoHolderOriginalTopSpace : CGFloat!
var loginBoxViewOriginalBottomSpace : CGFloat!
var kFourInchIphoneHeight : CGFloat = 568
var kFourInchIphoneLogoHolderNewTopSpace : CGFloat = 30
var kloginBoxViewPaddingFromKeyboard : CGFloat = 60
var presentingVC : UIViewController!
var noKeychainItems : Bool = true
var wormhole : MMWormhole?
/**
This method calls the setUpLoginBoxView, setUpSignUpButton, setUpTextFields, and saveUIElementOriginalConstraints methods when the view loads
*/
override func viewDidLoad() {
super.viewDidLoad()
if let groupAppID = GroupDataAccess.sharedInstance.groupAppID {
self.wormhole = MMWormhole(applicationGroupIdentifier: groupAppID, optionalDirectory: nil)
}
setUpLoginBoxView()
setUpLoginButton()
setUpSignUpButton()
setUpTextFields()
saveUIElementOriginalConstraints()
}
override func viewDidAppear(animated: Bool) {
self.navigationItem.title = NSLocalizedString("LOGIN", comment:"")
self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Oswald-Regular", size: 22)!, NSForegroundColorAttributeName: UIColor.whiteColor()]
}
/**
This method calls the registerForKeyboardNotifications when the viewWillAppear
- parameter animated:
*/
override func viewWillAppear(animated: Bool) {
self.registerForKeyboardNotifications()
// Attempt to fetch login details from the keychain
let usr : String? = KeychainWrapper.stringForKey("summit_username")
let pswd : String? = KeychainWrapper.stringForKey("summit_password")
if (usr != nil && pswd != nil) {
Utils.showProgressHud()
self.noKeychainItems = false
MILWLHelper.login(usr!, password: pswd!, callBack: self.loginCallback)
} else {
self.noKeychainItems = true
}
}
/**
This method calls the deregisterFromKeyboardNotifications when the viewWillDisappear
- parameter animated:
*/
override func viewWillDisappear(animated: Bool) {
self.deregisterFromKeyboardNotifications()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/**
This method sets up properties of the loginBoxView, specifically to make the corners rounded
*/
func setUpLoginBoxView(){
loginBoxView.layer.cornerRadius = 6;
loginBoxView.layer.masksToBounds = true;
}
/**
This method sets the title of the login button using a localized string
*/
func setUpLoginButton(){
loginButton.setTitle(NSLocalizedString("L O G I N", comment: "Another word for sign in"), forState: UIControlState.Normal)
}
/**
This method sets up the usernameTextField and the passwordTextField to make the corners rounded, to add the icon on the left side of the textfield, and to hide the iOS 8 suggested words toolbar
*/
func setUpTextFields(){
//*****set up usernameTextField*****
//make cursor color summit green
usernameTextField.tintColor = Utils.UIColorFromHex(0x005448, alpha: 1)
//create imageView of usernameIcon
let usernameIconImageView = UIImageView(frame: CGRectMake(13, 12, 16, 20))
usernameIconImageView.image = UIImage(named: "profile_selected")
//create paddingView that will be added to the usernameTextField. This paddingView will hold the usernameIconImageView
let usernamePaddingView = UIView(frame: CGRectMake(0, 0,usernameTextField.frame.size.height - 10, usernameTextField.frame.size.height))
usernamePaddingView.addSubview(usernameIconImageView)
//add usernamePaddingView to usernameTextField.leftView
usernameTextField.leftView = usernamePaddingView
usernameTextField.leftViewMode = UITextFieldViewMode.Always
//make usernameTextField have rounded corners
usernameTextField.borderStyle = UITextBorderStyle.RoundedRect
//hide iOS 8 suggested words toolbar
usernameTextField.autocorrectionType = UITextAutocorrectionType.No;
usernameTextField.placeholder = NSLocalizedString("Username", comment: "A word for mail over the internet")
//*****set up passwordTextField****
//make cursor color summit green
passwordTextField.tintColor = Utils.UIColorFromHex(0x005448, alpha: 1)
//create imageView for passwordIcon
let passwordIconImageView = UIImageView(frame: CGRectMake(13, 10, 18, 22))
passwordIconImageView.image = UIImage(named: "password")
//create paddingView that will be added to the passwordTextField. This paddingView will hold the passwordIconImageView
let passwordPaddingView = UIView(frame: CGRectMake(0, 0,usernameTextField.frame.size.height - 10, usernameTextField.frame.size.height))
passwordPaddingView.addSubview(passwordIconImageView)
//add passwordPaddingView to the passwordTextField.left
passwordTextField.leftView = passwordPaddingView
passwordTextField.leftViewMode = UITextFieldViewMode.Always
//Make passwordTextField have rounded corners
passwordTextField.borderStyle = UITextBorderStyle.RoundedRect
//hide iOS 8 suggested words toolbar
passwordTextField.autocorrectionType = UITextAutocorrectionType.No;
passwordTextField.placeholder = NSLocalizedString("Password", comment: "A secret phrase that allows you to login to a service")
}
/**
This method sets up the text of the signUpButton by creating an attributed string and assigning this attributed string to the signUpButtons attributed title
*/
func setUpSignUpButton(){
// create attributed string
let localizedString = NSLocalizedString("Don't have an Account?", comment: "A secret phrase that allows you to login to a service")
let string = localizedString
let attributedString = NSMutableAttributedString(string: string)
let localizedString2 = NSLocalizedString(" Sign Up.", comment: "A secret phrase that allows you to login to a service")
let string2 = localizedString2
let attributedString2 = NSMutableAttributedString(string: string2)
// create font descriptor for bold and italic font
let fontDescriptor = UIFontDescriptor.preferredFontDescriptorWithTextStyle(UIFontTextStyleBody)
let boldItalicFontDescriptor = fontDescriptor.fontDescriptorWithSymbolicTraits(.TraitBold)
//Create attributes for two parts of the string
let firstAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
let secondAttributes = [NSFontAttributeName: UIFont(descriptor: boldItalicFontDescriptor, size: 12), NSForegroundColorAttributeName: UIColor.whiteColor()]
//Add attributes to two parts of the string
attributedString.addAttributes(firstAttributes, range: NSRange(location: 0,length: string.characters.count))
attributedString2.addAttributes(secondAttributes, range: NSRange(location: 0, length: string2.characters.count))
attributedString.appendAttributedString(attributedString2)
//set Attributed Title for signUp Button
signUpButton.setAttributedTitle(attributedString, forState: UIControlState.Normal)
}
/**
This method saves the original constant for the the logoHolderOriginalTopSpace and the loginBoxViewOriginalBottomSpace. These CGFloats are needed in the keyboardWillHide method to bring the logoHolder and the loginBoxView back to their original constraint constants.
*/
func saveUIElementOriginalConstraints(){
logoHolderOriginalTopSpace = logoHolderTopSpace.constant
loginBoxViewOriginalBottomSpace = loginBoxViewBottomSpace.constant
}
/**
This method sets up the keyboardWillShow and keyboardWillHide methods to be called when NSNotificationCenter triggers the UIKeyboardWillShowNotification and UIKeyboardWillHideNotification notifications repspectively
*/
func registerForKeyboardNotifications(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
}
/**
This method removes the observer that triggers the UIKeyboardWillShowNotification. This method is invoked in the viewWillDisappear method
*/
func deregisterFromKeyboardNotifications(){
NSNotificationCenter.defaultCenter().removeObserver(self, name:UIKeyboardWillShowNotification, object: nil);
}
/**
This method is called when the loginButton is pressed. This method checks to see if the username and password entered in the textfields are of valid syntax. It does this by calling the checkEmail and checkPassword methods of the utility class SyntaxChecker.swift. This class assumes that the following regular expression is allowed for an email [A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4} and for a password [A-Z0-9a-z_@!&%$#*?]+. This method also calls the login method
- parameter sender:
*/
@IBAction func loginButtonAction(sender: UIButton) {
if(SyntaxChecker.checkUserName(usernameTextField.text!) == true && SyntaxChecker.checkPassword(passwordTextField.text!) == true){
self.login()
}
}
override func disablesAutomaticKeyboardDismissal() -> Bool {
return false
}
/**
This method uses the view controllers instance of milWLHelper to call the login method, passing it the username and password the user entered in the text fields.
*/
func login(){
Utils.showProgressHud()
MILWLHelper.login(self.usernameTextField.text!, password: self.passwordTextField.text!, callBack: self.loginCallback)
}
func loginCallback(success: Bool, errorMessage: String?) {
if success {
self.loginSuccessful()
}
else if (errorMessage != nil) {
self.loginFailure(errorMessage!)
}
else {
self.loginFailure("No message")
}
}
/**
This method is called from the LoginManager if the login was successful
*/
func loginSuccessful(){
// Store username and password in the keychain
if (noKeychainItems == true) {
KeychainWrapper.setString(self.usernameTextField.text!, forKey: "summit_username")
KeychainWrapper.setString(self.passwordTextField.text!, forKey: "summit_password")
}
// Let the Watch know that it can log in
self.wormhole!.passMessageObject(["username": KeychainWrapper.stringForKey("summit_username")!, "password": KeychainWrapper.stringForKey("summit_password")!], identifier: "loginNotification")
MILWLHelper.getDefaultList(self.defaultListResult)
}
func defaultListResult(success: Bool) {
if success {
self.defaultListsDownloaded()
} else {
self.failureDownloadingDefaultLists()
}
}
private func dismissLoginViewController(){
Utils.dismissProgressHud()
//dismiss login and present the appropriate next view based on which VC presented the login
self.usernameTextField.resignFirstResponder()
self.passwordTextField.resignFirstResponder()
self.view.endEditing(true)
self.dismissViewControllerAnimated(true, completion:{(Bool) in
if (self.presentingVC.isKindOfClass(ProductDetailViewController)) {
let detailVC: ProductDetailViewController = self.presentingVC as! ProductDetailViewController
detailVC.queryProductIsAvailable() //refresh product availability
detailVC.addToListTapped() //show add to list view
}
if (self.presentingVC.isKindOfClass(ListTableViewController)) {
let detailVC: ListTableViewController = self.presentingVC as! ListTableViewController
detailVC.performSegueWithIdentifier("createList", sender: self) //show create a list view
}
})
}
/**
This method is called from the GetDefaultListDataManager when the lists have been successfully downloaded, parsed, and added to realm
*/
func defaultListsDownloaded(){
Utils.dismissProgressHud()
dismissLoginViewController()
}
/**
This method is called by the GetDefaultListDataManager when the onFailure was called by Worklight. It first dismisses the progressHud and then shows the server error alert
*/
func failureDownloadingDefaultLists(){
Utils.dismissProgressHud()
Utils.showServerErrorAlert(self, tag: 1)
}
/**
This method is called when the Retry button is pressed from the server error alert. It first shows the progressHud and then retrys to call MILWLHelper's getDefaultList method
- parameter alertView:
- parameter buttonIndex:
*/
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if(alertView.tag == 1){
Utils.showProgressHud()
MILWLHelper.getDefaultList(self.defaultListResult)
}
}
/**
This method is called from the LoginManager if the login was a failure
*/
func loginFailure(errorMessage : String){
Utils.dismissProgressHud()
var alertTitle : String!
if(errorMessage == NSLocalizedString("Invalid username", comment:"")){
if (self.noKeychainItems == false) {
alertTitle = NSLocalizedString("Stale Keychain Credentials", comment:"")
KeychainWrapper.removeObjectForKey("summit_username")
KeychainWrapper.removeObjectForKey("summit_password")
self.noKeychainItems = true
}
alertTitle = NSLocalizedString("Invalid Username", comment:"")
}
else if(errorMessage == "Invalid password"){
if (self.noKeychainItems == false) {
alertTitle = NSLocalizedString("Stale Keychain Credentials", comment:"")
KeychainWrapper.removeObjectForKey("summit_username")
KeychainWrapper.removeObjectForKey("summit_password")
self.noKeychainItems = true
}
alertTitle = NSLocalizedString("Invalid Password", comment:"")
}
else {
alertTitle = NSLocalizedString("Can't Connect To Server", comment:"")
}
let alert = UIAlertView()
alert.title = alertTitle
alert.message = NSLocalizedString("Please Try Again", comment:"")
alert.addButtonWithTitle("OK")
alert.show()
Utils.dismissProgressHud()
}
/**
This method is called when the signUpButton is pressed
- parameter sender:
*/
@IBAction func signUpButtonAction(sender: UIButton) {
}
/**
This method is called when the user touches anywhere on the view that is not a textfield. This method triggers the keyboard to go down, which triggers the keyboardWillHide method to be called, thus bringing the loginBoxView and the logoHolderView back to their original positions
- parameter touches:
- parameter event:
*/
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
usernameTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
}
/**
This method is called when the keyboard shows. Its main purpose is to adjust the logoHolderView and the loginBoxView's constraints to raise these views up vertically to make room for the keyboard
- parameter notification:
*/
func keyboardWillShow(notification : NSNotification){
//if the loginBoxViewBottomSpace.constant is at its original position, aka only raise the views when they aren't already raised.
if(loginBoxViewBottomSpace.constant == loginBoxViewOriginalBottomSpace){
//if the iPhone's height is less than kFourInchIphoneHeight (568)
if(UIScreen.mainScreen().bounds.height <= kFourInchIphoneHeight){
let info : NSDictionary = notification.userInfo!
//grab the size of the keyboard that has popped up
let keyboardSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey)?.CGRectValue.size
//adjust the top space constraint for the logoHolder
logoHolderTopSpace.constant = kFourInchIphoneLogoHolderNewTopSpace
//adjust the loginBoxView bottom space
loginBoxViewBottomSpace.constant = (keyboardSize!.height - loginBoxViewBottomSpace.constant) + kloginBoxViewPaddingFromKeyboard //arbitrary 20 padding
UIView.animateWithDuration(0.3, animations: {
self.view.layoutIfNeeded()
self.appNameLabel.alpha = 0
})
}else{
let info : NSDictionary = notification.userInfo!
//grab the size of the keyboard
let keyboardSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey)?.CGRectValue.size
self.view.layoutIfNeeded()
//adjust the bottom space constraint for the loginBoxView
loginBoxViewBottomSpace.constant = (keyboardSize!.height - loginBoxViewBottomSpace.constant) + kloginBoxViewPaddingFromKeyboard //arbitrary 20 padding
UIView.animateWithDuration(0.3, animations: { self.view.layoutIfNeeded()})
}
}
}
/**
This method is called when the keyboard hides. It sets the logoHolderView and the loginBoxView's constraints to their original positions
- parameter notification:
*/
func keyboardWillHide(notification : NSNotification){
self.view.layoutIfNeeded()
//set the logoHolderTopSpace and loginBoxViewBottomSpace to their original constraint constants
logoHolderTopSpace.constant = logoHolderOriginalTopSpace
loginBoxViewBottomSpace.constant = loginBoxViewOriginalBottomSpace
UIView.animateWithDuration(0.2, animations: { self.view.layoutIfNeeded()
self.appNameLabel.alpha = 1
})
}
/**
If the user presses the return key while the passwordTextField is selected, it will call the login method
- parameter textField:
- returns:
*/
func textFieldShouldReturn(textField: UITextField) -> Bool {
if(textField == passwordTextField){
login()
}
return true
}
/**
This method is called when the user presses the x in the top left corner
- parameter sender:
*/
@IBAction func cancelLoginScreen(sender: AnyObject) {
self.dismissViewControllerAnimated(false, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| epl-1.0 |
Miroling/swift-playground | Lecture2/Lecture2/Controllers/LoginViewController.swift | 1 | 1084 | //
// LoginViewController.swift
// Lecture2
//
// Created by Taras Omelianenko on 08.09.14.
// Copyright (c) 2014 Taras Omelianenko. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
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 loginAction(sender: AnyObject) {
navigationController?.dismissViewControllerAnimated(true, completion: nil)
println("Button clicked")
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| unlicense |
happylance/MacKey | MacKey/Services/TouchIDService.swift | 1 | 1919 | //
// TouchIDUtils.swift
// MacKey
//
// Created by Liu Liang on 5/15/16.
// Copyright © 2016 Liu Liang. All rights reserved.
//
import LocalAuthentication
import RxSwift
class TouchIDService {
static func runTouchID(for host: HostInfo) -> Observable<(Bool, Error?)> {
return Observable.create { observer in
let context = LAContext()
context.localizedFallbackTitle = ""
context.evaluatePolicy(
.deviceOwnerAuthenticationWithBiometrics,
localizedReason: String(format:"Authentication required to unlock '%@'".localized(), host.alias))
{ success, error in
observer.onNext((success, error))
observer.onCompleted()
}
return Disposables.create()
}
}
static func getErrorMessage(_ error: Error?) -> String {
guard let error = error as? LAError else {
return "Touch ID error"
}
switch error.code {
case .appCancel:
return "App cancelled authentication"
case .authenticationFailed:
return "Authentication failed"
case .invalidContext:
return "Invalid authentication context"
case .passcodeNotSet:
return "User's passcode not set"
case .systemCancel:
return "System cancelled authetication"
case .touchIDLockout:
return "User is locked out of Touch ID"
case .touchIDNotAvailable:
return "Touch ID is not available on this device"
case .touchIDNotEnrolled:
return "User has not enrolled for Touch ID"
case .userCancel:
return "User cancelled authentication"
case .userFallback:
return "User opted for fallback authentication"
case .notInteractive:
return "Not interactive."
}
}
}
| mit |
EvsenevDev/SmartReceiptsiOS | SmartReceipts/Modules/Trips/TripsInteractor.swift | 2 | 843 | //
// TripsInteractor.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 11/06/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
import Foundation
import Viperit
import RxSwift
class TripsInteractor: Interactor {
let bag = DisposeBag()
func configureSubscribers() {
presenter.tripDeleteSubject.subscribe(onNext: { trip in
Logger.debug("Delete Trip: \(trip.name!)")
Database.sharedInstance().delete(trip)
}).disposed(by: bag)
}
func fetchedModelAdapter() -> FetchedModelAdapter? {
return Database.sharedInstance().createUpdatingAdapterForAllTrips()
}
}
// MARK: - VIPER COMPONENTS API (Auto-generated code)
private extension TripsInteractor {
var presenter: TripsPresenter {
return _presenter as! TripsPresenter
}
}
| agpl-3.0 |
laurentVeliscek/AudioKit | AudioKit/Common/Playgrounds/Filters.playground/Pages/High Shelf Filter.xcplaygroundpage/Contents.swift | 1 | 1518 | //: ## High Shelf Filter
//:
import XCPlayground
import AudioKit
let file = try AKAudioFile(readFileName: filtersPlaygroundFiles[0],
baseDir: .Resources)
let player = try AKAudioPlayer(file: file)
player.looping = true
var highShelfFilter = AKHighShelfFilter(player)
highShelfFilter.cutOffFrequency = 10000 // Hz
highShelfFilter.gain = 0 // dB
AudioKit.output = highShelfFilter
AudioKit.start()
player.play()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("High Shelf Filter")
addSubview(AKResourcesAudioFileLoaderView(
player: player,
filenames: filtersPlaygroundFiles))
addSubview(AKBypassButton(node: highShelfFilter))
addSubview(AKPropertySlider(
property: "Cutoff Frequency",
format: "%0.1f Hz",
value: highShelfFilter.cutOffFrequency, minimum: 20, maximum: 22050,
color: AKColor.greenColor()
) { sliderValue in
highShelfFilter.cutOffFrequency = sliderValue
})
addSubview(AKPropertySlider(
property: "Gain",
format: "%0.1f dB",
value: highShelfFilter.gain, minimum: -40, maximum: 40,
color: AKColor.redColor()
) { sliderValue in
highShelfFilter.gain = sliderValue
})
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
| mit |
benlangmuir/swift | test/decl/typealias/associated_types.swift | 4 | 777 | // RUN: %target-typecheck-verify-swift -parse-as-library
protocol BaseProto {
associatedtype AssocTy
}
var a: BaseProto.AssocTy = 4
// expected-error@-1{{cannot access associated type 'AssocTy' from 'BaseProto'; use a concrete type or generic parameter base instead}}
var a = BaseProto.AssocTy.self
// expected-error@-1{{cannot access associated type 'AssocTy' from 'BaseProto'; use a concrete type or generic parameter base instead}}
protocol DerivedProto : BaseProto {
func associated() -> AssocTy // no-warning
func existential() -> BaseProto.AssocTy
// expected-error@-1{{cannot access associated type 'AssocTy' from 'BaseProto'; use a concrete type or generic parameter base instead}}
}
func generic<T: BaseProto>(_: T, _ assoc: T.AssocTy) {} // no-warning
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.