hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
67acd676d8204b1e07846ada8f7e0b3535d0a07d | 2,393 | //
// AppDelegate.swift
// LocateMe
//
// Created by larryhou on 8/15/14.
// Copyright (c) 2014 larryhou. All rights reserved.
//
import UIKit
import CoreLocation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool
{
if !CLLocationManager.locationServicesEnabled()
{
var alert = UIAlertView(title: "定位服务已关闭", message: "您当前设备的定位服务已关闭,如果继续使用,你将会被请求重新打开定位服务。", delegate: nil, cancelButtonTitle: "我知道了")
alert.show();
}
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:.
}
}
| 39.883333 | 285 | 0.721688 |
22112890d2e091936145b05cb97cb30aa8fbb819 | 349 | //
// UnlockRouter.swift
// Swoorn
//
// Created by Peter IJlst | The Mobile Company on 01/07/2019.
// Copyright © 2019 Peter IJlst. All rights reserved.
//
//sourcery: AutoMockable
protocol UnlockRouterProtocol {
func unlock()
}
class UnlockRouter: UnlockRouterProtocol {
func unlock() {
MyApp.shared.process(.UNLOCK)
}
}
| 18.368421 | 62 | 0.679083 |
4b0dc665de9f7e1a17166acbe7ae02b27d432278 | 18,766 | /*
SKTilemap
SKTilemapLayer.swift
Created by Thomas Linthwaite on 07/04/2016.
GitHub: https://github.com/TomLinthwaite/SKTilemap
Website (Guide): http://tomlinthwaite.com/
Wiki: https://github.com/TomLinthwaite/SKTilemap/wiki
YouTube: https://www.youtube.com/channel/UCAlJgYx9-Ub_dKD48wz6vMw
Twitter: https://twitter.com/Mr_Tomoso
-----------------------------------------------------------------------------------------------------------------------
MIT License
Copyright (c) 2016 Tom Linthwaite
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-----------------------------------------------------------------------------------------------------------------------
*/
import SpriteKit
// MARK: SKTileLayer
class SKTilemapLayer : SKNode {
// MARK: Properties
override var hashValue: Int { get { return name!.hashValue } }
/** Properties shared by all TMX object types. */
var properties: [String : String] = [:]
/** The offset to draw this layer at from the tilemap position. */
let offset: CGPoint
/** The tilemap this layer has been added to. */
let tilemap: SKTilemap
/** A 2D array representing the tile layer data. */
private var tiles: [[SKTilemapTile?]]
/** The size of the layer in tiles. */
private var size: CGSize { get { return tilemap.size } }
private var sizeHalved: CGSize { get { return CGSize(width: size.width / 2, height: size.height / 2) } }
/** The tilemap tile size. */
private var tileSize: CGSize { get { return tilemap.tileSize } }
private var tileSizeHalved: CGSize { get { return CGSize(width: tileSize.width / 2, height: tileSize.height / 2) } }
/** Used when clipping tiles outside of a set bounds. See: 'func clipTilesOutOfBounds()'*/
private var previouslyShownTiles: [SKTilemapTile] = []
// MARK: Initialization
/** Initialize an empty tilemap layer */
init(tilemap: SKTilemap, name: String, offset: CGPoint = CGPoint.zero) {
self.tilemap = tilemap
self.offset = offset
tiles = Array(repeating: Array(repeating: nil, count: Int(tilemap.size.width)), count: Int(tilemap.size.height))
super.init()
self.name = name
}
/** Initialize a tile layer from tmx parser attributes. Should probably only be called by SKTilemapParser. */
init?(tilemap: SKTilemap, tmxParserAttributes attributes: [String : String]) {
guard
let name = attributes["name"]
else {
print("SKTilemapLayer: Failed to initialize with tmxAttributes.")
return nil
}
if
let offsetX = attributes["offsetx"] where (Int(offsetX) != nil),
let offsetY = attributes["offsety"] where (Int(offsetY) != nil) {
offset = CGPoint(x: Int(offsetX)!, y: Int(offsetY)!)
} else {
offset = CGPoint.zero
}
self.tilemap = tilemap
tiles = Array(repeating: Array(repeating: nil, count: Int(tilemap.size.width)), count: Int(tilemap.size.height))
super.init()
self.name = name
if let opacity = attributes["opacity"] where (Double(opacity)) != nil {
alpha = CGFloat(Double(opacity)!)
}
if let visible = attributes["visible"] where (Int(visible)) != nil {
isHidden = (Int(visible)! == 0 ? true : false)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Debug
func printDebugDescription() {
print("\nSKTileLayer: \(name), Offset: \(offset), Opacity: \(alpha), Visible: \(!isHidden)")
print("Properties: \(properties)")
}
// MARK: Tiles
/** Initialize the layer with in for the form of a 1 dimensional Int array. The array represents each a tile GID for
its respective location on the map. */
func initializeTilesWithData(data: [Int]) -> Bool {
if data.count != Int(size.width) * Int(size.height) {
print("SKTilemapLayer: Failed to initialize tile data. Data size is invalid.")
return false
}
//removeAllTiles()
for i in 0..<data.count {
let gid = data[i]
if gid == 0 { continue }
let x = i % Int(size.width)
let y = i / Int(size.width)
let tile = setTileAtCoord(x: x, y, id: gid).tileSet
tile?.playAnimation(tilemap: tilemap)
}
return true
}
/** Initialize the layer with a single tile GID. (All tiles will be set to this GID. */
func initializeTilesWithID(id: Int) {
for y in 0..<Int(size.height) {
for x in 0..<Int(size.width) {
setTileAtCoord(x: x, y, id: id)
}
}
}
/** Returns true if the x/y position passed into the function relates to a valid coordinate on the map. */
func isValidCoord(x: Int, y: Int) -> Bool {
return x >= 0 && x < Int(size.width) && y >= 0 && y < Int(size.height)
}
/** Remove a particular tile at a map position. Will return the tile that was removed or nil if the tile did not exist or
the location was invalid. */
func removeTileAtCoord(x: Int, _ y: Int) -> SKTilemapTile? {
return setTileAtCoord(x: x, y, tile: nil).tileRemoved
}
func removeTileAtCoord(coord: CGPoint) -> SKTilemapTile? {
return setTileAtCoord(x: Int(coord.x), Int(coord.y), tile: nil).tileRemoved
}
/** Removes all tiles from the layer. */
func removeAllTiles() {
for y in 0..<Int(size.height) {
for x in 0..<Int(size.width) {
removeTileAtCoord(x: x, y)
}
}
}
/** Returns a tile at a given map coord or nil if no tile exists or the position was outside of the map. */
func tileAtCoord(x: Int, _ y: Int) -> SKTilemapTile? {
if !isValidCoord(x: x, y: y) {
return nil
}
return tiles[y][x]
}
/** Returns a tile at a given map coord or nil if no tile exists or the position was outside of the map. */
func tileAtCoord(coord: CGPoint) -> SKTilemapTile? {
return tileAtCoord(x: Int(coord.x), Int(coord.y))
}
/** Returns the tile at a certain position within the layer. */
func tileAtPosition(positionInLayer: CGPoint) -> SKTilemapTile? {
if let coord = coordAtPosition(positionInLayer: positionInLayer, round: true) {
return tileAtCoord(x: Int(coord.x), Int(coord.y))
}
return nil
}
#if os(iOS)
/* Returns a tile at a given touch position. A custom offset can also be used. */
func tileAtTouchPosition(touch: UITouch, offset: CGPoint = CGPoint.zero) -> SKTilemapTile? {
if let coord = coordAtTouchPosition(touch: touch, offset: offset, round: true) {
return tileAtCoord(coord: coord)
}
return nil
}
#endif
#if os(OSX)
func tileAtMousePosition(event: NSEvent, offset: CGPoint = CGPointZero) -> SKTilemapTile? {
if let coord = coordAtMousePosition(event, offset: offset, round: true) {
return tileAtCoord(coord)
}
return nil
}
#endif
/* Returns a tile at a given screen position. A custom offet can be used. */
func tileAtScreenPosition(position: CGPoint, offset: CGPoint = CGPoint.zero) -> SKTilemapTile? {
if let coord = coordAtScreenPosition(position: position, offset: offset, round: true, mustBeValid: true) {
return tileAtCoord(coord: coord)
}
return nil
}
/** Set a specific position on the map to represent the given tile. Nil can also be passed to
remove a tile at this position (although removeTile(x:y:) is the prefered method for doing this).
Will return a tuple containing the tile that was removed and the tile that was set. They can be nil
if neither is true. */
func setTileAtCoord(x: Int, _ y: Int, tile: SKTilemapTile?) -> (tileSet: SKTilemapTile?, tileRemoved: SKTilemapTile?) {
if !isValidCoord(x: x, y: y) {
return (nil, nil)
}
var tileRemoved: SKTilemapTile?
if let tile = tileAtCoord(x: x, y) {
tile.removeFromParent()
tileRemoved = tile
}
tiles[y][x] = tile
if let setTile = tile {
addChild(setTile)
setTile.position = tilePositionAtCoord(x: x, y, offset: setTile.tileData.tileset.tileOffset)
setTile.anchorPoint = tilemap.orientation.tileAnchorPoint()
}
return (tile, tileRemoved)
}
func setTileAtCoord(coord: CGPoint, tile: SKTilemapTile?) -> (tileSet: SKTilemapTile?, tileRemoved: SKTilemapTile?) {
return setTileAtCoord(x: Int(coord.x), Int(coord.y), tile: tile)
}
/** Set a specific position on the map to represent the given tile by ID.
Will return a tuple containing the tile that was removed and the tile that was set. They can be nil
if neither is true. */
func setTileAtCoord(x: Int, _ y: Int, id: Int) -> (tileSet: SKTilemapTile?, tileRemoved: SKTilemapTile?) {
if let tileData = tilemap.getTileData(id: id) {
return setTileAtCoord(x: x, y, tile: SKTilemapTile(tileData: tileData, layer: self))
}
return (nil, nil)
}
func setTileAtCoord(coord: CGPoint, id: Int) -> (tileSet: SKTilemapTile?, tileRemoved: SKTilemapTile?) {
return setTileAtCoord(x: Int(coord.x), Int(coord.y), id: id)
}
// MARK: Tile Coordinates & Positioning
/** Returns the position a tile should be within the layer if they have a certain map position. */
func tilePositionAtCoord(x: Int, _ y: Int, offset: CGPoint = CGPoint.zero) -> CGPoint {
let tileAnchorPoint = tilemap.orientation.tileAnchorPoint()
var position = CGPoint.zero
switch tilemap.orientation {
case .Orthogonal:
position = CGPoint(x: x * Int(tileSize.width) + Int(tileAnchorPoint.x * tileSize.width),
y: y * Int(-tileSize.height) - Int(tileSize.height - tileAnchorPoint.y * tileSize.height))
case .Isometric:
position = CGPoint(x: (x - y) * Int(tileSizeHalved.width) - Int(tileSizeHalved.width - tileAnchorPoint.x * tileSize.width),
y: (x + y) * Int(-tileSizeHalved.height) - Int(tileSize.height - tileAnchorPoint.y * tileSize.height))
}
/* Re-position tile based on the tileset offset. */
position.x = position.x + (offset.x - tileAnchorPoint.x * offset.x)
position.y = position.y - (offset.y - tileAnchorPoint.y * offset.y)
return position
}
/** Returns the coordinate from a specific position within the layer.
If the position gets converted to a coordinate that is not valid nil is returned. Otherwise the tile coordinate
is returned.
A custom offset point can be passed to this function which is useful if the tileset being used has an offset.
Passing the round parameter as true will return a whole number coordinate (the default), or a decimal number
which can be used to determine where exactly within the tile the layer position is. */
func coordAtPosition(positionInLayer: CGPoint, offset: CGPoint = CGPoint.zero, round: Bool = true, mustBeValid: Bool = true) -> CGPoint? {
var coord = CGPoint.zero
let tileAnchorPoint = tilemap.orientation.tileAnchorPoint()
let position = CGPoint(x: positionInLayer.x - (self.offset.x * tileAnchorPoint.x) + (offset.x - tileAnchorPoint.x * offset.x),
y: positionInLayer.y + (self.offset.y * tileAnchorPoint.y) - (offset.y - tileAnchorPoint.y * offset.y))
switch tilemap.orientation {
case .Orthogonal:
coord = CGPoint(x: position.x / tileSize.width,
y: position.y / -tileSize.height)
case .Isometric:
coord = CGPoint(x: ((position.x / tileSizeHalved.width) + (position.y / -tileSizeHalved.height)) / 2,
y: ((position.y / -tileSizeHalved.height) - (position.x / tileSizeHalved.width)) / 2)
}
if mustBeValid && !isValidCoord(x: Int(floor(coord.x)), y: Int(floor(coord.y))) {
return nil
}
if round {
return CGPoint(x: Int(floor(coord.x)), y: Int(floor(coord.y)))
}
return coord
}
#if os(iOS)
/** Returns the coordinate of a tile using a touch position.
If the position gets converted to a coordinate that is not valid nil is returned. Otherwise the tile
coordinate is returned.
A custom offset point can be passed to this function which is useful if the tileset being used has an offset.
Passing the round parameter as true will return a whole number coordinate (the default), or a decimal number
which can be used to determine where exactly within the tile the layer position is. */
func coordAtTouchPosition(touch: UITouch, offset: CGPoint = CGPoint.zero, round: Bool = true) -> CGPoint? {
return coordAtPosition(positionInLayer: touch.location(in: self), offset: offset, round: round)
}
#endif
#if os(OSX)
/** Returns the coordinate of a tile using a mouse position.
If the position gets converted to a coordinate that is not valid nil is returned. Otherwise the tile
coordinate is returned.
A custom offset point can be passed to this function which is useful if the tileset being used has an offset.
Passing the round parameter as true will return a whole number coordinate (the default), or a decimal number
which can be used to determine where exactly within the tile the layer position is. */
func coordAtMousePosition(event: NSEvent, offset: CGPoint = CGPointZero, round: Bool = true) -> CGPoint? {
return coordAtPosition(event.locationInNode(self), offset: offset, round: round)
}
#endif
/** Returns the coord of a tile at a given screen (view) position. */
func coordAtScreenPosition(position: CGPoint, offset: CGPoint = CGPoint.zero, round: Bool = true, mustBeValid: Bool = true) -> CGPoint? {
guard let scene = self.scene, let view = scene.view else {
print("SKTilemapLayer: Error, Not connected to scene/view.")
return nil
}
let scenePosition = view.convert(position, to: scene)
let layerPosition = convert(scenePosition, from: scene)
return coordAtPosition(positionInLayer: layerPosition, offset: offset, round: round, mustBeValid: mustBeValid)
}
/** Will hide tiles outside of the set bounds rectangle. If no bounds is set the view bounds is used.
Increase the tileBufferSize to draw more tiles outside of the bounds. This can stop tiles that are part
way in/out of the bounds to get fully displayed. Not giving a tileBufferSize will default it to 2.
Scale is used for when you're expecting the layer to be scaled to anything other than 1.0. If you use a camera
with a zoom for example, you would want to pass the zoom level (or scale of the camera) in here. */
func clipTilesOutOfBounds(bounds: CGRect? = nil, scale: CGFloat = 1.0, tileBufferSize: CGFloat = 2) {
/* The bounds passed in should assume an origin in the bottom left corner. If no bounds are passed in the size
of the view is used. */
var viewBounds: CGRect
if bounds == nil {
if scene != nil && scene?.view != nil {
viewBounds = scene!.view!.bounds
} else {
print("SKTilemapLayer: Failed to clip tiles out of bounds. There is no view. Has the tilemap been added to the scene?")
return
}
} else {
viewBounds = bounds!
}
let fromX = Int(viewBounds.origin.x - (tileSize.width * tileBufferSize))
let fromY = Int(viewBounds.origin.y - (tileSize.height * tileBufferSize))
if let tile = tileAtScreenPosition(position: CGPoint(x: fromX, y: fromY)) where !previouslyShownTiles.isEmpty {
if tile == previouslyShownTiles[0] { return }
}
let toX = Int(viewBounds.origin.x + viewBounds.width + (tileSize.width * tileBufferSize))
let toY = Int(viewBounds.origin.y + viewBounds.height + (tileSize.height * tileBufferSize))
let yStep = Int(tileSizeHalved.height * scale)
let xStep = Int(tileSizeHalved.width * scale)
previouslyShownTiles.forEach( { $0.isHidden = true } )
previouslyShownTiles = []
for y in stride(from: fromY, to: toY, by: yStep) {
for x in stride(from: fromX, to: toX, by: xStep) {
if let tile = tileAtScreenPosition(position: CGPoint(x: x, y: y)) {
tile.isHidden = false
previouslyShownTiles.append(tile)
}
}
}
}
}
| 41.7951 | 142 | 0.604391 |
0ee5e7a8fc5b346c3bed771f5536cde4845c23c7 | 2,522 | //
// User.swift
// FromScratch
//
// Created by Yu Pengyang on 11/2/15.
// Copyright © 2015 Yu Pengyang. All rights reserved.
//
import Foundation
import SwiftyJSON
class User: NSObject {
let id: String?
let userName: String?
let faceURL: String?
let faceWidth: Int?
let faceHeight: Int?
let gender: String?
let astro: String?
let life: Int?
let qq: String?
let msn: String?
let homePage: String?
let level: String?
let isOnline: Bool?
let postCount: Int?
let lastLoginTime: NSDate?
let lastLoginIP: String?
let isHide: Bool?
let isRegister: Bool?
let firstLoginTime: NSDate?
let loginCount: Int?
let isAdmin: Bool?
let stayCount: Int?
init(data: JSON) {
id = data[_keys.id].string
userName = data[_keys.userName].string
faceURL = data[_keys.faceURL].string
faceWidth = data[_keys.faceWidth].int
faceHeight = data[_keys.faceHeight].int
gender = data[_keys.gender].string
astro = data[_keys.astro].string
life = data[_keys.life].int
qq = data[_keys.qq].string
msn = data[_keys.msn].string
homePage = data[_keys.homePage].string
level = data[_keys.level].string
isOnline = data[_keys.isOnline].bool
postCount = data[_keys.postCount].int
lastLoginTime = Utils.dateFromUnixTimestamp(data[_keys.lastLoginTime].int)
lastLoginIP = data[_keys.lastLoginIP].string
isHide = data[_keys.isHide].bool
isRegister = data[_keys.isRegister].bool
firstLoginTime = Utils.dateFromUnixTimestamp(data[_keys.firstLoginTime].int)
loginCount = data[_keys.loginCount].int
isAdmin = data[_keys.isAdmin].bool
stayCount = data[_keys.stayCount].int
}
struct _keys {
static let id = "id", userName = "user_name", faceURL = "face_url", faceWidth = "face_width", faceHeight = "face_height", gender = "gender", astro = "astro", life = "life", qq = "qq", msn = "msn", homePage = "home_page", level = "level", isOnline = "is_online", postCount = "post_count", lastLoginTime = "last_login_time", lastLoginIP = "last_login_ip", isHide = "is_hide", isRegister = "is_register", firstLoginTime = "first_login_time", loginCount = "login_count", isAdmin = "is_admin", stayCount = "stay_count"
}
} | 39.40625 | 521 | 0.609437 |
aba6aad6bdc7434c8f0eb4cab6112f58ca8d23df | 429 | // Q2-1. 方程式を解く
// https://algo-method.com/tasks/368
// MARK: Functions
private func readInt() -> Int {
Int(readLine()!)!
}
// MARK: Main
let N = readInt()
precondition(3 <= N && N <= 100_000)
var answer: Double = 0.0
for i in 0... {
let x: Double = Double(i) * 0.001
if x * (x * (x + 1) + 2) + 3 >= Double(N) {
precondition(0.0 <= x && x <= 100.0)
answer = x
break
}
}
print(answer)
| 17.16 | 47 | 0.522145 |
18fcb197582baa637b5656bfd887b352322eb71e | 267 | //
// BJFunc.swift
// TestSwift
//
// Created by 许宝吉 on 2018/2/13.
// Copyright © 2018年 许宝吉. All rights reserved.
//
import Foundation
func synchronized(lock: AnyObject, closure: () -> ()) {
objc_sync_enter(lock)
closure()
objc_sync_exit(lock)
}
| 14.052632 | 55 | 0.640449 |
0e5215ebfe4e7f94dc69d2a2a10b404461f4e173 | 2,691 | //
// StickyFooterBehavior.swift
// BrickKit
//
// Created by Ruben Cagnie on 6/2/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
/// A StickyFooterLayoutBehavior will stick certain bricks (based on the dataSource) on the bottom of its section
open class StickyFooterLayoutBehavior: StickyLayoutBehavior {
open override var needsDownstreamCalculation: Bool {
return true
}
open override func shouldUseForDownstreamCalculation(for indexPath: IndexPath, with identifier: String, for collectionViewLayout: UICollectionViewLayout) -> Bool {
if dataSource?.stickyLayoutBehavior(self, shouldStickItemAtIndexPath: indexPath, withIdentifier: identifier, inCollectionViewLayout: collectionViewLayout) == true {
return true
} else {
return super.shouldUseForDownstreamCalculation(for: indexPath, with: identifier, for: collectionViewLayout)
}
}
override func updateStickyAttributesInCollectionView(_ collectionViewLayout: UICollectionViewLayout, attributesDidUpdate: (_ attributes: BrickLayoutAttributes, _ oldFrame: CGRect?) -> Void) {
//Sort the attributes ascending
stickyAttributes.sort { (attributesOne, attributesTwo) -> Bool in
let maxYOne: CGFloat = attributesOne.originalFrame.maxY
let maxYTwo: CGFloat = attributesTwo.originalFrame.maxY
return maxYOne >= maxYTwo
}
super.updateStickyAttributesInCollectionView(collectionViewLayout, attributesDidUpdate: attributesDidUpdate)
}
override func updateFrameForAttribute(_ attributes:inout BrickLayoutAttributes, sectionAttributes: BrickLayoutAttributes?, lastStickyFrame: CGRect, contentBounds: CGRect, collectionViewLayout: UICollectionViewLayout) -> Bool {
let isOnFirstSection = sectionAttributes == nil || sectionAttributes?.indexPath == IndexPath(row: 0, section: 0)
let bottomInset = collectionViewLayout.collectionView!.contentInset.bottom
if isOnFirstSection {
collectionViewLayout.collectionView?.scrollIndicatorInsets.bottom = attributes.originalFrame.height + bottomInset
attributes.frame.origin.y = contentBounds.maxY - attributes.originalFrame.size.height - bottomInset
} else {
let y = contentBounds.maxY - attributes.originalFrame.size.height - bottomInset
attributes.frame.origin.y = min(y, attributes.originalFrame.origin.y)
}
if lastStickyFrame.size != CGSize.zero {
attributes.frame.origin.y = min(lastStickyFrame.minY - attributes.originalFrame.height, attributes.originalFrame.origin.y)
}
return !isOnFirstSection
}
}
| 48.927273 | 230 | 0.733928 |
50bbcb36d244b0a1a37005cce398209a3ebfb43f | 2,699 | //
// Copyright (c) 2018 KxCoding <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class SelfSizingCellViewController: UIViewController {
lazy var list: [String] = {
let lipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"
return lipsum.split(separator: " ").map { String($0) }
}()
@IBOutlet weak var listCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
if let layout = listCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
}
}
}
extension SelfSizingCellViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return list.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
if let label = cell.contentView.viewWithTag(100) as? UILabel {
label.text = list[indexPath.item]
}
return cell
}
}
| 38.557143 | 465 | 0.741756 |
33a526828048c00e245f67f3f7dc4c5ec6a0ad67 | 2,587 | //
// TransactionInfoVC.swift
// MyBankManagementApp
//
// Created by Rigoberto Sáenz Imbacuán on 1/31/16.
// Copyright © 2016 Rigoberto Saenz Imbacuan. All rights reserved.
//
import UIKit
import Foundation
class TransactionInfoVC: UIViewController {
@IBOutlet weak var toggleType: UISegmentedControl!
@IBOutlet weak var textfieldAmount: UITextField!
@IBAction func onClickSave(sender: UIBarButtonItem) {
// Transaction creation
var selectedType = TransactionType.Debit
if toggleType.selectedSegmentIndex == 0 { // Debit
selectedType = TransactionType.Debit
} else if toggleType.selectedSegmentIndex == 1 { // Credit
selectedType = TransactionType.Credit
}
// Input validation
if textfieldAmount.text == "" {
View.showAlert(self, messageToShow: "Amount can not be empty")
return
}
// Test if amount textfield contains a number
if let number = Int64(textfieldAmount.text!) {
if number <= 0 {
View.showAlert(self, messageToShow: "Amount can not be negative or zero")
return
}
// Transaction amount validation
if selectedType == TransactionType.Credit {
// Check if have any cash
if Bank.instance.getSelectedAccount().balance > 0 {
// Check if have enough cash to do this transaction
if number > Bank.instance.getSelectedAccount().balance {
View.showAlert(self, messageToShow: "Balance is not enough to do this transaction\nBalance: \(Bank.instance.getSelectedAccount().balance)")
return
}
}else{
View.showAlert(self, messageToShow: "Balance is not enough to do this transaction\nBalance: \(Bank.instance.getSelectedAccount().balance)")
return
}
}
}else {
View.showAlert(self, messageToShow: "Amount can not have letters and spaces")
return
}
// Transaction creation
let newTransaction = Transaction(newType: selectedType, newDate: NSDate(), newAmount: Int64(textfieldAmount.text!)!)
Bank.instance.addTransactionToAccount(newTransaction)
// Pop current screen
self.navigationController?.popViewControllerAnimated(true)
}
} | 36.43662 | 163 | 0.582141 |
14c17dae62ba3611b16422c1ecddff5bfe774f11 | 1,682 | // Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
// A copy of the License is located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file 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.
//
// StepFunctionsConfiguration.swift
// SmokeAWSGenerate
//
import Foundation
import ServiceModelEntities
internal struct StepFunctionsConfiguration {
static let modelOverride = ModelOverride(
enumerations: EnumerationNaming(usingUpperCamelCase:
["DecisionType", "EventType", "HistoryEventType"]),
fieldRawTypeOverride:
[Fields.timestamp.typeDescription: CommonConfiguration.integerDateOverride])
static let httpClientConfiguration = HttpClientConfiguration(
retryOnUnknownError: true,
knownErrorsDefaultRetryBehavior: .fail,
unretriableUnknownErrors: [],
retriableUnknownErrors: ["ActivityLimitExceeded", "ActivityWorkerLimitExceeded",
"ExecutionLimitExceeded", "StateMachineLimitExceeded"])
static let serviceModelDetails = ServiceModelDetails(
serviceName: "states", serviceVersion: "2016-11-23",
baseName: "StepFunctions", modelOverride: modelOverride,
httpClientConfiguration: httpClientConfiguration,
signAllHeaders: false)
}
| 41.02439 | 88 | 0.727111 |
e56aa32b631d5fcc5926342d01ed33c1e62aee13 | 3,002 | // 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 Foundation
import OAuth2
let CREDENTIALS = "google.json"
let TOKEN = "google.json"
fileprivate enum CommandLineOption {
case login
case me
case people
case data
case translate(text: String)
init?(arguments: [String]) {
if arguments.count > 1 {
let command = arguments[1]
switch command {
case "login": self = .login
case "me": self = .me
case "people": self = .people
case "data": self = .data
case "translate":
if arguments.count < 2 { return nil }
self = .translate(text: arguments[2])
default: return nil
}
} else {
return nil
}
}
func stringValue() -> String {
switch self {
case .login: return "login"
case .me: return "me"
case .people: return "people"
case .data: return "data"
case .translate(_): return "translate"
}
}
static func all() -> [String] {
return [CommandLineOption.login,
CommandLineOption.me,
CommandLineOption.people,
CommandLineOption.data,
CommandLineOption.translate(text: "")].map({$0.stringValue()})
}
}
func main() throws {
let arguments = CommandLine.arguments
guard let option = CommandLineOption(arguments: arguments) else {
print("Usage: \(arguments[0]) [options]")
print("Options list: \(CommandLineOption.all())")
return
}
let scopes = ["profile",
"https://www.googleapis.com/auth/contacts.readonly",
"https://www.googleapis.com/auth/cloud-platform"]
guard let browserTokenProvider = BrowserTokenProvider(credentials:CREDENTIALS, token:TOKEN) else {
print("Unable to create token provider.")
return
}
let google = try GoogleSession(tokenProvider:browserTokenProvider)
switch option {
case .login:
try browserTokenProvider.signIn(scopes:scopes)
try browserTokenProvider.saveToken(TOKEN)
case .me:
try google.getMe()
case .people:
try google.getPeople()
case .data:
try google.getData()
case .translate(let text):
try google.translate(text)
}
}
do {
try main()
} catch (let error) {
print("ERROR: \(error)")
}
| 29.145631 | 102 | 0.607928 |
0a0c9db3879b22eea3170a4c37d76725dbd7d0b6 | 5,928 | //
// AppearanceRuleTests.swift
// GaudiTests
//
// Created by Giuseppe Lanza on 10/12/2019.
// Copyright © 2019 Giuseppe Lanza. All rights reserved.
//
@testable import Gaudi
import XCTest
import UIKit
class AppearanceRuleTests: XCTestCase {
func test__a_property_rule__can_apply_appearance() {
let rule = PropertyAppearanceRule(keypath: \UINavigationBar.barTintColor, value: .black)
rule.apply()
XCTAssertEqual(UINavigationBar.appearance().barTintColor, .black)
}
func test__a_property_rule__created_with_subscript__can_apply_appearance() {
let rule = UINavigationBar[\.barTintColor, .black]
rule.apply()
XCTAssertEqual(UINavigationBar.appearance().barTintColor, .black)
}
func test__a_property_rule__can_revert_appearance() {
let originalValue = UINavigationBar.appearance().barTintColor
let rule = PropertyAppearanceRule(keypath: \UINavigationBar.barTintColor, value: .black)
rule.apply()
rule.revert()
XCTAssertEqual(UINavigationBar.appearance().barTintColor, originalValue)
}
func test__a_property_rule__created_with_subscript__can_revert_appearance() {
let originalValue = UINavigationBar.appearance().barTintColor
let rule = UINavigationBar[\.barTintColor, .black]
rule.apply()
rule.revert()
XCTAssertEqual(UINavigationBar.appearance().barTintColor, originalValue)
}
func test__a_selector_rule__can_apply_appearance() {
let rule = SelectorAppearanceRule<UIButton, UIColor?>(
get: { $0.titleColor(for: .selected) },
set: { $0.setTitleColor($1, for: .selected) },
value: .white
)
rule.apply()
XCTAssertEqual(UIButton.appearance().titleColor(for: .selected), .white)
}
func test__a_selector_rule__created_with_subscript__can_apply_appearance() {
let rule = UIButton[
get: { $0.titleColor(for: .selected) },
set: { $0.setTitleColor($1, for: .selected) },
value: .white
]
rule.apply()
XCTAssertEqual(UIButton.appearance().titleColor(for: .selected), .white)
}
func test__a_selector_rule__can_revert_appearance() {
let originalValue = UIButton.appearance().titleColor(for: .selected)
let rule = SelectorAppearanceRule<UIButton, UIColor?>(
get: { $0.titleColor(for: .selected) },
set: { $0.setTitleColor($1, for: .selected) },
value: .white
)
rule.apply()
rule.revert()
XCTAssertEqual(UIButton.appearance().titleColor(for: .selected), originalValue)
}
func test__a_selector_rule__created_with_subscript__can_revert_appearance() {
let originalValue = UIButton.appearance().titleColor(for: .selected)
let rule = UIButton[
get: { $0.titleColor(for: .selected) },
set: { $0.setTitleColor($1, for: .selected) },
value: .white
]
rule.apply()
rule.revert()
XCTAssertEqual(UIButton.appearance().titleColor(for: .selected), originalValue)
}
func test__a_rule_set__can_apply_appearances() {
let ruleSet = AppearanceRuleSet(rules: [
PropertyAppearanceRule(keypath: \UINavigationBar.barTintColor, value: .black),
SelectorAppearanceRule<UIButton, UIColor?>(
get: { $0.titleColor(for: .selected) },
set: { $0.setTitleColor($1, for: .selected) },
value: .white
)
])
ruleSet.apply()
XCTAssertEqual(UIButton.appearance().titleColor(for: .selected), .white)
XCTAssertEqual(UINavigationBar.appearance().barTintColor, .black)
}
func test__a_rule_set__created_with_dsl__can_apply_appearances() {
let ruleSet = AppearanceRuleSet {
UINavigationBar[\.barTintColor, .black]
UIButton[
get: { $0.titleColor(for: .selected) },
set: { $0.setTitleColor($1, for: .selected) },
value: .white
]
}
ruleSet.apply()
XCTAssertEqual(UIButton.appearance().titleColor(for: .selected), .white)
XCTAssertEqual(UINavigationBar.appearance().barTintColor, .black)
}
func test__a_rule_set__can_revert_appearances() {
let originalNavBarValue = UINavigationBar.appearance().barTintColor
let originalButtonValue = UIButton.appearance().titleColor(for: .selected)
let ruleSet = AppearanceRuleSet(rules: [
PropertyAppearanceRule(keypath: \UINavigationBar.barTintColor, value: .black),
SelectorAppearanceRule<UIButton, UIColor?>(
get: { $0.titleColor(for: .selected) },
set: { $0.setTitleColor($1, for: .selected) },
value: .white
)
])
ruleSet.apply()
ruleSet.revert()
XCTAssertEqual(UINavigationBar.appearance().barTintColor, originalNavBarValue)
XCTAssertEqual(UIButton.appearance().titleColor(for: .selected), originalButtonValue)
}
func test__a_rule_set__created_with_dsl__can_revert_appearances() {
let originalNavBarValue = UINavigationBar.appearance().barTintColor
let originalButtonValue = UIButton.appearance().titleColor(for: .selected)
let ruleSet = AppearanceRuleSet {
UINavigationBar[\.barTintColor, .black]
UIButton[
get: { $0.titleColor(for: .selected) },
set: { $0.setTitleColor($1, for: .selected) },
value: .white
]
}
ruleSet.apply()
ruleSet.revert()
XCTAssertEqual(UINavigationBar.appearance().barTintColor, originalNavBarValue)
XCTAssertEqual(UIButton.appearance().titleColor(for: .selected), originalButtonValue)
}
}
| 39 | 96 | 0.636134 |
1e0dc0d14722030d0b0908a61c414992d29d8523 | 1,486 | //
// ConstraintGroup.swift
// Cartography
//
// Created by Robert Böhnke on 22/01/15.
// Copyright (c) 2015 Robert Böhnke. All rights reserved.
//
import Foundation
public class ConstraintGroup {
private var constraints: [Constraint] = []
@availability(OSX, introduced=10.10)
@availability(iOS, introduced=8.0)
public var active: Bool {
get {
return constraints.map({ $0.layoutConstraint.active }).reduce(true) { $0 && $1 }
}
set {
for constraint in constraints {
constraint.layoutConstraint.active = newValue
}
for constraint in constraints {
constraint.view?.car_updateLayout()
}
}
}
public init() {
}
internal func replaceConstraints(constraints: [Constraint], performLayout: Bool) {
for constraint in self.constraints {
constraint.uninstall()
if performLayout {
constraint.view?.car_updateLayout()
}
}
if performLayout {
for view in self.constraints.map({ $0.view }) {
view?.car_updateLayout()
}
}
self.constraints = constraints
for constraint in self.constraints {
constraint.install()
}
if performLayout {
for view in self.constraints.map({ $0.view }) {
view?.car_updateLayout()
}
}
}
}
| 23.587302 | 92 | 0.547106 |
7587adc8f22f6abc72a01f3ab625c994430f0c73 | 2,178 | //
// MdST+Extensions.swift
// TransitPal
//
// Created by Robert Trencheny on 6/6/19.
// Copyright © 2019 Robert Trencheny. All rights reserved.
//
import Foundation
import MapKit
extension Station {
init(nameOnly: String) {
self.name.english = nameOnly
self.name.englishShort = nameOnly
self.name.local = nameOnly
self.name.localShort = nameOnly
}
var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: CLLocationDegrees(self.latitude), longitude: CLLocationDegrees(self.longitude))
}
var annotation: MKAnnotation {
let pin = MKPointAnnotation()
pin.coordinate = self.coordinate
pin.title = self.name.english
return pin
}
func bestName(_ short: Bool) -> String {
let englishFull = self.name.english
let englishShort = self.name.englishShort
var english: String?
let hasEnglishFull = !englishFull.isEmpty
let hasEnglishShort = !englishShort.isEmpty
if (hasEnglishFull && !hasEnglishShort) {
english = englishFull
} else if (!hasEnglishFull && hasEnglishShort) {
english = englishShort
} else if short {
english = englishShort
} else {
english = englishFull
}
let localFull = name.local
let localShort = name.localShort
let local: String?
let hasLocalFull = !localFull.isEmpty
let hasLocalShort = !localShort.isEmpty
if (hasLocalFull && !hasLocalShort) {
local = localFull
} else if (!hasLocalFull && hasLocalShort) {
local = localShort
} else if short {
local = localShort
} else {
local = localFull
}
if let english = english, !english.isEmpty, let currentCode = Locale.current.languageCode, currentCode.hasPrefix("en") {
return english
}
if let local = local, !local.isEmpty {
// Local preferred, or English not available
return local
}
// Local unavailable, use English
return english!
}
}
| 28.657895 | 128 | 0.60652 |
289dabba12f7d7bd92aecf1a1c3c3b5c3f0b7d5d | 1,274 | //
// GameScreenPresenter.swift
// ReversiInterfaceAdapter
//
// Created by yoshimasa36g on 2020/05/22.
// Copyright © 2020 yoshimasa36g. All rights reserved.
//
import ReversiUseCase
/// GameUseCaseの出力結果を表示用に加工する
public final class GameScreenPresenter {
private weak var screen: GameScreenPresentable?
public init(screen: GameScreenPresentable) {
self.screen = screen
}
}
// MARK: - GameUseCaseOutput
extension GameScreenPresenter: GameUseCaseOutput {
public func gettableCoordinates(color: Int, coordinates: [(x: Int, y: Int)]) {
screen?.changeDiscs(to: color, at: coordinates)
}
public func gameReloaded(state: OutputGameState) {
screen?.redrawEntireGame(state: PresentableGameState.from(state))
}
public func messageChanged(color: Int?, label: String) {
screen?.redrawMessage(color: color, label: label)
}
public func discCountChanged(dark: Int, light: Int) {
screen?.redrawDiscCount(dark: dark, light: light)
}
public func passed() {
screen?.showPassedMessage()
}
public func thinkingStarted(color: Int) {
screen?.showIndicator(for: color)
}
public func thinkingStopped(color: Int) {
screen?.hideIndicator(for: color)
}
}
| 24.980392 | 82 | 0.684458 |
69c42e9fb0a5470fef950026a87b0a5ebc61c0e1 | 6,333 | //
// WCLLaunchView.swift
// WCLLaunchView
//
// **************************************************
// * _____ *
// * __ _ __ ___ \ / *
// * \ \/ \/ / / __\ / / *
// * \ _ / | (__ / / *
// * \/ \/ \___/ / /__ *
// * /_____/ *
// * *
// **************************************************
// Github :https://github.com/631106979
// HomePage:https://imwcl.com
// CSDN :http://blog.csdn.net/wang631106979
//
// Created by 王崇磊 on 16/9/14.
// Copyright © 2016年 王崇磊. All rights reserved.
//
// @class WCLLaunchView
// @abstract 缓慢展开的启动图
// @discussion 缓慢展开的启动图
//
import UIKit
internal class WCLLaunchView: UIView, CAAnimationDelegate {
fileprivate var topLayer: CALayer = CALayer()
fileprivate var bottomLayer: CALayer = CALayer()
fileprivate var launchImage: UIImage?
//MARK: Public Methods
/**
展开的动画
*/
func starAnimation() {
//创建一个CABasicAnimation作用于CALayer的anchorPoint
let topAnimation = CABasicAnimation.init(keyPath: "anchorPoint")
//设置移动路径
topAnimation.toValue = NSValue.init(cgPoint: CGPoint(x: 1, y: 1))
//动画时间
topAnimation.duration = 0.6
//设置代理,方便完成动画后移除当前view
topAnimation.delegate = self
//设置动画速度为匀速
topAnimation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear)
//设置动画结束后不移除点,保持移动后的位置
topAnimation.isRemovedOnCompletion = false
topAnimation.fillMode = kCAFillModeForwards
topLayer.add(topAnimation, forKey: "topAnimation")
//创建一个CABasicAnimation作用于CALayer的anchorPoint
let bottomAnimation = CABasicAnimation.init(keyPath: "anchorPoint")
//设置移动路径
bottomAnimation.toValue = NSValue.init(cgPoint: CGPoint(x: 0, y: 0))
//动画时间
bottomAnimation.duration = 0.6
//设置动画速度为匀速
bottomAnimation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear)
//设置动画结束后不移除点,保持移动后的位置
bottomAnimation.isRemovedOnCompletion = false
bottomAnimation.fillMode = kCAFillModeForwards
bottomLayer.add(bottomAnimation, forKey: "topAnimation")
}
//MARK: Initial Methods
init(frame: CGRect, launchImage: UIImage?) {
super.init(frame: frame)
self.launchImage = launchImage
configTopShapeLayer()
configBottomShapeLayer()
}
override init(frame: CGRect) {
super.init(frame: frame)
if WCLImagePickerOptions.launchImage == nil {
launchImage = getDefaultLaunchImage()
}else {
launchImage = WCLImagePickerOptions.launchImage
}
configTopShapeLayer()
configBottomShapeLayer()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: Private Methods
/**
绘制上半部分的layer
*/
private func configTopShapeLayer() {
//绘制贝斯尔曲线
let topBezier:UIBezierPath = UIBezierPath()
topBezier.move(to: CGPoint(x: -1, y: -1))
topBezier.addLine(to: CGPoint(x: bounds.width+1, y: -1))
topBezier.addCurve(to: CGPoint(x: bounds.width/2.0+1, y: bounds.height/2.0+1), controlPoint1: CGPoint(x: bounds.width+1, y: 0+1), controlPoint2: CGPoint(x: 343.5+1, y: 242.5+1))
topBezier.addCurve(to: CGPoint(x: -1, y: bounds.height+2), controlPoint1: CGPoint(x: 31.5+2, y: 424.5+2), controlPoint2: CGPoint(x: 0+2, y: bounds.height+2))
topBezier.addLine(to: CGPoint(x: -1, y: -1))
topBezier.close()
//创建一个CAShapeLayer,将绘制的贝斯尔曲线的path给CAShapeLayer
let topShape = CAShapeLayer()
topShape.path = topBezier.cgPath
//给topLayer设置contents为启动图
topLayer.contents = launchImage?.cgImage
topLayer.frame = bounds
layer.addSublayer(topLayer)
//将绘制后的CAShapeLayer做为topLayer的mask
topLayer.mask = topShape
}
/**
绘制下半部分的layer
*/
private func configBottomShapeLayer() {
let width = bounds.width
let height = bounds.height
//绘制贝斯尔曲线
let bottomBezier:UIBezierPath = UIBezierPath()
bottomBezier.move(to: CGPoint(x: width, y: 0))
bottomBezier.addCurve(to: CGPoint(x: width/2.0, y: height/2.0), controlPoint1: CGPoint(x: width, y: 0), controlPoint2: CGPoint(x: width * 0.915, y: height * 0.364))
bottomBezier.addCurve(to: CGPoint(x: 0, y: bounds.height), controlPoint1: CGPoint(x: width * 0.084 , y: height * 0.636), controlPoint2: CGPoint(x: 0, y: bounds.height))
bottomBezier.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
bottomBezier.addLine(to: CGPoint(x: bounds.width, y: 0))
bottomBezier.close()
//创建一个CAShapeLayer,将绘制的贝斯尔曲线的path给CAShapeLayer
let bottomShape = CAShapeLayer()
bottomShape.path = bottomBezier.cgPath
//给bottomLayer设置contents为启动图
bottomLayer.contents = launchImage?.cgImage
bottomLayer.frame = bounds
layer.addSublayer(bottomLayer)
//将绘制后的CAShapeLayer做为bottomLayer的mask
bottomLayer.mask = bottomShape
}
private func getDefaultLaunchImage() -> UIImage? {
let screen = UIScreen.main
UIGraphicsBeginImageContextWithOptions(screen.bounds.size, true, screen.scale)
if let color = WCLImagePickerOptions.launchColor {
color.setFill()
}else {
WCLImagePickerOptions.tintColor.setFill()
}
UIRectFill(screen.bounds)
if let maskImage = WCLImagePickerBundle.imageFromBundle("image_photoAlbum") {
maskImage.draw(at: CGPoint(x: screen.bounds.size.width/2 - maskImage.size.width/2, y: screen.bounds.size.height/2 - maskImage.size.height/2))
}
let originImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return originImage
}
//MRAK: animationDelegate
/**
动画完成后移除当前view
*/
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if flag {
removeFromSuperview()
}
}
}
| 38.150602 | 185 | 0.606664 |
291933ac3fb90bb0b91da1a4879bb77d6796beef | 1,758 | //
// UIImageView+loadImage.swift
// HitchHiker
//
// Created by Mahmoud Eldesouky on 11/17/16.
// Copyright © 2016 Ahmed Mohamed Magdi. All rights reserved.
//
import UIKit
import Kingfisher
public extension UIImageView {
/// takes an url and provied an animated loading progress while
/// fetching the image from API
///
/// - Parameters:
/// - url: url to be fetched
public func loadImage(url:URL?, mode:UIViewContentMode = .scaleAspectFit, completion: ((_ image: UIImage?, _ error: Error?) -> ())? = nil) {
guard let `url` = url else {
return
}
let activity = UIActivityIndicatorView()
self.addSubview(activity)
activity.startAnimating()
activity.translatesAutoresizingMaskIntoConstraints = false
var constraints = [NSLayoutConstraint]()
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[activity]-|", options: [], metrics: nil, views: ["activity":activity])
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-[activity]-|", options: [], metrics: nil, views: ["activity":activity])
self.contentMode = mode
NSLayoutConstraint.activate(constraints)
self.kf.setImage(with: url, placeholder: self.image, options: [.transition(.fade(0.2))], progressBlock: { (progress, done) in
}, completionHandler: { (image, error, cacheType, url) in
if error == nil {
self.image = image
completion?(image, error)
}
DispatchQueue.main.async {
activity.stopAnimating()
activity.removeFromSuperview()
self.layoutIfNeeded()
}
})
}
}
| 37.404255 | 148 | 0.613766 |
dd3bc5410b1b4dcd18040cdaa1f25f507283b797 | 1,080 | //
// ViewController.swift
// Netflix_Clone
//
// Created by Kevin Topollaj on 11.3.22.
//
import UIKit
class MainTabBarViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
let vc1 = UINavigationController(rootViewController: HomeViewController())
let vc2 = UINavigationController(rootViewController: UpcomingViewController())
let vc3 = UINavigationController(rootViewController: SearchViewController())
let vc4 = UINavigationController(rootViewController: DownloadsViewController())
vc1.tabBarItem.image = UIImage(systemName: "house")
vc2.tabBarItem.image = UIImage(systemName: "play.circle")
vc3.tabBarItem.image = UIImage(systemName: "magnifyingglass")
vc4.tabBarItem.image = UIImage(systemName: "arrow.down.to.line")
vc1.title = "Home"
vc2.title = "Coming Soon"
vc3.title = "Top Search"
vc4.title = "Downloads"
tabBar.tintColor = .label
setViewControllers([vc1, vc2, vc3, vc4], animated: true)
}
}
| 27 | 83 | 0.713889 |
5b45e5b58f236038c0223a7f684b6b14b9829f9a | 9,133 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: google/protobuf/unittest_no_generic_services.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: [email protected] (Kenton Varda)
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 _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
enum ProtobufUnittest_NoGenericServicesTest_TestEnum: SwiftProtobuf.Enum {
typealias RawValue = Int
case foo // = 1
init() {
self = .foo
}
init?(rawValue: Int) {
switch rawValue {
case 1: self = .foo
default: return nil
}
}
var rawValue: Int {
switch self {
case .foo: return 1
}
}
}
#if swift(>=4.2)
extension ProtobufUnittest_NoGenericServicesTest_TestEnum: CaseIterable {
// Support synthesized by the compiler.
}
#endif // swift(>=4.2)
struct ProtobufUnittest_NoGenericServicesTest_TestMessage: SwiftProtobuf.ExtensibleMessage {
// 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 a: Int32 {
get {return _a ?? 0}
set {_a = newValue}
}
/// Returns true if `a` has been explicitly set.
var hasA: Bool {return self._a != nil}
/// Clears the value of `a`. Subsequent reads from it will return its default value.
mutating func clearA() {self._a = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
var _protobuf_extensionFieldValues = SwiftProtobuf.ExtensionFieldValueSet()
fileprivate var _a: Int32? = nil
}
#if swift(>=5.5) && canImport(_Concurrency)
extension ProtobufUnittest_NoGenericServicesTest_TestMessage: @unchecked Sendable {}
#endif // swift(>=5.5) && canImport(_Concurrency)
// MARK: - Extension support defined in unittest_no_generic_services.proto.
// MARK: - Extension Properties
// Swift Extensions on the exteneded Messages to add easy access to the declared
// extension fields. The names are based on the extension field name from the proto
// declaration. To avoid naming collisions, the names are prefixed with the name of
// the scope where the extend directive occurs.
extension ProtobufUnittest_NoGenericServicesTest_TestMessage {
var ProtobufUnittest_NoGenericServicesTest_testExtension: Int32 {
get {return getExtensionValue(ext: ProtobufUnittest_NoGenericServicesTest_Extensions_test_extension) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_NoGenericServicesTest_Extensions_test_extension, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_NoGenericServicesTest_Extensions_test_extension`
/// has been explicitly set.
var hasProtobufUnittest_NoGenericServicesTest_testExtension: Bool {
return hasExtensionValue(ext: ProtobufUnittest_NoGenericServicesTest_Extensions_test_extension)
}
/// Clears the value of extension `ProtobufUnittest_NoGenericServicesTest_Extensions_test_extension`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_NoGenericServicesTest_testExtension() {
clearExtensionValue(ext: ProtobufUnittest_NoGenericServicesTest_Extensions_test_extension)
}
}
// MARK: - File's ExtensionMap: ProtobufUnittest_NoGenericServicesTest_UnittestNoGenericServices_Extensions
/// A `SwiftProtobuf.SimpleExtensionMap` that includes all of the extensions defined by
/// this .proto file. It can be used any place an `SwiftProtobuf.ExtensionMap` is needed
/// in parsing, or it can be combined with other `SwiftProtobuf.SimpleExtensionMap`s to create
/// a larger `SwiftProtobuf.SimpleExtensionMap`.
let ProtobufUnittest_NoGenericServicesTest_UnittestNoGenericServices_Extensions: SwiftProtobuf.SimpleExtensionMap = [
ProtobufUnittest_NoGenericServicesTest_Extensions_test_extension
]
// Extension Objects - The only reason these might be needed is when manually
// constructing a `SimpleExtensionMap`, otherwise, use the above _Extension Properties_
// accessors for the extension fields on the messages directly.
let ProtobufUnittest_NoGenericServicesTest_Extensions_test_extension = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufInt32>, ProtobufUnittest_NoGenericServicesTest_TestMessage>(
_protobuf_fieldNumber: 1000,
fieldName: "protobuf_unittest.no_generic_services_test.test_extension"
)
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "protobuf_unittest.no_generic_services_test"
extension ProtobufUnittest_NoGenericServicesTest_TestEnum: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "FOO"),
]
}
extension ProtobufUnittest_NoGenericServicesTest_TestMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestMessage"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "a"),
]
public var isInitialized: Bool {
if !_protobuf_extensionFieldValues.isInitialized {return false}
return true
}
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._a) }()
case 1000..<536870912:
try { try decoder.decodeExtensionField(values: &_protobuf_extensionFieldValues, messageType: ProtobufUnittest_NoGenericServicesTest_TestMessage.self, fieldNumber: fieldNumber) }()
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._a {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)
} }()
try visitor.visitExtensionFields(fields: _protobuf_extensionFieldValues, start: 1000, end: 536870912)
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_NoGenericServicesTest_TestMessage, rhs: ProtobufUnittest_NoGenericServicesTest_TestMessage) -> Bool {
if lhs._a != rhs._a {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
if lhs._protobuf_extensionFieldValues != rhs._protobuf_extensionFieldValues {return false}
return true
}
}
| 42.877934 | 221 | 0.775868 |
db3ab5d02c0b69437bb2faf645df1a8859ebd9e1 | 1,256 | // Copyright 2021-present Xsolla (USA), Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at q
//
// 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 and permissions and
import UIKit
extension NSMutableAttributedString
{
func align(_ align: NSTextAlignment)
{
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
self.addAttribute(.paragraphStyle,
value: paragraphStyle,
range: NSRange(location: 0, length: self.length))
}
}
extension NSMutableAttributedString
{
func addAttributes(_ attributes: Attributes, toSubstring substring: String)
{
guard let range = string.range(of: substring) else { return }
addAttributes(attributes, range: NSRange(range, in: string))
}
}
| 33.052632 | 79 | 0.687898 |
3a601fa46063b76f20cec5384682c371d0663696 | 1,199 | import XCTest
import InputReader
import Year2020
class Day14Tests: XCTestCase {
let input = Input("Day14.input", Year2020.bundle).lines.compactMap(Day14.Instruction.parse2)
let day = Day14()
func test_part1() {
XCTAssertEqual(8566770985168, day.part1(input))
}
func test_part2() {
XCTAssertEqual(4832039794082, day.part2(input, applyMask: day.applyMask2))
}
func test_part2_v2() {
XCTAssertEqual(4832039794082, day.part2(input, applyMask: day.applyMask3))
}
func test_part1_example() {
let input = """
mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
mem[8] = 11
mem[7] = 101
mem[8] = 0
""".lines.compactMap(Day14.Instruction.parse2)
XCTAssertEqual(165, day.part1(input))
}
func test_part2_example() {
let day = Day14(iterationsToBuild: [2,3])
let input = """
mask = 000000000000000000000000000000X1001X
mem[42] = 100
mask = 00000000000000000000000000000000X0XX
mem[26] = 1
""".lines.compactMap(Day14.Instruction.parse2)
XCTAssertEqual(208, day.part2(input, applyMask: day.applyMask2))
}
}
| 28.547619 | 96 | 0.633862 |
ed956e84a943a2aac8acadf4d74273b7b6012377 | 1,339 | //
// Launcher.swift
// WiFiLanChat
//
// Created by Bilol Mamadjanov on 26/11/21.
//
import UIKit
var sharedLauncher: Launcher?
class Launcher {
let window: UIWindow
init(windowScene: UIWindowScene) {
window = UIWindow(windowScene: windowScene)
}
func launch() {
navigateToStartPage()
}
private func navigateToStartPage() {
let startVC = StartViewController()
let navController: BaseNavigationController = Launcher.makeNavController(rootViewController: startVC)
window.rootViewController = navController
window.makeKeyAndVisible()
}
static func makeNavController<T: UINavigationController>(rootViewController: UIViewController) -> T {
let navController = T(rootViewController: rootViewController)
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.configureWithOpaqueBackground()
navBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.black]
navBarAppearance.backgroundColor = .clear
navBarAppearance.shadowColor = nil
navController.navigationBar.tintColor = .black
navController.navigationBar.isTranslucent = true
navController.navigationBar.standardAppearance = navBarAppearance
return navController
}
}
| 30.431818 | 109 | 0.706497 |
fbd04b99e7e3f04f97aa574b7f100779c7d04442 | 1,235 | //
// RojakUITests.swift
// RojakUITests
//
// Created by Adi Nugroho on 10/11/16.
// Copyright © 2016 Rojak Team. All rights reserved.
//
import XCTest
class RojakUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
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() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.378378 | 182 | 0.659919 |
1a4392975b6b36d66fb05c0a16fdacc264dca2c3 | 7,577 | //
// StoreAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
import Combine
open class StoreAPI {
/**
Delete purchase order by ID
- parameter orderId: (path) ID of the order that needs to be deleted
- parameter apiResponseQueue: The queue on which api response is dispatched.
- returns: AnyPublisher<Void, Error>
*/
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher<Void, Error> {
return Future<Void, Error>.init { promisse in
deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in
switch result {
case .success:
promisse(.success(()))
case let .failure(error):
promisse(.failure(error))
}
}
}.eraseToAnyPublisher()
}
/**
Delete purchase order by ID
- DELETE /store/order/{order_id}
- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
- parameter orderId: (path) ID of the order that needs to be deleted
- returns: RequestBuilder<Void>
*/
open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder<Void> {
var path = "/store/order/{order_id}"
let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))"
let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let parameters: [String:Any]? = nil
let url = URLComponents(string: URLString)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false)
}
/**
Returns pet inventories by status
- parameter apiResponseQueue: The queue on which api response is dispatched.
- returns: AnyPublisher<[String:Int], Error>
*/
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher<[String:Int], Error> {
return Future<[String:Int], Error>.init { promisse in
getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in
switch result {
case let .success(response):
promisse(.success(response.body!))
case let .failure(error):
promisse(.failure(error))
}
}
}.eraseToAnyPublisher()
}
/**
Returns pet inventories by status
- GET /store/inventory
- Returns a map of status codes to quantities
- API Key:
- type: apiKey api_key
- name: api_key
- returns: RequestBuilder<[String:Int]>
*/
open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int]> {
let path = "/store/inventory"
let URLString = PetstoreClientAPI.basePath + path
let parameters: [String:Any]? = nil
let url = URLComponents(string: URLString)
let requestBuilder: RequestBuilder<[String:Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false)
}
/**
Find purchase order by ID
- parameter orderId: (path) ID of pet that needs to be fetched
- parameter apiResponseQueue: The queue on which api response is dispatched.
- returns: AnyPublisher<Order, Error>
*/
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher<Order, Error> {
return Future<Order, Error>.init { promisse in
getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in
switch result {
case let .success(response):
promisse(.success(response.body!))
case let .failure(error):
promisse(.failure(error))
}
}
}.eraseToAnyPublisher()
}
/**
Find purchase order by ID
- GET /store/order/{order_id}
- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
- parameter orderId: (path) ID of pet that needs to be fetched
- returns: RequestBuilder<Order>
*/
open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder<Order> {
var path = "/store/order/{order_id}"
let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))"
let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let parameters: [String:Any]? = nil
let url = URLComponents(string: URLString)
let requestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false)
}
/**
Place an order for a pet
- parameter body: (body) order placed for purchasing the pet
- parameter apiResponseQueue: The queue on which api response is dispatched.
- returns: AnyPublisher<Order, Error>
*/
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher<Order, Error> {
return Future<Order, Error>.init { promisse in
placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in
switch result {
case let .success(response):
promisse(.success(response.body!))
case let .failure(error):
promisse(.failure(error))
}
}
}.eraseToAnyPublisher()
}
/**
Place an order for a pet
- POST /store/order
- parameter body: (body) order placed for purchasing the pet
- returns: RequestBuilder<Order>
*/
open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder<Order> {
let path = "/store/order"
let URLString = PetstoreClientAPI.basePath + path
let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
let url = URLComponents(string: URLString)
let requestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true)
}
}
| 41.861878 | 150 | 0.64643 |
0ed2b717f1042a5303dc714f8b4028920da8fe7d | 1,716 | @testable import Currencies
import XCTest
class CurrencyRatesTests: XCTestCase {
func testConvertMoney() {
let currencyRates = CurrencyRates(
base: .eur,
rates:
[
.gbp: 0.89615,
.rub: 79.39,
.usd: 1.1607
]
)
let testData: [(Money, Currency, Money)] = [
(Money(1, .eur), .eur, Money(1, .eur)),
(Money(1, .eur), .gbp, Money(0.89615, .gbp)),
(Money(1, .eur), .rub, Money(79.39, .rub)),
(Money(1, .eur), .usd, Money(1.1607, .usd)),
(Money(100, .eur), .gbp, Money(89.615, .gbp)),
(Money(100, .eur), .rub, Money(7939, .rub)),
(Money(100, .eur), .usd, Money(116.07, .usd)),
(Money(0.89615, .gbp), .eur, Money(1, .eur)),
(Money(79.39, .rub), .eur, Money(1, .eur)),
(Money(1.1607, .usd), .eur, Money(1, .eur))
]
for (money, currency, expected) in testData {
if let actual = currencyRates.convert(money, to: currency) {
XCTAssertEqual(actual.amount, expected.amount, accuracy: 0.0000000001)
XCTAssertEqual(actual.currency, expected.currency)
} else {
XCTFail("Fail to convert \(money) to \(currency)")
}
}
}
func testConvertUnexpectedCurrencies() {
let currencyRates = CurrencyRates(
base: .eur,
rates: [.rub: 79.39]
)
XCTAssertNil(currencyRates.convert(Money(1, .jpy), to: .eur))
XCTAssertNil(currencyRates.convert(Money(1, .eur), to: .jpy))
}
}
| 33.647059 | 86 | 0.484266 |
efa447ba2a057591ecba02074f67d3fcad458a22 | 8,943 | //
// NetworkTools.swift
// JiaXingZJShop
//
// Created by jsonshenglong on 2019/1/15.
// Copyright © 2019年 jsonshenglong. All rights reserved.
//
import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class ProductsViewController: AnimationViewController {
fileprivate let headViewIdentifier = "supermarketHeadView"
fileprivate var lastOffsetY: CGFloat = 0
fileprivate var isScrollDown = false
fileprivate var isScrollDown2 = false
var productsTableView: LFBTableView?
weak var delegate: ProductsViewControllerDelegate?
var refreshUpPull:(() -> ())?
//商品模型组
fileprivate var goodsArr: [[GoodsModelDate]]? {
didSet {
isScrollDown2 = false
productsTableView?.reloadData()
print("测试2")
}
}
var goodsCategories : TabModel?
var goosDate : [GoodsModelDate]? {
didSet {
// print(goosDate)
// print("*** \n")
var arr = [[GoodsModelDate]]()
let arrt = [GoodsModelDate]()
for singegoods in (goodsCategories?.child_list)! {
var arr2 = [GoodsModelDate]()
var singegoodsIsLoadFinish = false
for singgoodsdate in goosDate! {
if singgoodsdate.category_id == singegoods.category_id {
arr2.append(singgoodsdate)
singegoodsIsLoadFinish = true
}
}
if singegoodsIsLoadFinish {
arr.append(arr2)
} else {
arr.append(arrt)
}
// print(goodsArr)
}
self.goodsArr = arr
}
}
var supermarketData: Supermarket? {
didSet {
let aa = [GoodsModelDate]() //分类资源
//self.goodsArr = Supermarket.searchCategoryMatchProducts(supermarketData?.data ?? aa)
//self.goodsArr = Supermarket.searchCategoryMatchProducts(supermarketData?.data ?? aa)
}
}
var categortsSelectedIndexPath: IndexPath? {
didSet {
var goodsselectRow = categortsSelectedIndexPath?.row
//分类为空时,右边不做 选择 响应;如果为空时可添加提示
// if goodsArr![goodsselectRow!].count != 0 {
// productsTableView?.selectRow(at: IndexPath(row: 0, section: (categortsSelectedIndexPath! as NSIndexPath).row), animated: true, scrollPosition: .top)
// }
productsTableView?.selectRow(at: IndexPath(row: 0, section: (categortsSelectedIndexPath! as NSIndexPath).row), animated: true, scrollPosition: .top)
}
}
// MARK: - Lift Cycle
// 超市商品分类列表
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(shopCarBuyProductNumberDidChange), name: NSNotification.Name(rawValue: LFBShopCarBuyProductNumberDidChangeNotification), object: nil)
// y : 位置
view = UIView(frame: CGRect(x: ScreenWidth * 0.25, y: 44, width: ScreenWidth * 0.75, height: ScreenHeight - NavigationH))
buildProductsTableView()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Build UI
fileprivate func buildProductsTableView() {
productsTableView = LFBTableView(frame: view.bounds, style: .plain)
productsTableView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 49, right: 0)
productsTableView?.backgroundColor = LFBGlobalBackgroundColor
productsTableView?.delegate = self
productsTableView?.dataSource = self
productsTableView?.register(SupermarketHeadView.self, forHeaderFooterViewReuseIdentifier: headViewIdentifier)
productsTableView?.tableFooterView = buildProductsTableViewTableFooterView()
//let headView = LFBRefreshHeader(refreshingTarget: self, refreshingAction: Selector(("startRefreshUpPull")))
let headView = LFBRefreshHeader(refreshingTarget: self, refreshingAction: #selector(ProductsViewController.startRefreshUpPull))
productsTableView?.mj_header = headView
view.addSubview(productsTableView!)
}
fileprivate func buildProductsTableViewTableFooterView() -> UIView {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: productsTableView!.width, height: 70))
imageView.contentMode = UIView.ContentMode.center
imageView.image = UIImage(named: "v2_common_footer")
return imageView
}
// MARK: - 上拉刷新
@objc func startRefreshUpPull() {
if refreshUpPull != nil {
refreshUpPull!()
}
}
// MARK: - Action
@objc func shopCarBuyProductNumberDidChange() {
productsTableView?.reloadData()
}
}
// MARK: UITableViewDelegate, UITableViewDataSource
extension ProductsViewController: UITableViewDelegate, UITableViewDataSource {
//返回某个节中的行数,如果没有可以做一个默认显示的数据
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if goodsArr?.count > 0 {
print(section)
print(goodsArr![section].count)
//section.count无限row
if goodsArr![section].count != 0{
return goodsArr![section].count
} else {
return 1
}
}
return 0
}
//返回节的个数
func numberOfSections(in tableView: UITableView) -> Int {
return goodsCategories?.child_list?.count ?? 0
}
//为cell提供数据 ->单元格
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ProductCell.cellWithTableView(tableView)
//let goods = goodsArr![(indexPath).section][(indexPath).row]
//cell.goods = goods
weak var tmpSelf = self
cell.addProductClick = { (imageView) -> () in
tmpSelf?.addProductsAnimation(imageView)
}
return cell
}
//行高
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 85
}
//头部高度
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 25
}
//节头自定义视图
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headView = tableView.dequeueReusableHeaderFooterView(withIdentifier: headViewIdentifier) as! SupermarketHeadView
if goodsCategories?.child_list?.count > 0 && goodsCategories!.child_list![section].category_name != nil {
headView.titleLabel.text = goodsCategories!.child_list![section].category_name
}
return headView
}
//节头消失时触发
func tableView(_ tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) {
if delegate != nil && delegate!.responds(to: #selector(ProductsViewControllerDelegate.didEndDisplayingHeaderView(_:))) && isScrollDown {
delegate!.didEndDisplayingHeaderView!(section)//通知左边table滚动
isScrollDown2 = true
}
}
// //节头将要显示时触发
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if delegate != nil && delegate!.responds(to: #selector(ProductsViewControllerDelegate.willDisplayHeaderView(_:))) && !isScrollDown {
delegate!.willDisplayHeaderView!(section)
}
}
//响应选择单元格时触发的方法
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//let goods = goodsArr![(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
//详情页面
//let productDetailVC = ProductDetailViewController(goods: goods)
//navigationController?.pushViewController(productDetailVC, animated: true)
}
}
// MARK: - UIScrollViewDelegate
extension ProductsViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if animationLayers?.count > 0 {
let transitionLayer = animationLayers![0]
transitionLayer.isHidden = true
}
isScrollDown = lastOffsetY < scrollView.contentOffset.y
lastOffsetY = scrollView.contentOffset.y
}
}
@objc protocol ProductsViewControllerDelegate: NSObjectProtocol {
@objc optional func didEndDisplayingHeaderView(_ section: Int)
@objc optional func willDisplayHeaderView(_ section: Int)
}
| 35.208661 | 206 | 0.629878 |
28651f89e8291291e1f51a2e374256f6c4df3f60 | 99 | import XCTest
@testable import SwiftTURNTests
XCTMain([
testCase(SwiftTURNTests.allTests),
])
| 14.142857 | 38 | 0.777778 |
0303f5f5489ff980ac1d39e9bdece2d0ab43a757 | 296 | //
// PlayerScreenMode.swift
// BrightcovePlayerTVOS
//
// Created by Egor Brel on 8/15/19.
//
import Foundation
enum PlayerScreenMode: String, Equatable {
case inline = "Inline Player"
case fullscreen = "Full Screen Player"
var key: String {
return "View"
}
}
| 15.578947 | 42 | 0.641892 |
79a380c04ad4dc32129ecbadf39efdc3674e3f49 | 238 | //
// TestViewTesterPod.swift
// Pods
//
// Created by Raffaele D'Alterio on 05/10/17.
//
//
import UIKit
open class TestViewTesterPod: NSObject {
open func testViewTestLog(){
print("Hello this is pod ^_^ ")
}
}
| 14 | 46 | 0.617647 |
03d9d6e20de2ae35b27b5cf8ad2b23db62665ba6 | 696 | final class SideButtonsArea: AvailableArea {
override var deferNotification: Bool { return false }
override func isAreaAffectingView(_ other: UIView) -> Bool {
return !other.sideButtonsAreaAffectDirections.isEmpty
}
override func addAffectingView(_ other: UIView) {
let ov = other.sideButtonsAreaAffectView
let directions = ov.sideButtonsAreaAffectDirections
addConstraints(otherView: ov, directions: directions)
}
override func notifyObserver() {
MWMSideButtons.updateAvailableArea(frame)
}
}
extension UIView {
var sideButtonsAreaAffectDirections: MWMAvailableAreaAffectDirections { return [] }
var sideButtonsAreaAffectView: UIView { return self }
}
| 29 | 85 | 0.772989 |
8f5e37879789183170984ad03d14a0b2c20c683c | 1,229 | //
// Extensions.swift
// firechat
//
// Created by Andrew Carvajal on 9/25/17.
// Copyright © 2017 Andrew Carvajal. All rights reserved.
//
import UIKit
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView {
func loadImageUsingCache(with URLString: String) {
self.image = nil
// check cache for image first
if let cachedImage = imageCache.object(forKey: URLString as AnyObject) as? UIImage {
self.image = cachedImage
return
}
// otherwise fire off a new download
let url = URL(string: URLString)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil {
print(error as Any)
return
}
DispatchQueue.main.async {
if let downloadedImage = UIImage(data: data!) {
imageCache.setObject(downloadedImage, forKey: URLString as AnyObject)
self.image = downloadedImage
}
}
}).resume()
}
}
| 25.604167 | 94 | 0.515053 |
28594ed1205951302a30a0f25e3ba332ddd90be4 | 432 | // swift-tools-version:3.1
import PackageDescription
let package = Package(
name: "PCA9685",
dependencies: [
// We need to use the fork for now. Sorry
// A workaround for projects like RPiLight that depend on the fork.
// Swift 4 doesn't have this problem, but Swift 3.1.1 does.
.Package(url: "https://github.com/Kaiede/SwiftyGPIO.git", majorVersion: 1),
],
swiftLanguageVersions: [3, 4]
)
| 28.8 | 83 | 0.662037 |
488b08c44285953ad2811069bf5f0cae0ad7a0c6 | 1,913 |
import Foundation
import UIKit
class NibLoadingView: UIView {
@IBOutlet weak var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
nibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
nibSetup()
}
fileprivate func nibSetup() {
backgroundColor = UIColor.clear
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.translatesAutoresizingMaskIntoConstraints = true
addSubview(view)
}
fileprivate func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView
return nibView
}
}
class SwiftCountryView: NibLoadingView {
@IBOutlet weak var flagImageView: UIImageView!
@IBOutlet weak var countryNameLabel: UILabel!
@IBOutlet weak var countryCodeLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setup(_ country: Country) {
flagImageView.layer.borderWidth = 0.5
flagImageView.layer.borderColor = UIColor.darkGray.cgColor
flagImageView.layer.cornerRadius = 1
flagImageView.layer.masksToBounds = true
DispatchQueue.global(qos: .background).async {
let image = country.flag
DispatchQueue.main.async {
self.flagImageView.image = image
}
}
countryCodeLabel.text = country.phoneCode
countryNameLabel.text = country.name
}
}
| 25.851351 | 85 | 0.609514 |
01b7330db27b34ac88f983bcd9e1fbf8d3bfbaf8 | 2,262 | /*
The MIT License (MIT)
Copyright (c) 2015 Cameron Pulsford
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
public class URLRequestWriter: DataWriter {
var url: NSURLRequest!
/**
Initializes a URLRequestWriter.
:param: request The NSURLRequest to write.
:returns: An initialized URLRequestWriter.
*/
public convenience init(request: NSURLRequest) {
var method = "GET"
if let urlMethod = request.HTTPMethod {
method = urlMethod
}
let cfRequest = CFHTTPMessageCreateRequest(nil, method, request.URL, kCFHTTPVersion1_1).takeUnretainedValue()
var host = ""
if let address = request.URL.host {
if let port = request.URL.port {
host = "\(address):\(port)"
} else {
host = address
}
}
CFHTTPMessageSetHeaderFieldValue(cfRequest, "Host", host)
if let headers = request.allHTTPHeaderFields {
for (field, value) in headers {
CFHTTPMessageSetHeaderFieldValue(cfRequest, field as String, value as String)
}
}
self.init(data: CFHTTPMessageCopySerializedMessage(cfRequest).takeUnretainedValue())
url = request
}
}
| 31.859155 | 117 | 0.697171 |
297f7c8eb975ea25d83b044341c47f3209854a36 | 13,098 | #if os(iOS) // Added by Auth0toSPM
import Foundation // Added by Auth0toSPM
import Auth0ObjC // Added by Auth0toSPM
// MobileWebAuth.swift
//
// Copyright (c) 2020 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS)
import UIKit
import SafariServices
#if canImport(AuthenticationServices)
import AuthenticationServices
#endif
typealias Auth0WebAuth = MobileWebAuth
#if swift(>=4.2)
public typealias A0URLOptionsKey = UIApplication.OpenURLOptionsKey
#else
public typealias A0URLOptionsKey = UIApplicationOpenURLOptionsKey
#endif
/**
Resumes the current Auth session (if any).
- parameter url: url received by the iOS application in AppDelegate
- parameter options: dictionary with launch options received by the iOS application in AppDelegate
- returns: if the url was handled by an on going session or not.
*/
public func resumeAuth(_ url: URL, options: [A0URLOptionsKey: Any] = [:]) -> Bool {
return TransactionStore.shared.resume(url)
}
public protocol WebAuth: WebAuthenticatable {
/**
Use `SFSafariViewController` instead of `SFAuthenticationSession` for WebAuth
in iOS 11.0+.
- Parameter style: modal presentation style
- returns: the same WebAuth instance to allow method chaining
*/
@available(iOS 11, *)
func useLegacyAuthentication(withStyle style: UIModalPresentationStyle) -> Self
}
public extension WebAuth {
/**
Use `SFSafariViewController` instead of `SFAuthenticationSession` for WebAuth
in iOS 11.0+.
Defaults to .fullScreen modal presentation style.
- returns: the same WebAuth instance to allow method chaining
*/
@available(iOS 11, *)
func useLegacyAuthentication() -> Self {
return useLegacyAuthentication(withStyle: .fullScreen)
}
}
final class MobileWebAuth: BaseWebAuth, WebAuth {
let presenter: ControllerModalPresenter
private var safariPresentationStyle = UIModalPresentationStyle.fullScreen
private var authenticationSession = true
init(clientId: String,
url: URL,
presenter: ControllerModalPresenter = ControllerModalPresenter(),
storage: TransactionStore = TransactionStore.shared,
telemetry: Telemetry = Telemetry()) {
self.presenter = presenter
super.init(platform: "ios",
clientId: clientId,
url: url,
storage: storage,
telemetry: telemetry)
}
func useLegacyAuthentication(withStyle style: UIModalPresentationStyle = .fullScreen) -> Self {
self.authenticationSession = false
self.safariPresentationStyle = style
return self
}
override func performLogin(authorizeURL: URL,
redirectURL: URL,
state: String?,
handler: OAuth2Grant,
callback: @escaping (Result<Credentials>) -> Void) -> AuthTransaction? {
if #available(iOS 11.0, *), self.authenticationSession {
if #available(iOS 12.0, *) {
return super.performLogin(authorizeURL: authorizeURL,
redirectURL: redirectURL,
state: state,
handler: handler,
callback: callback)
}
#if !targetEnvironment(macCatalyst)
return SafariServicesSession(authorizeURL: authorizeURL,
redirectURL: redirectURL,
state: state,
handler: handler,
logger: self.logger,
callback: callback)
#else
return nil // Will never get executed because Catalyst will use AuthenticationServices
#endif
}
let (controller, finish) = newSafari(authorizeURL, callback: callback)
let session = SafariSession(controller: controller,
redirectURL: redirectURL,
state: state,
handler: handler,
logger: self.logger,
callback: finish)
controller.delegate = session
self.presenter.present(controller: controller)
return session
}
override func performLogout(logoutURL: URL,
redirectURL: URL,
federated: Bool,
callback: @escaping (Bool) -> Void) -> AuthTransaction? {
if #available(iOS 11.0, *), self.authenticationSession {
if #available(iOS 12.0, *) {
return super.performLogout(logoutURL: logoutURL,
redirectURL: redirectURL,
federated: federated,
callback: callback)
}
#if !targetEnvironment(macCatalyst)
return SafariServicesSessionCallback(url: logoutURL,
schemeURL: redirectURL,
callback: callback)
#else
return nil // Will never get executed because Catalyst will use AuthenticationServices
#endif
}
var urlComponents = URLComponents(url: logoutURL, resolvingAgainstBaseURL: true)!
if federated, let firstQueryItem = urlComponents.queryItems?.first {
urlComponents.queryItems = [firstQueryItem]
} else {
urlComponents.query = nil
}
let url = urlComponents.url!
let controller = SilentSafariViewController(url: url) { callback($0) }
self.presenter.present(controller: controller)
self.logger?.trace(url: url, source: String(describing: "Safari"))
return nil
}
func newSafari(_ authorizeURL: URL,
callback: @escaping (Result<Credentials>) -> Void) -> (SFSafariViewController, (Result<Credentials>) -> Void) {
let controller = SFSafariViewController(url: authorizeURL)
controller.modalPresentationStyle = safariPresentationStyle
if #available(iOS 11.0, *) {
controller.dismissButtonStyle = .cancel
}
let finish: (Result<Credentials>) -> Void = { [weak controller] (result: Result<Credentials>) -> Void in
if case .failure(let cause as WebAuthError) = result, case .userCancelled = cause {
DispatchQueue.main.async {
callback(result)
}
} else {
DispatchQueue.main.async {
guard let presenting = controller?.presentingViewController else {
return callback(Result.failure(WebAuthError.cannotDismissWebAuthController))
}
presenting.dismiss(animated: true) {
callback(result)
}
}
}
}
return (controller, finish)
}
}
public extension _ObjectiveOAuth2 {
/**
Resumes the current Auth session (if any).
- parameter url: url received by iOS application in AppDelegate
- parameter options: dictionary with launch options received by iOS application in AppDelegate
- returns: if the url was handled by an on going session or not.
*/
@objc(resumeAuthWithURL:options:)
static func resume(_ url: URL, options: [A0URLOptionsKey: Any]) -> Bool {
return resumeAuth(url, options: options)
}
}
public protocol AuthResumable {
/**
Resumes the transaction when the third party application notifies the application using an url with a custom scheme.
This method should be called from the Application's `AppDelegate` or using `public func resumeAuth(_ url: URL, options: [UIApplicationOpenURLOptionsKey: Any]) -> Bool` method.
- parameter url: the url send by the third party application that contains the result of the Auth
- parameter options: options recieved in the openUrl method of the `AppDelegate`
- returns: if the url was expected and properly formatted otherwise it will return `false`.
*/
func resume(_ url: URL, options: [A0URLOptionsKey: Any]) -> Bool
}
public extension AuthResumable {
/**
Tries to resume (and complete) the OAuth2 session from the received URL
- parameter url: url received in application's AppDelegate
- parameter options: a dictionary of launch options received from application's AppDelegate
- returns: `true` if the url completed (successfuly or not) this session, `false` otherwise
*/
func resume(_ url: URL, options: [A0URLOptionsKey: Any] = [:]) -> Bool {
return self.resume(url, options: options)
}
}
extension AuthTransaction where Self: BaseAuthTransaction {
func resume(_ url: URL, options: [A0URLOptionsKey: Any]) -> Bool {
return self.handleUrl(url)
}
}
extension AuthTransaction where Self: SessionCallbackTransaction {
func resume(_ url: URL, options: [A0URLOptionsKey: Any]) -> Bool {
return self.handleUrl(url)
}
}
#if !targetEnvironment(macCatalyst)
@available(iOS 11.0, *)
final class SafariServicesSession: SessionTransaction {
init(authorizeURL: URL,
redirectURL: URL,
state: String? = nil,
handler: OAuth2Grant,
logger: Logger?,
callback: @escaping FinishTransaction) {
super.init(redirectURL: redirectURL,
state: state,
handler: handler,
logger: logger,
callback: callback)
authSession = SFAuthenticationSession(url: authorizeURL,
callbackURLScheme: self.redirectURL.absoluteString) { [unowned self] in
guard $1 == nil, let callbackURL = $0 else {
let authError = $1 ?? WebAuthError.unknownError
if case SFAuthenticationError.canceledLogin = authError {
self.callback(.failure(WebAuthError.userCancelled))
} else {
self.callback(.failure(authError))
}
return TransactionStore.shared.clear()
}
_ = TransactionStore.shared.resume(callbackURL)
}
_ = authSession?.start()
}
}
@available(iOS 11.0, *)
final class SafariServicesSessionCallback: SessionCallbackTransaction {
init(url: URL, schemeURL: URL, callback: @escaping (Bool) -> Void) {
super.init(callback: callback)
let authSession = SFAuthenticationSession(url: url,
callbackURLScheme: schemeURL.absoluteString) { [unowned self] url, _ in
self.callback(url != nil)
TransactionStore.shared.clear()
}
self.authSession = authSession
authSession.start()
}
}
@available(iOS 11.0, *)
extension SFAuthenticationSession: AuthSession {}
#endif
#if canImport(AuthenticationServices) && swift(>=5.1)
@available(iOS 13.0, *)
extension AuthenticationServicesSession: ASWebAuthenticationPresentationContextProviding {
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
return UIApplication.shared()?.windows.filter({ $0.isKeyWindow }).last ?? ASPresentationAnchor()
}
}
@available(iOS 13.0, *)
extension AuthenticationServicesSessionCallback: ASWebAuthenticationPresentationContextProviding {
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
return UIApplication.shared()?.windows.filter({ $0.isKeyWindow }).last ?? ASPresentationAnchor()
}
}
#endif
#endif
#endif // Added by Auth0toSPM
| 37.530086 | 180 | 0.618949 |
6a218df6327e8d93ef16283a7b9443299250e735 | 190 | //
// SceneDelegate.swift
// PatLock
//
// Created by Sahand Raeisi on 12/19/20.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
}
| 12.666667 | 57 | 0.694737 |
797bb749539d5a4c786fa1c0e46f97c0b7483611 | 1,378 | //
// VANSelfReportedGenders.swift
//
// Created by David Switzer on 1/26/18
// Copyright (c) Madison Labs. All rights reserved.
//
import Foundation
import SwiftyJSON
public class VANSelfReportedGender {
// MARK: Declaration for string constants to be used to decode and also serialize.
private struct SerializationKeys {
static let reportedGenderId = "reportedGenderId"
}
// MARK: Properties
public var reportedGenderId: Int?
// MARK: SwiftyJSON Initializers
/// Initiates the instance based on the object.
///
/// - parameter object: The object of either Dictionary or Array kind that was passed.
/// - returns: An initialized instance of the class.
public convenience init(object: Any) {
self.init(json: JSON(object))
}
/// Initiates the instance based on the JSON that was passed.
///
/// - parameter json: JSON object from SwiftyJSON.
public required init(json: JSON) {
reportedGenderId = json[SerializationKeys.reportedGenderId].int
}
/// Generates description of the object in the form of a NSDictionary.
///
/// - returns: A Key value pair containing all valid values in the object.
public func dictionaryRepresentation() -> [String: Any] {
var dictionary: [String: Any] = [:]
if let value = reportedGenderId { dictionary[SerializationKeys.reportedGenderId] = value }
return dictionary
}
}
| 29.319149 | 94 | 0.714078 |
644b0fbb7a336e1616d1ae04c45bd2b941a8c416 | 1,381 | //
// File.swift
// radar-prmt-iosTests
//
// Created by Joris Borgdorff on 15/04/2019.
// Copyright © 2019 Joris Borgdorff. All rights reserved.
//
import Foundation
import CoreData
@testable import radar_prmt_ios
class MockDataController {
let reader: AvroDataExtractor
let writer: AvroDataWriter
let container: NSPersistentContainer
init() {
guard let objectModel = NSManagedObjectModel.mergedModel(from: [Bundle.main]) else {
fatalError("Cannot instantiate data model")
}
container = NSPersistentContainer(name: "radar_prmt_ios", managedObjectModel: objectModel)
let description = NSPersistentStoreDescription()
description.type = NSInMemoryStoreType
// description.shouldAddStoreAsynchronously = false // Make it simpler in test env
container.persistentStoreDescriptions = [description]
container.loadPersistentStores { (description, error) in
// Check if the data store is in memory
precondition( description.type == NSInMemoryStoreType )
// Check if creating container wrong
if let error = error {
fatalError("Create an in-mem coordinator failed \(error)")
}
}
writer = AvroDataWriter(container: container)
reader = AvroDataExtractor(container: container)
}
}
| 32.116279 | 98 | 0.673425 |
8a40be544d5324c73ffbf490c30f6bc53c672259 | 31,714 | //
// File.swift
// Flatland
//
// Created by Stuart Rankin on 9/27/20.
// Copyright © 2020, 2021 Stuart Rankin. All rights reserved.
//
import Foundation
import AppKit
import SceneKit
/// Thin wrapper around `SCNNode` that provides a few auxiliary properties for carrying data and ID information.
class SCNNode2: SCNNode
{
// MARK: - Initialization and deinitialization.
/// Default initializer.
override init()
{
super.init()
Initialize()
}
/// Initializer.
/// - Parameter Tag: The tag value.
init(Tag: Any?)
{
super.init()
self.Tag = Tag
Initialize()
}
/// Initializer.
/// - Parameter Tag: The tag value.
/// - Parameter NodeID: The node's ID. Assumed to be unique.
/// - Parameter NodeClass: The node class ID. Assumed to be non-unique.
/// - Parameter Usage: Intended usage of the node.
init(Tag: Any? = nil, NodeID: UUID, NodeClass: UUID, Usage: NodeUsages = .Generic)
{
super.init()
self.Tag = Tag
self.NodeID = NodeID
self.NodeClass = NodeClass
self.NodeUsage = Usage
Initialize()
}
/// Initializer.
/// - Parameter geometry: The geometry of the node.
init(geometry: SCNGeometry?)
{
super.init()
self.geometry = geometry
Initialize()
}
/// Initializer.
/// - Parameter geometry: The geometry of the node.
/// - Parameter Tag: The tag value.
/// - Parameter SubComponent: The sub-component ID.
init(geometry: SCNGeometry?, Tag: Any?, SubComponent: UUID? = nil)
{
super.init()
self.geometry = geometry
self.Tag = Tag
Initialize()
}
/// Initializer.
/// - Parameter geometry: The geometry of the node.
/// - Parameter Tag: The tag value.
/// - Parameter NodeID: The node's ID. Assumed to be unique.
/// - Parameter NodeClass: The node class ID. Assumed to be non-unique.
/// - Parameter Usage: Intended usage of the node.
init(geometry: SCNGeometry?, Tag: Any? = nil, NodeID: UUID, NodeClass: UUID, Usage: NodeUsages = .Generic)
{
super.init()
self.geometry = geometry
self.Tag = Tag
self.NodeID = NodeID
self.NodeClass = NodeClass
self.NodeUsage = Usage
Initialize()
}
/// Initializer.
/// - Parameter CanChange: Sets the node can change state flag.
/// - Parameter Latitude: The real-world latitude of the node.
/// - Parameter Longitude: The real-word longitude of the node.
init(CanChange: Bool, _ Latitude: Double, _ Longitude: Double)
{
super.init()
CanSwitchState = CanChange
SetLocation(Latitude, Longitude)
Initialize()
}
/// Initializer.
/// - Parameter coder: See Apple documentation.
required init?(coder: NSCoder)
{
super.init(coder: coder)
Initialize()
}
/// Initializer.
/// - Parameter From: The `SCNNode` whose data is used to initialize the `SCNNode2`
/// instance.
init(From: SCNNode)
{
super.init()
self.geometry = From.geometry
self.scale = From.scale
self.position = From.position
self.eulerAngles = From.eulerAngles
self.categoryBitMask = From.categoryBitMask
Initialize()
}
/// Initializer.
/// - Parameter AsChild: `SCNNode` instance that will be added as a child to the
/// `SCNNode2` instance.
init(AsChild: SCNNode)
{
super.init()
self.addChildNode(AsChild)
Initialize()
}
/// Common initialization.
private func Initialize()
{
//StartDynamicUpdates()
}
/// Clears a node of its contents. Removes it from the parent. Prepares node to be deleted.
public func Clear()
{
self.removeAllAnimations()
self.removeAllActions()
self.removeFromParentNode()
self.geometry?.firstMaterial?.diffuse.contents = nil
self.geometry?.firstMaterial?.specular.contents = nil
self.geometry?.firstMaterial?.emission.contents = nil
self.geometry?.firstMaterial?.selfIllumination.contents = nil
self.geometry = nil
}
/// Clears a node of its contents. Does the same for all child nodes. Prepares the node to be deleted.
/// - Note: Only child nodes of type `SCNNode2` are cleared.
public func ClearAll()
{
for Child in ChildNodes2()
{
Child.ClearAll()
Child.Clear()
}
Clear()
}
// MARK: - Additional fields.
/// Tag value. Defaults to `nil`.
var Tag: Any? = nil
/// Name of the node.
var Name: String = ""
/// Sub-component ID. Defaults to `nil`.
var SubComponent: UUID? = nil
/// Node class ID. Defaults to `nil`.
var NodeClass: UUID? = nil
/// Node ID. Defaults to `nil`.
var NodeID: UUID? = nil
/// ID to use for editing the edit. Defaults to `nil`.
var EditID: UUID? = nil
/// Intended node usage. Defaults to `nil`.
var NodeUsage: NodeUsages? = nil
/// Initial angle of the node. Usage is context sensitive. Defaults to `nil`.
var InitialAngle: Double? = nil
/// The caller should set this to true if the node is showing SCNText geometry. Defaults to `false`.
var IsTextNode: Bool = false
/// Convenience property to hold hour angles.
var HourAngle: Double? = nil
/// Propagate the parent's `NodeUsage` value to its children.
func PropagateUsage()
{
for Child in self.childNodes
{
if let TheChild = Child as? SCNNode2
{
TheChild.NodeUsage = NodeUsage
}
}
}
/// Propagate the parent's IDs to its children.
func PropagateIDs()
{
for Child in self.childNodes
{
if let TheChild = Child as? SCNNode2
{
TheChild.NodeClass = NodeClass
TheChild.NodeID = NodeID
}
}
}
/// Convenience value.
var SourceAngle: Double = 0.0
/// Auxiliary string tag.
var AuxiliaryTag: String? = nil
/// Returns all child nodes that are of type `SCNNode2`.
/// - Returns: Array of child nodes that are of type `SCNNode2`.
func ChildNodes2() -> [SCNNode2]
{
var Results = [SCNNode2]()
for SomeNode in childNodes
{
if let TheNode = SomeNode as? SCNNode2
{
Results.append(TheNode)
}
}
return Results
}
/// Iterate over all child nodes in the instance node and execute the close against it. If a child node
/// cannot be converted to an `SCNNode2`, nil is passed to the closure.
/// - Parameter Closure: The closure block to execute against each child node in turn.
func ForEachChild(_ Closure: ((SCNNode2?) -> ())?)
{
for SomeNode in childNodes
{
Closure?((SomeNode as? SCNNode2))
}
}
/// Iterate over all child nodes in the instance node and execute the close against it. Only child nodes
/// that are of type `SCNNode2` are iterated here.
/// - Note: All nodes of type `SCNNode2` are passed to the closure (as non-nil references). If there are
/// no nodes of type `SCNNode2`, nothing is passed.
/// - Parameter Closure: The closure block to execute against each child node in turn.
func ForEachChild2(_ Closure: ((SCNNode2) -> ())?)
{
for SomeNode in ChildNodes2()
{
Closure?(SomeNode)
}
}
// MARK: - Text handling
/// Change the text geometry to the passed string.
/// - Note:
/// - If `IsTextNode` is false, no action is taken.
/// - If `geometry` hasn't been set, no action is taken.
/// - Parameter To: The new text to use for the text geometry.
func ChangeText(To NewText: String)
{
if !IsTextNode
{
return
}
if geometry == nil
{
return
}
(geometry as? SCNText)?.string = NewText
}
// MARK: - Bounding shape variables.
var _CanShowBoundingShape: Bool = true
{
didSet
{
if !_CanShowBoundingShape
{
HideBoundingSphere()
HideBoundingBox()
}
}
}
/// Holds the bounding box.
var BoxNode = SCNNode()
/// Holds the rotate on X axis flag.
private var _RotateOnX: Bool = true
/// Get or set the rotate bounding shape on X axis flag.
public var RotateOnX: Bool
{
get
{
return _RotateOnX
}
set
{
_RotateOnX = newValue
}
}
/// Holds the rotate on Y axis flag.
private var _RotateOnY: Bool = true
/// Get or set the rotate bounding shape on Y axis flag.
public var RotateOnY: Bool
{
get
{
return _RotateOnY
}
set
{
_RotateOnY = newValue
}
}
/// Holds the rotate on Z axis flag.
private var _RotateOnZ: Bool = true
/// Get or set the rotate bounding shape on Z axis flag.
public var RotateOnZ: Bool
{
get
{
return _RotateOnZ
}
set
{
_RotateOnZ = newValue
}
}
var _ShowingBoundingShape: Bool = false
/// Gets the current state of the bounding shape.
public var ShowingBoundingShape: Bool
{
get
{
return _ShowingBoundingShape
}
}
/// The bounding sphere node.
var BoundingSphereNode: SCNNode? = nil
/// The current bounding shape.
public var CurrentBoundingShape: NodeBoundingShapes = .Box
/// Array of bounding box lines.
var BoundingBoxLines = [SCNNode]()
// MARK: - Day/night settings.
/// Propagates the current daylight state to all child nodes.
/// - Parameter InDay: True indicates daylight, false indicates nighttime.
private func PropagateState(InDay: Bool)
{
for Child in ChildNodes2()
{
Child.IsInDaylight = InDay
}
}
/// Sets the day or night state for nodes that have diffuse materials made up of one or more
/// materials (usually images).
/// - Parameter For: Determines day or night state.
private func SetStateWithImages(For DayTime: Bool)
{
if DayTime
{
self.geometry?.firstMaterial?.lightingModel = DayState!.LightModel
let EmissionColor = DayState?.Emission ?? NSColor.clear
for Material in self.geometry!.materials
{
Material.emission.contents = EmissionColor
}
if DayState?.Metalness != nil
{
for Material in self.geometry!.materials
{
Material.metalness.contents = DayState!.Metalness
}
}
if DayState?.Roughness != nil
{
for Material in self.geometry!.materials
{
Material.roughness.contents = DayState!.Roughness
}
}
}
else
{
self.geometry?.firstMaterial?.lightingModel = NightState!.LightModel
let EmissionColor = NightState?.Emission ?? NSColor.clear
for Material in self.geometry!.materials
{
Material.emission.contents = EmissionColor
}
if NightState?.Metalness != nil
{
for Material in self.geometry!.materials
{
Material.metalness.contents = NightState!.Metalness
}
}
if NightState?.Roughness != nil
{
for Material in self.geometry!.materials
{
Material.roughness.contents = NightState!.Roughness
}
}
}
}
/// Assign the passed set of state values to the node.
/// - Parameter State: The set of state values to assign.
private func SetVisualAttributes(_ State: NodeState)
{
#if true
if let DiffuseTexture = State.Diffuse
{
self.geometry?.firstMaterial?.diffuse.contents = DiffuseTexture
}
else
{
self.geometry?.firstMaterial?.diffuse.contents = State.Color
}
self.geometry?.firstMaterial?.specular.contents = State.Specular ?? NSColor.white
self.geometry?.firstMaterial?.lightingModel = State.LightModel
self.geometry?.firstMaterial?.emission.contents = State.Emission ?? NSColor.clear
self.geometry?.firstMaterial?.lightingModel = State.LightModel
self.geometry?.firstMaterial?.metalness.contents = State.Metalness
self.geometry?.firstMaterial?.roughness.contents = State.Roughness
if let DoesCastShadow = State.CastsShadow
{
self.castsShadow = DoesCastShadow
}
#else
if UseProtocolToSetState
{
if let PNode = self as? ShapeAttribute
{
if let DiffuseTexture = State.Diffuse
{
MemoryDebug.Block("SetVisualAttributes.SetDiffuseTexture")
{
PNode.SetDiffuseTexture(DiffuseTexture)
}
}
else
{
MemoryDebug.Block("SetVisualAttributes.SetMaterialColor")
{
PNode.SetMaterialColor(State.Color)
}
}
MemoryDebug.Block("SetVisualAttributes.Other")
{
PNode.SetEmissionColor(State.Emission ?? NSColor.clear)
PNode.SetLightingModel(State.LightModel)
PNode.SetMetalness(State.Metalness)
PNode.SetRoughness(State.Roughness)
}
}
}
else
{
MemoryDebug.Block("SetVisualAttributes")
{
if let DiffuseTexture = State.Diffuse
{
self.geometry?.firstMaterial?.diffuse.contents = DiffuseTexture
}
else
{
self.geometry?.firstMaterial?.diffuse.contents = State.Color
}
self.geometry?.firstMaterial?.specular.contents = State.Specular ?? NSColor.white
self.geometry?.firstMaterial?.lightingModel = State.LightModel
self.geometry?.firstMaterial?.emission.contents = State.Emission ?? NSColor.clear
self.geometry?.firstMaterial?.lightingModel = State.LightModel
self.geometry?.firstMaterial?.metalness.contents = State.Metalness
self.geometry?.firstMaterial?.roughness.contents = State.Roughness
}
}
#endif
}
/// Set the visual state for the node (and all child nodes) to day or night time (based on the parameter).
/// - Note: If either `DayState` or `NightState` is nil, the state set is for the day.
/// - Parameter For: Determines which state to show.
public func SetState(For DayTime: Bool)
{
if DayState == nil || NightState == nil
{
for Child in self.ChildNodes2()
{
Child.SetState(For: DayTime)
}
return
}
if HasImageTextures
{
SetStateWithImages(For: DayTime)
return
}
let NodeState = DayTime ? DayState! : NightState!
SetVisualAttributes(NodeState)
for Child in self.ChildNodes2()
{
Child.SetState(For: DayTime)
}
}
/// Set to true if the contents of the diffuse material is made up of one or more images.
public var HasImageTextures: Bool = false
/// Holds the daylight state. Setting this property updates the visual state for this node and all child
/// nodes.
private var _IsInDaylight: Bool = true
{
didSet
{
self.PropagateState(InDay: self._IsInDaylight)
self.SetState(For: self._IsInDaylight)
}
}
/// Get or set the daylight state. Setting the same value two (or more) times in a row will not result
/// in any changes.
public var IsInDaylight: Bool
{
get
{
return _IsInDaylight
}
set
{
_IsInDaylight = newValue
}
}
/// Check to see if the node is in daylight or not. Sets the value of `IsInDaylight`
/// - Notes: If the position is not set or daylight cannot be determined, no action is taken.
public func SetDaylightState()
{
guard let Latitude = Latitude, let Longitude = Longitude else
{
Debug.Print("SetDaylightState: Position not set.")
return
}
guard let IsInDay = Solar.IsInDaylight(Latitude, Longitude) else
{
Debug.Print("SetDaylightState: Cannot determine sun's position.")
return
}
IsInDaylight = IsInDay
}
var PreviousDayState: Bool? = nil
/// Holds the can switch state flag.
private var _CanSwitchState: Bool = false
{
didSet
{
for Child in self.childNodes
{
if let Node = Child as? SCNNode2
{
Node.CanSwitchState = _CanSwitchState
}
}
}
}
/// Sets the can switch state flag. If false, the node does not respond to state changes. Setting this
/// property propagates the same value to all child nodes.
public var CanSwitchState: Bool
{
get
{
return _CanSwitchState
}
set
{
_CanSwitchState = newValue
}
}
public var DayState: NodeState? = nil
public var NightState: NodeState? = nil
/// Convenience function to set the state attributes.
/// - Parameter ForDay: If true, day time attributes are set. If false, night time attributes are set.
/// - Parameter Color: The color for the state.
/// - Parameter Specular: The specular color for the state. Defaults to `.white`.
/// - Parameter Emission: The color for the emmission material (eg, glowing). Defaults to `nil`.
/// - Parameter Model: The lighting model for the state. Defaults to `.phong`.
/// - Parameter Metalness: The metalness value of the state. If nil, not used. Defaults to `nil`.
/// - Parameter Roughness: The roughness value of the state. If nil, not used. Defaults to `nil`.
/// - Parameter CastsShadow: Sets the value of the `castsShadow` flat. If nil, not used. Defaults to `nil`.
/// - Parameter ChildrenToo: If true, child nodes (only of type `SCNNode2`) will also have the passed
/// state set. If false, child nodes are ignored.
public func SetState(ForDay: Bool,
Color: NSColor,
Specular: NSColor = NSColor.white,
Emission: NSColor? = nil,
Model: SCNMaterial.LightingModel = .phong,
Metalness: Double? = nil,
Roughness: Double? = nil,
CastsShadow: Bool? = nil,
ChildrenToo: Bool = true)
{
if ForDay
{
DayState = NodeState(State: .Day, Color: Color, Diffuse: nil, Emission: Emission,
Specular: Specular, LightModel: Model, Metalness: Metalness,
Roughness: Roughness, CastsShadow: CastsShadow)
}
else
{
NightState = NodeState(State: .Night, Color: Color, Diffuse: nil, Emission: Emission,
Specular: Specular, LightModel: Model, Metalness: Metalness,
Roughness: Roughness, CastsShadow: CastsShadow)
}
for Child in ChildNodes2()
{
Child.SetState(ForDay: ForDay, Color: Color, Emission: Emission, Model: Model,
Metalness: Metalness, Roughness: Roughness, CastsShadow: CastsShadow,
ChildrenToo: ChildrenToo)
}
}
/// Convenience function to set the state attributes.
/// - Parameter ForDay: If true, day time attributes are set. If false, night time attributes are set.
/// - Parameter Diffuse: The image to use as the diffuse surface texture.
/// - Parameter Emission: The color for the emmission material (eg, glowing). Defaults to `nil`.
/// - Parameter Model: The lighting model for the state. Defaults to `.phong`.
/// - Parameter Metalness: The metalness value of the state. If nil, not used. Defaults to `nil`.
/// - Parameter Roughness: The roughness value of the state. If nil, not used. Defaults to `nil`.
/// - Parameter CastsShadow: Sets the value of the `castsShadow` flat. If nil, not used. Defaults to `nil`.
/// - Parameter ChildrenToo: If true, child nodes (only of type `SCNNode2`) will also have the passed
/// state set. If false, child nodes are ignored.
public func SetState(ForDay: Bool,
Diffuse: NSImage,
Emission: NSColor? = nil,
Model: SCNMaterial.LightingModel = .phong,
Metalness: Double? = nil,
Roughness: Double? = nil,
CastsShadow: Bool? = nil,
ChildrenToo: Bool = true)
{
if ForDay
{
DayState = NodeState(State: .Day, Color: NSColor.white, Diffuse: Diffuse, Emission: Emission,
Specular: NSColor.white, LightModel: Model, Metalness: Metalness,
Roughness: Roughness, CastsShadow: CastsShadow)
}
else
{
NightState = NodeState(State: .Night, Color: NSColor.black, Diffuse: Diffuse, Emission: Emission,
Specular: NSColor.white, LightModel: Model, Metalness: Metalness,
Roughness: Roughness, CastsShadow: CastsShadow)
}
for Child in ChildNodes2()
{
Child.SetState(ForDay: ForDay, Diffuse: Diffuse, Emission: Emission, Model: Model,
Metalness: Metalness, Roughness: Roughness, CastsShadow: CastsShadow,
ChildrenToo: ChildrenToo)
}
}
/// If true, the ShapeAttribute protocol will be used to set attributes. This is provided for
/// nodes that have hard to reach child nodes. This lets such nodes handle setting state for
/// themselves. Defaults to `false`.
public var UseProtocolToSetState: Bool = false
// MARK: - Map location data.
/// Sets the geographic location of the node in terms of latitude, longitude. All child nodes
/// are also set with the same values.
/// - Parameter Latitude: The latitude of the node.
/// - Parameter Longitude: The longitude of the node.
public func SetLocation(_ Latitude: Double, _ Longitude: Double)
{
self.Latitude = Latitude
self.Longitude = Longitude
for Child in self.childNodes
{
if let Node = Child as? SCNNode2
{
Node.SetLocation(Latitude, Longitude)
}
}
}
/// Clears the geographic location of the node. All child nodes are also cleared.
public func ClearLocation()
{
self.Latitude = nil
self.Longitude = nil
for Child in self.childNodes
{
if let Node = Child as? SCNNode2
{
Node.ClearLocation()
}
}
}
/// Determines if the node has a geographic location.
/// - Returns: True if the node has both latitude and longitude set, false if not.
func HasLocation() -> Bool
{
return Latitude != nil && Longitude != nil
}
/// If provided, the latitude of the node.
public var Latitude: Double? = nil
/// If provided, the longitude of the node.
public var Longitude: Double? = nil
// MARK: - Dynamic updating.
/*
func StartDynamicUpdates()
{
DynamicTimer = Timer.scheduledTimer(timeInterval: 1.0,
target: self,
selector: #selector(TestDaylight),
userInfo: nil, repeats: true)
}
*/
weak var DynamicTimer: Timer? = nil
func StopDynamicUpdates()
{
DynamicTimer?.invalidate()
DynamicTimer = nil
}
/// Test to see if it is daylight.
@objc func TestDaylight()
{
DoTestDaylight()
}
/// See if the node is in day light or nighttime and change it appropriately.
func DoTestDaylight(_ Caller: String? = nil)
{
if HasLocation()
{
if let IsInDay = Solar.IsInDaylight(Latitude!, Longitude!)
{
_IsInDaylight = IsInDay
let SomeEvent = IsInDay ? NodeEvents.SwitchToDay : NodeEvents.SwitchToNight
TriggerEvent(SomeEvent)
for Child in ChildNodes2()
{
Child.IsInDaylight = _IsInDaylight
}
}
}
}
/// Holds events and associated attributes.
var EventMap = [NodeEvents: EventAttributes]()
/// Sets the opacity of the node to the passed value.
/// - Note: All child nodes have their opacity set to the same level.
/// - Note: The opacity stack is cleared when this function is called.
/// - Parameter To: New opacity value.
func SetOpacity(To NewValue: Double)
{
OpacityStack.Clear()
self.opacity = CGFloat(NewValue)
for Child in self.childNodes
{
if let ActualChild = Child as? SCNNode2
{
ActualChild.SetOpacity(To: NewValue)
}
else
{
Child.opacity = CGFloat(NewValue)
}
}
}
/// Push the current opacity value of the node onto a stack then set the opacity to the passed value.
/// - Note: This function is provided as a way to retain opacity levels over the course of changing
/// opacity levels on a temporary basis. Each node has its own opacity stack and by using this
/// function and `PopOpacity` opacity levels are restored correctly.
/// - Note: All child nodes have their opacities pushed. If a child node is of type `SCNNode`, the opacity
/// level is assigned but no pushing operation takes place since `SCNNode` does not support it.
/// - Parameter NewValue: The new opacity level.
/// - Parameter Animate: If true, the opacity level change is animated. Otherwise, it happens immediately.
/// Defaults to true.
func PushOpacity(_ NewValue: Double, Animate: Bool = true)
{
OpacityStack.Push(self.opacity)
if Animate
{
let OpacityAnimation = SCNAction.fadeOpacity(to: CGFloat(NewValue), duration: 0.5)
self.runAction(OpacityAnimation)
}
else
{
self.opacity = CGFloat(NewValue)
}
for Child in self.childNodes
{
if let ActualChild = Child as? SCNNode2
{
ActualChild.PushOpacity(NewValue)
}
else
{
if Animate
{
let OpacityAnimation = SCNAction.fadeOpacity(to: CGFloat(NewValue), duration: 0.5)
self.runAction(OpacityAnimation)
}
else
{
Child.opacity = CGFloat(NewValue)
}
}
}
}
/// Pop the opacity from the stack and set the node's opacity to that value.
/// - Note: All child nodes have their opacity popped as well. If a child node is of type `SCNNode`,
/// its opacity value is set to `IsEmpty`.
/// - Parameter IfEmpty: Value to use for the opacity if the opacity stack is empty.
/// - Parameter Animate: If true, the opacity level change is animated. Otherwise, it happens immediately.
/// Defaults to true.
func PopOpacity(_ IfEmpty: Double = 1.0, Animate: Bool = true)
{
if OpacityStack.IsEmpty
{
if Animate
{
let OpacityAnimation = SCNAction.fadeOpacity(to: CGFloat(IfEmpty), duration: 0.5)
self.runAction(OpacityAnimation)
}
else
{
self.opacity = CGFloat(IfEmpty)
}
}
else
{
if let OldValue = OpacityStack.Pop()
{
if Animate
{
let OpacityAnimation = SCNAction.fadeOpacity(to: CGFloat(OldValue), duration: 0.5)
self.runAction(OpacityAnimation)
}
else
{
self.opacity = OldValue
}
}
else
{
if Animate
{
let OpacityAnimation = SCNAction.fadeOpacity(to: CGFloat(IfEmpty), duration: 0.5)
self.runAction(OpacityAnimation)
}
else
{
self.opacity = CGFloat(IfEmpty)
}
}
}
for Child in self.childNodes
{
if let ActualChild = Child as? SCNNode2
{
ActualChild.PopOpacity(IfEmpty, Animate: Animate)
}
else
{
if Animate
{
let OpacityAnimation = SCNAction.fadeOpacity(to: CGFloat(IfEmpty), duration: 0.5)
Child.runAction(OpacityAnimation)
}
else
{
Child.opacity = CGFloat(IfEmpty)
}
}
}
}
/// Remove all entries in the opacity stack.
func ClearOpacityStack()
{
OpacityStack = Stack<CGFloat>()
}
var OpacityStack = Stack<CGFloat>()
// MARK: - Child management
/// Returns the total number of child nodes (must be of type `SCNNode2`) of the instance node.
func ChildCount() -> Int
{
var Count = 0
//Add grandchilden and lower.
for Child in childNodes
{
if let Child2 = Child as? SCNNode2
{
Count = Count + Child2.ChildCount()
}
}
//Add children.
Count = Count + childNodes.count
return Count
}
}
// MARK: - Bounding shapes.
/// Set of shapes for indicators for `SCNNode2` objects.
enum NodeBoundingShapes: String, CaseIterable
{
/// Indicator is a box.
case Box = "Box"
/// Indicator is a sphere.
case Sphere = "Sphere"
}
| 33.17364 | 112 | 0.552185 |
d9b119f2aa7410db01fa0566321ea44949d5caab | 984 | //
// XcodeBossTests.swift
// XcodeBossTests
//
// Created by Kim Ahlberg on 2017-05-14.
// Copyright © 2017 The Evil Boss. All rights reserved.
//
import XCTest
@testable import Comment_Boss
class XcodeBossTests: 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.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.594595 | 111 | 0.636179 |
eb7b121b707f04181f8614104ff3b011ac7bcca0 | 2,582 | // (c) 2017 Kajetan Michal Dabrowski
// This code is licensed under MIT license (see LICENSE for details)
import Vapor
import HTTP
/// This is the main class that you should be using to send notifications
public class Firebase {
/// The server key
internal let serverKey: ServerKey
private let serializer: MessageSerializer = MessageSerializer()
private let pushUrl: String = "https://fcm.googleapis.com/fcm/send"
private let requestAdapter: RequestAdapting
/// Convenience initializer taking a path to a file where the key is stored.
///
/// - Parameter drop: A droplet
/// - Parameter keyPath: Path to the Firebase Server Key
/// - Throws: Throws an error if file doesn't exist
public convenience init(drop: Droplet, keyPath: String) throws {
let keyBytes = try DataFile().read(at: keyPath)
guard let keyString = String(bytes: keyBytes, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) else {
throw FirebaseError.invalidServerKey
}
try self.init(drop: drop, serverKey: ServerKey(rawValue: keyString))
}
/// Initializes FCM with the key as the parameter. Please note that you should NOT store your server key in the source code and in your repository.
/// Instead, fetch your key from some configuration files, that are not stored in your repository.
///
/// - Parameter drop: A droplet
/// - Parameter serverKey: server key
public init(drop: Droplet, serverKey: ServerKey) throws {
self.requestAdapter = RequestAdapterVapor(droplet: drop)
self.serverKey = serverKey
}
/// Sends a single message to a single device. Returns parsed status response.
///
/// - Parameters:
/// - message: The message that you want to send
/// - target: Firebase Device Token or Topic that you want to send your message to
/// - Returns: Synchronous response
/// - Throws: Serialization error when the message could not be serialized
public func send(message: Message, to target: Targetable) throws -> FirebaseResponse {
let requestBytes: Bytes = try serializer.serialize(message: message, target: target)
do {
let response = try requestAdapter.send(bytes: requestBytes, headers: generateHeaders(), url: pushUrl)
return FirebaseResponse(bytes: response.body.bytes ?? [], statusCode: response.status.statusCode)
} catch {
return FirebaseResponse(error: error)
}
}
// MARK: Private methods
private func generateHeaders() -> [HeaderKey: String] {
return [
HeaderKey.contentType: "application/json",
HeaderKey.accept: "application/json",
HeaderKey.authorization: "key=\(serverKey.rawValue)"
]
}
}
| 37.42029 | 148 | 0.736251 |
ed655cdac4e07199e0a88eca55809ae074c990ca | 2,112 | //
// ItemTableViewCell.swift
// didactic-winner
//
// Created by Martin Mungai on 30/06/2021.
//
import Foundation
import UIKit
import RxSwift
import RxCocoa
class ItemTableViewCell: UITableViewCell {
// MARK: - Private Instance Properties
private let disposeBag = DisposeBag()
// MARK: - IB Outlets
@IBOutlet weak var cellImageView: UIImageView!
@IBOutlet weak var cellDetailLabel: UILabel!
@IBOutlet weak var cellTitleLabel: UILabel!
// MARK: - Overriden Instance Methods
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
APIClient.shared.isLoadingImage.asObservable().subscribe { event in
let isLoading = event.element ?? false
if isLoading {
self.cellImageView.addBlurView()
} else {
self.cellImageView.removeBlurView()
}
}.disposed(by: disposeBag)
}
override func prepareForReuse() {
super.prepareForReuse()
cellImageView.image = nil
}
// MARK: - IB Outlets
func populateData(item: Item) {
cellDetailLabel.text = item.detail
cellTitleLabel.text = item.title
guard let link = item.link else { return }
setImage(urlString: link)
}
// MARK: - Private Instance Methods
private func bindImageView(url: URL) {
APIClient.shared.fetchImage(url: url).subscribe { (event) in
guard let image = event.element?.image else { return }
DispatchQueue.main.async {
APIClient.shared.store.saveImage(image: image, url: url)
self.cellImageView.image = image
self.setNeedsLayout()
}
}.disposed(by: disposeBag)
}
private func setImage(urlString: String) {
guard let url = URL(string: urlString) else { return }
if let image = APIClient.shared.store.image(url: url) {
cellImageView.image = image
} else {
self.bindImageView(url: url)
}
}
}
| 28.16 | 75 | 0.596117 |
87027252300435320f101fd360c7d6db901f6d5b | 1,241 | //
// tippoUITests.swift
// tippoUITests
//
// Created by Agrawal, Ankur on 3/10/17.
// Copyright © 2017 Agrawal, Ankur. All rights reserved.
//
import XCTest
class tippoUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
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() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.540541 | 182 | 0.659952 |
7a36cf92249dc6e92eb820660b929746646b6909 | 1,247 | //
// ContainerViewController.swift
// DaCapo
//
// Created by Thomas Segkoulis on 12/11/16.
// Copyright © 2016 Thomas Segkoulis. All rights reserved.
//
import UIKit
class ContainerViewController: UIViewController
{
// MARK: - Subviews -
var playerView: PlayerView?
// MARK: - LifeCycle -
override func viewDidLoad()
{
super.viewDidLoad()
playerView = PlayerView.instanceFromNib() as? PlayerView
playerView?.delegate = self
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
playerView?.frame = CGRect.init(x: 0, y: 20, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 20)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// MARK: - Start Player -
func doStartVideo(forComposer composer: ComposerProtocol, forTrack track: ComposerSnippetTrackProtocol)
{
view.addSubview(playerView!)
playerView?.loadVideo(forComposer: composer, withTrack: track)
}
}
// MARK: - PlayerViewDelefate -
extension ContainerViewController: PlayerViewDelegate
{
func playerDidDismiss()
{
}
}
| 20.783333 | 129 | 0.65437 |
75982c689d5bdf634b75dc35dde0a8c6e768616d | 1,042 | //
// StringExTests.swift
// Wildlink-Unit-Tests
//
// Created by Kyle Kurz - Wildfire on 10/6/21.
//
import CommonCrypto
import Foundation
import XCTest
@testable import Wildlink
class StringExTests: XCTestCase {
func testStringFromResult() {
let string = "this is a long string to test"
let ptr = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: Int(CC_SHA256_DIGEST_LENGTH))
ptr.initialize(repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
for i in 0..<string.cString(using: .utf8)!.count {
ptr[i] = CUnsignedChar(string.cString(using: .utf8)![i])
}
let result = String.stringFrom(ptr, with: Int(CC_SHA256_DIGEST_LENGTH))
XCTAssertEqual(result, "746869732069732061206c6f6e6720737472696e6720746f2074657374000000")
}
func testDigestHMac256() {
let encoded = "abcdef".digestHMac256(key: "12345")
XCTAssertNotNil(encoded)
XCTAssertEqual(encoded, "b00b5b769a95a266310c071c4588687e4296d479f131827bfc59a04f771e2f0d")
}
}
| 33.612903 | 102 | 0.705374 |
16411dd2ed5aaf91730baab81b5ddc32a2ad4129 | 8,429 | //
// ScriptFactory.swift
//
// Copyright © 2018 BitcoinKit developers
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public struct ScriptFactory {
// Basic
public struct Standard {}
public struct LockTime {}
public struct MultiSig {}
public struct OpReturn {}
public struct Condition {}
// Contract
public struct HashedTimeLockedContract {}
}
// MARK: - Standard
public extension ScriptFactory.Standard {
static func buildP2PK(publickey: PublicKey) -> Script? {
return try? Script()
.appendData(publickey.toDer())
.append(.OP_CHECKSIG)
}
// static func buildP2PKH(address: Address) -> Script? {
// return Script(address: address)
// }
static func buildP2SH(script: Script) -> Script {
return script.toP2SH()
}
static func buildMultiSig(publicKeys: [PublicKey]) -> Script? {
return Script(publicKeys: publicKeys, signaturesRequired: UInt(publicKeys.count))
}
static func buildMultiSig(publicKeys: [PublicKey], signaturesRequired: UInt) -> Script? {
return Script(publicKeys: publicKeys, signaturesRequired: signaturesRequired)
}
}
// MARK: - LockTime
public extension ScriptFactory.LockTime {
// Base
static func build(script: Script, lockDate: Date) -> Script? {
return try? Script()
.appendData(lockDate.bigNumData)
.append(.OP_CHECKLOCKTIMEVERIFY)
.append(.OP_DROP)
.appendScript(script)
}
static func build(script: Script, lockIntervalSinceNow: TimeInterval) -> Script? {
let lockDate = Date(timeIntervalSinceNow: lockIntervalSinceNow)
return build(script: script, lockDate: lockDate)
}
// P2PKH + LockTime
// static func build(address: Address, lockIntervalSinceNow: TimeInterval) -> Script? {
// guard let p2pkh = Script(address: address) else {
// return nil
// }
// let lockDate = Date(timeIntervalSinceNow: lockIntervalSinceNow)
// return build(script: p2pkh, lockDate: lockDate)
// }
//
// static func build(address: Address, lockDate: Date) -> Script? {
// guard let p2pkh = Script(address: address) else {
// return nil
// }
// return build(script: p2pkh, lockDate: lockDate)
// }
}
// MARK: - OpReturn
public extension ScriptFactory.OpReturn {
static func build(text: String) -> Script? {
let MAX_OP_RETURN_DATA_SIZE: Int = 220
guard let data = text.data(using: .utf8), data.count <= MAX_OP_RETURN_DATA_SIZE else {
return nil
}
return try? Script()
.append(.OP_RETURN)
.appendData(data)
}
}
// MARK: - Condition
public extension ScriptFactory.Condition {
static func build(scripts: [Script]) -> Script? {
guard !scripts.isEmpty else {
return nil
}
guard scripts.count > 1 else {
return scripts[0]
}
var scripts: [Script] = scripts
while scripts.count > 1 {
var newScripts: [Script] = []
while !scripts.isEmpty {
let script = Script()
do {
if scripts.count == 1 {
try script
.append(.OP_DROP)
.appendScript(scripts.removeFirst())
} else {
try script
.append(.OP_IF)
.appendScript(scripts.removeFirst())
.append(.OP_ELSE)
.appendScript(scripts.removeFirst())
.append(.OP_ENDIF)
}
} catch {
return nil
}
newScripts.append(script)
}
scripts = newScripts
}
return scripts[0]
}
}
// MARK: - HTLC
/*
OP_IF
[HASHOP] <digest> OP_EQUALVERIFY OP_DUP OP_HASH160 <recipient pubkey hash>
OP_ELSE
<num> [TIMEOUTOP] OP_DROP OP_DUP OP_HASH160 <sender pubkey hash>
OP_ENDIF
OP_EQUALVERIFYs
OP_CHECKSIG
*/
public extension ScriptFactory.HashedTimeLockedContract {
// Base
// static func build(recipient: Address, sender: Address, lockDate: Date, hash: Data, hashOp: HashOperator) -> Script? {
// guard hash.count == hashOp.hashSize else {
// return nil
// }
//
// return try? Script()
// .append(.OP_IF)
// .append(hashOp.opcode)
// .appendData(hash)
// .append(.OP_EQUALVERIFY)
// .append(.OP_DUP)
// .append(.OP_HASH160)
// .appendData(recipient.data)
// .append(.OP_ELSE)
// .appendData(lockDate.bigNumData)
// .append(.OP_CHECKLOCKTIMEVERIFY)
// .append(.OP_DROP)
// .append(.OP_DUP)
// .append(.OP_HASH160)
// .appendData(sender.data)
// .append(.OP_ENDIF)
// .append(.OP_EQUALVERIFY)
// .append(.OP_CHECKSIG)
// }
// convenience
// static func build(recipient: Address, sender: Address, lockIntervalSinceNow: TimeInterval, hash: Data, hashOp: HashOperator) -> Script? {
// let lockDate = Date(timeIntervalSinceNow: lockIntervalSinceNow)
// return build(recipient: recipient, sender: sender, lockDate: lockDate, hash: hash, hashOp: hashOp)
// }
//
// static func build(recipient: Address, sender: Address, lockIntervalSinceNow: TimeInterval, secret: Data, hashOp: HashOperator) -> Script? {
// let hash = hashOp.hash(secret)
// let lockDate = Date(timeIntervalSinceNow: lockIntervalSinceNow)
// return build(recipient: recipient, sender: sender, lockDate: lockDate, hash: hash, hashOp: hashOp)
// }
//
// static func build(recipient: Address, sender: Address, lockDate: Date, secret: Data, hashOp: HashOperator) -> Script? {
// let hash = hashOp.hash(secret)
// return build(recipient: recipient, sender: sender, lockDate: lockDate, hash: hash, hashOp: hashOp)
// }
}
public class HashOperator {
public static let SHA256: HashOperator = HashOperatorSha256()
public static let HASH160: HashOperator = HashOperatorHash160()
public var opcode: OpCode { return .OP_INVALIDOPCODE }
public var hashSize: Int { return 0 }
public func hash(_ data: Data) -> Data { return Data() }
fileprivate init() {}
}
final public class HashOperatorSha256: HashOperator {
override public var opcode: OpCode { return .OP_SHA256 }
override public var hashSize: Int { return 32 }
override public func hash(_ data: Data) -> Data {
return Crypto.sha256(data)
}
}
final public class HashOperatorHash160: HashOperator {
override public var opcode: OpCode { return .OP_HASH160 }
override public var hashSize: Int { return 20 }
override public func hash(_ data: Data) -> Data {
return Crypto.sha256ripemd160(data)
}
}
// MARK: - Utility Extension
private extension Date {
var bigNumData: Data {
let dateUnix: TimeInterval = timeIntervalSince1970
let bn = BInt(Int32(dateUnix).littleEndian)
// let bn = BigNumber(Int32(dateUnix).littleEndian)
return bn.data
}
}
| 34.545082 | 145 | 0.616918 |
ef64189027e82ad4c9698f4b2db204ce1c5640cb | 1,161 | //
// ViewController.swift
// TipCalculator
//
// Created by Ka Lee on 8/30/18.
// Copyright © 2018 Ka Lee. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func OnTap(_ sender: Any) {
view.endEditing(true)
}
@IBAction func calculateTip(_ sender: Any) {
let tipPercentage = [0.18, 0.2, 0.25]
let bill = Double(billField.text!) ?? 0
let tip = bill * tipPercentage[tipControl.selectedSegmentIndex]
let total = bill + tip
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
}
}
| 25.8 | 80 | 0.62963 |
2fd336030a7da4a9742df3db7a6691b3d516a2f6 | 794 | //
// CTMediator+CloudVillage.swift
// SFCloudMusic
//
// Created by Alex.Shen on 2/27/20.
// Copyright © 2020 沈海超. All rights reserved.
//
import CTMediator
private let cloudVillageKitName = "SFCloudMusic"//"SFCloudMusicCloudVillageKit"
private let cloudVillageTargetName = "CloudVillage"
private let cloudVillageViewControllerActionName = "cloudVillageViewController"
public extension CTMediator {
func cloudVillageViewController() -> UIViewController? {
let params = [kCTMediatorParamsKeySwiftTargetModuleName:cloudVillageKitName] as [AnyHashable:Any]
let viewController = self.performTarget(cloudVillageTargetName, action: cloudVillageViewControllerActionName, params: params, shouldCacheTarget: false) as? UIViewController
return viewController
}
}
| 36.090909 | 181 | 0.783375 |
ef46ce9c01d2e5716e3b92af79eaa113ad766bb1 | 15,900 | //===--- DictTest.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let Dictionary = [
BenchmarkInfo(name: "Dictionary", runFunction: run_Dictionary, tags: [.validation, .api, .Dictionary]),
BenchmarkInfo(name: "DictionaryOfObjects", runFunction: run_DictionaryOfObjects, tags: [.validation, .api, .Dictionary]),
]
@inline(never)
public func run_Dictionary(scale: Int) {
let Input = [
// Text from http://en.wikipedia.org/wiki/Hash_table
"hash", "table",
"in", "computing", "a", "hash", "table", "also", "hash", "map", "is",
"a", "data", "structure", "used", "to", "implement", "an", "associative",
"array", "a", "structure", "that", "can", "map", "keys", "to", "values",
"a", "hash", "table", "uses", "a", "hash", "function", "to", "compute",
"an", "index", "into", "an", "array", "of", "buckets", "or", "slots",
"from", "which", "the", "correct", "value", "can", "be", "found",
"ideally", "the", "hash", "function", "will", "assign", "each", "key",
"to", "a", "unique", "bucket", "but", "this", "situation", "is",
"rarely", "achievable", "in", "practice", "usually", "some", "keys",
"will", "hash", "to", "the", "same", "bucket", "instead", "most", "hash",
"table", "designs", "assume", "that", "hash", "collisions", "different",
"keys", "that", "are", "assigned", "by", "the", "hash", "function", "to",
"the", "same", "bucket", "will", "occur", "and", "must", "be",
"accommodated", "in", "some", "way", "in", "a", "well", "dimensioned",
"hash", "table", "the", "average", "cost", "number", "of",
"instructions", "for", "each", "lookup", "is", "independent", "of",
"the", "number", "of", "elements", "stored", "in", "the", "table",
"many", "hash", "table", "designs", "also", "allow", "arbitrary",
"insertions", "and", "deletions", "of", "key", "value", "pairs", "at",
"amortized", "constant", "average", "cost", "per", "operation", "in",
"many", "situations", "hash", "tables", "turn", "out", "to", "be",
"more", "efficient", "than", "search", "trees", "or", "any", "other",
"table", "lookup", "structure", "for", "this", "reason", "they", "are",
"widely", "used", "in", "many", "kinds", "of", "computer", "software",
"particularly", "for", "associative", "arrays", "database", "indexing",
"caches", "and", "sets",
"hashing",
"the", "idea", "of", "hashing", "is", "to", "distribute", "the",
"entries", "key", "value", "pairs", "across", "an", "array", "of",
"buckets", "given", "a", "key", "the", "algorithm", "computes", "an",
"index", "that", "suggests", "where", "the", "entry", "can", "be",
"found", "index", "f", "key", "array", "size", "often", "this", "is",
"done", "in", "two", "steps", "hash", "hashfunc", "key", "index", "hash",
"array", "size", "in", "this", "method", "the", "hash", "is",
"independent", "of", "the", "array", "size", "and", "it", "is", "then",
"reduced", "to", "an", "index", "a", "number", "between", "and", "array",
"size", "using", "the", "modulus", "operator", "in", "the", "case",
"that", "the", "array", "size", "is", "a", "power", "of", "two", "the",
"remainder", "operation", "is", "reduced", "to", "masking", "which",
"improves", "speed", "but", "can", "increase", "problems", "with", "a",
"poor", "hash", "function",
"choosing", "a", "good", "hash", "function",
"a", "good", "hash", "function", "and", "implementation", "algorithm",
"are", "essential", "for", "good", "hash", "table", "performance", "but",
"may", "be", "difficult", "to", "achieve", "a", "basic", "requirement",
"is", "that", "the", "function", "should", "provide", "a", "uniform",
"distribution", "of", "hash", "values", "a", "non", "uniform",
"distribution", "increases", "the", "number", "of", "collisions", "and",
"the", "cost", "of", "resolving", "them", "uniformity", "is",
"sometimes", "difficult", "to", "ensure", "by", "design", "but", "may",
"be", "evaluated", "empirically", "using", "statistical", "tests", "e",
"g", "a", "pearson", "s", "chi", "squared", "test", "for", "discrete",
"uniform", "distributions", "the", "distribution", "needs", "to", "be",
"uniform", "only", "for", "table", "sizes", "that", "occur", "in", "the",
"application", "in", "particular", "if", "one", "uses", "dynamic",
"resizing", "with", "exact", "doubling", "and", "halving", "of", "the",
"table", "size", "s", "then", "the", "hash", "function", "needs", "to",
"be", "uniform", "only", "when", "s", "is", "a", "power", "of", "two",
"on", "the", "other", "hand", "some", "hashing", "algorithms", "provide",
"uniform", "hashes", "only", "when", "s", "is", "a", "prime", "number",
"for", "open", "addressing", "schemes", "the", "hash", "function",
"should", "also", "avoid", "clustering", "the", "mapping", "of", "two",
"or", "more", "keys", "to", "consecutive", "slots", "such", "clustering",
"may", "cause", "the", "lookup", "cost", "to", "skyrocket", "even", "if",
"the", "load", "factor", "is", "low", "and", "collisions", "are",
"infrequent", "the", "popular", "multiplicative", "hash", "3", "is",
"claimed", "to", "have", "particularly", "poor", "clustering",
"behavior", "cryptographic", "hash", "functions", "are", "believed",
"to", "provide", "good", "hash", "functions", "for", "any", "table",
"size", "s", "either", "by", "modulo", "reduction", "or", "by", "bit",
"masking", "they", "may", "also", "be", "appropriate", "if", "there",
"is", "a", "risk", "of", "malicious", "users", "trying", "to",
"sabotage", "a", "network", "service", "by", "submitting", "requests",
"designed", "to", "generate", "a", "large", "number", "of", "collisions",
"in", "the", "server", "s", "hash", "tables", "however", "the", "risk",
"of", "sabotage", "can", "also", "be", "avoided", "by", "cheaper",
"methods", "such", "as", "applying", "a", "secret", "salt", "to", "the",
"data", "or", "using", "a", "universal", "hash", "function",
"perfect", "hash", "function",
"if", "all", "keys", "are", "known", "ahead", "of", "time", "a",
"perfect", "hash", "function", "can", "be", "used", "to", "create", "a",
"perfect", "hash", "table", "that", "has", "no", "collisions", "if",
"minimal", "perfect", "hashing", "is", "used", "every", "location", "in",
"the", "hash", "table", "can", "be", "used", "as", "well", "perfect",
"hashing", "allows", "for", "constant", "time", "lookups", "in", "the",
"worst", "case", "this", "is", "in", "contrast", "to", "most",
"chaining", "and", "open", "addressing", "methods", "where", "the",
"time", "for", "lookup", "is", "low", "on", "average", "but", "may",
"be", "very", "large", "proportional", "to", "the", "number", "of",
"entries", "for", "some", "sets", "of", "keys"
]
var Dict: Dictionary<String, Bool> = [:]
let N = 5*scale
// Check performance of filling the dictionary:
for _ in 1...N {
Dict = [:]
for word in Input {
Dict[word] = true
}
}
CheckResults(Dict.count == 270)
// Check performance of searching in the dictionary:
// Fill the dictionary with words from the first half of the text
Dict = [:]
for i in 0 ..< Input.count/2 {
let word = Input[i]
Dict[word] = true
}
// Count number of words from the first half in the entire text
var count = 0
for _ in 1...N {
for word in Input {
if Dict[word] != nil {
count += 1
}
}
}
CheckResults(count == N*541)
}
class Box<T : Hashable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
var hashValue: Int {
return value.hashValue
}
static func ==(lhs: Box, rhs: Box) -> Bool {
return lhs.value == rhs.value
}
}
@inline(never)
public func run_DictionaryOfObjects(scale: Int) {
let Input = [
// Text from http://en.wikipedia.org/wiki/Hash_table
"hash", "table",
"in", "computing", "a", "hash", "table", "also", "hash", "map", "is",
"a", "data", "structure", "used", "to", "implement", "an", "associative",
"array", "a", "structure", "that", "can", "map", "keys", "to", "values",
"a", "hash", "table", "uses", "a", "hash", "function", "to", "compute",
"an", "index", "into", "an", "array", "of", "buckets", "or", "slots",
"from", "which", "the", "correct", "value", "can", "be", "found",
"ideally", "the", "hash", "function", "will", "assign", "each", "key",
"to", "a", "unique", "bucket", "but", "this", "situation", "is",
"rarely", "achievable", "in", "practice", "usually", "some", "keys",
"will", "hash", "to", "the", "same", "bucket", "instead", "most", "hash",
"table", "designs", "assume", "that", "hash", "collisions", "different",
"keys", "that", "are", "assigned", "by", "the", "hash", "function", "to",
"the", "same", "bucket", "will", "occur", "and", "must", "be",
"accommodated", "in", "some", "way", "in", "a", "well", "dimensioned",
"hash", "table", "the", "average", "cost", "number", "of",
"instructions", "for", "each", "lookup", "is", "independent", "of",
"the", "number", "of", "elements", "stored", "in", "the", "table",
"many", "hash", "table", "designs", "also", "allow", "arbitrary",
"insertions", "and", "deletions", "of", "key", "value", "pairs", "at",
"amortized", "constant", "average", "cost", "per", "operation", "in",
"many", "situations", "hash", "tables", "turn", "out", "to", "be",
"more", "efficient", "than", "search", "trees", "or", "any", "other",
"table", "lookup", "structure", "for", "this", "reason", "they", "are",
"widely", "used", "in", "many", "kinds", "of", "computer", "software",
"particularly", "for", "associative", "arrays", "database", "indexing",
"caches", "and", "sets",
"hashing",
"the", "idea", "of", "hashing", "is", "to", "distribute", "the",
"entries", "key", "value", "pairs", "across", "an", "array", "of",
"buckets", "given", "a", "key", "the", "algorithm", "computes", "an",
"index", "that", "suggests", "where", "the", "entry", "can", "be",
"found", "index", "f", "key", "array", "size", "often", "this", "is",
"done", "in", "two", "steps", "hash", "hashfunc", "key", "index", "hash",
"array", "size", "in", "this", "method", "the", "hash", "is",
"independent", "of", "the", "array", "size", "and", "it", "is", "then",
"reduced", "to", "an", "index", "a", "number", "between", "and", "array",
"size", "using", "the", "modulus", "operator", "in", "the", "case",
"that", "the", "array", "size", "is", "a", "power", "of", "two", "the",
"remainder", "operation", "is", "reduced", "to", "masking", "which",
"improves", "speed", "but", "can", "increase", "problems", "with", "a",
"poor", "hash", "function",
"choosing", "a", "good", "hash", "function",
"a", "good", "hash", "function", "and", "implementation", "algorithm",
"are", "essential", "for", "good", "hash", "table", "performance", "but",
"may", "be", "difficult", "to", "achieve", "a", "basic", "requirement",
"is", "that", "the", "function", "should", "provide", "a", "uniform",
"distribution", "of", "hash", "values", "a", "non", "uniform",
"distribution", "increases", "the", "number", "of", "collisions", "and",
"the", "cost", "of", "resolving", "them", "uniformity", "is",
"sometimes", "difficult", "to", "ensure", "by", "design", "but", "may",
"be", "evaluated", "empirically", "using", "statistical", "tests", "e",
"g", "a", "pearson", "s", "chi", "squared", "test", "for", "discrete",
"uniform", "distributions", "the", "distribution", "needs", "to", "be",
"uniform", "only", "for", "table", "sizes", "that", "occur", "in", "the",
"application", "in", "particular", "if", "one", "uses", "dynamic",
"resizing", "with", "exact", "doubling", "and", "halving", "of", "the",
"table", "size", "s", "then", "the", "hash", "function", "needs", "to",
"be", "uniform", "only", "when", "s", "is", "a", "power", "of", "two",
"on", "the", "other", "hand", "some", "hashing", "algorithms", "provide",
"uniform", "hashes", "only", "when", "s", "is", "a", "prime", "number",
"for", "open", "addressing", "schemes", "the", "hash", "function",
"should", "also", "avoid", "clustering", "the", "mapping", "of", "two",
"or", "more", "keys", "to", "consecutive", "slots", "such", "clustering",
"may", "cause", "the", "lookup", "cost", "to", "skyrocket", "even", "if",
"the", "load", "factor", "is", "low", "and", "collisions", "are",
"infrequent", "the", "popular", "multiplicative", "hash", "3", "is",
"claimed", "to", "have", "particularly", "poor", "clustering",
"behavior", "cryptographic", "hash", "functions", "are", "believed",
"to", "provide", "good", "hash", "functions", "for", "any", "table",
"size", "s", "either", "by", "modulo", "reduction", "or", "by", "bit",
"masking", "they", "may", "also", "be", "appropriate", "if", "there",
"is", "a", "risk", "of", "malicious", "users", "trying", "to",
"sabotage", "a", "network", "service", "by", "submitting", "requests",
"designed", "to", "generate", "a", "large", "number", "of", "collisions",
"in", "the", "server", "s", "hash", "tables", "however", "the", "risk",
"of", "sabotage", "can", "also", "be", "avoided", "by", "cheaper",
"methods", "such", "as", "applying", "a", "secret", "salt", "to", "the",
"data", "or", "using", "a", "universal", "hash", "function",
"perfect", "hash", "function",
"if", "all", "keys", "are", "known", "ahead", "of", "time", "a",
"perfect", "hash", "function", "can", "be", "used", "to", "create", "a",
"perfect", "hash", "table", "that", "has", "no", "collisions", "if",
"minimal", "perfect", "hashing", "is", "used", "every", "location", "in",
"the", "hash", "table", "can", "be", "used", "as", "well", "perfect",
"hashing", "allows", "for", "constant", "time", "lookups", "in", "the",
"worst", "case", "this", "is", "in", "contrast", "to", "most",
"chaining", "and", "open", "addressing", "methods", "where", "the",
"time", "for", "lookup", "is", "low", "on", "average", "but", "may",
"be", "very", "large", "proportional", "to", "the", "number", "of",
"entries", "for", "some", "sets", "of", "keys"
]
var Dict: Dictionary<Box<String>, Box<Bool>> = [:]
let N = 5*scale
// Check performance of filling the dictionary:
for _ in 1...N {
Dict = [:]
for word in Input {
Dict[Box(word)] = Box(true)
}
}
CheckResults(Dict.count == 270)
// Check performance of searching in the dictionary:
// Fill the dictionary with words from the first half of the text
Dict = [:]
for i in 0 ..< Input.count/2 {
let word = Input[i]
Dict[Box(word)] = Box(true)
}
// Count number of words from the first half in the entire text
var count = 0
for _ in 1...N {
for word in Input {
if Dict[Box(word)] != nil {
count += 1
}
}
}
CheckResults(count == N*541)
}
| 53 | 123 | 0.513711 |
4bc837bbddb0e6a97cc05fa4a6cde45f0a966580 | 679 | //
// UITestMessage.swift
// AndesUI - UITests
//
// Created by Nicolas Rostan Talasimov on 4/28/20.
// Copyright © 2020 MercadoLibre. All rights reserved.
//
import XCTest
class AndesUI_UITestsMessage: XCTestCase {
let app = XCUIApplication()
override func setUp() {
super.setUp()
app.launchArguments = ["UITesting"]
setupSnapshot(app)
app.launch()
}
override func tearDown() {
super.tearDown()
}
func testMessageScreen() {
app.buttons["andesMessages"].tap()
app.swipeLeft()
snapshot("Message 1")
app.swipeUp()
snapshot("Message 3")
app.swipeDown()
}
}
| 19.970588 | 55 | 0.599411 |
3a37ef979be7439e19063d9a4ae0cabe96b0d4b2 | 5,296 | //
// TestVideoViewController.swift
// flash
//
// Created by Songwut Maneefun on 16/6/2564 BE.
//
import UIKit
import AVKit
class TestVideoViewController: UIViewController {
var importBtn:UIButton!
var playerView: UIView!
var gifView: UIView!
var playerLayer: AVPlayerLayer!
var player: AVPlayer!
var playerItem: AVPlayerItem!
var textView = UITextView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.playerView = UIView()
self.playerView.frame = self.view.frame
self.view.addSubview(self.playerView)
self.gifView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
self.gifView.center = self.view.center
let gif = GIF()
gif.view = self.gifView
//https://media.giphy.com/media/9aq5HD3izQNbDadBB1/giphy.gif
//https://media.giphy.com/media/kEdI683LJtrGmTVVCM/giphy.gif
let gifUrl = URL(string: "https://media.giphy.com/media/kEdI683LJtrGmTVVCM/giphy.gif")
gif.startGifAnimation(with: gifUrl, in: self.gifView.layer)
self.view.addSubview(self.gifView)
//self.gifView.frame
self.player = AVPlayer()
self.playerLayer = AVPlayerLayer(player: self.player)
self.playerView!.layer.addSublayer(self.playerLayer!)
self.importBtn = UIButton(type: .custom)
self.importBtn.frame = CGRect(x: 0, y: 0, width: 100, height: 50)
self.importBtn.setTitle("import", for: .normal)
self.importBtn.center = self.view.center
self.importBtn.addTarget(self, action: #selector(self.importPressed), for: .touchUpInside)
self.view.addSubview(self.importBtn)
self.textView = UITextView()
//self.textView.add
self.textView.text = gifUrl?.absoluteString
self.textView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 60)
}
func play(_ videoURL: URL) {
NotificationCenter.default.addObserver(self, selector: #selector(self.playerItemDidReachEnd(notification:)), name: .AVPlayerItemDidPlayToEndTime, object: nil)
self.playerItem = AVPlayerItem(url: videoURL)
self.player.replaceCurrentItem(with: self.playerItem)
DispatchQueue.main.async {
self.playerLayer!.frame = self.view!.bounds
}
self.player.play()
}
// Notification Handling
@objc func playerItemDidReachEnd(notification: NSNotification) {
player.seek(to: CMTime.zero)
player.play()
}
// Remove Observer
deinit {
NotificationCenter.default.removeObserver(self)
}
func trimVideo(_ videoUrl: URL, complete: @escaping (_ url: URL) -> Void) {
let sourceURL = videoUrl
/*
if let destinationURL = destinationUrl() {
do {
try time {
let asset = AVURLAsset(url: sourceURL)
let trimmedAsset = try asset.assetByTrimming(seconds: 1.0)
try trimmedAsset.export(to: destinationURL) {
complete(destinationURL)
}
}
} catch let error {
print("💩 \(error)")
}
}
*/
}
func destinationUrl() -> URL? {
guard
let documentDirectory = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask).first
else { return nil }
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .short
let date = dateFormatter.string(from: Date())
let url = documentDirectory.appendingPathComponent("mergeVideo-\(date).mp4")
return url
}
@objc @IBAction func importPressed() {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary) ?? []
picker.mediaTypes = ["public.movie"]
picker.videoQuality = .typeHigh
picker.videoExportPreset = AVAssetExportPresetHEVC1920x1080
//picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}
func time(_ operation: () throws -> ()) rethrows {
let start = Date()
try operation()
let end = Date().timeIntervalSince(start)
print(end)
}
}
extension TestVideoViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true, completion: nil)
guard let movieUrl = info[.mediaURL] as? URL else { return }
self.trimVideo(movieUrl) { [weak self] (destinationURL) in
self?.play(destinationURL)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
| 33.732484 | 166 | 0.615559 |
48adb59ccb46322a73526d618d50da2a54f384fa | 10,584 | //
// UIView+GestureClosure.swift
// XFBConsumer
//
// Created by hy110831 on 3/31/16.
// Copyright © 2016 hy110831. All rights reserved.
//
import UIKit
extension UIView {
typealias TapResponseClosure = (_ tap: UITapGestureRecognizer) -> Void
typealias PanResponseClosure = (_ pan: UIPanGestureRecognizer) -> Void
typealias SwipeResponseClosure = (_ swipe: UISwipeGestureRecognizer) -> Void
typealias PinchResponseClosure = (_ pinch: UIPinchGestureRecognizer) -> Void
typealias LongPressResponseClosure = (_ longPress: UILongPressGestureRecognizer) -> Void
typealias RotationResponseClosure = (_ rotation: UIRotationGestureRecognizer) -> Void
fileprivate struct ClosureStorage {
static var TapClosureStorage: [UITapGestureRecognizer : TapResponseClosure] = [:]
static var PanClosureStorage: [UIPanGestureRecognizer : PanResponseClosure] = [:]
static var SwipeClosureStorage: [UISwipeGestureRecognizer : SwipeResponseClosure] = [:]
static var PinchClosureStorage: [UIPinchGestureRecognizer : PinchResponseClosure] = [:]
static var LongPressClosureStorage: [UILongPressGestureRecognizer: LongPressResponseClosure] = [:]
static var RotationClosureStorage: [UIRotationGestureRecognizer: RotationResponseClosure] = [:]
}
fileprivate struct Swizzler {
fileprivate static var __once: () = {
let UIViewClass: AnyClass! = NSClassFromString("UIView")
let originalSelector = #selector(UIView.removeFromSuperview)
let swizzleSelector = #selector(UIView.swizzled_removeFromSuperview)
let original: Method = class_getInstanceMethod(UIViewClass, originalSelector)
let swizzle: Method = class_getInstanceMethod(UIViewClass, swizzleSelector)
method_exchangeImplementations(original, swizzle)
}()
fileprivate static var OnceToken : Int = 0
static func Swizzle() {
_ = Swizzler.__once
}
}
func swizzled_removeFromSuperview() {
self.removeGestureRecognizersFromStorage()
/*
Will call the original representation of removeFromSuperview, not endless cycle:
http://darkdust.net/writings/objective-c/method-swizzling
*/
self.swizzled_removeFromSuperview()
}
func removeGestureRecognizersFromStorage() {
if let gestureRecognizers = self.gestureRecognizers {
for recognizer: UIGestureRecognizer in gestureRecognizers as [UIGestureRecognizer] {
if let tap = recognizer as? UITapGestureRecognizer {
self.removeGestureRecognizer(tap)
ClosureStorage.TapClosureStorage[tap] = nil
}
else if let pan = recognizer as? UIPanGestureRecognizer {
ClosureStorage.PanClosureStorage[pan] = nil
}
else if let swipe = recognizer as? UISwipeGestureRecognizer {
ClosureStorage.SwipeClosureStorage[swipe] = nil
}
else if let pinch = recognizer as? UIPinchGestureRecognizer {
ClosureStorage.PinchClosureStorage[pinch] = nil
}
else if let rotation = recognizer as? UIRotationGestureRecognizer {
ClosureStorage.RotationClosureStorage[rotation] = nil
}
else if let longPress = recognizer as? UILongPressGestureRecognizer {
ClosureStorage.LongPressClosureStorage[longPress] = nil
}
}
}
}
// MARK: Taps
func addSingleTapGestureRecognizerWithResponder(_ responder: @escaping TapResponseClosure) {
self.addTapGestureRecognizerForNumberOfTaps(withResponder: responder)
}
func addDoubleTapGestureRecognizerWithResponder(_ responder: @escaping TapResponseClosure) {
self.addTapGestureRecognizerForNumberOfTaps(2, withResponder: responder)
}
func addTapGestureRecognizerForNumberOfTaps(_ numberOfTaps: Int = 1, numberOfTouches: Int = 1, withResponder responder: @escaping TapResponseClosure) {
let tap = UITapGestureRecognizer()
tap.numberOfTapsRequired = numberOfTaps
tap.numberOfTouchesRequired = numberOfTouches
tap.addTarget(self, action: #selector(UIView.handleTap(_:)))
self.addGestureRecognizer(tap)
ClosureStorage.TapClosureStorage[tap] = responder
Swizzler.Swizzle()
}
func handleTap(_ sender: UITapGestureRecognizer) {
if let closureForTap = ClosureStorage.TapClosureStorage[sender] {
closureForTap(sender)
}
}
// MARK: Pans
func addSingleTouchPanGestureRecognizerWithResponder(_ responder: @escaping PanResponseClosure) {
self.addPanGestureRecognizerForNumberOfTouches(1, withResponder: responder)
}
func addDoubleTouchPanGestureRecognizerWithResponder(_ responder: @escaping PanResponseClosure) {
self.addPanGestureRecognizerForNumberOfTouches(2, withResponder: responder)
}
func addPanGestureRecognizerForNumberOfTouches(_ numberOfTouches: Int, withResponder responder: @escaping PanResponseClosure) {
let pan = UIPanGestureRecognizer()
pan.minimumNumberOfTouches = numberOfTouches
pan.addTarget(self, action: #selector(UIView.handlePan(_:)))
self.addGestureRecognizer(pan)
ClosureStorage.PanClosureStorage[pan] = responder
Swizzler.Swizzle()
}
func handlePan(_ sender: UIPanGestureRecognizer) {
if let closureForPan = ClosureStorage.PanClosureStorage[sender] {
closureForPan(sender)
}
}
// MARK: Swipes
func addLeftSwipeGestureRecognizerWithResponder(_ responder: @escaping SwipeResponseClosure) {
self.addLeftSwipeGestureRecognizerForNumberOfTouches(1, withResponder: responder)
}
func addLeftSwipeGestureRecognizerForNumberOfTouches(_ numberOfTouches: Int, withResponder responder: @escaping SwipeResponseClosure) {
self.addSwipeGestureRecognizerForNumberOfTouches(numberOfTouches, forSwipeDirection: .left, withResponder: responder)
}
func addRightSwipeGestureRecognizerWithResponder(_ responder: @escaping SwipeResponseClosure) {
self.addRightSwipeGestureRecognizerForNumberOfTouches(1, withResponder: responder)
}
func addRightSwipeGestureRecognizerForNumberOfTouches(_ numberOfTouches: Int, withResponder responder: @escaping SwipeResponseClosure) {
self.addSwipeGestureRecognizerForNumberOfTouches(numberOfTouches, forSwipeDirection: .right, withResponder: responder)
}
func addUpSwipeGestureRecognizerWithResponder(_ responder: @escaping SwipeResponseClosure) {
self.addUpSwipeGestureRecognizerForNumberOfTouches(1, withResponder: responder)
}
func addUpSwipeGestureRecognizerForNumberOfTouches(_ numberOfTouches: Int, withResponder responder: @escaping SwipeResponseClosure) {
self.addSwipeGestureRecognizerForNumberOfTouches(numberOfTouches, forSwipeDirection: .up, withResponder: responder)
}
func addDownSwipeGestureRecognizerWithResponder(_ responder: @escaping SwipeResponseClosure) {
self.addDownSwipeGestureRecognizerForNumberOfTouches(1, withResponder: responder)
}
func addDownSwipeGestureRecognizerForNumberOfTouches(_ numberOfTouches: Int, withResponder responder: @escaping SwipeResponseClosure) {
self.addSwipeGestureRecognizerForNumberOfTouches(numberOfTouches, forSwipeDirection: .down, withResponder: responder)
}
func addSwipeGestureRecognizerForNumberOfTouches(_ numberOfTouches: Int, forSwipeDirection swipeDirection: UISwipeGestureRecognizerDirection, withResponder responder: @escaping SwipeResponseClosure) {
let swipe = UISwipeGestureRecognizer()
swipe.direction = swipeDirection
swipe.numberOfTouchesRequired = numberOfTouches
swipe.addTarget(self, action: #selector(UIView.handleSwipe(_:)))
self.addGestureRecognizer(swipe)
ClosureStorage.SwipeClosureStorage[swipe] = responder
Swizzler.Swizzle()
}
func handleSwipe(_ sender: UISwipeGestureRecognizer) {
if let closureForSwipe = ClosureStorage.SwipeClosureStorage[sender] {
closureForSwipe(sender)
}
}
// MARK: Pinches
func addPinchGestureRecognizerWithResponder(_ responder: @escaping PinchResponseClosure) {
let pinch = UIPinchGestureRecognizer()
pinch.addTarget(self, action: #selector(UIView.handlePinch(_:)))
self.addGestureRecognizer(pinch)
ClosureStorage.PinchClosureStorage[pinch] = responder
Swizzler.Swizzle()
}
func handlePinch(_ sender: UIPinchGestureRecognizer) {
if let closureForPinch = ClosureStorage.PinchClosureStorage[sender] {
closureForPinch(sender)
}
}
// MARK: LongPress
func addLongPressGestureRecognizerWithResponder(_ responder: @escaping LongPressResponseClosure) {
self.addLongPressGestureRecognizerForNumberOfTouches(1, withResponder: responder)
}
func addLongPressGestureRecognizerForNumberOfTouches(_ numberOfTouches: Int, withResponder responder: @escaping LongPressResponseClosure) {
let longPress = UILongPressGestureRecognizer()
longPress.numberOfTouchesRequired = numberOfTouches
longPress.addTarget(self, action: #selector(UIView.handleLongPress(_:)))
self.addGestureRecognizer(longPress)
ClosureStorage.LongPressClosureStorage[longPress] = responder
Swizzler.Swizzle()
}
func handleLongPress(_ sender: UILongPressGestureRecognizer) {
if let closureForLongPinch = ClosureStorage.LongPressClosureStorage[sender] {
closureForLongPinch(sender)
}
}
// MARK: Rotation
func addRotationGestureRecognizerWithResponder(_ responder: @escaping RotationResponseClosure) {
let rotation = UIRotationGestureRecognizer()
rotation.addTarget(self, action: #selector(UIView.handleRotation(_:)))
self.addGestureRecognizer(rotation)
ClosureStorage.RotationClosureStorage[rotation] = responder
Swizzler.Swizzle()
}
func handleRotation(_ sender: UIRotationGestureRecognizer) {
if let closureForRotation = ClosureStorage.RotationClosureStorage[sender] {
closureForRotation(sender)
}
}
}
| 46.625551 | 204 | 0.710601 |
e97fafd66ff6c8d2502eb58e2ef4b60e9e305299 | 272 | //
// MovieCollectionCell.swift
// MovieViewer
//
// Created by Vincent Duong on 2/2/16.
// Copyright © 2016 Vincent Duong. All rights reserved.
//
import UIKit
class MovieCollectionCell: UICollectionViewCell {
@IBOutlet weak var posterView: UIImageView!
}
| 18.133333 | 56 | 0.716912 |
26b78a300eba88b10665638a7d1c29dc543086dd | 2,494 | //
// MarkupToogleButton.swift
// MacroPepelelipa
//
// Created by Pedro Henrique Guedes Silveira on 24/09/20.
// Copyright © 2020 Pedro Giuliano Farina. All rights reserved.
//
import UIKit
internal class MarkupToggleButton: UIButton {
var baseColor: UIColor?
var selectedColor: UIColor?
/**
Initializes the button with an image or a title, with a base color and a selected color.
*/
init(normalStateImage: UIImage?, title: String?, baseColor: UIColor? = UIColor.placeholderColor, selectedColor: UIColor? = UIColor.bodyColor) {
super.init(frame: .zero)
self.addTarget(self, action: #selector(toogleButton), for: .touchDown)
self.setTitle(title, for: .normal)
self.setTitle(title, for: .selected)
self.baseColor = baseColor
self.selectedColor = selectedColor
self.tintColor = baseColor
if let titleLabel = title {
self.setTitleColor(baseColor, for: .normal)
self.setTitleColor(selectedColor, for: .selected)
setFont(fontName: titleLabel)
}
self.setBackgroundImage(normalStateImage, for: .normal)
}
/**
Initializes the button with a frame and color, making the view a circle.
*/
init(frame: CGRect, color: UIColor) {
super.init(frame: frame)
self.addTarget(self, action: #selector(toogleButton), for: .touchDown)
self.backgroundColor = color
self.layer.cornerRadius = frame.height / 2
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
Sets the buttons font.
- Parameter fontName: The string containing the font's name.
*/
private func setFont(fontName: String) {
guard let font = UIFont(name: fontName, size: 16) else {
return
}
self.titleLabel?.font = font
}
/**
Sets the corner radius to be equal to half the frame's height.
*/
public func setCornerRadius() {
self.layer.cornerRadius = self.frame.height / 2
}
/**
This method changes the button's color based on its selection state.
*/
@objc private func toogleButton() {
self.isSelected.toggle()
if isSelected {
self.tintColor = selectedColor
} else {
self.tintColor = baseColor
}
}
}
| 28.340909 | 147 | 0.601043 |
e2e10cfbe85d2a0df90cd47703a8f1c2760aa7d6 | 2,122 | //
// Client.swift
// Worldb
//
// Created by Luis Ezcurdia on 9/29/18.
// Copyright © 2018 Luis Ezcurdia. All rights reserved.
//
import Foundation
typealias dataHandler = (Data?) -> Void
struct Client {
let baseURLComponents: URLComponents
func get(path: String, successHandler: dataHandler?) {
get(path: path, body: nil, successHandler: successHandler)
}
func get(path: String, body: Data?, successHandler: dataHandler?) {
request("GET", path: path, body: body, successHandler: successHandler)
}
func post(path: String, body: Data?, successHandler: dataHandler?) {
request("POST", path: path, body: body, successHandler: successHandler)
}
func put(path: String, body: Data?, successHandler: dataHandler?) {
request("PUT", path: path, body: body, successHandler: successHandler)
}
func patch(path: String, body: Data?, successHandler: dataHandler?) {
request("PATCH", path: path, body: body, successHandler: successHandler)
}
func delete(path: String, successHandler: dataHandler?) {
delete(path: path, body: nil, successHandler: successHandler)
}
func delete(path: String, body: Data?, successHandler: dataHandler?) {
request("DELETE", path: path, body: body, successHandler: successHandler)
}
func request(_ method: String, path: String, body: Data?, successHandler: dataHandler?) {
var requestURLComponents = baseURLComponents
requestURLComponents.path = path
var request = URLRequest(url: requestURLComponents.url!)
request.httpMethod = method
request.httpBody = body
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil { return }
let httpResponse = response as! HTTPURLResponse
if httpResponse.statusCode == 200, let handler = successHandler {
handler(data)
}
}
task.resume()
}
}
| 34.225806 | 93 | 0.641376 |
fce9bbe43948b7c3871433589c966024d1432f71 | 2,972 | //
// AppDelegate.swift
// BlurryBackgroundPopUp
//
// Created by Bijan Cronin on 6/28/18.
// Copyright © 2018 Bijan Cronin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let tabVC = UITabBarController()
let vc = UINavigationController(rootViewController: ViewController())
let tabBarAppearnce = UITabBar.appearance()
tabBarAppearnce.barTintColor = .white
tabBarAppearnce.tintColor = .darkGray
let vcTabBarItem = UITabBarItem(title: "Home", image: nil, tag: 1)
vcTabBarItem.setTitleTextAttributes([NSAttributedStringKey.font: UIFont.systemFont(ofSize: 22, weight: .semibold)], for: .normal)
vcTabBarItem.titlePositionAdjustment = UIOffset(horizontal:0, vertical:-10)
vc.tabBarItem = vcTabBarItem
tabVC.viewControllers = [vc]
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = tabVC
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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 47.935484 | 285 | 0.73755 |
1c74abf9d6b1a2cb4b47f168b03acc8b7000544d | 6,703 | //
// Bitmark.swift
// BitmarkSDK
//
// Created by Anh Nguyen on 12/23/16.
// Copyright © 2016 Bitmark. All rights reserved.
//
import Foundation
public struct TransferOffer: Codable {
let id: String
let from: String
let to: String
let record: CountersignedTransferRequest
let created_at: Date
let open: Bool
}
public struct Bitmark: Codable {
public let id: String
public let asset_id: String
public let head_id: String
public let issuer: String
public let owner: String
public let edition: Int?
public let status: String
public let offer: TransferOffer?
public let block_number: Int64
public let offset: Int64
public let created_at: Date?
public let confirmed_at: Date?
}
public extension Bitmark {
// MARK:- Issue
public static func newIssuanceParams(assetID: String, quantity: Int) throws -> IssuanceParams {
if quantity <= 0 {
throw("Invalid quantity")
}
let baseNonce = UInt64(Date().timeIntervalSince1970) * 1000
var requests = [IssueRequest]()
// Get asset info
let bitmarkQuery = try Bitmark.newBitmarkQueryParams()
.referencedAsset(assetID: assetID)
.pending(true)
.limit(size: 1)
let (bitmarks, _) = try Bitmark.list(params: bitmarkQuery)
if bitmarks == nil || bitmarks?.count == 0 {
// Create first one with nonce = 0
requests.append(createIssueRequest(assetID: assetID, nonce: 0))
}
// Create the rest with random nonce
for i in requests.count..<quantity {
requests.append(createIssueRequest(assetID: assetID, nonce: baseNonce + UInt64(i % 1000)))
}
let params = IssuanceParams(issuances: requests)
return params
}
public static func issue(_ params: IssuanceParams) throws -> [String] {
let api = API()
let step = 100
var i = 0
var shouldContinue = true
var bitmarkIDs = [String]()
while shouldContinue {
var last = i*step + step
if last > params.issuances.count {
shouldContinue = false
last = params.issuances.count
}
let parts = [IssueRequest](params.issuances[(i*step)..<last])
let ids = try api.issue(withIssueParams: IssuanceParams(issuances: parts))
bitmarkIDs += ids
i += 1
}
return bitmarkIDs
}
private static func createIssueRequest(assetID: String, nonce: UInt64) -> IssueRequest {
var issuanceRequest = IssueRequest()
issuanceRequest.set(assetId: assetID)
issuanceRequest.set(nonce: nonce)
return issuanceRequest
}
}
extension Bitmark {
// MARK:- Transfer
public static func newTransferParams(to owner: AccountNumber) throws -> TransferParams {
var transferRequest = TransferRequest()
try transferRequest.set(to: owner)
return TransferParams(transfer: transferRequest)
}
public static func transfer(withTransferParams params: TransferParams) throws -> String {
let api = API()
return try api.transfer(params)
}
}
extension Bitmark {
// MARK:- Transfer offer
public static func newOfferParams(to owner: AccountNumber, info: [String: Any]?) throws -> OfferParams {
var transferRequest = TransferRequest()
transferRequest.set(requireCountersignature: true)
try transferRequest.set(to: owner)
let offer = Offer(transfer: transferRequest, extraInfo: info)
return OfferParams(offer: offer)
}
public static func offer(withOfferParams params: OfferParams) throws {
let api = API()
return try api.offer(params)
}
public static func newTransferResponseParams(withBitmark bitmark: Bitmark, action: CountersignedTransferAction) throws -> OfferResponseParams {
guard let offer = bitmark.offer else {
throw("Cannot find any offer with this bitmark")
}
return OfferResponseParams(id: offer.id, action: action, record: offer.record, counterSignature: nil, apiHeader: nil)
}
public static func respond(withResponseParams responseParam: OfferResponseParams) throws -> String? {
let api = API()
return try api.respond(responseParam)
}
}
extension Bitmark {
// MARK:- Query
public static func get(bitmarkID: String, completionHandler: @escaping (Bitmark?, Error?) -> Void) {
DispatchQueue.global().async {
do {
let bitmark = try get(bitmarkID: bitmarkID)
completionHandler(bitmark, nil)
} catch let e {
completionHandler(nil, e)
}
}
}
public static func get(bitmarkID: String) throws -> Bitmark {
let api = API()
return try api.get(bitmarkID: bitmarkID)
}
public static func getWithAsset(bitmarkID: String, completionHandler: @escaping (Bitmark?, Asset?, Error?) -> Void) {
DispatchQueue.global().async {
do {
let (bitmark, asset) = try getWithAsset(bitmarkID: bitmarkID)
completionHandler(bitmark, asset, nil)
} catch let e {
completionHandler(nil, nil, e)
}
}
}
public static func getWithAsset(bitmarkID: String) throws -> (Bitmark, Asset) {
let api = API()
return try api.getWithAsset(bitmarkID: bitmarkID)
}
public static func newBitmarkQueryParams() -> QueryParam {
return QueryParam(queryItems: [URLQueryItem(name: "pending", value: "true")])
}
public static func list(params: QueryParam, completionHandler: @escaping ([Bitmark]?, [Asset]?, Error?) -> Void) {
DispatchQueue.global().async {
do {
let (bitmarks, assets) = try list(params: params)
completionHandler(bitmarks, assets, nil)
} catch let e {
completionHandler(nil, nil, e)
}
}
}
public static func list(params: QueryParam) throws -> ([Bitmark]?, [Asset]?) {
let api = API()
return try api.listBitmark(builder: params)
}
}
extension Bitmark: Hashable {
public var hashValue: Int {
return self.id.hashValue
}
public func hash(into hasher: inout Hasher) {
hasher.combine(self.id)
}
}
extension Bitmark: Equatable {
public static func == (lhs: Bitmark, rhs: Bitmark) -> Bool {
return lhs.id == rhs.id
}
}
| 32.07177 | 147 | 0.608235 |
61a15982fab4ffbc7d8243c8c87050c37c8373ab | 538 | /*:

# Welcome to Swift Club!
Learn more in [The Swift Programming Language](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/index.html) and [Using Swift with Cocoa and Objectice-C](https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/index.html)
### [Function](Function)
### [Classes and Structures](ClassesAndStructures)
### [Collection Type](CollectionType)
### [Control Flow](ControlFlow)
*/
| 31.647059 | 311 | 0.754647 |
fff1bac48ed539cdedd75b212acae4340b8d75ff | 2,119 | //
// AppDelegate.swift
// SampleApplication
//
// Created by demo on 02/02/18.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.065217 | 285 | 0.756489 |
1a4e6e1c66ce10c44effe402dfcb67d0d8751f88 | 6,313 | //
// GameViewController.swift
// MagicBall
//
// Created by shenjie on 2021/11/22.
//
import UIKit
import SceneKit
// Our iOS specific view controller
class GameViewController: UIViewController {
let CategoryTree = 2
var sceneView:SCNView!
var scene:SCNScene!
var ballNode:SCNNode!
var selfieStickNode:SCNNode!
var motion = MotionHelper()
var motionForce = SCNVector3(0, 0, 0)
var sounds:[String:SCNAudioSource] = [:]
override func viewDidLoad() {
super.viewDidLoad()
setupScene()
setupNodes()
setupSounds()
}
func setupScene(){
sceneView = self.view as! SCNView
sceneView.frame = self.view.bounds
sceneView.delegate = self
// sceneView.allowsCameraControl = true
scene = SCNScene(named: "art.scnassets/MainScene.scn")
sceneView.scene = scene
let joyStick = GameScene(size: self.view.bounds.size)
sceneView.overlaySKScene = joyStick
scene.physicsWorld.contactDelegate = self
let tapRecognizer = UITapGestureRecognizer()
tapRecognizer.numberOfTapsRequired = 1
tapRecognizer.numberOfTouchesRequired = 1
tapRecognizer.addTarget(self, action: #selector(GameViewController.sceneViewTapped(recognizer:)))
sceneView.addGestureRecognizer(tapRecognizer)
}
func setupNodes() {
ballNode = scene.rootNode.childNode(withName: "ball", recursively: true)!
ballNode.physicsBody?.contactTestBitMask = CategoryTree
selfieStickNode = scene.rootNode.childNode(withName: "selfieStick", recursively: true)!
}
func setupSounds() {
let sawSound = SCNAudioSource(fileNamed: "chainsaw.wav")!
let jumpSound = SCNAudioSource(fileNamed: "jump.wav")!
sawSound.load()
jumpSound.load()
sawSound.volume = 0.3
jumpSound.volume = 0.4
sounds["saw"] = sawSound
sounds["jump"] = jumpSound
let backgroundMusic = SCNAudioSource(fileNamed: "background.mp3")!
backgroundMusic.volume = 0.1
backgroundMusic.loops = true
backgroundMusic.load()
let musicPlayer = SCNAudioPlayer(source: backgroundMusic)
ballNode.addAudioPlayer(musicPlayer)
}
@objc func sceneViewTapped (recognizer: UITapGestureRecognizer) {
let location = recognizer.location(in: sceneView)
let hitResults = sceneView.hitTest(location, options: nil)
if hitResults.count > 0 {
let result = hitResults.first
if let node = result?.node {
if node.name == "ball" {
let jumpSound = sounds["jump"]!
ballNode.runAction(SCNAction.playAudio(jumpSound, waitForCompletion: false))
ballNode.physicsBody?.applyForce(SCNVector3(x: 0, y:4, z: -2), asImpulse: true)
}
}
}
}
override var shouldAutorotate: Bool {
return false
}
override var prefersStatusBarHidden: Bool {
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
// override func didMove(toParent parent: UIViewController?) {
//// scene.physicsBody = SKPhysicsBody(edgeLoopFrom: self.view.frame)
//
// let moveJoystickHiddenArea = TLAnalogJoystickHiddenArea(rect: CGRect(x: 0, y: 0, width: self.view.frame.midX, height: self.view.frame.height))
// moveJoystickHiddenArea.joystick = moveJoystick
// moveJoystick.isMoveable = true
// scene.addChild(moveJoystickHiddenArea)
// }
// MARK: touch events
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
}
}
extension GameViewController : SCNSceneRendererDelegate {
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
let ball = ballNode.presentation
let ballPosition = ball.position
let targetPosition = SCNVector3(x: ballPosition.x, y: ballPosition.y + 5, z:ballPosition.z + 5)
var cameraPosition = selfieStickNode.position
let camDamping:Float = 0.3
let xComponent = cameraPosition.x * (1 - camDamping) + targetPosition.x * camDamping
let yComponent = cameraPosition.y * (1 - camDamping) + targetPosition.y * camDamping
let zComponent = cameraPosition.z * (1 - camDamping) + targetPosition.z * camDamping
cameraPosition = SCNVector3(x: xComponent, y: yComponent, z: zComponent)
selfieStickNode.position = cameraPosition
motion.getAccelerometerData { (x, y, z) in
self.motionForce = SCNVector3(x: x * 0.05, y:0, z: (y + 0.8) * -0.05)
}
ballNode.physicsBody?.velocity += motionForce
}
}
extension GameViewController : SCNPhysicsContactDelegate {
func physicsWorld(_ world: SCNPhysicsWorld, didBegin contact: SCNPhysicsContact) {
var contactNode:SCNNode!
if contact.nodeA.name == "ball" {
contactNode = contact.nodeB
}else{
contactNode = contact.nodeA
}
if contactNode.physicsBody?.categoryBitMask == CategoryTree {
contactNode.isHidden = true
let sawSound = sounds["saw"]!
ballNode.runAction(SCNAction.playAudio(sawSound, waitForCompletion: false))
let waitAction = SCNAction.wait(duration: 15)
let unhideAction = SCNAction.run { (node) in
node.isHidden = false
}
let actionSequence = SCNAction.sequence([waitAction, unhideAction])
contactNode.runAction(actionSequence)
}
}
}
| 31.723618 | 152 | 0.613971 |
2f61b03afb36538e182d8f36253e2115fc4ff436 | 1,881 | //
// PasswordLoginViewController.swift
// SmileLock-Example
//
// Created by rain on 4/22/16.
// Copyright © 2016 RECRUIT LIFESTYLE CO., LTD. All rights reserved.
//
import UIKit
import SmileLock
class PasswordLoginViewController: UIViewController {
@IBOutlet weak var passwordStackView: UIStackView!
//MARK: Property
var passwordContainerView: PasswordContainerView!
let kPasswordDigit = 6
override func viewDidLoad() {
super.viewDidLoad()
//create PasswordContainerView
passwordContainerView = PasswordContainerView.create(in: passwordStackView, digit: kPasswordDigit)
passwordContainerView.delegate = self
passwordContainerView.deleteButtonLocalizedTitle = "smilelock_delete"
//customize password UI
passwordContainerView.tintColor = UIColor.color(.textColor)
passwordContainerView.highlightedColor = UIColor.color(.blue)
}
}
extension PasswordLoginViewController: PasswordInputCompleteProtocol {
func passwordInputComplete(_ passwordContainerView: PasswordContainerView, input: String) {
if validation(input) {
validationSuccess()
} else {
validationFail()
}
}
func touchAuthenticationComplete(_ passwordContainerView: PasswordContainerView, success: Bool, error: Error?) {
if success {
self.validationSuccess()
} else {
passwordContainerView.clearInput()
}
}
}
private extension PasswordLoginViewController {
func validation(_ input: String) -> Bool {
return input == "123456"
}
func validationSuccess() {
print("*️⃣ success!")
dismiss(animated: true, completion: nil)
}
func validationFail() {
print("*️⃣ failure!")
passwordContainerView.wrongPassword()
}
}
| 28.074627 | 116 | 0.668262 |
bffd100101b7b6e389dbc8a1748bca8b3ed33dae | 882 | //
// String+Dictionary.swift
// #github-ios
//
// Created by Artur on 20/03/2017.
// Copyright © 2017 Artur Matusiak. All rights reserved.
//
import Foundation
extension String {
var dictionary: [String : String] {
let separated1 = self.components(separatedBy: "&")
let separated2 = separated1.map {
$0.components(separatedBy: "=")
}
let filtered = separated2.filter {
$0.count == 2
}
let map = filtered.map {
[$0[0] : $0[1]]
}
let flatMap = map.flatMap { $0 }
let reduced = flatMap.reduce([String : String]()) {
(res, tuple) -> [String : String] in
var dict = res
dict.updateValue(tuple.1, forKey: tuple.0)
return dict
}
return reduced
}
}
| 22.615385 | 59 | 0.496599 |
fb68500850ca1ea292ac8753fc342b641d424446 | 915 | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "JiraSwift",
products: [
.library(name: "JiraSwift", targets: ["JiraSwift"]),
.executable(name: "jira", targets: ["JiraSwiftCLI"])
],
dependencies: [
.package(url: "https://github.com/swift-server/async-http-client", from: "1.0.0-alpha.4"),
.package(url: "https://github.com/vapor/console-kit", from: "4.0.0-alpha.2.1"),
.package(url: "https://github.com/scottrhoyt/SwiftyTextTable.git", from: "0.9.0")
],
targets: [
.target(name: "JiraSwift", dependencies: ["AsyncHTTPClient"]),
.target(name: "JiraSwiftCLI", dependencies: ["JiraSwift", "ConsoleKit", "SwiftyTextTable"]),
.testTarget(name: "JiraSwiftTests", dependencies: ["JiraSwift"])
]
)
| 39.782609 | 100 | 0.643716 |
eb356a45dee26a550a6cef438b0b3c3ff3844f30 | 1,170 | import TSCBasic
import TuistGraph
import XCTest
@testable import TuistCore
@testable import TuistSupportTesting
final class FrameworkMetadataProviderTests: XCTestCase {
var subject: FrameworkMetadataProvider!
override func setUp() {
super.setUp()
subject = FrameworkMetadataProvider()
}
override func tearDown() {
subject = nil
super.tearDown()
}
func test_loadMetadata() throws {
// Given
let frameworkPath = fixturePath(path: RelativePath("xpm.framework"))
// When
let metadata = try subject.loadMetadata(at: frameworkPath)
// Then
let expectedBinaryPath = frameworkPath.appending(component: frameworkPath.basenameWithoutExt)
let expectedDsymPath = frameworkPath.parentDirectory.appending(component: "xpm.framework.dSYM")
XCTAssertEqual(metadata, FrameworkMetadata(
path: frameworkPath,
binaryPath: expectedBinaryPath,
dsymPath: expectedDsymPath,
bcsymbolmapPaths: [],
linking: .dynamic,
architectures: [.x8664, .arm64],
isCarthage: false
))
}
}
| 28.536585 | 103 | 0.65641 |
c1c58e8c52f996d73238589804a085fa073e3278 | 1,493 | //
// EventInterceptor.swift
// eqMac
//
// Created by Roman Kisil on 18/01/2019.
// Copyright © 2019 Roman Kisil. All rights reserved.
//
import Foundation
import Cocoa
@objc(EventInterceptor)
class EventInterceptor: NSApplication {
override func sendEvent (_ event: NSEvent) {
if (event.type == .systemDefined && event.subtype.rawValue == 8) {
let keyCode = ((event.data1 & 0xFFFF0000) >> 16)
let keyFlags = (event.data1 & 0x0000FFFF)
// Get the key state. 0xA is KeyDown, OxB is KeyUp
let keyDown = (((keyFlags & 0xFF00) >> 8)) == 0xA
if (keyDown) {
switch Int32(keyCode) {
case NX_KEYTYPE_SOUND_UP:
Application.volumeChangeButtonPressed(direction: .UP, quarterStep: shiftPressed(event: event) && optionPressed(event: event))
return
case NX_KEYTYPE_SOUND_DOWN:
Application.volumeChangeButtonPressed(direction: .DOWN, quarterStep: shiftPressed(event: event) && optionPressed(event: event))
return
case NX_KEYTYPE_MUTE:
Application.muteButtonPressed()
return
default: break
}
}
}
if (event.type == .keyDown && event.keyCode == 53) {
// Application.escapePressed()
}
super.sendEvent(event)
}
func shiftPressed (event: NSEvent) -> Bool {
return event.modifierFlags.contains(.shift)
}
func optionPressed (event: NSEvent) -> Bool {
return event.modifierFlags.contains(.option)
}
}
| 28.169811 | 137 | 0.640991 |
d71303d3a85fcd8f1644b38029d683e20384db04 | 881 | //
// CVPixelBuffer+Extension.swift
// VideoToolboxCompression
//
// Created by tomisacat on 14/08/2017.
// Copyright © 2017 tomisacat. All rights reserved.
//
import Foundation
import VideoToolbox
import CoreVideo
extension CVPixelBuffer {
public enum LockFlag {
case readwrite
case readonly
func flag() -> CVPixelBufferLockFlags {
switch self {
case .readonly:
return .readOnly
default:
return CVPixelBufferLockFlags.init(rawValue: 0)
}
}
}
public func lock(_ flag: LockFlag, closure: (() -> Void)?) {
if CVPixelBufferLockBaseAddress(self, flag.flag()) == kCVReturnSuccess {
if let c = closure {
c()
}
}
CVPixelBufferUnlockBaseAddress(self, flag.flag())
}
}
| 23.184211 | 80 | 0.564132 |
ef6a0bc35ea0fca71fed3c1e2586f8a9c8859170 | 3,248 |
import XCTest
import Foundation
@testable import JSON
class AccessorTests: XCTestCase {
let json: JSON =
[
"array": [1, 2, 3] as JSON,
"object": ["Hello": "World", "Goodbye": "Brisbane"] as JSON,
"intLiteral": 1,
"intString": "1",
"floatLiteral": 6.28,
"floatString": "6.28",
"string": "hello",
"trueLiteral": true,
"falseLiteral": false,
"trueString": "true",
"falseString": "false",
"nullLiteral": JSON.null
]
func testInts() {
var value: Int
do {
value = try json.get("intLiteral")
XCTAssert(value == 1)
value = try json.get("intString")
XCTAssert(value == 1)
} catch {
XCTFail("Failed to access a member: \(error)")
}
}
func testFloatingPoints() {
var value: Double
do {
value = try json.get("floatLiteral")
XCTAssert(value == 6.28)
value = try json.get("floatString")
XCTAssert(value == 6.28)
} catch {
XCTFail("Failed to access a member: \(error)")
}
}
func testBool() {
var value: Bool
do {
value = try json.get("trueLiteral")
XCTAssert(value == true)
value = try json.get("trueString")
XCTAssert(value == true)
value = try json.get("falseLiteral")
XCTAssert(value == false)
value = try json.get("falseString")
XCTAssert(value == false)
} catch {
XCTFail("Failed to access a member: \(error)")
}
}
func testNull() {
var value: Bool?
do {
value = try json.get("nullLiteral")
XCTAssert(value == nil)
value = try json.get("404 key not found")
XCTAssert(value == nil)
} catch {
XCTFail("Failed to access a member: \(error)")
}
}
func testDefaulting() {
enum Color: String { case teal, unknown }
let json: JSON = ["name": "Harry", "age": 38, "color": "teal"]
do {
var name: String
name = try json.get("404", default: "vdka")
XCTAssert(name == "vdka")
name = try json.get("name", default: "Bob")
XCTAssert(name == "Harry")
name = try json.get("age", default: "Julia")
XCTAssert(name == "Julia")
var color: Color
color = try json.get("color", default: Color.unknown)
XCTAssert(color == .teal)
color = try json.get("404", default: Color.unknown)
XCTAssert(color == .unknown)
} catch {
XCTFail("An error occured: \(error)")
}
}
func testIterator() {
var values: [JSON] = []
for value in json["array"]! {
values.append(value)
}
XCTAssert(values == [1, 2, 3] as [JSON])
values.removeAll()
for value in json["intLiteral"]! {
values.append(value)
}
XCTAssert(values == [1] as [JSON])
values.removeAll()
for value in json["nullLiteral"]! {
values.append(value)
}
XCTAssert(values == [])
}
}
#if os(Linux)
extension JSONTests: XCTestCaseProvider {
var allTests : [(String, () throws -> Void)] {
return [
("testSerializeArray", testSerializeArray),
("testParse", testParse),
("testSanity", testSanity),
("testAccessors", testAccessors),
("testMutation", testMutation),
]
}
}
#endif
| 21.368421 | 66 | 0.559729 |
726e36eb99be0cfe40c9539f45f8f83ffbfa72ee | 2,662 | //
// KVOViewController.swift
// DifferentWaysToPassValueSwift
//
// Created by Linus on 15-9-2.
// Copyright (c) 2015年 Linus. All rights reserved.
//
import UIKit
// 要监听的对象的定义
class kvo: NSObject {
var ptitle : String = ""
// dynamic修饰的即为可支持KVO
dynamic var title : String {
get {
return self.ptitle
}
set {
self.ptitle = newValue
}
}
override init() {
print("init")
}
deinit {
print("deinit")
}
}
class KVOViewController: UIViewController {
var k = kvo() // 监听的对象
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
print("KVOViewController viewDidLoad")
self.view.backgroundColor = UIColor.whiteColor()
let tf:UITextField = UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 20))
tf.backgroundColor = UIColor.lightGrayColor()
tf.text = k.title
tf.tag = 10003
self.view.addSubview(tf)
// k.addObserver(self, forKeyPath: "title", options: NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old, context: nil)
let but:UIButton = UIButton(frame: CGRect(x: 20, y: 140, width: 50, height: 20))
but.setTitle("返回", forState: UIControlState.Normal)
but.backgroundColor = UIColor.lightGrayColor()
self.view.addSubview(but)
but.addTarget(self, action: "back:", forControlEvents: UIControlEvents.TouchUpInside)
}
func back(sender:UIButton) {
let tit = (self.view.viewWithTag(10003) as! UITextField).text
k.title = tit! // 对监听的属性赋值会触发observeValueForKeyPath方法
self.dismissViewControllerAnimated(true, completion: nil)
}
deinit {
// k.removeObserver(self, forKeyPath: "title", context: nil)
}
// override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
// println("observeValueForKeyPath")
// if keyPath == "title" {
// println(change)
// var newvalue: AnyObject? = change["new"]
// println("the new value is \(newvalue)")
// k.title = newvalue as String
// }
// }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.view.endEditing(true)
}
}
| 29.577778 | 158 | 0.613824 |
760307245a196cf5f7b9287fb3a0bcafea07fd0a | 5,942 | //
// TagCloudView.swift
// DevToys
//
// Created by yuki on 2022/02/01.
//
import CoreUtil
final class TagCloudView: NSLoadView {
let collectionView = NSCollectionView()
let flowLayout = LeftAlignedCollectionViewFlowLayout()
let buttonPublisher = PassthroughSubject<Int, Never>()
let selectPublisher = PassthroughSubject<Int, Never>()
var selectedItem: Int? {
didSet {
if let selectedItem = selectedItem {
collectionView.selectItems(at: [IndexPath(item: selectedItem, section: 0)], scrollPosition: .bottom)
} else {
collectionView.deselectAll(nil)
}
}
}
var isSelectable = false {
didSet { collectionView.isSelectable = isSelectable; collectionView.reloadData() }
}
var items: [String] = ["Hello", "World"] {
didSet {
collectionView.reloadData()
DispatchQueue.main.async {[self] in self.reloadHeight() }
}
}
override func layout() {
self.reloadHeight()
super.layout()
}
private func reloadHeight() {
let collectionViewContentSize = flowLayout.collectionViewContentSize
self.snp.remakeConstraints{ make in
make.height.equalTo(collectionViewContentSize.height)
}
}
override func onAwake() {
self.frame.size = [1, 1]
flowLayout.scrollDirection = .vertical
flowLayout.estimatedItemSize = .zero
flowLayout.minimumInteritemSpacing = 10
flowLayout.minimumLineSpacing = 10
flowLayout.invalidateLayout()
collectionView.collectionViewLayout = flowLayout
self.addSubview(collectionView)
self.collectionView.dataSource = self
self.collectionView.delegate = self
self.collectionView.register(TagCloudItem.self, forItemWithIdentifier: TagCloudItem.identifier)
self.collectionView.snp.makeConstraints{ make in
make.edges.equalToSuperview()
}
}
}
extension TagCloudView: NSCollectionViewDelegateFlowLayout, NSCollectionViewDataSource {
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
items.count
}
func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
guard let indexPath = indexPaths.first else { return }
selectPublisher.send(indexPath.item)
}
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: TagCloudItem.identifier, for: indexPath) as! TagCloudItem
item.cell.isEnabled = !isSelectable
item.cell.actionPublisher
.sink{ self.buttonPublisher.send(indexPath.item) }.store(in: &item.objectBag)
item.cell.label.stringValue = items[indexPath.item]
return item
}
func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
let label = NSTextField(labelWithString: items[indexPath.item])
label.font = .systemFont(ofSize: 14)
label.sizeToFit()
return label.frame.size + [16, 12]
}
}
final private class TagCloudItem: NSCollectionViewItem {
static let identifier = NSUserInterfaceItemIdentifier(rawValue: "TagCloudItem")
override var isSelected: Bool { didSet { cell.isSelected = isSelected } }
class Cell: NSLoadButton {
let label = NSTextField(labelWithString: "")
let backgroundLayer = ControlButtonBackgroundLayer.animationDisabled()
var isSelected: Bool = false { didSet { needsDisplay = true } }
override func layout() {
super.layout()
self.backgroundLayer.frame = bounds
}
override func updateLayer() {
backgroundLayer.update(isHighlighted: isHighlighted)
backgroundLayer.areAnimationsEnabled = true
if isSelected {
backgroundLayer.backgroundColor = NSColor.controlAccentColor.withAlphaComponent(0.5).cgColor
backgroundLayer.borderColor = NSColor.controlAccentColor.cgColor
backgroundLayer.borderWidth = 1
} else {
backgroundLayer.borderWidth = 0
}
backgroundLayer.areAnimationsEnabled = false
}
override func onAwake() {
self.wantsLayer = true
self.title = ""
self.isBordered = false
self.layer?.addSublayer(backgroundLayer)
self.addSubview(label)
self.label.alignment = .center
self.label.snp.makeConstraints{ make in
make.left.right.equalToSuperview().inset(8)
make.centerY.equalToSuperview()
}
}
}
let cell = Cell()
override func loadView() { self.view = cell }
}
final class LeftAlignedCollectionViewFlowLayout: NSCollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: NSRect) -> [NSCollectionViewLayoutAttributes] {
let attributes = super.layoutAttributesForElements(in: rect)
var leftMargin = sectionInset.left
var maxY: CGFloat = -1.0
attributes.forEach { layoutAttribute in
if layoutAttribute.representedElementCategory == .item {
if layoutAttribute.frame.origin.y >= maxY {
leftMargin = sectionInset.left
}
layoutAttribute.frame.origin.x = leftMargin
leftMargin += layoutAttribute.frame.width + minimumInteritemSpacing
maxY = max(layoutAttribute.frame.maxY, maxY)
}
}
return attributes
}
}
| 36.231707 | 160 | 0.643049 |
1a54f7ceac296315ce079d0ddfee335bb5204284 | 537 | import Foundation
import AppKit
struct DockIcon {
static var standard = DockIcon()
var isVisible: Bool {
get {
return NSApp.activationPolicy() == .regular
}
set {
setVisibility(isVisible)
}
}
@discardableResult
func setVisibility(_ state: Bool) -> Bool {
if state {
NSApp.setActivationPolicy(.regular)
} else {
NSApp.setActivationPolicy(.accessory)
}
return isVisible
}
}
| 19.178571 | 55 | 0.527002 |
f521eddc5866adaac8b55d0ac283af6568080736 | 266 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol A {
protocol A : e {
{
}
typealias e
}
}
if true {
protocol a {
typealias e : e
let : A
| 16.625 | 87 | 0.714286 |
5d03dc8f3833486dd1337fae9748fe7b664f5711 | 1,496 | //
// CodeSystems.swift
// HealthRecords
//
// Generated from FHIR 4.0.1-9346c8cc45
// Copyright 2020 Apple Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import FMCore
/**
Example Message Reasons. These are the set of codes that might be used an updating an encounter using admin-update.
URL: http://terminology.hl7.org/CodeSystem/message-reasons-encounter
ValueSet: http://hl7.org/fhir/ValueSet/message-reason-encounter
*/
public enum ExampleMessageReasonCodes: String, FHIRPrimitiveType {
/// The patient has been admitted.
case admit = "admit"
/// The patient has been discharged.
case discharge = "discharge"
/// The patient has temporarily left the institution.
case absent = "absent"
/// The patient has returned from a temporary absence.
case `return` = "return"
/// The patient has been moved to a new location.
case moved = "moved"
/// Encounter details have been updated (e.g. to correct a coding error).
case edit = "edit"
}
| 31.166667 | 116 | 0.727941 |
7107222e41852ab7c2530ae45a542631335dece9 | 5,752 | //
// PopupDialogView.swift
//
// Copyright (c) 2016 Orderella Ltd. (http://orderella.co.uk)
// Author - Martin Wildfeuer (http://www.mwfire.de)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import UIKit
/// The main view of the popup dialog
final public class PopupDialogDefaultView: UIView {
// MARK: - Appearance
/// The font and size of the title label
@objc public dynamic var titleFont: UIFont {
get { return titleLabel.font }
set { titleLabel.font = newValue }
}
/// The color of the title label
@objc public dynamic var titleColor: UIColor? {
get { return titleLabel.textColor }
set { titleLabel.textColor = newValue }
}
/// The text alignment of the title label
@objc public dynamic var titleTextAlignment: NSTextAlignment {
get { return titleLabel.textAlignment }
set { titleLabel.textAlignment = newValue }
}
/// The font and size of the body label
@objc public dynamic var messageFont: UIFont {
get { return messageLabel.font }
set { messageLabel.font = newValue }
}
/// The color of the message label
@objc public dynamic var messageColor: UIColor? {
get { return messageLabel.textColor }
set { messageLabel.textColor = newValue}
}
/// The text alignment of the message label
@objc public dynamic var messageTextAlignment: NSTextAlignment {
get { return messageLabel.textAlignment }
set { messageLabel.textAlignment = newValue }
}
// MARK: - Views
/// The view that will contain the image, if set
internal lazy var imageView: UIImageView = {
let imageView = UIImageView(frame: .zero)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
/// The title label of the dialog
internal lazy var titleLabel: UILabel = {
let titleLabel = UILabel(frame: .zero)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .center
titleLabel.textColor = UIColor(white: 0.4, alpha: 1)
titleLabel.font = .boldSystemFont(ofSize: 14)
return titleLabel
}()
/// The message label of the dialog
internal lazy var messageLabel: UILabel = {
let messageLabel = UILabel(frame: .zero)
messageLabel.translatesAutoresizingMaskIntoConstraints = false
messageLabel.numberOfLines = 0
messageLabel.textAlignment = .center
messageLabel.textColor = UIColor(white: 0.6, alpha: 1)
messageLabel.font = .systemFont(ofSize: 14)
return messageLabel
}()
/// The height constraint of the image view, 0 by default
internal var imageHeightConstraint: NSLayoutConstraint?
// MARK: - Initializers
internal override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View setup
internal func setupViews() {
// Self setup
translatesAutoresizingMaskIntoConstraints = false
// Add views
addSubview(imageView)
addSubview(titleLabel)
addSubview(messageLabel)
// Layout views
let views = ["imageView": imageView, "titleLabel": titleLabel, "messageLabel": messageLabel] as [String: Any]
var constraints = [NSLayoutConstraint]()
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[imageView]|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-(==20@900)-[titleLabel]-(==20@900)-|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-(==20@900)-[messageLabel]-(==20@900)-|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[imageView]-(==30@900)-[titleLabel]-(==8@900)-[messageLabel]-(==30@900)-|", options: [], metrics: nil, views: views)
// ImageView height constraint
imageHeightConstraint = NSLayoutConstraint(item: imageView, attribute: .height, relatedBy: .equal, toItem: imageView, attribute: .height, multiplier: 0, constant: 0)
if let imageHeightConstraint = imageHeightConstraint {
constraints.append(imageHeightConstraint)
}
// Activate constraints
NSLayoutConstraint.activate(constraints)
}
}
| 38.604027 | 192 | 0.678547 |
209a7b4b1810e4795e8ceeff75fc58d99654b360 | 2,435 | import Foundation
/// Defines a card that can play animated GIFs or short videos.
public struct AnimationCard {
internal static let contentType = "application/vnd.microsoft.card.animation"
/// Flag that indicates whether to replay the list of animated GIFs when the last one ends.
public let autoloop: Bool
/// Flag that indicates whether to automatically play the animation when the card is displayed.
public let autostart: Bool
/// Array of `CardAction` values that enable the user to perform one or more actions.
public let buttons: [CardAction]
/// A `ThumbnailURL` value that specifies the image to display on the card.
public let image: ThumbnailURL?
/// Array of `MediaURL` values that specifies the list of animated GIFs to play.
public let media: [MediaURL]
/// Flag that indicates whether the animation may be shared with others.
public let isShareable: Bool
/// Subtitle to display under the card's title.
public let subtitle: String?
/// Description or prompt to display under the card's title or subtitle.
public let text: String?
/// Title of the card.
public let title: String?
}
extension AnimationCard: Decodable {
private enum CodingKeys: String, CodingKey {
case autoloop
case autostart
case buttons
case image
case media
case shareable
case subtitle
case text
case title
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let autoloop = try container.decodeIfPresent(Bool.self, forKey: .autoloop) ?? true
let autostart = try container.decodeIfPresent(Bool.self, forKey: .autostart) ?? true
let buttons = try container.decode([CardAction].self, forKey: .buttons)
let image = try container.decodeIfPresent(ThumbnailURL.self, forKey: .image)
let media = try container.decode([MediaURL].self, forKey: .media)
let isShareable = try container.decodeIfPresent(Bool.self, forKey: .shareable) ?? true
let subtitle = try container.decodeIfPresent(String.self, forKey: .subtitle)
let text = try container.decodeIfPresent(String.self, forKey: .text)
let title = try container.decodeIfPresent(String.self, forKey: .title)
self.init(autoloop: autoloop,
autostart: autostart,
buttons: buttons,
image: image,
media: media,
isShareable: isShareable,
subtitle: subtitle,
text: text,
title: title)
}
}
| 33.819444 | 96 | 0.725257 |
39acfc718d6286e2e71d2f839994365014e51080 | 5,391 | //
// BRAPIProxy.swift
// BreadWallet
//
// Created by Samuel Sutch on 2/8/16.
// Copyright (c) 2016 breadwallet 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 Foundation
// Add this middleware to a BRHTTPServer to expose a proxy to the breadwallet HTTP api
// It has all the capabilities of the real API but with the ability to authenticate
// requests using the users private keys stored on device.
//
// Clients should set the "X-Should-Verify" to enable response verification and can set
// "X-Should-Authenticate" to sign requests with the users private authentication key
@objc open class BRAPIProxy: NSObject, BRHTTPMiddleware {
var mountPoint: String
var apiInstance: BRAPIClient
var shouldVerifyHeader: String = "x-should-verify"
var shouldAuthHeader: String = "x-should-authenticate"
var bannedSendHeaders: [String] {
return [
shouldVerifyHeader,
shouldAuthHeader,
"connection",
"authorization",
"host",
"user-agent"
]
}
var bannedReceiveHeaders: [String] = ["content-length", "content-encoding", "connection"]
init(mountAt: String, client: BRAPIClient) {
mountPoint = mountAt
if mountPoint.hasSuffix("/") {
mountPoint = mountPoint.substring(to: mountPoint.characters.index(mountPoint.endIndex, offsetBy: -1))
}
apiInstance = client
super.init()
}
open func handle(_ request: BRHTTPRequest, next: @escaping (BRHTTPMiddlewareResponse) -> Void) {
if request.path.hasPrefix(mountPoint) {
let idx = request.path.characters.index(request.path.startIndex, offsetBy: mountPoint.characters.count)
var path = request.path.substring(from: idx)
if request.queryString.utf8.count > 0 {
path += "?\(request.queryString)"
}
var nsReq = URLRequest(url: apiInstance.url(path))
nsReq.httpMethod = request.method
// copy body
if request.hasBody {
nsReq.httpBody = request.body()
}
// copy headers
for (hdrName, hdrs) in request.headers {
if bannedSendHeaders.contains(hdrName) { continue }
for hdr in hdrs {
nsReq.setValue(hdr, forHTTPHeaderField: hdrName)
}
}
var auth = false
if let authHeader = request.headers[shouldAuthHeader] , authHeader.count > 0 {
if authHeader[0].lowercased() == "yes" {
auth = true
}
}
apiInstance.dataTaskWithRequest(nsReq, authenticated: auth, retryCount: 0, handler:
{ (nsData, nsHttpResponse, nsError) -> Void in
if let httpResp = nsHttpResponse {
var hdrs = [String: [String]]()
for (k, v) in httpResp.allHeaderFields {
if self.bannedReceiveHeaders.contains((k as! String).lowercased()) { continue }
hdrs[k as! String] = [v as! String]
}
var body: [UInt8]? = nil
if let bod = nsData {
let bp = (bod as NSData).bytes.bindMemory(to: UInt8.self, capacity: bod.count)
let b = UnsafeBufferPointer<UInt8>(start: bp, count: bod.count)
body = Array(b)
}
let resp = BRHTTPResponse(
request: request, statusCode: httpResp.statusCode,
statusReason: HTTPURLResponse.localizedString(forStatusCode: httpResp.statusCode),
headers: hdrs, body: body)
return next(BRHTTPMiddlewareResponse(request: request, response: resp))
} else {
print("[BRAPIProxy] error getting response from backend: \(nsError)")
return next(BRHTTPMiddlewareResponse(request: request, response: nil))
}
}).resume()
} else {
return next(BRHTTPMiddlewareResponse(request: request, response: nil))
}
}
}
| 45.686441 | 115 | 0.595437 |
143cd97625f4dea55d890f226fbad1f63eb8bf04 | 1,647 | //
// UINavigationController-Extern.swift
// KLDouYu
//
// Created by WKL on 2020/9/3.
// Copyright © 2020 ray. All rights reserved.
//
import UIKit
extension UINavigationController {
public class func initializeMethod(){
let originalSelector = #selector(pushViewController(_:animated:))
let swizzledSelector = #selector( klpushViewController(_:animated:))
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
//在进行 Swizzling 的时候,需要用 class_addMethod 先进行判断一下原有类中是否有要替换方法的实现
let didAddMethod: Bool = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
//如果 class_addMethod 返回 yes,说明当前类中没有要替换方法的实现,所以需要在父类中查找,这时候就用到 method_getImplemetation 去获取 class_getInstanceMethod 里面的方法实现,然后再进行 class_replaceMethod 来实现 Swizzing
if didAddMethod {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
} else {
method_exchangeImplementations(originalMethod!, swizzledMethod!)
}
}
@objc func klpushViewController(_ viewController: UIViewController, animated: Bool) {
if viewControllers.count == 1
{
viewController.hidesBottomBarWhenPushed = true
}
self.klpushViewController(viewController, animated: animated)
}
}
| 30.5 | 169 | 0.669702 |
728f277006d05cc564847b86ac8a8df59ad9a61b | 1,153 | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "OTPKit",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "OTPKit",
targets: ["OTPKit"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/norio-nomura/Base32.git", from: "0.9.0"),
.package(url: "https://github.com/kishikawakatsumi/KeychainAccess.git", from: "4.2.2"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "OTPKit",
dependencies: ["Base32", "KeychainAccess"]),
.testTarget(
name: "OTPKitTests",
dependencies: ["OTPKit"]),
]
)
| 38.433333 | 122 | 0.629662 |
ebd2f66f72b6641c39d797fb8a888b24ff5621a4 | 76 | import Foundation
enum FileStorageKey : String{
case genre = "genre"
}
| 12.666667 | 29 | 0.710526 |
148ad13a243a6c03e9e96c2074181b187851c960 | 5,988 | //
// ThemeEditor.swift
// Memorize3.0
//
// Created by sun on 2021/11/21.
//
import SwiftUI
struct ThemeEditor: View {
@Binding var theme: Theme
@Environment(\.presentationMode) private var presentationMode
var body: some View {
NavigationView {
Form {
nameSection
removeEmojiSection
addEmojiSection
// emojiHistorySection
cardPairSection
colorSection
}
.navigationTitle("\(name)")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
cancelButton
}
ToolbarItem { doneButton }
}
}
}
// @State private var removedEmojis: String
//
// private var emojiHistorySection: some View {
// Section(header: Text("Removed Emojis")) {
// LazyVGrid(columns: [GridItem(.adaptive(minimum: 20))]) {
// ForEach(removedEmojis.map {String($0)}, id: \.self) { emoji in
// Text(emoji)
// .onTapGesture {
// addToCandidateEmojis(emoji)
// withAnimation {
// removedEmojis.removeAll { String($0) == emoji }
// }
// }
// }
// }
// }
// }
private var doneButton: some View {
Button("Done") {
if presentationMode.wrappedValue.isPresented && candidateEmojis.count >= 2 {
saveAllEdits()
presentationMode.wrappedValue.dismiss()
}
}
}
private func saveAllEdits() {
// theme.removedEmojis = getRemovedEmojis(from: theme.emojis)
theme.name = name
theme.emojis = candidateEmojis
theme.numberOfPairsOfCards = min(numberOfPairs, candidateEmojis.count)
theme.color = RGBAColor(color: chosenColor)
}
// private func getRemovedEmojis(from oldEmojis: String) -> String {
// (oldEmojis.filter { !candidateEmojis.contains($0) } + removedEmojis)
// return removedEmojis
//
// }
private var cancelButton: some View {
Button("Cancel") {
if presentationMode.wrappedValue.isPresented {
presentationMode.wrappedValue.dismiss()
}
}
}
init(theme: Binding<Theme>) {
self._theme = theme
self._name = State(initialValue: theme.wrappedValue.name)
self._candidateEmojis = State(initialValue: theme.wrappedValue.emojis)
// self._removedEmojis = State(initialValue: theme.wrappedValue.removedEmojis)
self._numberOfPairs = State(initialValue: theme.wrappedValue.numberOfPairsOfCards)
self._chosenColor = State(initialValue: Color(rgbaColor: theme.wrappedValue.color))
}
// MARK: - Name Section
@State private var name: String
private var nameSection: some View {
Section(header: Text("theme name")) {
TextField("Theme name", text: $name)
}
}
// MARK: - Remove Emojis Section
@State private var candidateEmojis: String
private var removeEmojiSection: some View {
let header = HStack {
Text("Emojis")
Spacer()
Text("Tap To Remove")
}
return Section(header: header) {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 20))]) {
ForEach(candidateEmojis.map { String($0) }, id: \.self) { emoji in
Text(emoji)
.onTapGesture {
withAnimation {
if candidateEmojis.count > 2 {
candidateEmojis.removeAll { String($0) == emoji}
}
}
}
}
}
}
}
// MARK: - Add Emojis Section
@State private var emojisToAdd = ""
private var addEmojiSection: some View {
Section(header: Text("add Emojis")) {
TextField("Emojis", text: $emojisToAdd)
.onChange(of: emojisToAdd) { emoji in
addToCandidateEmojis(emoji)
}
}
}
private func addToCandidateEmojis(_ emojis: String) {
withAnimation {
candidateEmojis = (emojis + candidateEmojis)
.filter { $0.isEmoji }
.removingDuplicateCharacters
}
}
// MARK: - Number of Card Pairs Section
@State var numberOfPairs: Int
private var cardPairSection: some View {
Section(header: Text("Card Count")) {
Stepper("\(numberOfPairs) Pairs", value: $numberOfPairs, in: candidateEmojis.count < 2 ? 2...2 : 2...candidateEmojis.count)
.onChange(of: candidateEmojis) { _ in
numberOfPairs = max(2, min(numberOfPairs, candidateEmojis.count))
}
}
}
// MARK: - Color Section
@State var chosenColor: Color = .red
private var colorSection: some View {
if #available(iOS 15.0, *) {
return Section("COLOR") {
ColorPicker("Current color is", selection: $chosenColor, supportsOpacity: false)
.foregroundColor(chosenColor)
}
} else {
return Section(header: Text("Current color is")) {
ColorPicker("", selection: $chosenColor, supportsOpacity: false)
.foregroundColor(chosenColor)
}
}
}
}
//struct SwiftUIView_Previews: PreviewProvider {
// static var previews: some View {
// ThemeEditor(theme: .constant(ThemeStore(named: "preview").themes[1]))
// }
//}
| 30.707692 | 136 | 0.523881 |
fc64ca4cda99be376419bad228321a51689a3276 | 2,401 | //
// Persistence.swift
// reed
//
// Created by Lukas Fülling on 21.12.20.
//
import CoreData
import SwiftUI
struct PersistenceController {
@AppStorage("resetData") private var resetData = false
static let shared = PersistenceController()
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let viewContext = result.container.viewContext
for _ in 0..<10 {
let newItem = Article(context: viewContext)
newItem.date = Date()
}
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
return result
}()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "reedModel")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
var shouldResetModel: Bool = resetData
container.loadPersistentStores(completionHandler: {(storeDescription, error) in
if let _ = error as NSError? {
print("Error loading data, probably a corrupt model!")
shouldResetModel = true
}
})
if(shouldResetModel) {
print("Resetting data...")
container.persistentStoreDescriptions.forEach({desc in
do {
try container.persistentStoreCoordinator.destroyPersistentStore(at: desc.url!, ofType: NSSQLiteStoreType)
} catch {
print(error)
}
})
// reload model
container.loadPersistentStores(completionHandler: {(storeDescription, error) in
if let e = error as NSError? {
fatalError(e.localizedDescription)
}
})
if resetData {
resetData = false
}
}
}
}
| 33.816901 | 195 | 0.577676 |
333ba07de25422617be6f5007fb069632cf5cc58 | 2,394 | //
// UIColor_EXT.swift
// Bankroll
//
// Created by Etienne Goulet-Lang on 5/25/16.
// Copyright © 2016 Etienne Goulet-Lang. All rights reserved.
//
import Foundation
import UIKit
/// Represents RGB color values (0xRRGGBB)
public typealias UIColorRGB = Int64
public extension UIColor {
public convenience init(rgb: Int64) {
if rgb > 0xFFFFFF { // there is some alpha component
self.init(argb: rgb)
} else {
let red = CGFloat((rgb>>16)&0xFF) / 255
let green = CGFloat((rgb>>8)&0xFF) / 255
let blue = CGFloat(rgb&0xFF) / 255
self.init(red: red, green: green, blue: blue, alpha: 1)
}
}
public convenience init(argb: Int64) {
if argb <= 0xFFFFFF {
self.init(rgb: argb)
} else {
let alpha = CGFloat((argb>>24)&0xFF) / 255
let red = CGFloat((argb>>16)&0xFF) / 255
let green = CGFloat((argb>>8)&0xFF) / 255
let blue = CGFloat(argb&0xFF) / 255
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
public convenience init?(hexString: String) {
var r, g, b, a: CGFloat
let scrubbedStr = hexString
.stringByReplacingOccurrencesOfString("#", withString: "")
.stringByReplacingOccurrencesOfString("0x", withString: "")
.uppercaseString
let scanner = NSScanner(string: scrubbedStr)
var hexNumber: UInt64 = 0
if scanner.scanHexLongLong(&hexNumber) {
a = CGFloat((hexNumber & 0xff000000) >> 24) / 255
r = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
g = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
b = CGFloat(hexNumber & 0x000000ff) / 255
if (scrubbedStr as NSString).length == 6 {
a = 1
}
self.init(red: r, green: g, blue: b, alpha: a)
return
}
return nil
}
public func toColorComponents() -> [CGFloat] {
return self.CGColor.toColorComponents()
}
public func toRGB() -> UIColorRGB {
return self.CGColor.toRGB()
}
public func toRGBString(prefixWithHash: Bool = true) -> String {
return self.CGColor.toRGBString(prefixWithHash)
}
} | 29.555556 | 71 | 0.54386 |
0e9203ff07bc1c0641f79abd79f8c77d50be1880 | 2,710 | //
// UniqueIntegerType.swift
// WTUniquePrimitiveTypes
//
// Created by Wagner Truppel on 31/05/2017.
// Copyright © 2017 wtruppel. All rights reserved.
//
// swiftlint:disable vertical_whitespace
// swiftlint:disable trailing_newline
import Foundation
public protocol UniqueIntegerType: WTUniquePrimitiveType, ExpressibleByIntegerLiteral {
associatedtype PrimitiveType: Integer
}
// MARK: - ExpressibleByIntegerLiteral
extension UniqueIntegerType {
public init(integerLiteral value: Self.PrimitiveType) {
self.init(value)
}
}
// MARK: - Convenience
extension UniqueIntegerType {
public var valueAsInt: Int? {
guard let intValue = Int("\(value)") else { return nil }
return intValue
}
}
extension UniqueIntegerType where Self.PrimitiveType == Int8 {
public init?(intValue value: Int) {
guard let primitiveValue = Int8.init("\(value)") else { return nil }
self.init(primitiveValue)
}
}
extension UniqueIntegerType where Self.PrimitiveType == Int16 {
public init?(intValue value: Int) {
guard let primitiveValue = Int16.init("\(value)") else { return nil }
self.init(primitiveValue)
}
}
extension UniqueIntegerType where Self.PrimitiveType == Int32 {
public init?(intValue value: Int) {
guard let primitiveValue = Int32.init("\(value)") else { return nil }
self.init(primitiveValue)
}
}
extension UniqueIntegerType where Self.PrimitiveType == Int64 {
public init?(intValue value: Int) {
// Never fails while Int64 is the largest type available.
// guard let primitiveValue = Int64.init("\(value)") else { return nil }
// self.init(primitiveValue)
self.init(Int64(value))
}
}
extension UniqueIntegerType where Self.PrimitiveType == UInt8 {
public init?(intValue value: Int) {
guard let primitiveValue = UInt8.init("\(value)") else { return nil }
self.init(primitiveValue)
}
}
extension UniqueIntegerType where Self.PrimitiveType == UInt16 {
public init?(intValue value: Int) {
guard let primitiveValue = UInt16.init("\(value)") else { return nil }
self.init(primitiveValue)
}
}
extension UniqueIntegerType where Self.PrimitiveType == UInt32 {
public init?(intValue value: Int) {
guard let primitiveValue = UInt32.init("\(value)") else { return nil }
self.init(primitiveValue)
}
}
extension UniqueIntegerType where Self.PrimitiveType == UInt64 {
public init?(intValue value: Int) {
guard let primitiveValue = UInt64.init("\(value)") else { return nil }
self.init(primitiveValue)
}
}
| 23.565217 | 87 | 0.66679 |
76a87576ba5f2d5da831d6206721be9ee76d4ccb | 991 | //
// InMemoryStorage.swift
// Noze.io
//
// Created by Helge Heß on 7/24/16.
// Copyright © 2016 ZeeZide GmbH. All rights reserved.
//
/// A collection store which just stores everything in memory. Data added will
/// be gone when the process is stopped.
///
class InMemoryCollectionStore<T> : CollectionStore {
// TODO: move to Redis
var sequence = 1337
var objects = [ Int : T ]()
init() {
}
func nextKey(cb: @escaping ( Int ) -> Void) {
sequence += 1
cb(sequence)
}
func getAll(cb: @escaping ( [ T ] ) -> Void) {
cb(Array(objects.values))
}
func get(id key: Int, cb: @escaping ( T? ) -> Void) {
cb(objects[key])
}
func delete(id key: Int, cb: @escaping () -> Void) {
objects.removeValue(forKey: key)
cb()
}
func update(id key: Int, value v: T, cb: @escaping ( T ) -> Void) {
objects[key] = v // value type!
cb(v)
}
func deleteAll(cb: @escaping () -> Void) {
objects.removeAll()
cb()
}
}
| 19.82 | 78 | 0.58224 |
d6e6d8fb8a822a0cb41cd69612a5821346038683 | 26 | class PageHandler {
} | 8.666667 | 19 | 0.615385 |
bbb1fd791092978be36b40077bd9c3d28aeb7cff | 15,105 | //
// Show.swift
// SwiftShow
//
// Created by iOS on 2020/1/16.
// Copyright © 2020 iOS. All rights reserved.
//
import UIKit
//MARK: --Toast
extension Show{
public typealias ConfigToast = ((_ config : ShowToastConfig) -> Void)
/// 在屏幕中间展示toast
/// - Parameters:
/// - text: 文案
/// - image: 图片
public class func showToast(_ text: String, image: UIImage? = nil, config : ConfigToast? = nil){
let model = ShowToastConfig()
if let _ = image{
model.space = 10
}
config?(model)
toast(text: text, image: image, config: model)
}
private class func toast(text: String, image: UIImage? = nil, config: ShowToastConfig){
getWindow().subviews.forEach { (view) in
if view.isKind(of: ToastView.self){
view.removeFromSuperview()
}
}
let toast = ToastView.init(config)
toast.title = text
toast.image = image
getWindow().addSubview(toast)
toast.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
switch config.offSetType {
case .center:
make.centerY.equalToSuperview()
case .top:
make.top.equalToSuperview().offset(config.offSet)
case .bottom:
make.bottom.equalToSuperview().offset(-config.offSet)
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + config.showTime) {
UIView.animate(withDuration: config.animateDuration, animations: {
toast.alpha = 0
}) { (_) in
toast.removeFromSuperview()
}
}
}
}
////MARK: --Loading
extension Show{
public typealias ConfigLoading = ((_ config : ShowLoadingConfig) -> Void)
/// 在当前VC中展示loading
/// - Parameters:
/// - text: 文本
/// - config: 配置
public class func showLoading(_ text : String? = nil, config : ConfigLoading? = nil) {
guard let vc = currentViewController() else {
return
}
let model = ShowLoadingConfig()
if let title = text , title.count > 0 {
model.space = 10
}
config?(model)
loading(text, onView: vc.view, config: model)
}
/// 隐藏上层VC中的loading
public class func hiddenLoading() {
guard let vc = currentViewController() else {
return
}
hiddenLoadingOnView(vc.view)
}
/// 在window中展示loading
/// - Parameters:
/// - text: 文本
/// - config: 配置
public class func showLoadingOnWindow(_ text : String? = nil, config : ConfigLoading? = nil){
let model = ShowLoadingConfig()
config?(model)
loading(text, onView: getWindow(), config: model)
}
/// 隐藏window中loading
public class func hiddenLoadingOnWindow() {
hiddenLoadingOnView(getWindow())
}
/// 在指定view中添加loading
/// - Parameters:
/// - onView: view
/// - text: 文本
/// - config: 配置
public class func showLoadingOnView(_ onView: UIView, text : String? = nil, config : ConfigLoading? = nil){
let model = ShowLoadingConfig()
config?(model)
loading(text, onView: onView, config: model)
}
/// 隐藏指定view中loading
/// - Parameter onView: view
public class func hiddenLoadingOnView(_ onView: UIView) {
onView.subviews.forEach { (view) in
if view.isKind(of: LoadingView.self){
view.removeFromSuperview()
}
}
}
private class func loading(_ text: String? = nil, onView: UIView? = nil, config : ShowLoadingConfig) {
let loadingView = LoadingView.init(config)
loadingView.title = text
loadingView.isUserInteractionEnabled = !config.enableEvent
if onView != nil {
hiddenLoadingOnView(onView!)
onView?.addSubview(loadingView)
onView?.bringSubviewToFront(loadingView)
loadingView.layer.zPosition = CGFloat(MAXFLOAT)
}else{
hiddenLoadingOnWindow()
getWindow().addSubview(loadingView)
}
loadingView.snp.makeConstraints { (make) in
make.edges.equalTo(UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0))
}
}
}
////MARK: --Alert
extension Show{
public typealias ConfigAlert = ((_ config : ShowAlertConfig) -> Void)
public class func showAlert(title: String? = nil,
message: String? = nil,
leftBtnTitle: String? = nil,
rightBtnTitle: String? = nil,
leftBlock: LeftCallBack? = nil,
rightBlock: RightCallback? = nil) {
showCustomAlert(title: title,
message: message,
leftBtnTitle: leftBtnTitle,
rightBtnTitle: rightBtnTitle,
leftBlock: leftBlock,
rightBlock: rightBlock)
}
public class func showAttributedAlert(attributedTitle : NSAttributedString? = nil,
attributedMessage : NSAttributedString? = nil,
leftBtnAttributedTitle: NSAttributedString? = nil,
rightBtnAttributedTitle: NSAttributedString? = nil,
leftBlock: LeftCallBack? = nil,
rightBlock: RightCallback? = nil) {
showCustomAlert(attributedTitle: attributedTitle,
attributedMessage: attributedMessage,
leftBtnAttributedTitle: leftBtnAttributedTitle,
rightBtnAttributedTitle: rightBtnAttributedTitle,
leftBlock: leftBlock,
rightBlock: rightBlock)
}
public class func showCustomAlert(title: String? = nil,
attributedTitle : NSAttributedString? = nil,
titleImage: UIImage? = nil,
message: String? = nil,
attributedMessage : NSAttributedString? = nil,
leftBtnTitle: String? = nil,
leftBtnAttributedTitle: NSAttributedString? = nil,
rightBtnTitle: String? = nil,
rightBtnAttributedTitle: NSAttributedString? = nil,
leftBlock: LeftCallBack? = nil,
rightBlock: RightCallback? = nil,
config : ConfigAlert? = nil) {
hiddenAlert()
let model = ShowAlertConfig()
if let _ = titleImage{
model.space = 10
}
config?(model)
let alertView = AlertView.init(title: title,
attributedTitle: attributedTitle,
titleImage: titleImage,
message: message,
attributedMessage: attributedMessage,
leftBtnTitle: leftBtnTitle,
leftBtnAttributedTitle: leftBtnAttributedTitle,
rightBtnTitle: rightBtnTitle,
rightBtnAttributedTitle: rightBtnAttributedTitle,
config: model)
alertView.leftBlock = leftBlock
alertView.rightBlock = rightBlock
alertView.dismissBlock = {
hiddenAlert()
}
getWindow().addSubview(alertView)
alertView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
}
public class func hiddenAlert() {
getWindow().subviews.forEach { (view) in
if view.isKind(of: AlertView.self){
UIView.animate(withDuration: 0.3, animations: {
view.alpha = 0
}) { (_) in
view.removeFromSuperview()
}
}
}
}
}
//MARK: --pop
extension Show{
public typealias ConfigPop = ((_ config : ShowPopViewConfig) -> Void)
/// 弹出view
/// - Parameters:
/// - contentView: 被弹出的view
/// - config: 配置信息
public class func showPopView(contentView: UIView,
config : ConfigPop? = nil,
showClosure: CallBack? = nil,
hideClosure: CallBack? = nil) {
getWindow().subviews.forEach { (view) in
if view.isKind(of: PopView.self){
view.removeFromSuperview()
}
}
showPopCallBack = showClosure
hidePopCallBack = hideClosure
let model = ShowPopViewConfig()
config?(model)
let popView = PopView.init(contentView: contentView, config: model) {
hidenPopView()
}
getWindow().addSubview(popView)
popView.showAnimate()
showPopCallBack?()
}
public class func hidenPopView(_ complete : (() -> Void)? = nil ) {
getWindow().subviews.forEach { (view) in
if view.isKind(of: PopView.self){
let popView : PopView = view as! PopView
popView.hideAnimate {
UIView.animate(withDuration: 0.1, animations: {
view.alpha = 0
}) { (_) in
complete?()
view.removeFromSuperview()
hidePopCallBack?()
}
}
}
}
}
}
//MARK: --DropDown
extension Show{
/// 弹出下拉视图,盖住Tabbar
/// - Parameters:
/// - contentView: view
/// - config: 配置
public class func showCoverTabbarView(contentView: UIView,
config: ((_ config : ShowDropDownConfig) -> Void)? = nil,
showClosure: CallBack? = nil,
hideClosure: CallBack? = nil,
willShowClosure: CallBack? = nil,
willHideClosure: CallBack? = nil) {
if !isHaveCoverTabbarView() {
showCoverCallBack = showClosure
hideCoverCallBack = hideClosure
willShowCoverCallBack = willShowClosure
willHideCoverCallBack = willHideClosure
willShowCoverCallBack?()
let model = ShowDropDownConfig()
config?(model)
let popView = DropDownView.init(contentView: contentView, config: model) {
hidenCoverTabbarView()
}
getWindow().rootViewController?.view.addSubview(popView)
popView.showAnimate {
showCoverCallBack?()
}
}
}
public class func isHaveCoverTabbarView() -> Bool{
var isHave = false
getWindow().rootViewController?.view.subviews.forEach { (view) in
if view.isKind(of: DropDownView.self){
isHave = true
}
}
return isHave
}
public class func hidenCoverTabbarView(_ complete : (() -> Void)? = nil ) {
getWindow().rootViewController?.view.subviews.forEach { (view) in
if view.isKind(of: DropDownView.self){
let popView : DropDownView = view as! DropDownView
willHideCoverCallBack?()
popView.hideAnimate {
UIView.animate(withDuration: 0.1, animations: {
view.alpha = 0
}) { (_) in
complete?()
view.removeFromSuperview()
hideCoverCallBack?()
}
}
}
}
}
}
//MARK: -- 获取最上层视图
public class Show{
public typealias CallBack = () -> Void
private static var showCoverCallBack : CallBack?
private static var hideCoverCallBack : CallBack?
private static var willShowCoverCallBack : CallBack?
private static var willHideCoverCallBack : CallBack?
private static var showPopCallBack : CallBack?
private static var hidePopCallBack : CallBack?
private class func getWindow() -> UIWindow {
var window = UIApplication.shared.keyWindow
//是否为当前显示的window
if window?.windowLevel != UIWindow.Level.normal{
let windows = UIApplication.shared.windows
for windowTemp in windows{
if windowTemp.windowLevel == UIWindow.Level.normal{
window = windowTemp
break
}
}
}
return window!
}
/// 获取顶层VC 根据window
public class func currentViewController() -> (UIViewController?) {
let vc = getWindow().rootViewController
return getCurrentViewController(withCurrentVC: vc)
}
///根据控制器获取 顶层控制器 递归
private class func getCurrentViewController(withCurrentVC VC :UIViewController?) -> UIViewController? {
if VC == nil {
debugPrint("🌶: 找不到顶层控制器")
return nil
}
if let presentVC = VC?.presentedViewController {
//modal出来的 控制器
return getCurrentViewController(withCurrentVC: presentVC)
}
else if let splitVC = VC as? UISplitViewController {
// UISplitViewController 的跟控制器
if splitVC.viewControllers.count > 0 {
return getCurrentViewController(withCurrentVC: splitVC.viewControllers.last)
}else{
return VC
}
}
else if let tabVC = VC as? UITabBarController {
// tabBar 的跟控制器
if tabVC.viewControllers != nil {
return getCurrentViewController(withCurrentVC: tabVC.selectedViewController)
}else{
return VC
}
}
else if let naiVC = VC as? UINavigationController {
// 控制器是 nav
if naiVC.viewControllers.count > 0 {
// return getCurrentViewController(withCurrentVC: naiVC.topViewController)
return getCurrentViewController(withCurrentVC:naiVC.visibleViewController)
}else{
return VC
}
}
else {
// 返回顶控制器
return VC
}
}
}
| 34.565217 | 111 | 0.507977 |
89816d107de6979dad646085d6924f582e8d5fa1 | 1,687 | import XCTest
@testable import kubrick
class SourceTests: XCTestCase {
override func setUp() {
super.setUp()
useMockDeviceIO()
}
func test_that_we_can_add_a_video_input() {
let session = CaptureSession()
let cameraSource = MockCameraSource("")
let camera = Camera(cameraSource)
XCTAssertNil(camera.input)
XCTAssertNil(camera.output)
XCTAssertEqual(camera.source.type, .video)
session.addInput(camera)
XCTAssertNotNil(camera.input)
XCTAssertNotNil(camera.output)
}
func test_that_we_can_add_an_audio_input() {
let session = CaptureSession()
let micSource = MockMicrophoneSource()
let mic = Microphone(micSource)
XCTAssertNil(mic.input)
XCTAssertNil(mic.output)
XCTAssertEqual(mic.source.type, .audio)
session.addInput(mic)
XCTAssertNotNil(mic.input)
XCTAssertNotNil(mic.output)
}
#if os(macOS) || os(iOS)
func test_that_we_can_remove_a_video_input() {
useRealDeviceIO()
let session = CaptureSession()
let devA = AVDeviceDiscoverer().devices.first
XCTAssertNotNil(devA)
XCTAssertEqual(0, session.inputs.count)
XCTAssertEqual(0, session.outputs.count)
session.addInput(devA!)
XCTAssertEqual(1, session.inputs.count)
XCTAssertEqual(1, session.outputs.count)
session.removeInput(devA!)
XCTAssertEqual(0, session.inputs.count)
XCTAssertEqual(0, session.outputs.count)
}
#endif
}
| 27.655738 | 59 | 0.611737 |
1ad7c0b52b39c2e317aa5e4b1c42f7edba4e2421 | 1,159 | // ===----------------------------------------------------------------------===
//
// ClassDescriptor.swift
// BSRuntime
//
// Created by 0x41c on 2022-03-13.
//
// ===----------------------------------------------------------------------===
//
// Copyright 2022 0x41c
//
// 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.
//
// ===----------------------------------------------------------------------===
// TODO: Complete this
public struct ClassDescriptor: StructureRepresentation {
public struct InternalRepresentation: InternalStructureBase {
}
public var `_`: UnsafeMutablePointer<InternalRepresentation>
}
| 32.194444 | 79 | 0.569456 |
468d56103b168521670012d3d5b06f9ac8fd65ee | 60 | public enum APIKeys {
public static let someKey = ""
}
| 12 | 34 | 0.65 |
29ad0d89219912bf78db8128c68b1a3d7eec7265 | 760 | //
// IoCContainer.swift
// SwiftKit
//
// Created by Daniel Saidi on 2016-03-10.
// Copyright © 2020 Daniel Saidi. All rights reserved.
//
import Foundation
/**
This protocol can be implemented by classes that can handle
inversion of control, by dynamically resolving types, given
any required arguments.
*/
public protocol IoCContainer {
func resolve<T>() -> T
func resolve<T, A>(arguments arg1: A) -> T
func resolve<T, A, B>(arguments arg1: A, _ arg2: B) -> T
func resolve<T, A, B, C>(arguments arg1: A, _ arg2: B, _ arg3: C) -> T
func resolve<T, A, B, C, D>(arguments arg1: A, _ arg2: B, _ arg3: C, _ arg4: D) -> T
func resolve<T, A, B, C, D, E>(arguments arg1: A, _ arg2: B, _ arg3: C, _ arg4: D, _ arg5: E) -> T
}
| 29.230769 | 102 | 0.632895 |
0e524289dee924da823ff4ec3269a0f88a793be9 | 383 | // 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
var b {
let a<Int>(n: T>? = c: AnyObject) {
}
print()
class A, Any, U) -> {
typealias A {
}
}
protocol A {
func f(T>(t.E == 1
let foo as String) -> ()
typealias e : e)
| 20.157895 | 87 | 0.660574 |
e6ba198045dbb245a958b7f662358d11942757df | 1,483 | //
// CustomNavigationView.swift
// OilPrice-Where
//
// Created by wargi_p on 2021/12/17.
// Copyright © 2021 sangwook park. All rights reserved.
//
import Foundation
import UIKit
//MARK: 길찾기 버튼
final class CustomNavigationView: UIView {
// Properties
let logoImageView = UIImageView().then {
$0.image = Asset.Images.navigationIcon.image
$0.contentMode = .scaleAspectFit
$0.backgroundColor = .white
}
let titleLabel = UILabel().then {
$0.text = "길찾기"
$0.textColor = Asset.Colors.mainColor.color
$0.textAlignment = .left
}
// Initializer
override init(frame: CGRect) {
super.init(frame: frame)
makeUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Set UI
private func makeUI() {
layer.cornerRadius = 6
layer.borderColor = Asset.Colors.mainColor.color.cgColor
layer.borderWidth = 1.5
addSubview(logoImageView)
addSubview(titleLabel)
logoImageView.snp.makeConstraints {
$0.centerY.equalToSuperview()
$0.centerX.equalToSuperview().offset(-25.5)
$0.size.equalTo(22)
}
titleLabel.snp.makeConstraints {
$0.centerY.equalToSuperview()
$0.left.equalTo(logoImageView.snp.right).offset(7)
$0.right.equalToSuperview()
}
}
}
| 25.568966 | 64 | 0.59002 |
7642cf75ff806d741a2cc5544e5ddb6fd4423e64 | 3,107 | //
// LoadingDemoViewController.swift
// development-pods-instantsearch
//
// Created by Vladislav Fitc on 25/06/2019.
// Copyright © 2019 Algolia. All rights reserved.
//
import Foundation
import UIKit
import InstantSearch
import SDWebImage
class LoadingDemoViewController: UIViewController {
typealias HitType = Movie
let controller: LoadingDemoController
let activityIndicator = UIActivityIndicatorView(style: .medium)
let searchBar: UISearchBar
let searchBarController: TextFieldController
let loadingController: ActivityIndicatorController
let statsController: LabelStatsController
let hitsTableViewController: MovieHitsTableViewController<HitType>
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
searchBar = .init()
searchBarController = .init(searchBar: searchBar)
statsController = .init(label: .init())
loadingController = .init(activityIndicator: activityIndicator)
hitsTableViewController = MovieHitsTableViewController()
self.controller = .init(queryInputController: searchBarController,
loadingController: loadingController,
statsController: statsController,
hitsController: hitsTableViewController)
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
}
private func setup() {
addChild(hitsTableViewController)
hitsTableViewController.didMove(toParent: self)
activityIndicator.hidesWhenStopped = true
hitsTableViewController.tableView.register(MovieTableViewCell.self, forCellReuseIdentifier: hitsTableViewController.cellIdentifier)
}
}
private extension LoadingDemoViewController {
func configureUI() {
view.backgroundColor = .white
searchBar.translatesAutoresizingMaskIntoConstraints = false
statsController.label.translatesAutoresizingMaskIntoConstraints = false
let barStackView = UIStackView()
.set(\.translatesAutoresizingMaskIntoConstraints, to: false)
.set(\.axis, to: .horizontal)
barStackView.addArrangedSubview(searchBar)
barStackView.addArrangedSubview(activityIndicator)
let statsContainer = UIView()
.set(\.translatesAutoresizingMaskIntoConstraints, to: false)
.set(\.layoutMargins, to: UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20))
statsContainer.addSubview(statsController.label)
statsController.label.pin(to: statsContainer.layoutMarginsGuide)
let stackView = UIStackView()
.set(\.spacing, to: .px16)
.set(\.axis, to: .vertical)
.set(\.translatesAutoresizingMaskIntoConstraints, to: false)
stackView.addArrangedSubview(barStackView)
stackView.addArrangedSubview(statsContainer)
stackView.addArrangedSubview(hitsTableViewController.view)
view.addSubview(stackView)
stackView.pin(to: view.safeAreaLayoutGuide)
}
}
| 32.364583 | 135 | 0.73962 |
e21231eff7e1468007d72ebc68b31338dc6cadc9 | 2,903 | protocol PeripheralTaskSpec {
associatedtype Key: Equatable
associatedtype Group = PeripheralID
associatedtype Params
associatedtype Stage
associatedtype Result
static var tag: String { get }
static func isMember(_ key: Key, of group: Group) -> Bool
}
enum PeripheralTaskState<Stage, Result> {
case pending
case processing(since: Date, Stage)
case finished(in: TimeInterval, Result)
func processing(_ stage: Stage) -> PeripheralTaskState {
switch self {
case .pending:
return .processing(since: Date(), stage)
case .processing(let start, _):
return .processing(since: start, stage)
case .finished:
assert(false, "Invalid transition: \(self) -> .processing")
return .processing(since: .distantPast, stage)
}
}
func finished(_ result: Result) -> PeripheralTaskState {
switch self {
case .pending:
return .finished(in: 0, result)
case .processing(let start, _):
return .finished(in: -start.timeIntervalSinceNow, result)
case .finished:
assert(false, "Invalid transition: \(self) -> .finished")
return .finished(in: 0, result)
}
}
}
struct PeripheralTask<Spec: PeripheralTaskSpec> {
typealias Key = Spec.Key
typealias Group = Spec.Group
typealias Params = Spec.Params
typealias Stage = Spec.Stage
typealias Result = Spec.Result
typealias State = PeripheralTaskState<Stage, Result>
typealias Timeout = (duration: TimeInterval, handler: () -> Void)
typealias CompletionHandler = (Result) -> Void
let key: Key
let params: Params
let state: State
let timeout: Timeout?
let completion: CompletionHandler
init(key: Key, params: Params, timeout: Timeout?, completion: @escaping CompletionHandler) {
self.init(key: key, params: params, state: .pending, timeout: timeout, completion: completion)
}
private init(key: Key, params: Params, state: State, timeout: Timeout?, completion: @escaping CompletionHandler) {
self.key = key
self.params = params
self.state = state
self.timeout = timeout
self.completion = completion
}
func with(state newState: State) -> PeripheralTask {
return PeripheralTask(
key: key,
params: params,
state: newState,
timeout: timeout,
completion: completion
)
}
func isMember(of group: Group) -> Bool {
return Spec.isMember(key, of: group)
}
func iif<T>(finished: (TimeInterval, Result) -> T, otherwise: () -> T) -> T {
switch state {
case .pending, .processing:
return otherwise()
case .finished(let duration, let result):
return finished(duration, result)
}
}
}
| 29.622449 | 118 | 0.619015 |
defda931748759e47d0cf0d8b8f56cfe47a5e487 | 6,055 | //
// InAppBrowserManager.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 18/12/2019.
//
import Flutter
import UIKit
import WebKit
import Foundation
import AVFoundation
let WEBVIEW_STORYBOARD = "WebView"
let WEBVIEW_STORYBOARD_CONTROLLER_ID = "viewController"
let NAV_STORYBOARD_CONTROLLER_ID = "navController"
public class InAppBrowserManager: NSObject, FlutterPlugin {
static var registrar: FlutterPluginRegistrar?
static var channel: FlutterMethodChannel?
private var previousStatusBarStyle = -1
public static func register(with registrar: FlutterPluginRegistrar) {
}
init(registrar: FlutterPluginRegistrar) {
super.init()
InAppBrowserManager.registrar = registrar
InAppBrowserManager.channel = FlutterMethodChannel(name: "com.pichillilorenzo/flutter_inappbrowser", binaryMessenger: registrar.messenger())
registrar.addMethodCallDelegate(self, channel: InAppBrowserManager.channel!)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let arguments = call.arguments as? NSDictionary
switch call.method {
case "open":
open(arguments: arguments!)
result(true)
break
case "openWithSystemBrowser":
let url = arguments!["url"] as! String
openWithSystemBrowser(url: url, result: result)
break
default:
result(FlutterMethodNotImplemented)
break
}
}
public func prepareInAppBrowserWebViewController(options: [String: Any?]) -> InAppBrowserWebViewController {
if previousStatusBarStyle == -1 {
previousStatusBarStyle = UIApplication.shared.statusBarStyle.rawValue
}
let browserOptions = InAppBrowserOptions()
let _ = browserOptions.parse(options: options)
let webViewOptions = InAppWebViewOptions()
let _ = webViewOptions.parse(options: options)
let webViewController = InAppBrowserWebViewController()
webViewController.browserOptions = browserOptions
webViewController.webViewOptions = webViewOptions
webViewController.previousStatusBarStyle = previousStatusBarStyle
return webViewController
}
public func open(arguments: NSDictionary) {
let id = arguments["id"] as! String
let urlRequest = arguments["urlRequest"] as? [String:Any?]
let assetFilePath = arguments["assetFilePath"] as? String
let data = arguments["data"] as? String
let mimeType = arguments["mimeType"] as? String
let encoding = arguments["encoding"] as? String
let baseUrl = arguments["baseUrl"] as? String
let options = arguments["options"] as! [String: Any?]
let contextMenu = arguments["contextMenu"] as! [String: Any]
let windowId = arguments["windowId"] as? Int64
let initialUserScripts = arguments["initialUserScripts"] as? [[String: Any]]
let pullToRefreshInitialOptions = arguments["pullToRefreshOptions"] as! [String: Any?]
let webViewController = prepareInAppBrowserWebViewController(options: options)
webViewController.id = id
webViewController.initialUrlRequest = urlRequest != nil ? URLRequest.init(fromPluginMap: urlRequest!) : nil
webViewController.initialFile = assetFilePath
webViewController.initialData = data
webViewController.initialMimeType = mimeType
webViewController.initialEncoding = encoding
webViewController.initialBaseUrl = baseUrl
webViewController.contextMenu = contextMenu
webViewController.windowId = windowId
webViewController.initialUserScripts = initialUserScripts ?? []
webViewController.pullToRefreshInitialOptions = pullToRefreshInitialOptions
presentViewController(webViewController: webViewController)
}
public func presentViewController(webViewController: InAppBrowserWebViewController) {
let storyboard = UIStoryboard(name: WEBVIEW_STORYBOARD, bundle: Bundle(for: InAppWebViewFlutterPlugin.self))
let navController = storyboard.instantiateViewController(withIdentifier: NAV_STORYBOARD_CONTROLLER_ID) as! InAppBrowserNavigationController
webViewController.edgesForExtendedLayout = []
navController.pushViewController(webViewController, animated: false)
webViewController.prepareNavigationControllerBeforeViewWillAppear()
let frame: CGRect = UIScreen.main.bounds
let tmpWindow = UIWindow(frame: frame)
let tmpController = UIViewController()
let baseWindowLevel = UIApplication.shared.keyWindow?.windowLevel
tmpWindow.rootViewController = tmpController
tmpWindow.windowLevel = UIWindow.Level(baseWindowLevel!.rawValue + 1.0)
tmpWindow.makeKeyAndVisible()
navController.tmpWindow = tmpWindow
var animated = true
if let browserOptions = webViewController.browserOptions, browserOptions.hidden {
tmpWindow.isHidden = true
UIApplication.shared.delegate?.window??.makeKeyAndVisible()
animated = false
}
tmpWindow.rootViewController!.present(navController, animated: animated, completion: nil)
}
public func openWithSystemBrowser(url: String, result: @escaping FlutterResult) {
let absoluteUrl = URL(string: url)!.absoluteURL
if !UIApplication.shared.canOpenURL(absoluteUrl) {
result(FlutterError(code: "InAppBrowserManager", message: url + " cannot be opened!", details: nil))
return
}
else {
if #available(iOS 10.0, *) {
UIApplication.shared.open(absoluteUrl, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(absoluteUrl)
}
}
result(true)
}
}
| 42.048611 | 148 | 0.681751 |
4b4112e00ee6c84e40b322eb70277c68de5db017 | 1,644 | //
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 CBIban. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationLineScale: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 1
fileprivate let timingFunction = CAMediaTimingFunction(controlPoints: 0.2, 0.68, 0.18, 1.08)
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let lineSize = size.width / 9
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let beginTime = CACurrentMediaTime()
let beginTimes = [0.1, 0.2, 0.3, 0.4, 0.5]
let animation = defaultAnimation
for i in 0 ..< 5 {
let line = ActivityIndicatorShape.line.makeLayer(size: CGSize(width: lineSize, height: size.height), color: color)
let frame = CGRect(x: x + lineSize * 2 * CGFloat(i), y: y, width: lineSize, height: size.height)
animation.beginTime = beginTime + beginTimes[i]
line.frame = frame
line.add(animation, forKey: "animation")
layer.addSublayer(line)
}
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationLineScale {
var defaultAnimation: CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: "transform.scale.y")
animation.keyTimes = [0, 0.5, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.4, 1]
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
}
| 30.444444 | 120 | 0.698905 |
4a589b458e1e5d5f455fa2f09e461eb4b92f9cc5 | 36,581 | //
// ChartViewBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
// Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
@objc
public protocol ChartViewDelegate
{
/// Called when a value has been selected inside the chart.
/// - parameter entry: The selected Entry.
/// - parameter dataSetIndex: The index in the datasets array of the data object the Entrys DataSet is in.
optional func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlight)
// Called when nothing has been selected or an "un-select" has been made.
optional func chartValueNothingSelected(chartView: ChartViewBase)
// Callbacks when the chart is scaled / zoomed via pinch zoom gesture.
optional func chartScaled(chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat)
// Callbacks when the chart is moved / translated via drag gesture.
optional func chartTranslated(chartView: ChartViewBase, dX: CGFloat, dY: CGFloat)
}
public class ChartViewBase: NSUIView, ChartDataProvider, ChartAnimatorDelegate
{
// MARK: - Properties
/// - returns: the object representing all x-labels, this method can be used to
/// acquire the XAxis object and modify it (e.g. change the position of the
/// labels)
public var xAxis: ChartXAxis
{
return _xAxis
}
/// the default value formatter
internal var _defaultValueFormatter: NSNumberFormatter = ChartUtils.defaultValueFormatter()
/// object that holds all data that was originally set for the chart, before it was modified or any filtering algorithms had been applied
internal var _data: ChartData?
/// Flag that indicates if highlighting per tap (touch) is enabled
private var _highlightPerTapEnabled = true
/// If set to true, chart continues to scroll after touch up
public var dragDecelerationEnabled = true
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
private var _dragDecelerationFrictionCoef: CGFloat = 0.9
/// Font object used for drawing the description text (by default in the bottom right corner of the chart)
public var descriptionFont: NSUIFont? = NSUIFont(name: "HelveticaNeue", size: 9.0)
/// Text color used for drawing the description text
public var descriptionTextColor: NSUIColor? = NSUIColor.blackColor()
/// Text align used for drawing the description text
public var descriptionTextAlign: NSTextAlignment = NSTextAlignment.Right
/// Custom position for the description text in pixels on the screen.
public var descriptionTextPosition: CGPoint? = nil
/// font object for drawing the information text when there are no values in the chart
public var infoFont: NSUIFont! = NSUIFont(name: "HelveticaNeue", size: 12.0)
public var infoTextColor: NSUIColor! = NSUIColor(red: 247.0/255.0, green: 189.0/255.0, blue: 51.0/255.0, alpha: 1.0) // orange
/// description text that appears in the bottom right corner of the chart
public var descriptionText = "Description"
/// if true, units are drawn next to the values in the chart
internal var _drawUnitInChart = false
/// the object representing the labels on the x-axis
internal var _xAxis: ChartXAxis!
/// the legend object containing all data associated with the legend
internal var _legend: ChartLegend!
/// delegate to receive chart events
public weak var delegate: ChartViewDelegate?
/// text that is displayed when the chart is empty
public var noDataText = "No chart data available."
/// text that is displayed when the chart is empty that describes why the chart is empty
public var noDataTextDescription: String?
internal var _legendRenderer: ChartLegendRenderer!
/// object responsible for rendering the data
public var renderer: ChartDataRendererBase?
public var highlighter: ChartHighlighter?
/// object that manages the bounds and drawing constraints of the chart
internal var _viewPortHandler: ChartViewPortHandler!
/// object responsible for animations
internal var _animator: ChartAnimator!
/// flag that indicates if offsets calculation has already been done or not
private var _offsetsCalculated = false
/// array of Highlight objects that reference the highlighted slices in the chart
internal var _indicesToHighlight = [ChartHighlight]()
/// if set to true, the marker is drawn when a value is clicked
public var drawMarkers = true
/// the view that represents the marker
public var marker: ChartMarker?
private var _interceptTouchEvents = false
/// An extra offset to be appended to the viewport's top
public var extraTopOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's right
public var extraRightOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's bottom
public var extraBottomOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's left
public var extraLeftOffset: CGFloat = 0.0
public func setExtraOffsets(left left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
extraLeftOffset = left
extraTopOffset = top
extraRightOffset = right
extraBottomOffset = bottom
}
// MARK: - Initializers
public override init(frame: CGRect)
{
super.init(frame: frame)
#if os(iOS)
self.backgroundColor = NSUIColor.clearColor()
#endif
initialize()
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
initialize()
}
deinit
{
self.removeObserver(self, forKeyPath: "bounds")
self.removeObserver(self, forKeyPath: "frame")
}
internal func initialize()
{
_animator = ChartAnimator()
_animator.delegate = self
_viewPortHandler = ChartViewPortHandler()
_viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height)
_legend = ChartLegend()
_legendRenderer = ChartLegendRenderer(viewPortHandler: _viewPortHandler, legend: _legend)
_xAxis = ChartXAxis()
self.addObserver(self, forKeyPath: "bounds", options: .New, context: nil)
self.addObserver(self, forKeyPath: "frame", options: .New, context: nil)
}
// MARK: - ChartViewBase
/// The data for the chart
public var data: ChartData?
{
get
{
return _data
}
set
{
_offsetsCalculated = false
_data = newValue
// calculate how many digits are needed
if let data = _data
{
calculateFormatter(min: data.getYMin(), max: data.getYMax())
}
notifyDataSetChanged()
}
}
/// Clears the chart from all data (sets it to null) and refreshes it (by calling setNeedsDisplay()).
public func clear()
{
_data = nil
_indicesToHighlight.removeAll()
setNeedsDisplay()
}
/// Removes all DataSets (and thereby Entries) from the chart. Does not remove the x-values. Also refreshes the chart by calling setNeedsDisplay().
public func clearValues()
{
_data?.clearValues()
setNeedsDisplay()
}
/// - returns: true if the chart is empty (meaning it's data object is either null or contains no entries).
public func isEmpty() -> Bool
{
guard let data = _data else { return true }
if (data.yValCount <= 0)
{
return true
}
else
{
return false
}
}
/// Lets the chart know its underlying data has changed and should perform all necessary recalculations.
/// It is crucial that this method is called everytime data is changed dynamically. Not calling this method can lead to crashes or unexpected behaviour.
public func notifyDataSetChanged()
{
fatalError("notifyDataSetChanged() cannot be called on ChartViewBase")
}
/// calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position
internal func calculateOffsets()
{
fatalError("calculateOffsets() cannot be called on ChartViewBase")
}
/// calcualtes the y-min and y-max value and the y-delta and x-delta value
internal func calcMinMax()
{
fatalError("calcMinMax() cannot be called on ChartViewBase")
}
/// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter
internal func calculateFormatter(min min: Double, max: Double)
{
// check if a custom formatter is set or not
var reference = Double(0.0)
if let data = _data where data.xValCount >= 2
{
reference = fabs(max - min)
}
else
{
let absMin = fabs(min)
let absMax = fabs(max)
reference = absMin > absMax ? absMin : absMax
}
let digits = ChartUtils.decimals(reference)
_defaultValueFormatter.maximumFractionDigits = digits
_defaultValueFormatter.minimumFractionDigits = digits
}
public override func drawRect(rect: CGRect)
{
let optionalContext = NSUIGraphicsGetCurrentContext()
guard let context = optionalContext else { return }
let frame = self.bounds
if _data === nil
{
CGContextSaveGState(context)
defer { CGContextRestoreGState(context) }
let hasText = noDataText.characters.count > 0
let hasDescription = noDataTextDescription?.characters.count > 0
var textHeight = hasText ? infoFont.lineHeight : 0.0
if hasDescription
{
textHeight += infoFont.lineHeight
}
// if no data, inform the user
var y = (frame.height - textHeight) / 2.0
if hasText
{
ChartUtils.drawText(
context: context,
text: noDataText,
point: CGPoint(x: frame.width / 2.0, y: y),
align: .Center,
attributes: [NSFontAttributeName: infoFont, NSForegroundColorAttributeName: infoTextColor]
)
y = y + infoFont.lineHeight
}
if (noDataTextDescription != nil && (noDataTextDescription!).characters.count > 0)
{
ChartUtils.drawText(context: context, text: noDataTextDescription!, point: CGPoint(x: frame.width / 2.0, y: y), align: .Center, attributes: [NSFontAttributeName: infoFont, NSForegroundColorAttributeName: infoTextColor])
}
return
}
if (!_offsetsCalculated)
{
calculateOffsets()
_offsetsCalculated = true
}
}
/// draws the description text in the bottom right corner of the chart
internal func drawDescription(context context: CGContext)
{
if (descriptionText.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) == 0)
{
return
}
let frame = self.bounds
var attrs = [String : AnyObject]()
var font = descriptionFont
if (font == nil)
{
#if os(tvOS)
// 23 is the smallest recommended font size on the TV
font = NSUIFont.systemFontOfSize(23, weight: UIFontWeightMedium)
#else
font = NSUIFont.systemFontOfSize(NSUIFont.systemFontSize())
#endif
}
attrs[NSFontAttributeName] = font
attrs[NSForegroundColorAttributeName] = descriptionTextColor
if descriptionTextPosition == nil
{
ChartUtils.drawText(
context: context,
text: descriptionText,
point: CGPoint(
x: frame.width - _viewPortHandler.offsetRight - 10.0,
y: frame.height - _viewPortHandler.offsetBottom - 10.0 - (font?.lineHeight ?? 0.0)),
align: descriptionTextAlign,
attributes: attrs)
}
else
{
ChartUtils.drawText(
context: context,
text: descriptionText,
point: descriptionTextPosition!,
align: descriptionTextAlign,
attributes: attrs)
}
}
// MARK: - Highlighting
/// - returns: the array of currently highlighted values. This might an empty if nothing is highlighted.
public var highlighted: [ChartHighlight]
{
return _indicesToHighlight
}
/// Set this to false to prevent values from being highlighted by tap gesture.
/// Values can still be highlighted via drag or programmatically.
/// **default**: true
public var highlightPerTapEnabled: Bool
{
get { return _highlightPerTapEnabled }
set { _highlightPerTapEnabled = newValue }
}
/// Returns true if values can be highlighted via tap gesture, false if not.
public var isHighLightPerTapEnabled: Bool
{
return highlightPerTapEnabled
}
/// Checks if the highlight array is null, has a length of zero or if the first object is null.
/// - returns: true if there are values to highlight, false if there are no values to highlight.
public func valuesToHighlight() -> Bool
{
return _indicesToHighlight.count > 0
}
/// Highlights the values at the given indices in the given DataSets. Provide
/// null or an empty array to undo all highlighting.
/// This should be used to programmatically highlight values.
/// This DOES NOT generate a callback to the delegate.
public func highlightValues(highs: [ChartHighlight]?)
{
// set the indices to highlight
_indicesToHighlight = highs ?? [ChartHighlight]()
if (_indicesToHighlight.isEmpty)
{
self.lastHighlighted = nil
}
else
{
self.lastHighlighted = _indicesToHighlight[0];
}
// redraw the chart
setNeedsDisplay()
}
/// Highlights the values represented by the provided Highlight object
/// This DOES NOT generate a callback to the delegate.
/// - parameter highlight: contains information about which entry should be highlighted
public func highlightValue(highlight: ChartHighlight?)
{
highlightValue(highlight: highlight, callDelegate: false)
}
/// Highlights the value at the given x-index in the given DataSet.
/// Provide -1 as the x-index to undo all highlighting.
public func highlightValue(xIndex xIndex: Int, dataSetIndex: Int)
{
highlightValue(xIndex: xIndex, dataSetIndex: dataSetIndex, callDelegate: true)
}
/// Highlights the value at the given x-index in the given DataSet.
/// Provide -1 as the x-index to undo all highlighting.
public func highlightValue(xIndex xIndex: Int, dataSetIndex: Int, callDelegate: Bool)
{
guard let data = _data else
{
Swift.print("Value not highlighted because data is nil")
return
}
if (xIndex < 0 || dataSetIndex < 0 || xIndex >= data.xValCount || dataSetIndex >= data.dataSetCount)
{
highlightValue(highlight: nil, callDelegate: callDelegate)
}
else
{
highlightValue(highlight: ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex), callDelegate: callDelegate)
}
}
/// Highlights the value selected by touch gesture.
public func highlightValue(highlight highlight: ChartHighlight?, callDelegate: Bool)
{
var entry: ChartDataEntry?
var h = highlight
if (h == nil)
{
_indicesToHighlight.removeAll(keepCapacity: false)
}
else
{
// set the indices to highlight
entry = _data?.getEntryForHighlight(h!)
if (entry == nil)
{
h = nil
_indicesToHighlight.removeAll(keepCapacity: false)
}
else
{
if self is BarLineChartViewBase
&& (self as! BarLineChartViewBase).isHighlightFullBarEnabled
{
h = ChartHighlight(xIndex: h!.xIndex, value: Double.NaN, dataIndex: -1, dataSetIndex: -1, stackIndex: -1)
}
_indicesToHighlight = [h!]
}
}
if (callDelegate && delegate != nil)
{
if (h == nil)
{
delegate!.chartValueNothingSelected?(self)
}
else
{
// notify the listener
delegate!.chartValueSelected?(self, entry: entry!, dataSetIndex: h!.dataSetIndex, highlight: h!)
}
}
// redraw the chart
setNeedsDisplay()
}
/// The last value that was highlighted via touch.
public var lastHighlighted: ChartHighlight?
// MARK: - Markers
/// draws all MarkerViews on the highlighted positions
internal func drawMarkers(context context: CGContext)
{
// if there is no marker view or drawing marker is disabled
if (marker === nil || !drawMarkers || !valuesToHighlight())
{
return
}
for i in 0 ..< _indicesToHighlight.count
{
let highlight = _indicesToHighlight[i]
let xIndex = highlight.xIndex
let deltaX = _xAxis?.axisRange ?? (Double(_data?.xValCount ?? 0) - 1)
if xIndex <= Int(deltaX) && xIndex <= Int(CGFloat(deltaX) * _animator.phaseX)
{
let e = _data?.getEntryForHighlight(highlight)
if (e === nil || e!.xIndex != highlight.xIndex)
{
continue
}
let pos = getMarkerPosition(entry: e!, highlight: highlight)
// check bounds
if (!_viewPortHandler.isInBounds(x: pos.x, y: pos.y))
{
continue
}
// callbacks to update the content
marker!.refreshContent(entry: e!, highlight: highlight)
let markerSize = marker!.size
if (pos.y - markerSize.height <= 0.0)
{
let y = markerSize.height - pos.y
marker!.draw(context: context, point: CGPoint(x: pos.x, y: pos.y + y))
}
else
{
marker!.draw(context: context, point: pos)
}
}
}
}
/// - returns: the actual position in pixels of the MarkerView for the given Entry in the given DataSet.
public func getMarkerPosition(entry entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint
{
fatalError("getMarkerPosition() cannot be called on ChartViewBase")
}
// MARK: - Animation
/// - returns: the animator responsible for animating chart values.
public var chartAnimator: ChartAnimator!
{
return _animator
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingX: an easing function for the animation on the x axis
/// - parameter easingY: an easing function for the animation on the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOptionX: the easing function for the animation on the x axis
/// - parameter easingOptionY: the easing function for the animation on the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easing: an easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easingOption: the easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval)
{
_animator.animate(xAxisDuration: xAxisDuration)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
public func animate(yAxisDuration yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
public func animate(yAxisDuration yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
public func animate(yAxisDuration yAxisDuration: NSTimeInterval)
{
_animator.animate(yAxisDuration: yAxisDuration)
}
// MARK: - Accessors
/// - returns: the current y-max value across all DataSets
public var chartYMax: Double
{
return _data?.yMax ?? 0.0
}
/// - returns: the current y-min value across all DataSets
public var chartYMin: Double
{
return _data?.yMin ?? 0.0
}
public var chartXMax: Double
{
return _xAxis._axisMaximum
}
public var chartXMin: Double
{
return _xAxis._axisMinimum
}
public var xValCount: Int
{
return _data?.xValCount ?? 0
}
/// - returns: the total number of (y) values the chart holds (across all DataSets)
public var valueCount: Int
{
return _data?.yValCount ?? 0
}
/// *Note: (Equivalent of getCenter() in MPAndroidChart, as center is already a standard in iOS that returns the center point relative to superview, and MPAndroidChart returns relative to self)*
/// - returns: the center point of the chart (the whole View) in pixels.
public var midPoint: CGPoint
{
let bounds = self.bounds
return CGPoint(x: bounds.origin.x + bounds.size.width / 2.0, y: bounds.origin.y + bounds.size.height / 2.0)
}
public func setDescriptionTextPosition(x x: CGFloat, y: CGFloat)
{
descriptionTextPosition = CGPoint(x: x, y: y)
}
/// - returns: the center of the chart taking offsets under consideration. (returns the center of the content rectangle)
public var centerOffsets: CGPoint
{
return _viewPortHandler.contentCenter
}
/// - returns: the Legend object of the chart. This method can be used to get an instance of the legend in order to customize the automatically generated Legend.
public var legend: ChartLegend
{
return _legend
}
/// - returns: the renderer object responsible for rendering / drawing the Legend.
public var legendRenderer: ChartLegendRenderer!
{
return _legendRenderer
}
/// - returns: the rectangle that defines the borders of the chart-value surface (into which the actual values are drawn).
public var contentRect: CGRect
{
return _viewPortHandler.contentRect
}
/// - returns: the x-value at the given index
public func getXValue(index: Int) -> String!
{
guard let data = _data where data.xValCount > index else
{
return nil
}
return data.xVals[index]
}
/// Get all Entry objects at the given index across all DataSets.
public func getEntriesAtIndex(xIndex: Int) -> [ChartDataEntry]
{
var vals = [ChartDataEntry]()
guard let data = _data else { return vals }
for i in 0 ..< data.dataSetCount
{
let set = data.getDataSetByIndex(i)
let e = set.entryForXIndex(xIndex)
if (e !== nil)
{
vals.append(e!)
}
}
return vals
}
/// - returns: the ViewPortHandler of the chart that is responsible for the
/// content area of the chart and its offsets and dimensions.
public var viewPortHandler: ChartViewPortHandler!
{
return _viewPortHandler
}
/// - returns: the bitmap that represents the chart.
public func getChartImage(transparent transparent: Bool) -> NSUIImage?
{
NSUIGraphicsBeginImageContextWithOptions(bounds.size, opaque || !transparent, NSUIMainScreen()?.nsuiScale ?? 1.0)
let context = NSUIGraphicsGetCurrentContext()
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: bounds.size)
if (opaque || !transparent)
{
// Background color may be partially transparent, we must fill with white if we want to output an opaque image
CGContextSetFillColorWithColor(context, NSUIColor.whiteColor().CGColor)
CGContextFillRect(context, rect)
if (self.backgroundColor !== nil)
{
CGContextSetFillColorWithColor(context, self.backgroundColor?.CGColor)
CGContextFillRect(context, rect)
}
}
if let context = context
{
nsuiLayer?.renderInContext(context)
}
let image = NSUIGraphicsGetImageFromCurrentImageContext()
NSUIGraphicsEndImageContext()
return image
}
public enum ImageFormat
{
case JPEG
case PNG
}
/// Saves the current chart state with the given name to the given path on
/// the sdcard leaving the path empty "" will put the saved file directly on
/// the SD card chart is saved as a PNG image, example:
/// saveToPath("myfilename", "foldername1/foldername2")
///
/// - parameter filePath: path to the image to save
/// - parameter format: the format to save
/// - parameter compressionQuality: compression quality for lossless formats (JPEG)
///
/// - returns: true if the image was saved successfully
public func saveToPath(path: String, format: ImageFormat, compressionQuality: Double) -> Bool
{
if let image = getChartImage(transparent: format != .JPEG) {
var imageData: NSData!
switch (format)
{
case .PNG:
imageData = NSUIImagePNGRepresentation(image)
break
case .JPEG:
imageData = NSUIImageJPEGRepresentation(image, CGFloat(compressionQuality))
break
}
return imageData.writeToFile(path, atomically: true)
}
return false
}
#if !os(tvOS) && !os(OSX)
/// Saves the current state of the chart to the camera roll
public func saveToCameraRoll()
{
if let img = getChartImage(transparent: false) {
UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil)
}
}
#endif
internal var _viewportJobs = [ChartViewPortJob]()
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>)
{
if (keyPath == "bounds" || keyPath == "frame")
{
let bounds = self.bounds
if (_viewPortHandler !== nil &&
(bounds.size.width != _viewPortHandler.chartWidth ||
bounds.size.height != _viewPortHandler.chartHeight))
{
_viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height)
// Finish any pending viewport changes
while (!_viewportJobs.isEmpty)
{
let job = _viewportJobs.removeAtIndex(0)
job.doJob()
}
notifyDataSetChanged()
}
}
}
public func removeViewportJob(job: ChartViewPortJob)
{
if let index = _viewportJobs.indexOf({ $0 === job })
{
_viewportJobs.removeAtIndex(index)
}
}
public func clearAllViewportJobs()
{
_viewportJobs.removeAll(keepCapacity: false)
}
public func addViewportJob(job: ChartViewPortJob)
{
if (_viewPortHandler.hasChartDimens)
{
job.doJob()
}
else
{
_viewportJobs.append(job)
}
}
/// **default**: true
/// - returns: true if chart continues to scroll after touch up, false if not.
public var isDragDecelerationEnabled: Bool
{
return dragDecelerationEnabled
}
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
///
/// **default**: true
public var dragDecelerationFrictionCoef: CGFloat
{
get
{
return _dragDecelerationFrictionCoef
}
set
{
var val = newValue
if (val < 0.0)
{
val = 0.0
}
if (val >= 1.0)
{
val = 0.999
}
_dragDecelerationFrictionCoef = val
}
}
// MARK: - ChartAnimatorDelegate
public func chartAnimatorUpdated(chartAnimator: ChartAnimator)
{
setNeedsDisplay()
}
public func chartAnimatorStopped(chartAnimator: ChartAnimator)
{
}
// MARK: - Touches
public override func nsuiTouchesBegan(touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
if (!_interceptTouchEvents)
{
super.nsuiTouchesBegan(touches, withEvent: event)
}
}
public override func nsuiTouchesMoved(touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
if (!_interceptTouchEvents)
{
super.nsuiTouchesMoved(touches, withEvent: event)
}
}
public override func nsuiTouchesEnded(touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
if (!_interceptTouchEvents)
{
super.nsuiTouchesEnded(touches, withEvent: event)
}
}
public override func nsuiTouchesCancelled(touches: Set<NSUITouch>?, withEvent event: NSUIEvent?)
{
if (!_interceptTouchEvents)
{
super.nsuiTouchesCancelled(touches, withEvent: event)
}
}
}
| 36.040394 | 235 | 0.626063 |
891b0fff3517fe31591550d0bf452c49b5e5f2c2 | 5,835 | //===--- FunctionConversion.swift -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
//
// XFAIL: interpret
import StdlibUnittest
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif
var FunctionConversionTestSuite = TestSuite("FunctionConversion")
protocol Quilt {
var n: Int8 { get }
}
protocol Patchwork : Quilt {}
struct Trivial : Patchwork {
let n: Int8
}
struct Loadable : Patchwork {
let c: Fabric
var n: Int8 {
return c.n
}
init(n: Int8) {
c = Fabric(n: n)
}
}
struct AddrOnly : Patchwork {
let a: Any
var n: Int8 {
return a as! Int8
}
init(n: Int8) {
a = n
}
}
class Fabric {
let n: Int8
init(n: Int8) {
self.n = n
}
}
class Parent : Patchwork {
let n: Int8
required init(n: Int8) {
self.n = n
}
}
class Child : Parent {}
func t1(s: Trivial?) -> Trivial {
return Trivial(n: s!.n * 2)
}
func l1(s: Loadable?) -> Loadable {
return Loadable(n: s!.n * 2)
}
func a1(s: AddrOnly?) -> AddrOnly {
return AddrOnly(n: s!.n * 2)
}
FunctionConversionTestSuite.test("Optional") {
let g11: Trivial -> Trivial? = t1
let g12: Trivial! -> Trivial? = t1
expectEqual(22, g11(Trivial(n: 11))?.n)
expectEqual(24, g12(Trivial(n: 12))?.n)
let g21: Loadable? -> Loadable? = l1
let g22: Loadable! -> Loadable? = l1
expectEqual(42, g21(Loadable(n: 21))?.n)
expectEqual(44, g22(Loadable(n: 22))?.n)
let g31: AddrOnly? -> AddrOnly? = a1
let g32: AddrOnly! -> AddrOnly? = a1
expectEqual(62, g31(AddrOnly(n: 31))?.n)
expectEqual(64, g32(AddrOnly(n: 32))?.n)
}
func t2(s: Quilt) -> Trivial {
return s as! Trivial
}
func t3(s: Quilt?) -> Trivial {
return s! as! Trivial
}
func l2(s: Quilt) -> Loadable {
return s as! Loadable
}
func l3(s: Quilt?) -> Loadable {
return s! as! Loadable
}
func a2(s: Quilt) -> AddrOnly {
return s as! AddrOnly
}
func a3(s: Quilt?) -> AddrOnly {
return s! as! AddrOnly
}
FunctionConversionTestSuite.test("Existential") {
let g11: Trivial -> Patchwork = t2
let g12: Trivial? -> Patchwork = t3
let g13: Patchwork -> Patchwork = t2
expectEqual(11, g11(Trivial(n: 11)).n)
expectEqual(12, g12(Trivial(n: 12)).n)
expectEqual(13, g13(Trivial(n: 13)).n)
let g21: Loadable -> Patchwork = l2
let g22: Loadable? -> Patchwork = l3
let g23: Patchwork -> Patchwork = l2
expectEqual(21, g21(Loadable(n: 21)).n)
expectEqual(22, g22(Loadable(n: 22)).n)
expectEqual(23, g23(Loadable(n: 23)).n)
let g31: AddrOnly -> Patchwork = a2
let g32: AddrOnly -> Patchwork = a3
let g33: Patchwork -> Patchwork = a2
expectEqual(31, g31(AddrOnly(n: 31)).n)
expectEqual(32, g32(AddrOnly(n: 32)).n)
expectEqual(33, g33(AddrOnly(n: 33)).n)
}
func em(t: Quilt.Type?) -> Trivial.Type {
return t! as! Trivial.Type
}
FunctionConversionTestSuite.test("ExistentialMetatype") {
let g1: Trivial.Type -> Patchwork.Type = em
let g2: Trivial.Type? -> Patchwork.Type = em
let g3: Patchwork.Type -> Patchwork.Type = em
let g4: Patchwork.Type -> Any = em
let result1 = g1(Trivial.self)
let result2 = g2(Trivial.self)
let result3 = g3(Trivial.self)
let result4 = g4(Trivial.self)
expectEqual(true, result1 == Trivial.self)
expectEqual(true, result2 == Trivial.self)
expectEqual(true, result3 == Trivial.self)
expectEqual(true, result4 as! Trivial.Type == Trivial.self)
}
func c1(p: Parent) -> (Child, Trivial) {
return (Child(n: p.n), Trivial(n: p.n))
}
func c2(p: Parent?) -> (Child, Trivial) {
return (Child(n: p!.n), Trivial(n: p!.n))
}
FunctionConversionTestSuite.test("ClassUpcast") {
let g1: Child -> (Parent, Trivial?) = c1
let g2: Child -> (Parent?, Trivial?) = c2
expectEqual(g1(Child(n: 2)).0.n, 2)
expectEqual(g2(Child(n: 4)).0!.n, 4)
}
func cm1(p: Parent.Type) -> (Child.Type, Trivial) {
return (Child.self, Trivial(n: 0))
}
func cm2(p: Parent.Type?) -> (Child.Type, Trivial) {
return (Child.self, Trivial(n: 0))
}
FunctionConversionTestSuite.test("ClassMetatypeUpcast") {
let g1: Child.Type -> (Parent.Type, Trivial?) = cm1
let g2: Child.Type -> (Parent.Type, Trivial?) = cm2
let g3: Child.Type? -> (Parent.Type?, Trivial?) = cm2
let result1 = g1(Child.self)
let result2 = g2(Child.self)
let result3 = g3(Child.self)
expectEqual(true, result1.0 == Child.self)
expectEqual(true, result2.0 == Child.self)
expectEqual(true, result3.0! == Child.self)
}
func sq(i: Int) -> Int {
return i * i
}
func f1(f: Any) -> Int -> Int {
return f as! (Int -> Int)
}
FunctionConversionTestSuite.test("FuncExistential") {
let g11: (Int -> Int) -> Any = f1
expectEqual(100, f1(g11(sq))(10))
}
func generic1<T>(t: Parent) -> (T, Trivial) {
return (t as! T, Trivial(n: 0))
}
func generic2<T : Parent>(f: Parent -> (T, Trivial), t: T) -> Child -> (Parent, Trivial?) {
return f
}
FunctionConversionTestSuite.test("ClassArchetypeUpcast") {
let g11: Child -> (Parent, Trivial?) = generic2(generic1, t: Child(n: 10))
expectEqual(10, g11(Child(n: 10)).0.n)
}
func doesNotThrow() {}
FunctionConversionTestSuite.test("ThrowVariance") {
let g: () throws -> () = doesNotThrow
do { try print(g()) } catch {}
}
runAllTests()
| 22.70428 | 91 | 0.639417 |
e5cb1033e8360be4a3a961700ea7a9da66dfbfd3 | 906 | //
// SKClientFacade.swift
// StampServerKit
//
// Created by Sam Smallman on 01/03/2020.
// Copyright © 2020 Artifice Industries Ltd. All rights reserved.
//
import Foundation
import OSCKit
public class SKClientFacade {
public var isConnected: Bool { get { return socket.isConnected }}
internal let socket: OSCSocket
init(socket: OSCSocket) {
self.socket = socket
}
internal func hasSocket(socket: OSCSocket) -> Bool {
return self.socket.interface == socket.interface && self.socket.host == socket.host && self.socket.port == socket.port
}
}
extension SKClientFacade: Equatable {
public static func == (lhs: SKClientFacade, rhs: SKClientFacade) -> Bool {
return lhs.socket.interface == rhs.socket.interface &&
lhs.socket.host == rhs.socket.host &&
lhs.socket.port == rhs.socket.port
}
}
| 25.885714 | 126 | 0.646799 |
8a91cab703be72d142d0ad81604c72ea840050a0 | 1,105 | // swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "CustomLoadingButton",
platforms: [.iOS(.v13)],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "CustomLoadingButton",
targets: ["CustomLoadingButton"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "CustomLoadingButton",
dependencies: []),
.testTarget(
name: "CustomLoadingButtonTests",
dependencies: ["CustomLoadingButton"]),
]
)
| 36.833333 | 117 | 0.637104 |
f7b7828519ad6e03cdcf824bed14176eb2f4ecac | 591 | //
// StorageTabViewController.swift
// Skyskanner
//
// Created by 김인환 on 2021/12/23.
//
import UIKit
class StorageTabViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
}
init() {
super.init(nibName: nil, bundle: nil)
setTabbarItem()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setTabbarItem() {
tabBarItem = UITabBarItem(tabBarSystemItem: .bookmarks, tag: 2)
}
}
| 19.7 | 71 | 0.622673 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.